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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b4164edbfe7518bde515d81efcbc03e2a258e6c4
| 15,065
|
cpp
|
C++
|
lanelet2_traffic_rules/src/GenericTrafficRules.cpp
|
icolwell-as/Lanelet2
|
0e2e222352936cd70a9fab5256684a97c3091996
|
[
"BSD-3-Clause"
] | 2
|
2019-07-17T16:54:03.000Z
|
2020-01-31T08:56:39.000Z
|
lanelet2_traffic_rules/src/GenericTrafficRules.cpp
|
icolwell-as/Lanelet2
|
0e2e222352936cd70a9fab5256684a97c3091996
|
[
"BSD-3-Clause"
] | null | null | null |
lanelet2_traffic_rules/src/GenericTrafficRules.cpp
|
icolwell-as/Lanelet2
|
0e2e222352936cd70a9fab5256684a97c3091996
|
[
"BSD-3-Clause"
] | 1
|
2021-06-01T21:08:37.000Z
|
2021-06-01T21:08:37.000Z
|
#include "GenericTrafficRules.h"
#include <lanelet2_core/geometry/Area.h>
#include <lanelet2_core/geometry/Lanelet.h>
#include <lanelet2_core/primitives/RegulatoryElement.h>
#include <lanelet2_core/utility/Units.h>
#include "Exceptions.h"
namespace lanelet {
namespace traffic_rules {
namespace {
bool canChangeToLeft(LaneChangeType t) { return t == LaneChangeType::Both || t == LaneChangeType::ToLeft; }
bool canChangeToRight(LaneChangeType t) { return t == LaneChangeType::Both || t == LaneChangeType::ToRight; }
template <typename Map, typename Key, typename Value>
Value getMapOrDefault(const Map& map, Key key, Value defaultVal) {
auto elem = map.find(key);
if (elem == map.end()) {
return defaultVal;
}
return elem->second;
}
bool startswith(const std::string& str, const std::string& substr) {
return str.compare(0, substr.size(), substr) == 0;
}
LaneChangeType getChangeType(const std::string& type, const std::string& subtype, const std::string& participant) {
using LaneChangeMap = std::map<std::pair<std::string, std::string>, LaneChangeType>;
const static LaneChangeMap VehicleChangeType{
{{AttributeValueString::LineThin, AttributeValueString::Dashed}, LaneChangeType::Both},
{{AttributeValueString::LineThick, AttributeValueString::Dashed}, LaneChangeType::Both},
{{AttributeValueString::LineThin, AttributeValueString::DashedSolid}, LaneChangeType::ToRight},
{{AttributeValueString::LineThick, AttributeValueString::DashedSolid}, LaneChangeType::ToRight},
{{AttributeValueString::LineThin, AttributeValueString::SolidDashed}, LaneChangeType::ToLeft},
{{AttributeValueString::LineThick, AttributeValueString::SolidDashed}, LaneChangeType::ToLeft}};
const static LaneChangeMap PedestrianChangeType{
{{AttributeValueString::Curbstone, AttributeValueString::Low}, LaneChangeType::Both}};
if (startswith(participant, Participants::Vehicle)) {
return getMapOrDefault(VehicleChangeType, std::make_pair(type, subtype), LaneChangeType::None);
}
if (participant == Participants::Pedestrian) {
return getMapOrDefault(PedestrianChangeType, std::make_pair(type, subtype), LaneChangeType::None);
}
if (participant == Participants::Bicycle) {
auto asVehicle = getMapOrDefault(VehicleChangeType, std::make_pair(type, subtype), LaneChangeType::None);
if (asVehicle != LaneChangeType::None) {
return asVehicle;
}
return getMapOrDefault(PedestrianChangeType, std::make_pair(type, subtype), LaneChangeType::None);
}
return LaneChangeType::None;
}
Optional<LaneChangeType> getHardcodedChangeType(const ConstLineString3d& boundary) {
if (boundary.hasAttribute(AttributeNamesString::LaneChange)) {
if (boundary.attributeOr(AttributeNamesString::LaneChange, false)) {
return {true, LaneChangeType::Both};
}
return {true, LaneChangeType::None};
}
if (boundary.hasAttribute(AttributeNamesString::LaneChangeLeft)) {
if (boundary.attributeOr(AttributeNamesString::LaneChangeLeft, false)) {
if (boundary.attributeOr(AttributeNamesString::LaneChangeRight, false)) {
return {true, LaneChangeType::Both};
}
return {true, LaneChangeType::ToLeft};
}
return {true, LaneChangeType::None};
}
if (boundary.hasAttribute(AttributeNamesString::LaneChangeRight)) {
if (boundary.attributeOr(AttributeNamesString::LaneChangeRight, false)) {
return {true, LaneChangeType::ToRight};
}
return {true, LaneChangeType::None};
}
return {false, LaneChangeType::None};
}
bool hasOverride(const AttributeMap& attrs, const std::string& overridePrefix) {
return utils::anyOf(attrs, [&overridePrefix](auto& attr) { return startswith(attr.first, overridePrefix); });
}
template <typename T>
T getOverride(const AttributeMap& attrs, const std::string& overridePrefix, const std::string& override, T defaultVal) {
auto overrideAttr = utils::findIf(attrs, [&override, &overridePrefix](auto& attr) {
// it is forbidden to define overrides at different hierachical levels, so we just have to search for one single
// hit.
if (attr.first.size() < overridePrefix.size()) {
return false;
}
return startswith(override, attr.first);
});
if (!overrideAttr) {
return defaultVal;
}
return overrideAttr->second.template as<T>().get_value_or(defaultVal);
}
bool isDrivingDir(const lanelet::ConstLanelet& ll, const std::string& participant) {
if (!ll.inverted()) {
return true;
}
auto hasOneWay = ll.attributeOr(AttributeName::OneWay, Optional<bool>());
if (!!hasOneWay) {
return !*hasOneWay;
}
if (hasOverride(ll.attributes(), AttributeNamesString::OneWay)) {
return !getOverride(ll.attributes(), AttributeNamesString::OneWay,
AttributeNamesString::OneWay + (":" + participant), true);
}
return participant == Participants::Pedestrian;
}
template <typename T>
T sort(const T& toSort) {
auto sorted = toSort;
std::sort(sorted.begin(), sorted.end());
return sorted;
}
} // namespace
TrafficRules::~TrafficRules() = default;
bool GenericTrafficRules::hasDynamicRules(const ConstLanelet& lanelet) const {
auto regelems = lanelet.regulatoryElements();
auto isDynamic = [](const auto& elem) { return elem->attributeOr(AttributeName::Dynamic, false); };
return std::any_of(regelems.begin(), regelems.end(), isDynamic);
}
bool GenericTrafficRules::canPass(const lanelet::ConstLanelet& lanelet) const {
if (!isDrivingDir(lanelet, participant())) {
return false;
}
auto canPassByRule = canPass(lanelet.regulatoryElements());
if (!!canPassByRule) {
return *canPassByRule;
}
if (hasOverride(lanelet.attributes(), AttributeNamesString::Participant)) {
return getOverride(lanelet.attributes(), AttributeNamesString::Participant, Participants::tag(participant()),
false);
}
return canPass(lanelet.attributeOr(AttributeName::Subtype, ""), lanelet.attributeOr(AttributeName::Location, ""))
.get_value_or(false);
}
bool GenericTrafficRules::canPass(const ConstArea& area) const {
auto canPassByRule = canPass(area.regulatoryElements());
if (!!canPassByRule) {
return *canPassByRule;
}
if (hasOverride(area.attributes(), AttributeNamesString::Participant)) {
return getOverride(area.attributes(), AttributeNamesString::Participant, Participants::tag(participant()), false);
}
return canPass(area.attributeOr(AttributeName::Subtype, ""), area.attributeOr(AttributeName::Location, ""))
.get_value_or(false);
}
LaneChangeType GenericTrafficRules::laneChangeType(const ConstLineString3d& boundary,
bool virtualIsPassable = false) const {
using namespace std::string_literals;
LaneChangeType changeType;
auto result = getHardcodedChangeType(boundary);
if (!!result) {
changeType = *result;
} else {
auto type = boundary.attributeOr(AttributeName::Type, ""s);
if (virtualIsPassable && type == AttributeValueString::Virtual) {
return LaneChangeType::Both;
}
changeType = getChangeType(type, boundary.attributeOr(AttributeName::Subtype, ""s), participant());
}
// handle inverted ls
if (boundary.inverted()) {
if (changeType == LaneChangeType::ToLeft) {
return LaneChangeType::ToRight;
}
if (changeType == LaneChangeType::ToRight) {
return LaneChangeType::ToLeft;
}
}
return changeType;
}
bool GenericTrafficRules::canPass(const ConstLanelet& from, const ConstLanelet& to) const {
return geometry::follows(from, to) && canPass(from) && canPass(to);
}
Optional<ConstLineString3d> determineCommonLine(const ConstLanelet& ll, const ConstArea& ar) {
return utils::findIf(ar.outerBound(), [p1 = ll.leftBound().back(), p2 = ll.rightBound().back()](auto& boundLs) {
return (boundLs.back() == p1 && boundLs.front() == p2);
});
}
Optional<ConstLineString3d> determineCommonLine(const ConstArea& ar1, const ConstArea& ar2) {
return utils::findIf(ar1.outerBound(), [&ar2](auto& ar1Bound) {
return !!utils::findIf(ar2.outerBound(),
[ar1Bound = ar1Bound.invert()](auto& ar2Bound) { return ar2Bound == ar1Bound; });
});
}
bool GenericTrafficRules::canPass(const ConstLanelet& from, const ConstArea& to) const {
if (!canPass(from) || !canPass(to)) {
return false;
}
if (geometry::leftOf(from, to)) {
return canChangeToLeft(laneChangeType(from.leftBound(), true));
}
if (geometry::rightOf(from, to)) {
return canChangeToRight(laneChangeType(from.rightBound(), true));
}
auto line = determineCommonLine(from, to);
if (!!line) {
return canChangeToRight(laneChangeType(*line, true));
}
return false;
}
bool GenericTrafficRules::canPass(const ConstArea& from, const ConstLanelet& to) const {
if (!canPass(from) || !canPass(to)) {
return false;
}
if (geometry::leftOf(to, from)) {
return canChangeToRight(laneChangeType(to.leftBound(), true));
}
if (geometry::rightOf(to, from)) {
return canChangeToLeft(laneChangeType(to.rightBound(), true));
}
auto line = determineCommonLine(to.invert(), from);
if (!!line) {
return canChangeToLeft(laneChangeType(*line, true));
}
return false;
}
bool GenericTrafficRules::canPass(const ConstArea& from, const ConstArea& to) const {
if (!canPass(from) && canPass(to)) {
return false;
}
auto line = determineCommonLine(from, to);
if (!line) {
return false;
}
return canChangeToLeft(laneChangeType(*line, true));
}
bool GenericTrafficRules::canChangeLane(const ConstLanelet& from, const ConstLanelet& to) const {
if (!canPass(from) || !canPass(to)) {
return false;
}
bool isLeft = false;
if (geometry::leftOf(from, to)) {
isLeft = true;
} else if (!geometry::rightOf(from, to)) {
return false;
}
auto type = laneChangeType(isLeft ? from.rightBound() : from.leftBound());
return isLeft ? canChangeToRight(type) : canChangeToLeft(type);
}
SpeedLimitInformation getSpeedLimitFromType(const AttributeMap& attributes, const CountrySpeedLimits& countryLimits,
const std::string& participant) {
using Value = AttributeValueString;
using SpeedLimitMap = std::map<std::pair<std::string, std::string>, SpeedLimitInformation(CountrySpeedLimits::*)>;
const static SpeedLimitMap SpeedLimitLookup{
{{Value::Urban, Value::Road}, &CountrySpeedLimits::vehicleUrbanRoad},
{{Value::Nonurban, Value::Road}, &CountrySpeedLimits::vehicleNonurbanRoad},
{{Value::Urban, Value::Highway}, &CountrySpeedLimits::vehicleUrbanHighway},
{{Value::Nonurban, Value::Highway}, &CountrySpeedLimits::vehicleNonurbanHighway},
{{Value::Urban, Value::PlayStreet}, &CountrySpeedLimits::playStreet},
{{Value::Nonurban, Value::PlayStreet}, &CountrySpeedLimits::playStreet},
{{Value::Urban, Value::Exit}, &CountrySpeedLimits::vehicleUrbanRoad},
};
if (participant == Participants::Pedestrian) {
return countryLimits.pedestrian;
}
if (participant == Participants::Bicycle) {
return countryLimits.bicycle;
}
const std::string vehicle = Participants::Vehicle;
if (startswith(participant, vehicle)) {
auto location =
getMapOrDefault(attributes, AttributeName::Location, Attribute(AttributeValueString::Urban)).value();
auto type = getMapOrDefault(attributes, AttributeName::Subtype, Attribute(AttributeValueString::Road)).value();
auto limit = SpeedLimitLookup.find(std::make_pair(location, type));
if (limit != SpeedLimitLookup.end()) {
return countryLimits.*(limit->second);
}
}
return {};
}
SpeedLimitInformation GenericTrafficRules::speedLimit(const RegulatoryElementConstPtrs& regelems,
const AttributeMap& attributes) const {
using namespace std::string_literals;
using namespace units::literals;
using Attr = AttributeNamesString;
auto regelemSpeedLimit = speedLimit(regelems);
if (!!regelemSpeedLimit) {
return *regelemSpeedLimit;
}
if (hasOverride(attributes, Attr::SpeedLimit) || hasOverride(attributes, Attr::SpeedLimitMandatory)) {
auto defaultLimit =
getMapOrDefault(attributes, AttributeName::SpeedLimit, Attribute(0_kmh)).asVelocity().get_value_or(0_kmh);
auto limit =
getOverride(attributes, Attr::SpeedLimit + ":"s, Attr::SpeedLimit + ":"s + participant(), defaultLimit);
auto mandatory =
getOverride(attributes, Attr::SpeedLimitMandatory, Attr::SpeedLimitMandatory + ":"s + participant(), true);
return {limit, mandatory};
}
return getSpeedLimitFromType(attributes, countrySpeedLimits(), participant());
}
SpeedLimitInformation GenericTrafficRules::speedLimit(const ConstLanelet& lanelet) const {
return speedLimit(lanelet.regulatoryElements(), lanelet.attributes());
}
SpeedLimitInformation GenericTrafficRules::speedLimit(const ConstArea& area) const {
return speedLimit(area.regulatoryElements(), area.attributes());
}
const std::string& TrafficRules::participant() const { return config_.at("participant").value(); }
const std::string& TrafficRules::location() const { return config_.at("location").value(); }
Optional<bool> GenericTrafficRules::canPass(const std::string& type, const std::string& /*location*/) const {
using ParticantsMap = std::map<std::string, std::vector<std::string>>;
using Value = AttributeValueString;
const static ParticantsMap ParticipantMap{
{"", {Participants::Vehicle}},
{Value::Road, {Participants::Vehicle, Participants::Bicycle}},
{Value::Highway, {Participants::Vehicle}},
{Value::BicycleLane, {Participants::Bicycle}},
{Value::PlayStreet, {Participants::Pedestrian, Participants::Bicycle, Participants::Vehicle}},
{Value::EmergencyLane, {Participants::VehicleEmergency}},
{Value::Exit, {Participants::Pedestrian, Participants::Bicycle, Participants::Vehicle}},
{Value::Walkway, {Participants::Pedestrian}},
{Value::Crosswalk, {Participants::Pedestrian}},
{Value::Stairs, {Participants::Pedestrian}},
{Value::SharedWalkway, {Participants::Pedestrian, Participants::Bicycle}}};
auto participants = ParticipantMap.find(type);
if (participants == ParticipantMap.end()) {
return {};
}
return utils::anyOf(participants->second,
[this](auto& participant) { return startswith(this->participant(), participant); });
}
bool GenericTrafficRules::isOneWay(const ConstLanelet& lanelet) const {
return isDrivingDir(lanelet, participant()) != isDrivingDir(lanelet.invert(), participant());
}
std::ostream& operator<<(std::ostream& stream, const SpeedLimitInformation& obj) {
return stream << "speedLimit: " << units::KmHQuantity(obj.speedLimit).value()
<< "km/h, mandatory: " << (obj.isMandatory ? "yes" : "no");
}
std::ostream& operator<<(std::ostream& stream, const TrafficRules& obj) {
return stream << "location: " << obj.location() << ", participant: " << obj.participant();
}
} // namespace traffic_rules
} // namespace lanelet
| 41.387363
| 120
| 0.709525
|
icolwell-as
|
b4247dbf89f1df83991196174a5440113f1f4df2
| 2,305
|
cpp
|
C++
|
cognitics/src/ctl/ID.cpp
|
mikedig/cdb-productivity-api
|
e2bedaa550a8afa780c01f864d72e0aebd87dd5a
|
[
"MIT"
] | null | null | null |
cognitics/src/ctl/ID.cpp
|
mikedig/cdb-productivity-api
|
e2bedaa550a8afa780c01f864d72e0aebd87dd5a
|
[
"MIT"
] | null | null | null |
cognitics/src/ctl/ID.cpp
|
mikedig/cdb-productivity-api
|
e2bedaa550a8afa780c01f864d72e0aebd87dd5a
|
[
"MIT"
] | null | null | null |
/*************************************************************************
Copyright (c) 2019 Cognitics, Inc.
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 "ctl/ID.h"
namespace ctl {
IDGenerator::IDGenerator(void)
{
AvailableIDs.push_back(0);
}
ID IDGenerator::getID(void)
{
if (AvailableIDs.size() > 1)
{
ID id = AvailableIDs.back();
AvailableIDs.pop_back();
return id;
}
else
return (AvailableIDs.front()++);
}
void IDGenerator::freeID(ID id)
{
AvailableIDs.push_back(id);
}
bool IDGenerator::isIDUsed(ID id) const
{
for (int i = int(AvailableIDs.size())-1; i > 0; i--)
{
if (id == AvailableIDs[i]) return false;
}
if (id < AvailableIDs[0]) return true;
else return false;
}
ccl::uint32_t IDGenerator::numUsedIDs(void) const
{
return AvailableIDs.front() - ccl::uint32_t(AvailableIDs.size()) + 1;
}
ccl::uint32_t IDGenerator::numFreeIDs(void) const
{
return ccl::uint32_t(AvailableIDs.size()) - 1;
}
ccl::uint32_t IDGenerator::peekNextID(void)
{
return AvailableIDs[0];
}
}
| 31.575342
| 77
| 0.62603
|
mikedig
|
b425167be87e0b43fbb43d796c5b546638d0bd4f
| 26,475
|
cpp
|
C++
|
gdal/ogr/ogrsf_frmts/mdb/ogrmdbjackcess.cpp
|
CesiumGS/gdal
|
a52a503d72554226b955e4607eb0c2404c107e74
|
[
"MIT"
] | 1
|
2020-02-22T01:28:29.000Z
|
2020-02-22T01:28:29.000Z
|
gdal/ogr/ogrsf_frmts/mdb/ogrmdbjackcess.cpp
|
AnalyticalGraphicsInc/gdal
|
a52a503d72554226b955e4607eb0c2404c107e74
|
[
"MIT"
] | null | null | null |
gdal/ogr/ogrsf_frmts/mdb/ogrmdbjackcess.cpp
|
AnalyticalGraphicsInc/gdal
|
a52a503d72554226b955e4607eb0c2404c107e74
|
[
"MIT"
] | 2
|
2018-05-08T01:51:34.000Z
|
2019-06-26T05:08:56.000Z
|
/******************************************************************************
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Implements OGRMDBJavaEnv class.
* Author: Even Rouault, <even dot rouault at mines dash paris dot org>
*
******************************************************************************
* Copyright (c) 2011, Even Rouault <even dot rouault at mines-paris dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "ogr_mdb.h"
CPL_CVSID("$Id$");
static JavaVM *jvm_static = NULL;
static JNIEnv *env_static = NULL;
/************************************************************************/
/* OGRMDBJavaEnv() */
/************************************************************************/
OGRMDBJavaEnv::OGRMDBJavaEnv()
{
jvm = NULL;
env = NULL;
bCalledFromJava = FALSE;
byteArray_class = NULL;
file_class = NULL;
file_constructor = NULL;
database_class = NULL;
database_open = NULL;
database_close = NULL;
database_getTableNames = NULL;
database_getTable = NULL;
table_class = NULL;
table_getColumns = NULL;
table_iterator = NULL;
table_getRowCount = NULL;
column_class = NULL;
column_getName = NULL;
column_getType = NULL;
column_getLength = NULL;
column_isVariableLength = NULL;
datatype_class = NULL;
datatype_getValue = NULL;
list_class = NULL;
list_iterator = NULL;
set_class = NULL;
set_iterator = NULL;
map_class = NULL;
map_get = NULL;
iterator_class = NULL;
iterator_hasNext = NULL;
iterator_next = NULL;
object_class = NULL;
object_toString = NULL;
object_getClass = NULL;
boolean_class = NULL;
boolean_booleanValue = NULL;
byte_class = NULL;
byte_byteValue = NULL;
short_class = NULL;
short_shortValue = NULL;
integer_class = NULL;
integer_intValue = NULL;
float_class = NULL;
float_floatValue = NULL;
double_class = NULL;
double_doubleValue = NULL;
}
/************************************************************************/
/* ~OGRMDBJavaEnv() */
/************************************************************************/
OGRMDBJavaEnv::~OGRMDBJavaEnv()
{
if (jvm)
{
env->DeleteLocalRef(byteArray_class);
env->DeleteLocalRef(file_class);
env->DeleteLocalRef(database_class);
env->DeleteLocalRef(table_class);
env->DeleteLocalRef(column_class);
env->DeleteLocalRef(datatype_class);
env->DeleteLocalRef(list_class);
env->DeleteLocalRef(set_class);
env->DeleteLocalRef(map_class);
env->DeleteLocalRef(iterator_class);
env->DeleteLocalRef(object_class);
env->DeleteLocalRef(boolean_class);
env->DeleteLocalRef(byte_class);
env->DeleteLocalRef(short_class);
env->DeleteLocalRef(integer_class);
env->DeleteLocalRef(float_class);
env->DeleteLocalRef(double_class);
/*if (!bCalledFromJava)
{
CPLDebug("MDB", "Destroying JVM");
int ret = jvm->DestroyJavaVM();
CPLDebug("MDB", "ret=%d", ret);
}*/
}
}
#define CHECK(x, y) do {x = y; if (!x) { CPLError(CE_Failure, CPLE_AppDefined, #y " failed"); return FALSE;} } while(0)
/************************************************************************/
/* Init() */
/************************************************************************/
int OGRMDBJavaEnv::Init()
{
if (jvm_static == NULL)
{
JavaVM* vmBuf[1];
jsize nVMs;
/* Are we already called from Java ? */
if (JNI_GetCreatedJavaVMs(vmBuf, 1, &nVMs) == JNI_OK && nVMs == 1)
{
jvm = vmBuf[0];
if (jvm->GetEnv((void **)&env, JNI_VERSION_1_2) == JNI_OK)
{
bCalledFromJava = TRUE;
}
else
{
jvm = NULL;
env = NULL;
}
}
else
{
JavaVMInitArgs args;
JavaVMOption options[1];
args.version = JNI_VERSION_1_2;
const char* pszClassPath = CPLGetConfigOption("CLASSPATH", NULL);
char* pszClassPathOption = NULL;
if (pszClassPath)
{
args.nOptions = 1;
pszClassPathOption = CPLStrdup(CPLSPrintf("-Djava.class.path=%s", pszClassPath));
options[0].optionString = pszClassPathOption;
args.options = options;
}
else
args.nOptions = 0;
args.ignoreUnrecognized = JNI_FALSE;
int ret = JNI_CreateJavaVM(&jvm, (void **)&env, &args);
CPLFree(pszClassPathOption);
if (ret != 0 || jvm == NULL || env == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "JNI_CreateJavaVM failed (%d)", ret);
return FALSE;
}
jvm_static = jvm;
env_static = env;
}
}
else
{
jvm = jvm_static;
env = env_static;
}
if( env == NULL )
return FALSE;
CHECK(byteArray_class, env->FindClass("[B"));
CHECK(file_class, env->FindClass("java/io/File"));
CHECK(file_constructor, env->GetMethodID(file_class, "<init>", "(Ljava/lang/String;)V"));
CHECK(database_class, env->FindClass("com/healthmarketscience/jackcess/Database"));
CHECK(database_open, env->GetStaticMethodID(database_class, "open", "(Ljava/io/File;Z)Lcom/healthmarketscience/jackcess/Database;"));
CHECK(database_close, env->GetMethodID(database_class, "close", "()V"));
CHECK(database_getTableNames, env->GetMethodID(database_class, "getTableNames", "()Ljava/util/Set;"));
CHECK(database_getTable, env->GetMethodID(database_class, "getTable", "(Ljava/lang/String;)Lcom/healthmarketscience/jackcess/Table;"));
CHECK(table_class, env->FindClass("com/healthmarketscience/jackcess/Table"));
CHECK(table_getColumns, env->GetMethodID(table_class, "getColumns", "()Ljava/util/List;"));
CHECK(table_iterator, env->GetMethodID(table_class, "iterator", "()Ljava/util/Iterator;"));
CHECK(table_getRowCount, env->GetMethodID(table_class, "getRowCount", "()I"));
CHECK(column_class, env->FindClass("com/healthmarketscience/jackcess/Column"));
CHECK(column_getName, env->GetMethodID(column_class, "getName", "()Ljava/lang/String;"));
CHECK(column_getType, env->GetMethodID(column_class, "getType", "()Lcom/healthmarketscience/jackcess/DataType;"));
CHECK(column_getLength, env->GetMethodID(column_class, "getLength", "()S"));
CHECK(column_isVariableLength, env->GetMethodID(column_class, "isVariableLength", "()Z"));
CHECK(datatype_class, env->FindClass("com/healthmarketscience/jackcess/DataType"));
CHECK(datatype_getValue, env->GetMethodID(datatype_class, "getValue", "()B"));
CHECK(list_class, env->FindClass("java/util/List"));
CHECK(list_iterator, env->GetMethodID(list_class, "iterator", "()Ljava/util/Iterator;"));
CHECK(set_class, env->FindClass("java/util/Set"));
CHECK(set_iterator, env->GetMethodID(set_class, "iterator", "()Ljava/util/Iterator;"));
CHECK(map_class, env->FindClass("java/util/Map"));
CHECK(map_get, env->GetMethodID(map_class, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"));
CHECK(iterator_class, env->FindClass("java/util/Iterator"));
CHECK(iterator_hasNext, env->GetMethodID(iterator_class, "hasNext", "()Z"));
CHECK(iterator_next, env->GetMethodID(iterator_class, "next", "()Ljava/lang/Object;"));
CHECK(object_class, env->FindClass("java/lang/Object"));
CHECK(object_toString, env->GetMethodID(object_class, "toString", "()Ljava/lang/String;"));
CHECK(object_getClass, env->GetMethodID(object_class, "getClass", "()Ljava/lang/Class;"));
CHECK(boolean_class, env->FindClass("java/lang/Boolean"));
CHECK(boolean_booleanValue, env->GetMethodID(boolean_class, "booleanValue", "()Z"));
CHECK(byte_class, env->FindClass("java/lang/Byte"));
CHECK(byte_byteValue, env->GetMethodID(byte_class, "byteValue", "()B"));
CHECK(short_class, env->FindClass("java/lang/Short"));
CHECK(short_shortValue, env->GetMethodID(short_class, "shortValue", "()S"));
CHECK(integer_class, env->FindClass("java/lang/Integer"));
CHECK(integer_intValue, env->GetMethodID(integer_class, "intValue", "()I"));
CHECK(float_class, env->FindClass("java/lang/Float"));
CHECK(float_floatValue, env->GetMethodID(float_class, "floatValue", "()F"));
CHECK(double_class, env->FindClass("java/lang/Double"));
CHECK(double_doubleValue, env->GetMethodID(integer_class, "doubleValue", "()D"));
return TRUE;
}
/************************************************************************/
/* ExceptionOccurred() */
/************************************************************************/
int OGRMDBJavaEnv::ExceptionOccurred()
{
jthrowable exc = env->ExceptionOccurred();
if (exc)
{
env->ExceptionDescribe();
env->ExceptionClear();
return TRUE;
}
return FALSE;
}
/************************************************************************/
/* OGRMDBDatabase() */
/************************************************************************/
OGRMDBDatabase::OGRMDBDatabase()
{
env = NULL;
database = NULL;
}
/************************************************************************/
/* ~OGRMDBDatabase() */
/************************************************************************/
OGRMDBDatabase::~OGRMDBDatabase()
{
if (database)
{
CPLDebug("MDB", "Closing database");
env->env->CallVoidMethod(database, env->database_close);
env->env->DeleteGlobalRef(database);
}
}
/************************************************************************/
/* Open() */
/************************************************************************/
OGRMDBDatabase* OGRMDBDatabase::Open(OGRMDBJavaEnv* env, const char* pszName)
{
jstring jstr = env->env->NewStringUTF(pszName);
jobject file = env->env->NewObject(env->file_class, env->file_constructor, jstr);
if (env->ExceptionOccurred()) return NULL;
env->env->ReleaseStringUTFChars(jstr, NULL);
jobject database = env->env->CallStaticObjectMethod(env->database_class, env->database_open, file, JNI_TRUE);
env->env->DeleteLocalRef(file);
if (env->ExceptionOccurred()) return NULL;
if (database == NULL)
return NULL;
OGRMDBDatabase* poDB = new OGRMDBDatabase();
poDB->env = env;
poDB->database = env->env->NewGlobalRef(database);
env->env->DeleteLocalRef(database);
return poDB;
}
/************************************************************************/
/* FetchTableNames() */
/************************************************************************/
int OGRMDBDatabase::FetchTableNames()
{
if (env->bCalledFromJava)
env->Init();
jobject table_set = env->env->CallObjectMethod(database, env->database_getTableNames);
if (env->ExceptionOccurred()) return FALSE;
jobject iterator = env->env->CallObjectMethod(table_set, env->set_iterator);
if (env->ExceptionOccurred()) return FALSE;
while( env->env->CallBooleanMethod(iterator, env->iterator_hasNext) )
{
if (env->ExceptionOccurred()) return FALSE;
jstring table_name_jstring = (jstring) env->env->CallObjectMethod(iterator, env->iterator_next);
if (env->ExceptionOccurred()) return FALSE;
jboolean is_copy;
const char* table_name_str = env->env->GetStringUTFChars(table_name_jstring, &is_copy);
apoTableNames.push_back(table_name_str);
//CPLDebug("MDB", "Table %s", table_name_str);
env->env->ReleaseStringUTFChars(table_name_jstring, table_name_str);
env->env->DeleteLocalRef(table_name_jstring);
}
env->env->DeleteLocalRef(iterator);
env->env->DeleteLocalRef(table_set);
return TRUE;
}
/************************************************************************/
/* GetTable() */
/************************************************************************/
OGRMDBTable* OGRMDBDatabase::GetTable(const char* pszTableName)
{
if (env->bCalledFromJava)
env->Init();
jstring table_name_jstring = env->env->NewStringUTF(pszTableName);
jobject table = env->env->CallObjectMethod(database, env->database_getTable, table_name_jstring);
if (env->ExceptionOccurred()) return NULL;
env->env->DeleteLocalRef(table_name_jstring);
if (!table)
return NULL;
jobject global_table = env->env->NewGlobalRef(table);
env->env->DeleteLocalRef(table);
table = global_table;
OGRMDBTable* poTable = new OGRMDBTable(env, this, table, pszTableName);
if (!poTable->FetchColumns())
{
delete poTable;
return NULL;
}
return poTable;
}
/************************************************************************/
/* OGRMDBTable() */
/************************************************************************/
OGRMDBTable::OGRMDBTable(OGRMDBJavaEnv* envIn, OGRMDBDatabase* poDBIn, jobject tableIn, const char* pszTableName )
{
this->env = envIn;
this->poDB = poDBIn;
this->table = tableIn;
osTableName = pszTableName;
table_iterator_obj = NULL;
row = NULL;
}
/************************************************************************/
/* ~OGRMDBTable() */
/************************************************************************/
OGRMDBTable::~OGRMDBTable()
{
if (env)
{
//CPLDebug("MDB", "Freeing table %s", osTableName.c_str());
if (env->bCalledFromJava)
env->Init();
int i;
for(i=0;i<(int)apoColumnNameObjects.size();i++)
env->env->DeleteGlobalRef(apoColumnNameObjects[i]);
env->env->DeleteGlobalRef(table_iterator_obj);
env->env->DeleteGlobalRef(row);
env->env->DeleteGlobalRef(table);
}
}
/************************************************************************/
/* FetchColumns() */
/************************************************************************/
int OGRMDBTable::FetchColumns()
{
if (env->bCalledFromJava)
env->Init();
jobject column_lists = env->env->CallObjectMethod(table, env->table_getColumns);
if (env->ExceptionOccurred()) return FALSE;
jobject iterator_cols = env->env->CallObjectMethod(column_lists, env->list_iterator);
if (env->ExceptionOccurred()) return FALSE;
while( env->env->CallBooleanMethod(iterator_cols, env->iterator_hasNext) )
{
if (env->ExceptionOccurred()) return FALSE;
jobject column = env->env->CallObjectMethod(iterator_cols, env->iterator_next);
if (env->ExceptionOccurred()) return FALSE;
jstring column_name_jstring = (jstring) env->env->CallObjectMethod(column, env->column_getName);
if (env->ExceptionOccurred()) return FALSE;
jboolean is_copy;
const char* column_name_str = env->env->GetStringUTFChars(column_name_jstring, &is_copy);
apoColumnNames.push_back(column_name_str);
env->env->ReleaseStringUTFChars(column_name_jstring, column_name_str);
apoColumnNameObjects.push_back((jstring) env->env->NewGlobalRef(column_name_jstring));
env->env->DeleteLocalRef(column_name_jstring);
jobject column_type = env->env->CallObjectMethod(column, env->column_getType);
if (env->ExceptionOccurred()) return FALSE;
int type = env->env->CallByteMethod(column_type, env->datatype_getValue);
if (env->ExceptionOccurred()) return FALSE;
apoColumnTypes.push_back(type);
int isvariablelength = env->env->CallBooleanMethod(column, env->column_isVariableLength);
if (env->ExceptionOccurred()) return FALSE;
if (!isvariablelength)
{
int length = env->env->CallShortMethod(column, env->column_getLength);
if (env->ExceptionOccurred()) return FALSE;
apoColumnLengths.push_back(length);
}
else
apoColumnLengths.push_back(0);
//CPLDebug("MDB", "Column %s, type = %d", apoColumnNames[apoColumnNames.size()-1].c_str(), type);
env->env->DeleteLocalRef(column_type);
env->env->DeleteLocalRef(column);
}
env->env->DeleteLocalRef(iterator_cols);
env->env->DeleteLocalRef(column_lists);
return TRUE;
}
/************************************************************************/
/* ResetReading() */
/************************************************************************/
void OGRMDBTable::ResetReading()
{
if (env->bCalledFromJava)
env->Init();
env->env->DeleteGlobalRef(table_iterator_obj);
table_iterator_obj = NULL;
env->env->DeleteGlobalRef(row);
row = NULL;
}
/************************************************************************/
/* GetNextRow() */
/************************************************************************/
int OGRMDBTable::GetNextRow()
{
if (env->bCalledFromJava)
env->Init();
if (table_iterator_obj == NULL)
{
table_iterator_obj = env->env->CallObjectMethod(table, env->table_iterator);
if (env->ExceptionOccurred()) return FALSE;
if (table_iterator_obj)
{
jobject global_table_iterator_obj = env->env->NewGlobalRef(table_iterator_obj);
env->env->DeleteLocalRef(table_iterator_obj);
table_iterator_obj = global_table_iterator_obj;
}
}
if (table_iterator_obj == NULL)
return FALSE;
if (!env->env->CallBooleanMethod(table_iterator_obj, env->iterator_hasNext))
return FALSE;
if (env->ExceptionOccurred()) return FALSE;
if (row)
{
env->env->DeleteGlobalRef(row);
row = NULL;
}
row = env->env->CallObjectMethod(table_iterator_obj, env->iterator_next);
if (env->ExceptionOccurred()) return FALSE;
if (row == NULL)
return FALSE;
jobject global_row = env->env->NewGlobalRef(row);
env->env->DeleteLocalRef(row);
row = global_row;
return TRUE;
}
/************************************************************************/
/* GetColumnVal() */
/************************************************************************/
jobject OGRMDBTable::GetColumnVal(int iCol)
{
if (row == NULL)
return NULL;
jobject val = env->env->CallObjectMethod(row, env->map_get, apoColumnNameObjects[iCol]);
if (env->ExceptionOccurred()) return NULL;
return val;
}
/************************************************************************/
/* GetColumnAsString() */
/************************************************************************/
char* OGRMDBTable::GetColumnAsString(int iCol)
{
jobject val = GetColumnVal(iCol);
if (!val) return NULL;
jstring val_jstring = (jstring) env->env->CallObjectMethod(val, env->object_toString);
if (env->ExceptionOccurred()) return NULL;
jboolean is_copy;
const char* val_str = env->env->GetStringUTFChars(val_jstring, &is_copy);
char* dup_str = (val_str) ? CPLStrdup(val_str) : NULL;
env->env->ReleaseStringUTFChars(val_jstring, val_str);
env->env->DeleteLocalRef(val_jstring);
env->env->DeleteLocalRef(val);
return dup_str;
}
/************************************************************************/
/* GetColumnAsInt() */
/************************************************************************/
int OGRMDBTable::GetColumnAsInt(int iCol)
{
jobject val = GetColumnVal(iCol);
if (!val) return 0;
int int_val = 0;
if (apoColumnTypes[iCol] == MDB_Boolean)
int_val = env->env->CallBooleanMethod(val, env->boolean_booleanValue);
else if (apoColumnTypes[iCol] == MDB_Byte)
int_val = env->env->CallByteMethod(val, env->byte_byteValue);
else if (apoColumnTypes[iCol] == MDB_Short)
int_val = env->env->CallShortMethod(val, env->short_shortValue);
else if (apoColumnTypes[iCol] == MDB_Int)
int_val = env->env->CallIntMethod(val, env->integer_intValue);
if (env->ExceptionOccurred()) return 0;
env->env->DeleteLocalRef(val);
return int_val;
}
/************************************************************************/
/* GetColumnAsDouble() */
/************************************************************************/
double OGRMDBTable::GetColumnAsDouble(int iCol)
{
jobject val = GetColumnVal(iCol);
if (!val) return 0;
double double_val = 0;
if (apoColumnTypes[iCol] == MDB_Double)
double_val = env->env->CallDoubleMethod(val, env->double_doubleValue);
else if (apoColumnTypes[iCol] == MDB_Float)
double_val = env->env->CallFloatMethod(val, env->float_floatValue);
if (env->ExceptionOccurred()) return 0;
env->env->DeleteLocalRef(val);
return double_val;
}
/************************************************************************/
/* GetColumnAsBinary() */
/************************************************************************/
GByte* OGRMDBTable::GetColumnAsBinary(int iCol, int* pnBytes)
{
*pnBytes = 0;
jobject val = GetColumnVal(iCol);
if (!val) return NULL;
if (!env->env->IsInstanceOf(val, env->byteArray_class))
return NULL;
jbyteArray byteArray = (jbyteArray) val;
*pnBytes = env->env->GetArrayLength(byteArray);
if (env->ExceptionOccurred()) return NULL;
jboolean is_copy;
jbyte* elts = env->env->GetByteArrayElements(byteArray, &is_copy);
if (env->ExceptionOccurred()) return NULL;
GByte* pData = (GByte*)CPLMalloc(*pnBytes);
memcpy(pData, elts, *pnBytes);
env->env->ReleaseByteArrayElements(byteArray, elts, JNI_ABORT);
env->env->DeleteLocalRef(val);
return pData;
}
/************************************************************************/
/* DumpTable() */
/************************************************************************/
void OGRMDBTable::DumpTable()
{
ResetReading();
int iRow = 0;
int nCols = static_cast<int>(apoColumnNames.size());
while(GetNextRow())
{
printf("Row = %d\n", iRow ++);
for(int i=0;i<nCols;i++)
{
printf("%s = ", apoColumnNames[i].c_str());
if (apoColumnTypes[i] == MDB_Float ||
apoColumnTypes[i] == MDB_Double)
{
printf("%.15f\n", GetColumnAsDouble(i));
}
else if (apoColumnTypes[i] == MDB_Boolean ||
apoColumnTypes[i] == MDB_Byte ||
apoColumnTypes[i] == MDB_Short ||
apoColumnTypes[i] == MDB_Int)
{
printf("%d\n", GetColumnAsInt(i));
}
else if (apoColumnTypes[i] == MDB_Binary ||
apoColumnTypes[i] == MDB_OLE)
{
int nBytes;
GByte* pData = GetColumnAsBinary(i, &nBytes);
printf("(%d bytes)\n", nBytes);
CPLFree(pData);
}
else
{
char* val = GetColumnAsString(i);
printf("'%s'\n", val);
CPLFree(val);
}
}
}
}
/************************************************************************/
/* GetColumnIndex() */
/************************************************************************/
int OGRMDBTable::GetColumnIndex(const char* pszColName, int bEmitErrorIfNotFound)
{
int nCols = static_cast<int>(apoColumnNames.size());
CPLString osColName(pszColName);
for(int i=0;i<nCols;i++)
{
if (apoColumnNames[i] == osColName)
return i;
}
if (bEmitErrorIfNotFound)
CPLError(CE_Failure, CPLE_AppDefined, "Cannot find column %s", pszColName);
return -1;
}
/************************************************************************/
/* GetRowCount() */
/************************************************************************/
int OGRMDBTable::GetRowCount()
{
if (env->bCalledFromJava)
env->Init();
int nRowCount = env->env->CallIntMethod(table, env->table_getRowCount);
if (env->ExceptionOccurred()) return 0;
return nRowCount;
}
| 35.066225
| 139
| 0.529443
|
CesiumGS
|
b426a44097f1413183635bbaed32be8276ea14e1
| 18,333
|
cpp
|
C++
|
Test/UnitTests/ThreadSafeTests.cpp
|
Colorfingers/QuantumGate
|
e183e02464859f4ca486999182c4c41221f3261a
|
[
"MIT"
] | 87
|
2018-09-01T05:29:22.000Z
|
2022-03-13T17:44:00.000Z
|
Test/UnitTests/ThreadSafeTests.cpp
|
Colorfingers/QuantumGate
|
e183e02464859f4ca486999182c4c41221f3261a
|
[
"MIT"
] | 6
|
2019-01-30T14:48:17.000Z
|
2022-03-14T21:10:56.000Z
|
Test/UnitTests/ThreadSafeTests.cpp
|
Colorfingers/QuantumGate
|
e183e02464859f4ca486999182c4c41221f3261a
|
[
"MIT"
] | 16
|
2018-11-25T23:09:47.000Z
|
2022-02-01T22:14:11.000Z
|
// This file is part of the QuantumGate project. For copyright and
// licensing information refer to the license file(s) in the project root.
#include "pch.h"
#include "Concurrency\ThreadSafe.h"
#include <thread>
#include <atomic>
#include <condition_variable>
using namespace std::literals;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace QuantumGate::Implementation::Concurrency;
class DummyMutex final
{
public:
constexpr DummyMutex() noexcept {}
DummyMutex(const DummyMutex&) = delete;
DummyMutex(DummyMutex&&) = delete;
~DummyMutex() = default;
DummyMutex& operator=(const DummyMutex&) = delete;
DummyMutex& operator=(DummyMutex&&) = delete;
constexpr void lock() noexcept {}
constexpr bool try_lock() noexcept { return true; }
constexpr void unlock() noexcept {}
constexpr void lock_shared() noexcept {}
constexpr bool try_lock_shared() noexcept { return true; }
constexpr void unlock_shared() noexcept {}
};
bool TestTypeConstFuncOperatorExecuted{ false };
struct TestType
{
constexpr TestType() noexcept {}
constexpr TestType(int v) : Value(v) {}
constexpr TestType(const TestType& other) noexcept : Value(other.Value) {}
constexpr TestType(TestType&& other) noexcept : Value(other.Value) {}
TestType& operator=(const TestType& other) noexcept
{
Value = other.Value;
return *this;
}
TestType& operator=(TestType&& other) noexcept
{
Value = other.Value;
return *this;
}
bool operator==(const TestType& other) const noexcept
{
return (Value == other.Value);
}
void operator()(int v) noexcept { Value = v; }
void operator()(int v) const noexcept { TestTypeConstFuncOperatorExecuted = true; }
int& operator[](int idx) noexcept { return Value; }
const int& operator[](int idx) const noexcept { return Value; }
int Value{ 0 };
};
bool TestTypeMAConstFuncOperatorExecuted{ false };
struct TestTypeMA
{
constexpr TestTypeMA() noexcept {}
constexpr TestTypeMA(int v1, double v2) : Value1(v1), Value2(v2) {}
constexpr TestTypeMA(const TestTypeMA& other) : Value1(other.Value1), Value2(other.Value2) {}
constexpr TestTypeMA(TestTypeMA&& other) : Value1(other.Value1), Value2(other.Value2) {}
TestTypeMA& operator=(const TestTypeMA& other)
{
Value1 = other.Value1;
Value2 = other.Value2;
return *this;
}
TestTypeMA& operator=(TestTypeMA&& other)
{
Value1 = other.Value1;
Value2 = other.Value2;
return *this;
}
bool operator==(const TestTypeMA& other) const noexcept
{
return (Value1 == other.Value1 && Value2 == other.Value2);
}
void operator()(int v) { Value1 = v; }
void operator()(int v) const { TestTypeMAConstFuncOperatorExecuted = true; }
int& operator[](int idx) { return Value1; }
const int& operator[](int idx) const { return Value1; }
int Value1{ 0 };
double Value2{ 0 };
};
auto ExceptLambda = [](auto& val) {};
auto NoexceptLambda = [](auto& val) noexcept {};
namespace UnitTests
{
TEST_CLASS(ThreadSafeTests)
{
public:
TEST_METHOD(Constructors)
{
// Default
{
ThreadSafe<TestType> test;
static_assert(std::is_nothrow_constructible_v<ThreadSafe<TestType>>, "Should be no throw constructible");
Assert::AreEqual(true, test.WithUniqueLock()->Value == 0);
}
// Parameters
{
ThreadSafe<TestType> test(9);
static_assert(!std::is_nothrow_constructible_v<ThreadSafe<TestType>, int>, "Should not be no throw constructible");
Assert::AreEqual(true, test.WithUniqueLock()->Value == 9);
}
{
ThreadSafe<TestTypeMA, DummyMutex> test(15, 20.5);
Assert::AreEqual(true, test.WithUniqueLock()->Value1 == 15);
Assert::AreEqual(true, test.WithUniqueLock()->Value2 == 20.5);
}
// Copy
{
TestType tt;
tt.Value = 999;
ThreadSafe<TestType> test(tt);
static_assert(std::is_nothrow_constructible_v<ThreadSafe<TestType>, TestType>, "Should be no throw constructible");
Assert::AreEqual(true, test.WithUniqueLock()->Value == 999);
TestTypeMA ttma;
ttma.Value1 = 1999;
ttma.Value2 = 2999;
ThreadSafe<TestTypeMA> testma(ttma);
static_assert(!std::is_nothrow_constructible_v<ThreadSafe<TestTypeMA>, TestTypeMA>, "Should not be no throw constructible");
Assert::AreEqual(true, testma.WithUniqueLock()->Value1 == 1999);
Assert::AreEqual(true, testma.WithUniqueLock()->Value2 == 2999);
}
// Move
{
TestType tt;
tt.Value = 333;
ThreadSafe<TestType> test(std::move(tt));
static_assert(std::is_nothrow_constructible_v<ThreadSafe<TestType>, TestType&&>, "Should be no throw constructible");
Assert::AreEqual(true, test.WithUniqueLock()->Value == 333);
TestTypeMA ttma;
ttma.Value1 = 1333;
ttma.Value2 = 2333;
ThreadSafe<TestTypeMA> testma(std::move(ttma));
static_assert(!std::is_nothrow_constructible_v<ThreadSafe<TestTypeMA>, TestTypeMA&&>, "Should not be no throw constructible");
Assert::AreEqual(true, testma.WithUniqueLock()->Value1 == 1333);
Assert::AreEqual(true, testma.WithUniqueLock()->Value2 == 2333);
}
}
TEST_METHOD(UniqueLock)
{
ThreadSafe<TestType> test(111);
std::condition_variable_any th1_cv1, th1_cv2;
std::condition_variable_any th2_cv1, th2_cv2;
std::atomic<int> flag{ 0 };
auto thread1 = std::thread([&]()
{
DummyMutex mtx;
std::unique_lock<DummyMutex> umtx(mtx);
auto tulock = test.WithUniqueLock();
Assert::AreEqual(true, tulock.operator bool());
flag = 1;
th2_cv1.notify_one();
th1_cv1.wait(umtx);
tulock.Unlock();
Assert::AreEqual(false, tulock.operator bool());
Assert::AreEqual(true, test.WithUniqueLock()->Value == 111);
th2_cv2.notify_one();
th1_cv2.wait(umtx);
Assert::AreEqual(true, test.WithUniqueLock()->Value == 666);
// Stage 2 Begin
tulock.Lock();
Assert::AreEqual(true, tulock.operator bool());
tulock->Value = 999;
th2_cv2.notify_one();
std::this_thread::sleep_for(2s);
tulock.Unlock();
Assert::AreEqual(false, tulock.operator bool());
});
auto thread2 = std::thread([&]()
{
DummyMutex mtx;
std::unique_lock<DummyMutex> umtx(mtx);
th2_cv1.wait(umtx, [&]() { return (flag.load() == 1); });
// This should not succeed
test.IfUniqueLock([](auto& value)
{
value.Value = 369;
});
th1_cv1.notify_one();
th2_cv2.wait(umtx);
// This should succeed
test.IfUniqueLock([](auto& value)
{
value.Value = 666;
});
th1_cv2.notify_one();
// Stage 2 Begin
th2_cv2.wait(umtx);
auto curtime = std::chrono::steady_clock::now();
test.WithUniqueLock([](auto& value)
{
Assert::AreEqual(true, value.Value == 999);
value.Value = 339;
});
Assert::AreEqual(true, std::chrono::steady_clock::now() - curtime >= 2s);
Assert::AreEqual(true, test.WithUniqueLock()->Value == 339);
});
thread1.join();
thread2.join();
}
TEST_METHOD(TryWithUniqueLock)
{
ThreadSafe<TestType, std::mutex> test(111);
std::condition_variable_any th1_cv1;
auto thread1 = std::thread([&]()
{
DummyMutex mtx;
std::unique_lock<DummyMutex> umtx(mtx);
auto lock = test.WithUniqueLock();
th1_cv1.wait(umtx);
});
std::this_thread::sleep_for(1s);
auto testlock = test.TryWithUniqueLock();
Assert::AreEqual(false, testlock.operator bool());
th1_cv1.notify_one();
thread1.join();
Assert::AreEqual(true, testlock.TryLock());
Assert::AreEqual(true, testlock.operator bool());
}
TEST_METHOD(SharedLock)
{
ThreadSafe<TestType, std::shared_mutex> test(111);
std::condition_variable_any th1_cv1;
std::condition_variable_any th2_cv1, th2_cv2;
std::atomic<int> flag{ 0 };
auto thread1 = std::thread([&]()
{
DummyMutex mtx;
std::unique_lock<DummyMutex> umtx(mtx);
auto tulock = test.WithSharedLock();
flag = 1;
th2_cv1.notify_one();
th1_cv1.wait(umtx);
Assert::AreEqual(true, tulock.operator bool());
tulock.UnlockShared();
Assert::AreEqual(false, tulock.operator bool());
auto tulock2 = test.WithUniqueLock();
Assert::AreEqual(true, tulock2.operator bool());
th2_cv2.notify_one();
tulock2->Value = 669;
std::this_thread::sleep_for(2s);
tulock2.Reset();
Assert::AreEqual(false, tulock2.operator bool());
});
auto thread2 = std::thread([&]()
{
DummyMutex mtx;
std::unique_lock<DummyMutex> umtx(mtx);
th2_cv1.wait(umtx, [&]() { return (flag.load() == 1); });
auto sflag = false;
// This should succeed
test.IfSharedLock([&](auto& value)
{
sflag = true;
Assert::AreEqual(true, value.Value == 111);
});
Assert::AreEqual(true, sflag);
th1_cv1.notify_one();
th2_cv2.wait(umtx);
auto curtime = std::chrono::steady_clock::now();
// Will block for 2s
test.WithSharedLock([](auto& value)
{
Assert::AreEqual(true, value.Value == 669);
});
Assert::AreEqual(true, std::chrono::steady_clock::now() - curtime >= 2s);
});
thread1.join();
thread2.join();
}
TEST_METHOD(TryWithSharedLock)
{
ThreadSafe<TestType, std::shared_mutex> test(111);
std::condition_variable_any th1_cv1;
auto thread1 = std::thread([&]()
{
DummyMutex mtx;
std::unique_lock<DummyMutex> umtx(mtx);
auto lock = test.WithUniqueLock();
th1_cv1.wait(umtx);
});
std::this_thread::sleep_for(1s);
auto testlock = test.TryWithSharedLock();
Assert::AreEqual(false, testlock.operator bool());
th1_cv1.notify_one();
thread1.join();
Assert::AreEqual(true, testlock.TryLockShared());
Assert::AreEqual(true, testlock.operator bool());
}
TEST_METHOD(UniqueMethodsExceptionCheck)
{
{
ThreadSafe<TestType, DummyMutex> test(9);
Assert::AreEqual(true, test.WithUniqueLock()->Value == 9);
static_assert(!noexcept(test.WithUniqueLock()), "Should not be noexcept");
static_assert(!noexcept(test.WithUniqueLock(NoexceptLambda)), "Should not be noexcept");
static_assert(!noexcept(test.WithUniqueLock(ExceptLambda)), "Should not be noexcept");
static_assert(noexcept(test.IfUniqueLock(NoexceptLambda)), "Should be noexcept");
static_assert(!noexcept(test.IfUniqueLock(ExceptLambda)), "Should not be noexcept");
static_assert(!noexcept(test.TryWithUniqueLock()), "Should not be noexcept");
}
{
const ThreadSafe<TestType, DummyMutex> test(9);
Assert::AreEqual(true, test.WithUniqueLock()->Value == 9);
static_assert(!noexcept(test.WithUniqueLock()), "Should not be noexcept");
static_assert(!noexcept(test.WithUniqueLock(NoexceptLambda)), "Should not be noexcept");
static_assert(!noexcept(test.WithUniqueLock(ExceptLambda)), "Should not be noexcept");
static_assert(noexcept(test.IfUniqueLock(NoexceptLambda)), "Should be noexcept");
static_assert(!noexcept(test.IfUniqueLock(ExceptLambda)), "Should not be noexcept");
static_assert(!noexcept(test.TryWithUniqueLock()), "Should not be noexcept");
}
}
TEST_METHOD(SharedMethodsExceptionCheck)
{
{
ThreadSafe<TestType, DummyMutex> test(9);
Assert::AreEqual(true, test.WithSharedLock()->Value == 9);
static_assert(!noexcept(test.WithSharedLock()), "Should not be noexcept");
static_assert(!noexcept(test.WithSharedLock(NoexceptLambda)), "Should not be noexcept");
static_assert(!noexcept(test.WithSharedLock(ExceptLambda)), "Should not be noexcept");
static_assert(noexcept(test.IfSharedLock(NoexceptLambda)), "Should be noexcept");
static_assert(!noexcept(test.IfSharedLock(ExceptLambda)), "Should not be noexcept");
ThreadSafe<TestType, std::shared_mutex> test2(9);
static_assert(noexcept(test2.IfSharedLock(NoexceptLambda)), "Should be noexcept");
static_assert(!noexcept(test2.TryWithSharedLock()), "Should not be noexcept");
}
{
const ThreadSafe<TestType, DummyMutex> test(9);
Assert::AreEqual(true, test.WithSharedLock()->Value == 9);
static_assert(!noexcept(test.WithSharedLock()), "Should not be noexcept");
static_assert(!noexcept(test.WithSharedLock(NoexceptLambda)), "Should not be noexcept");
static_assert(!noexcept(test.WithSharedLock(ExceptLambda)), "Should not be noexcept");
static_assert(noexcept(test.IfSharedLock(NoexceptLambda)), "Should be noexcept");
static_assert(!noexcept(test.IfSharedLock(ExceptLambda)), "Should not be noexcept");
const ThreadSafe<TestType, std::shared_mutex> test2(9);
static_assert(noexcept(test2.IfSharedLock(NoexceptLambda)), "Should be noexcept");
static_assert(!noexcept(test2.TryWithSharedLock()), "Should not be noexcept");
}
}
TEST_METHOD(Constexpr)
{
constexpr ThreadSafe<TestType, DummyMutex> test;
constexpr ThreadSafe<TestType, DummyMutex> test2(5);
Assert::AreEqual(true, test2.WithUniqueLock()->Value == 5);
constexpr ThreadSafe<TestTypeMA, DummyMutex> test3(15, 20.5);
Assert::AreEqual(true, test3.WithUniqueLock()->Value1 == 15);
Assert::AreEqual(true, test3.WithUniqueLock()->Value2 == 20.5);
}
TEST_METHOD(Value)
{
ThreadSafe<TestType, std::shared_mutex> test(111);
ThreadSafe<TestType, std::shared_mutex>::UniqueLockedType testul;
Assert::AreEqual(false, testul.operator bool());
testul = test.WithUniqueLock();
Assert::AreEqual(true, testul.operator bool());
const ThreadSafe<TestType, std::shared_mutex> ctest(111);
ThreadSafe<TestType, std::shared_mutex>::UniqueLockedConstType ctestul;
Assert::AreEqual(false, ctestul.operator bool());
ctestul = ctest.WithUniqueLock();
Assert::AreEqual(true, ctestul.operator bool());
ThreadSafe<TestTypeMA, std::shared_mutex> testma(999, 333);
const ThreadSafe<TestTypeMA, std::shared_mutex> ctestma(999, 333);
auto testmaul = testma.WithUniqueLock();
auto ctestmaul = ctestma.WithUniqueLock();
// operator()
{
{
static_assert(noexcept(testul(333)), "Should be noexcept");
testul(333);
Assert::AreEqual(true, testul->Value == 333);
static_assert(noexcept(ctestul(333)), "Should be noexcept");
ctestul(0);
Assert::AreEqual(true, TestTypeConstFuncOperatorExecuted);
}
{
static_assert(!noexcept(testmaul(666)), "Should not be noexcept");
testmaul(666);
Assert::AreEqual(true, testmaul->Value1 == 666);
static_assert(!noexcept(ctestmaul(666)), "Should not be noexcept");
ctestmaul(0);
Assert::AreEqual(true, TestTypeMAConstFuncOperatorExecuted);
}
}
// operator[]
{
{
static_assert(noexcept(testul[1]), "Should be noexcept");
Assert::AreEqual(true, testul[1] == 333);
static_assert(!std::is_const_v<std::remove_reference_t<decltype(testul[1])>>, "Return value should not be const");
static_assert(noexcept(ctestul[1]), "Should be noexcept");
static_assert(std::is_const_v<std::remove_reference_t<decltype(ctestul[1])>>, "Return value should be const");
}
{
static_assert(!noexcept(testmaul[1]), "Should not be noexcept");
Assert::AreEqual(true, testmaul[1] == 666);
static_assert(!std::is_const_v<std::remove_reference_t<decltype(testmaul[1])>>, "Return value should not be const");
static_assert(!noexcept(ctestmaul[1]), "Should not be noexcept");
static_assert(std::is_const_v<std::remove_reference_t<decltype(ctestmaul[1])>>, "Return value should be const");
}
}
// Copy assignment and comparison
{
TestType atest;
atest.Value = 336699;
Assert::AreEqual(true, testul != atest);
static_assert(noexcept(testul.operator=(atest)), "Should be no throw copy assignable");
testul = atest;
Assert::AreEqual(true, testul->Value == 336699);
Assert::AreEqual(true, testul == atest);
TestTypeMA atestma;
atestma.Value1 = 336699;
Assert::AreEqual(true, testmaul != atestma);
static_assert(!noexcept(testmaul.operator=(atestma)), "Should not be no throw copy assignable");
testmaul = atestma;
Assert::AreEqual(true, testmaul->Value1 == 336699);
Assert::AreEqual(true, testmaul == atestma);
}
// Move assignment
{
TestType atest;
atest.Value = 669933;
static_assert(noexcept(testul.operator=(std::move(atest))), "Should be no throw move assignable");
testul = std::move(atest);
Assert::AreEqual(true, testul->Value == 669933);
TestTypeMA atestma;
atestma.Value1 = 669933;
static_assert(!noexcept(testmaul.operator=(std::move(atestma))), "Should not be no throw move assignable");
testmaul = std::move(atestma);
Assert::AreEqual(true, testmaul->Value1 == 669933);
}
testul.Reset();
Assert::AreEqual(false, testul.operator bool());
ctestul.Reset();
Assert::AreEqual(false, ctestul.operator bool());
}
TEST_METHOD(ValueWhileUnlockedUnique)
{
ThreadSafe<TestType, std::shared_mutex> test(111);
auto value = test.WithUniqueLock();
std::atomic_bool flag{ false };
auto thread1 = std::thread([&]()
{
DummyMutex mtx;
std::unique_lock<DummyMutex> umtx(mtx);
auto lock = test.WithUniqueLock();
flag = true;
});
std::this_thread::sleep_for(1s);
Assert::AreEqual(false, flag.load());
value.WhileUnlocked([&]()
{
Assert::AreEqual(false, value.operator bool());
std::this_thread::sleep_for(1s);
Assert::AreEqual(true, flag.load());
});
Assert::AreEqual(true, value.operator bool());
thread1.join();
}
TEST_METHOD(ValueWhileUnlockedShared)
{
ThreadSafe<TestType, std::shared_mutex> test(111);
auto value = test.WithSharedLock();
std::atomic_bool flag{ false };
auto thread1 = std::thread([&]()
{
DummyMutex mtx;
std::unique_lock<DummyMutex> umtx(mtx);
auto lock = test.WithUniqueLock();
flag = true;
});
std::this_thread::sleep_for(1s);
Assert::AreEqual(false, flag.load());
value.WhileUnlockedShared([&]()
{
Assert::AreEqual(false, value.operator bool());
std::this_thread::sleep_for(1s);
Assert::AreEqual(true, flag.load());
});
Assert::AreEqual(true, value.operator bool());
thread1.join();
}
TEST_METHOD(ShouldNotCompile)
{
ThreadSafe<TestType, std::shared_mutex> test(111);
// Following line should fail to compile because constructor
// is disabled for same type
//ThreadSafe<TestType, std::shared_mutex> test2(test);
}
};
}
| 28.248074
| 130
| 0.680903
|
Colorfingers
|
b4281155493026c32652ab3fdd5f09123e6f3054
| 295
|
cpp
|
C++
|
2019Homeworks/20191019_2018MidTerm/2.GroupPhoto.cpp
|
Guyutongxue/Introduction_to_Computation
|
062f688fe3ffb8e29cfaf139223e4994edbf64d6
|
[
"WTFPL"
] | 8
|
2019-10-09T14:33:42.000Z
|
2020-12-03T00:49:29.000Z
|
2019Homeworks/20191019_2018MidTerm/2.GroupPhoto.cpp
|
Guyutongxue/Introduction_to_Computation
|
062f688fe3ffb8e29cfaf139223e4994edbf64d6
|
[
"WTFPL"
] | null | null | null |
2019Homeworks/20191019_2018MidTerm/2.GroupPhoto.cpp
|
Guyutongxue/Introduction_to_Computation
|
062f688fe3ffb8e29cfaf139223e4994edbf64d6
|
[
"WTFPL"
] | null | null | null |
#include<iostream>
#include<algorithm>
using namespace std;
int a[102];
int main(){
while(true){
int n;
cin>>n;
if(n==0)break;
for(int i=1;i<=n;i++){
cin>>a[i];
}
sort(a+1,a+n+1);
cout<<a[n/2+1]<<endl;
}
return 0;
}
| 17.352941
| 30
| 0.447458
|
Guyutongxue
|
b42f35f91004d9c68fe896a91e86c85c7afb9590
| 13,404
|
cpp
|
C++
|
test/binary.cpp
|
ckeitz/arrayfire
|
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
|
[
"BSD-3-Clause"
] | 4
|
2015-12-16T09:41:32.000Z
|
2018-10-29T10:38:53.000Z
|
test/binary.cpp
|
ckeitz/arrayfire
|
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
|
[
"BSD-3-Clause"
] | 3
|
2015-11-15T18:43:47.000Z
|
2015-12-16T09:43:14.000Z
|
test/binary.cpp
|
pavanky/arrayfire
|
f983a79c7d402450bd2a704bbc1015b89f0cd504
|
[
"BSD-3-Clause"
] | null | null | null |
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <af/array.h>
#include <af/arith.h>
#include <af/data.h>
#include <testHelpers.hpp>
using namespace std;
using namespace af;
const int num = 10000;
#define add(left, right) (left) + (right)
#define sub(left, right) (left) - (right)
#define mul(left, right) (left) * (right)
#define div(left, right) (left) / (right)
template<typename T> T mod(T a, T b)
{
return std::fmod(a, b);
}
af::array randgen(const int num, af::dtype ty)
{
af::array tmp = af::round(1 + 2 * af::randu(num, f32)).as(ty);
tmp.eval();
return tmp;
}
#define BINARY_TESTS(Ta, Tb, Tc, func) \
TEST(BinaryTests, Test_##func##_##Ta##_##Tb) \
{ \
if (noDoubleTests<Ta>()) return; \
if (noDoubleTests<Tb>()) return; \
if (noDoubleTests<Tc>()) return; \
\
af_dtype ta = (af_dtype)dtype_traits<Ta>::af_type; \
af_dtype tb = (af_dtype)dtype_traits<Tb>::af_type; \
af::array a = randgen(num, ta); \
af::array b = randgen(num, tb); \
af::array c = func(a, b); \
Ta *h_a = a.host<Ta>(); \
Tb *h_b = b.host<Tb>(); \
Tc *h_c = c.host<Tc>(); \
for (int i = 0; i < num; i++) \
ASSERT_EQ(h_c[i], func(h_a[i], h_b[i])) << \
"for values: " << h_a[i] << "," << h_b[i] << std::endl; \
delete[] h_a; \
delete[] h_b; \
delete[] h_c; \
} \
\
TEST(BinaryTests, Test_##func##_##Ta##_##Tb##_left) \
{ \
if (noDoubleTests<Ta>()) return; \
if (noDoubleTests<Tb>()) return; \
\
af_dtype ta = (af_dtype)dtype_traits<Ta>::af_type; \
af::array a = randgen(num, ta); \
Tb h_b = 3.0; \
af::array c = func(a, h_b); \
Ta *h_a = a.host<Ta>(); \
Ta *h_c = c.host<Ta>(); \
for (int i = 0; i < num; i++) \
ASSERT_EQ(h_c[i], func(h_a[i], h_b)) << \
"for values: " << h_a[i] << "," << h_b << std::endl; \
delete[] h_a; \
delete[] h_c; \
} \
\
TEST(BinaryTests, Test_##func##_##Ta##_##Tb##_right) \
{ \
if (noDoubleTests<Ta>()) return; \
if (noDoubleTests<Tb>()) return; \
\
af_dtype tb = (af_dtype)dtype_traits<Tb>::af_type; \
Ta h_a = 5.0; \
af::array b = randgen(num, tb); \
af::array c = func(h_a, b); \
Tb *h_b = b.host<Tb>(); \
Tb *h_c = c.host<Tb>(); \
for (int i = 0; i < num; i++) \
ASSERT_EQ(h_c[i], func(h_a, h_b[i])) << \
"for values: " << h_a << "," << h_b[i] << std::endl; \
delete[] h_b; \
delete[] h_c; \
} \
#define BINARY_TESTS_NEAR(Ta, Tb, Tc, func, err) \
TEST(BinaryTests, Test_##func##_##Ta##_##Tb) \
{ \
if (noDoubleTests<Ta>()) return; \
if (noDoubleTests<Tb>()) return; \
if (noDoubleTests<Tc>()) return; \
\
af_dtype ta = (af_dtype)dtype_traits<Ta>::af_type; \
af_dtype tb = (af_dtype)dtype_traits<Tb>::af_type; \
af::array a = randgen(num, ta); \
af::array b = randgen(num, tb); \
af::array c = func(a, b); \
Ta *h_a = a.host<Ta>(); \
Tb *h_b = b.host<Tb>(); \
Tc *h_c = c.host<Tc>(); \
for (int i = 0; i < num; i++) \
ASSERT_NEAR(h_c[i], func(h_a[i], h_b[i]), err) << \
"for values: " << h_a[i] << "," << h_b[i] << std::endl; \
delete[] h_a; \
delete[] h_b; \
delete[] h_c; \
} \
\
TEST(BinaryTests, Test_##func##_##Ta##_##Tb##_left) \
{ \
if (noDoubleTests<Ta>()) return; \
if (noDoubleTests<Tb>()) return; \
\
af_dtype ta = (af_dtype)dtype_traits<Ta>::af_type; \
af::array a = randgen(num, ta); \
Tb h_b = 0.3; \
af::array c = func(a, h_b); \
Ta *h_a = a.host<Ta>(); \
Ta *h_c = c.host<Ta>(); \
for (int i = 0; i < num; i++) \
ASSERT_NEAR(h_c[i], func(h_a[i], h_b), err) << \
"for values: " << h_a[i] << "," << h_b << std::endl; \
delete[] h_a; \
delete[] h_c; \
} \
\
TEST(BinaryTests, Test_##func##_##Ta##_##Tb##_right) \
{ \
if (noDoubleTests<Ta>()) return; \
if (noDoubleTests<Tb>()) return; \
if (noDoubleTests<Tc>()) return; \
\
af_dtype tb = (af_dtype)dtype_traits<Tb>::af_type; \
Ta h_a = 0.3; \
af::array b = randgen(num, tb); \
af::array c = func(h_a, b); \
Tb *h_b = b.host<Tb>(); \
Tb *h_c = c.host<Tb>(); \
for (int i = 0; i < num; i++) \
ASSERT_NEAR(h_c[i], func(h_a, h_b[i]), err) << \
"for values: " << h_a << "," << h_b[i] << std::endl; \
delete[] h_b; \
delete[] h_c; \
} \
#define BINARY_TESTS_FLOAT(func) BINARY_TESTS(float, float, float, func)
#define BINARY_TESTS_DOUBLE(func) BINARY_TESTS(double, double, double, func)
#define BINARY_TESTS_CFLOAT(func) BINARY_TESTS(cfloat, cfloat, cfloat, func)
#define BINARY_TESTS_CDOUBLE(func) BINARY_TESTS(cdouble, cdouble, cdouble, func)
#define BINARY_TESTS_INT(func) BINARY_TESTS(int, int, int, func)
#define BINARY_TESTS_UINT(func) BINARY_TESTS(uint, uint, uint, func)
#define BINARY_TESTS_INTL(func) BINARY_TESTS(intl, intl, intl, func)
#define BINARY_TESTS_UINTL(func) BINARY_TESTS(uintl, uintl, uintl, func)
#define BINARY_TESTS_NEAR_FLOAT(func) BINARY_TESTS_NEAR(float, float, float, func, 1e-5)
#define BINARY_TESTS_NEAR_DOUBLE(func) BINARY_TESTS_NEAR(double, double, double, func, 1e-10)
BINARY_TESTS_FLOAT(add)
BINARY_TESTS_FLOAT(sub)
BINARY_TESTS_FLOAT(mul)
BINARY_TESTS_NEAR(float, float, float, div, 1e-3) // FIXME
BINARY_TESTS_FLOAT(min)
BINARY_TESTS_FLOAT(max)
BINARY_TESTS_NEAR(float, float, float, mod, 1e-5) // FIXME
BINARY_TESTS_DOUBLE(add)
BINARY_TESTS_DOUBLE(sub)
BINARY_TESTS_DOUBLE(mul)
BINARY_TESTS_DOUBLE(div)
BINARY_TESTS_DOUBLE(min)
BINARY_TESTS_DOUBLE(max)
BINARY_TESTS_DOUBLE(mod)
BINARY_TESTS_NEAR_FLOAT(atan2)
BINARY_TESTS_NEAR_FLOAT(pow)
BINARY_TESTS_NEAR_FLOAT(hypot)
BINARY_TESTS_NEAR_DOUBLE(atan2)
BINARY_TESTS_NEAR_DOUBLE(pow)
BINARY_TESTS_NEAR_DOUBLE(hypot)
BINARY_TESTS_INT(add)
BINARY_TESTS_INT(sub)
BINARY_TESTS_INT(mul)
BINARY_TESTS_UINT(add)
BINARY_TESTS_UINT(sub)
BINARY_TESTS_UINT(mul)
BINARY_TESTS_INTL(add)
BINARY_TESTS_INTL(sub)
BINARY_TESTS_INTL(mul)
BINARY_TESTS_UINTL(add)
BINARY_TESTS_UINTL(sub)
BINARY_TESTS_UINTL(mul)
BINARY_TESTS_CFLOAT(add)
BINARY_TESTS_CFLOAT(sub)
BINARY_TESTS_CDOUBLE(add)
BINARY_TESTS_CDOUBLE(sub)
// Mixed types
BINARY_TESTS_NEAR(float, double, double, add, 1e-5)
BINARY_TESTS_NEAR(float, double, double, sub, 1e-5)
BINARY_TESTS_NEAR(float, double, double, mul, 1e-5)
BINARY_TESTS_NEAR(float, double, double, div, 1e-5)
#define BITOP(func, T, op) \
TEST(BinaryTests, Test_##func##_##T) \
{ \
af_dtype ty = (af_dtype)dtype_traits<T>::af_type; \
const T vala = 4095; \
const T valb = 3; \
const T valc = vala op valb; \
const int num = 10; \
af::array a = af::constant(vala, num, ty); \
af::array b = af::constant(valb, num, ty); \
af::array c = a op b; \
T *h_a = a.host<T>(); \
T *h_b = b.host<T>(); \
T *h_c = c.host<T>(); \
for (int i = 0; i < num; i++) \
ASSERT_EQ(h_c[i], valc) << \
"for values: " << h_a[i] << \
"," << h_b[i] << std::endl; \
delete[] h_a; \
delete[] h_b; \
delete[] h_c; \
} \
BITOP(bitor, int, |)
BITOP(bitand, int, &)
BITOP(bitxor, int, ^)
BITOP(bitshiftl, int, <<)
BITOP(bitshiftr, int, >>)
BITOP(bitor, uint, |)
BITOP(bitand, uint, &)
BITOP(bitxor, uint, ^)
BITOP(bitshiftl, uint, <<)
BITOP(bitshiftr, uint, >>)
BITOP(bitor, intl, |)
BITOP(bitand, intl, &)
BITOP(bitxor, intl, ^)
BITOP(bitshiftl, intl, <<)
BITOP(bitshiftr, intl, >>)
BITOP(bitor, uintl, |)
BITOP(bitand, uintl, &)
BITOP(bitxor, uintl, ^)
BITOP(bitshiftl, uintl, <<)
BITOP(bitshiftr, uintl, >>)
| 50.202247
| 93
| 0.348478
|
ckeitz
|
b43261efe5427bd3076949005633fdf41c001c09
| 988
|
hpp
|
C++
|
lib/enhance/iterator_utility.hpp
|
simonraschke/vesicle2
|
14aa0b2c7a7f587a861c67ba736e2047faecc0e0
|
[
"Apache-2.0"
] | 1
|
2019-03-15T15:27:28.000Z
|
2019-03-15T15:27:28.000Z
|
lib/enhance/iterator_utility.hpp
|
simonraschke/vesicle2
|
14aa0b2c7a7f587a861c67ba736e2047faecc0e0
|
[
"Apache-2.0"
] | null | null | null |
lib/enhance/iterator_utility.hpp
|
simonraschke/vesicle2
|
14aa0b2c7a7f587a861c67ba736e2047faecc0e0
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2019 Simon Raschke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
namespace enhance
{
template<typename InputIt, typename UnaryFunction>
UnaryFunction for_each_from(InputIt first, InputIt last, InputIt firstNEW, UnaryFunction f)
{
InputIt from_firstNEW = firstNEW;
for (; firstNEW != last; ++firstNEW) f(*firstNEW);
for (; first != from_firstNEW; ++first) f(*first);
return f;
}
}
| 32.933333
| 95
| 0.696356
|
simonraschke
|
b4351c596c7ca51a9fc78c7cf2468538eaaf6ad4
| 2,648
|
cpp
|
C++
|
ext/libgecode3/vendor/gecode-3.7.3/test/int/basic.cpp
|
skottler/dep-selector-libgecode
|
d6be8b2a3fe7eed74e287e3e208659212dfc4b1d
|
[
"Apache-2.0"
] | 8
|
2015-02-02T19:45:57.000Z
|
2021-11-27T17:54:56.000Z
|
ext/libgecode3/vendor/gecode-3.7.3/test/int/basic.cpp
|
skottler/dep-selector-libgecode
|
d6be8b2a3fe7eed74e287e3e208659212dfc4b1d
|
[
"Apache-2.0"
] | 28
|
2015-01-26T16:17:42.000Z
|
2021-06-25T15:31:09.000Z
|
ext/libgecode3/vendor/gecode-3.7.3/test/int/basic.cpp
|
skottler/dep-selector-libgecode
|
d6be8b2a3fe7eed74e287e3e208659212dfc4b1d
|
[
"Apache-2.0"
] | 14
|
2015-03-27T23:01:40.000Z
|
2022-03-26T11:21:49.000Z
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2005
*
* Last modified:
* $Date: 2010-04-08 20:35:31 +1000 (Thu, 08 Apr 2010) $ by $Author: schulte $
* $Revision: 10684 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "test/int.hh"
namespace Test { namespace Int {
/// %Tests for basic setup
namespace Basic {
/**
* \defgroup TaskTestIntBasic Basic setup
* \ingroup TaskTestInt
*/
//@{
/// %Test whether testing infrastructure for integer variables works
class Basic : public Test {
public:
/// Initialize test
Basic(int n)
: Test("Basic",3,-n,n,true) {}
/// Initialize test
Basic(Gecode::IntArgs& i)
: Test("Basic",3,Gecode::IntSet(i),true) {}
/// Check whether \a x is a solution
virtual bool solution(const Assignment&) const {
return true;
}
/// Post constraint on \a x
virtual void post(Gecode::Space&, Gecode::IntVarArray&) {
}
/// Post reified constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray&,
Gecode::BoolVar b) {
Gecode::rel(home, b, Gecode::IRT_EQ, 1);
}
};
Gecode::IntArgs i(4, 1,2,3,4);
Basic b1(3);
Basic b2(i);
//@}
}
}}
// STATISTICS: test-int
| 31.903614
| 82
| 0.63935
|
skottler
|
b4384f2f7e3a6a979ab45443a1a339e5911ebc71
| 701
|
hpp
|
C++
|
src/feata-gui/gui/wgt/basewidget.hpp
|
master-clown/ofeata
|
306cbc3a402551fb62b3925d23a2d4f63f60d525
|
[
"MIT"
] | 1
|
2021-08-30T13:51:42.000Z
|
2021-08-30T13:51:42.000Z
|
src/feata-gui/gui/wgt/basewidget.hpp
|
master-clown/ofeata
|
306cbc3a402551fb62b3925d23a2d4f63f60d525
|
[
"MIT"
] | null | null | null |
src/feata-gui/gui/wgt/basewidget.hpp
|
master-clown/ofeata
|
306cbc3a402551fb62b3925d23a2d4f63f60d525
|
[
"MIT"
] | 1
|
2021-08-30T13:51:35.000Z
|
2021-08-30T13:51:35.000Z
|
#pragma once
#include <QFrame>
namespace plug { struct PluginSettingValue; }
namespace gui::wgt
{
class BaseWidget
: public QFrame
{
public:
BaseWidget(QWidget* parent = nullptr);
virtual bool Init(const plug::PluginSettingValue& val) = 0;
/**
* Assumed the method will have to update only 'val.Value' field
*/
virtual bool ToPlugSettValue(plug::PluginSettingValue& val) const = 0;
virtual bool IsValid() const = 0;
static void DestroyLayout(QLayout* lout);
signals:
void BecameDirty();
private:
using Base = QFrame;
Q_OBJECT
};
}
| 20.028571
| 79
| 0.570613
|
master-clown
|
b440984398fda7f6f76e495381f0d08ef94be3e6
| 32,432
|
cc
|
C++
|
src/bgp/test/routepath_replicator_random_test.cc
|
awesome-sdx/contrail-controller
|
ff328a928a32ea755dab0b9c9e25ab9b1a6b6267
|
[
"Apache-2.0"
] | null | null | null |
src/bgp/test/routepath_replicator_random_test.cc
|
awesome-sdx/contrail-controller
|
ff328a928a32ea755dab0b9c9e25ab9b1a6b6267
|
[
"Apache-2.0"
] | null | null | null |
src/bgp/test/routepath_replicator_random_test.cc
|
awesome-sdx/contrail-controller
|
ff328a928a32ea755dab0b9c9e25ab9b1a6b6267
|
[
"Apache-2.0"
] | 1
|
2021-03-09T10:44:33.000Z
|
2021-03-09T10:44:33.000Z
|
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "bgp/routing-instance/routepath_replicator.h"
#include <algorithm>
#include <iostream>
#include <sstream>
#include <set>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#include <boost/lambda/lambda.hpp>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include <boost/program_options.hpp>
#include "base/test/task_test_util.h"
#include "bgp/bgp_config_ifmap.h"
#include "bgp/bgp_factory.h"
#include "bgp/bgp_log.h"
#include "bgp/bgp_server.h"
#include "bgp/inet/inet_table.h"
#include "bgp/l3vpn/inetvpn_table.h"
#include "bgp/routing-instance/routing_instance.h"
#include "bgp/routing-instance/rtarget_group_mgr.h"
#include "bgp/test/bgp_test_util.h"
#include "control-node/control_node.h"
#include "db/db_graph.h"
#include "db/test/db_test_util.h"
#include "ifmap/ifmap_link_table.h"
#include "ifmap/ifmap_server_parser.h"
#include "ifmap/test/ifmap_test_util.h"
#include "schema/bgp_schema_types.h"
#include "schema/vnc_cfg_types.h"
using namespace std;
using boost::assign::list_of;
using boost::assign::map_list_of;
using namespace boost::program_options;
using ::testing::TestWithParam;
using ::testing::ValuesIn;
using ::testing::Combine;
static char **gargv;
static int gargc;
typedef std::tr1::tuple<int, int, int> TestParams;
class BgpPeerMock : public IPeer {
public:
BgpPeerMock(const Ip4Address &address) : address_(address) { }
virtual ~BgpPeerMock() { }
virtual std::string ToString() const {
return address_.to_string();
}
virtual std::string ToUVEKey() const {
return address_.to_string();
}
virtual bool SendUpdate(const uint8_t *msg, size_t msgsize) {
return true;
}
virtual BgpServer *server() {
return NULL;
}
virtual IPeerClose *peer_close() {
return NULL;
}
virtual IPeerDebugStats *peer_stats() {
return NULL;
}
virtual const IPeerDebugStats *peer_stats() const {
return NULL;
}
virtual bool IsReady() const {
return true;
}
virtual bool IsXmppPeer() const { return false; }
virtual void Close(bool non_graceful) { }
BgpProto::BgpPeerType PeerType() const {
return BgpProto::IBGP;
}
virtual uint32_t bgp_identifier() const {
return htonl(address_.to_ulong());
}
virtual const std::string GetStateName() const {
return "";
}
virtual void UpdateRefCount(int count) const { }
virtual tbb::atomic<int> GetRefCount() const {
tbb::atomic<int> count;
count = 0;
return count;
}
virtual void UpdatePrimaryPathCount(int count) const { }
virtual int GetPrimaryPathCount() const { return 0; }
private:
Ip4Address address_;
};
#define VERIFY_EQ(expected, actual) \
TASK_UTIL_EXPECT_EQ(expected, actual)
class ReplicationTest : public ::testing::TestWithParam<TestParams> {
public:
// .second == "vpn" for VPN table
typedef std::map<string, string> RouteAddMap;
typedef std::vector<string> VrfList;
typedef std::multimap<string, string> ConnectionMap;
protected:
ReplicationTest()
: bgp_server_(new BgpServer(&evm_)) {
min_vrf_ = 32;
IFMapLinkTable_Init(&config_db_, &config_graph_);
vnc_cfg_Server_ModuleInit(&config_db_, &config_graph_);
bgp_schema_Server_ModuleInit(&config_db_, &config_graph_);
}
~ReplicationTest() {
STLDeleteValues(&peers_);
}
virtual void SetUp() {
InitParams();
IFMapServerParser *parser = IFMapServerParser::GetInstance("schema");
vnc_cfg_ParserInit(parser);
bgp_schema_ParserInit(parser);
BgpIfmapConfigManager *config_manager =
static_cast<BgpIfmapConfigManager *>(
bgp_server_->config_manager());
config_manager->Initialize(&config_db_, &config_graph_, "localhost");
bgp_server_->rtarget_group_mgr()->Initialize();
}
virtual void TearDown() {
task_util::WaitForIdle();
bgp_server_->Shutdown();
task_util::WaitForIdle();
TASK_UTIL_EXPECT_EQ_MSG(0, bgp_server_->routing_instance_mgr()->count(),
"Waiting for all routing-instances' deletion");
task_util::WaitForIdle();
db_util::Clear(&config_db_);
task_util::WaitForIdle();
IFMapServerParser *parser = IFMapServerParser::GetInstance("schema");
parser->MetadataClear("schema");
task_util::WaitForIdle();
}
void InitParams() {
max_vrf_ = std::tr1::get<0>(GetParam());
max_num_connections_ = std::tr1::get<1>(GetParam());
max_iterations_ = std::tr1::get<2>(GetParam());
}
void NetworkConfig(const VrfList &instance_names,
const ConnectionMap &connections) {
string netconf(
bgp_util::NetworkConfigGenerate(instance_names, connections));
IFMapServerParser *parser =
IFMapServerParser::GetInstance("schema");
parser->Receive(&config_db_, netconf.data(), netconf.length(), 0);
}
void DeleteRoutingInstance(string name, bool wait = true) {
BGP_DEBUG_UT("DELETE routing instance " << name);
// Remove All connections
for(ConnectionMap::iterator it = connections_.find(name);
((it != connections_.end()) && (it->first == name)); it++) {
RemoveConnection(name, it->second);
}
connections_.erase(name);
// Remove All connections to this VRF
for(ConnectionMap::iterator it = connections_.begin(), next;
it != connections_.end(); it = next) {
next = it;
next++;
if (it->second == name) {
RemoveConnection(it->first, name);
connections_.erase(it);
}
}
// Delete Route
for(RouteAddMap::iterator it = routes_added_.begin(), next;
it != routes_added_.end(); it = next) {
next = it;
next++;
if (it->second == name) {
DeleteInetRoute(peers_[0], it->second, it->first);
routes_added_.erase(it);
}
}
TASK_UTIL_EXPECT_NE(static_cast<RoutingInstance *>(NULL),
bgp_server_->routing_instance_mgr()->GetRoutingInstance(name));
RoutingInstance *rti =
bgp_server_->routing_instance_mgr()->GetRoutingInstance(name);
//
// Cache a copy of the export route-targets before the instance is
// deleted
//
const RoutingInstance::RouteTargetList
target_list(rti->GetExportList());
BOOST_FOREACH(RouteTarget tgt, target_list) {
ifmap_test_util::IFMapMsgUnlink(&config_db_,
"routing-instance", name,
"route-target", tgt.ToString(),
"instance-target");
}
for(VrfList::iterator it = vrfs_.begin(); it != vrfs_.end(); it++) {
if (*it == name) {
*it = string("DELETED");
break;
}
}
if (wait) task_util::WaitForIdle();
}
void AddRoutingInstance(string name, bool wait = true) {
TASK_UTIL_EXPECT_EQ(static_cast<RoutingInstance *>(NULL),
bgp_server_->routing_instance_mgr()->GetRoutingInstance(name));
stringstream target;
target << "target:64496:" << (vrfs_.size()+1);
BGP_DEBUG_UT("ADD routing instance " << name << " Route Target "
<< target.str());
ifmap_test_util::IFMapMsgLink(&config_db_,
"routing-instance", name,
"route-target", target.str(),
"instance-target");
vrfs_.push_back(name);
if (wait) task_util::WaitForIdle();
TASK_UTIL_EXPECT_NE(static_cast<RoutingInstance *>(NULL),
bgp_server_->routing_instance_mgr()->GetRoutingInstance(name));
}
void RemoveConnection(string src, string tgt, bool wait = true) {
BGP_DEBUG_UT("DELETE connection " << src << "<->" << tgt);
ifmap_test_util::IFMapMsgUnlink(&config_db_,
"routing-instance", src,
"routing-instance", tgt,
"connection");
if (wait) task_util::WaitForIdle();
}
void AddConnection(string src, string tgt, bool wait = true) {
BGP_DEBUG_UT("ADD connection " << src << "<->" << tgt);
ifmap_test_util::IFMapMsgLink(&config_db_,
"routing-instance", src,
"routing-instance", tgt,
"connection");
connections_.insert(std::pair<string, string>(src, tgt));
if (wait) task_util::WaitForIdle();
}
void AddInetRoute(IPeer *peer, const string &vrf,
const string &prefix, int localpref, bool wait = true) {
BGP_DEBUG_UT("ADD inet route " << vrf << ":" << prefix);
boost::system::error_code error;
Ip4Prefix nlri = Ip4Prefix::FromString(prefix, &error);
EXPECT_FALSE(error);
DBRequest request;
request.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
request.key.reset(new InetTable::RequestKey(nlri, peer));
BgpAttrSpec attr_spec;
boost::scoped_ptr<BgpAttrLocalPref> local_pref(
new BgpAttrLocalPref(localpref));
attr_spec.push_back(local_pref.get());
BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attr_spec);
request.data.reset(new BgpTable::RequestData(attr, 0, 0));
string tbl_name(vrf+".inet.0");
TASK_UTIL_WAIT_NE_NO_MSG(bgp_server_->database()->FindTable(tbl_name),
NULL, 1000, 10000, "Wait for Inet table..");
TASK_UTIL_EXPECT_NE(static_cast<BgpTable *>(NULL),
static_cast<BgpTable *>(
bgp_server_->database()->FindTable(tbl_name)));
BgpTable *table = static_cast<BgpTable *>(
bgp_server_->database()->FindTable(tbl_name));
table->Enqueue(&request);
if (wait) task_util::WaitForIdle();
}
void DeleteInetRoute(IPeer *peer, const string &instance_name,
const string &prefix, bool wait = true) {
BGP_DEBUG_UT("DELETE inet route " << instance_name << ":" << prefix);
boost::system::error_code error;
Ip4Prefix nlri = Ip4Prefix::FromString(prefix, &error);
EXPECT_FALSE(error);
DBRequest request;
request.oper = DBRequest::DB_ENTRY_DELETE;
request.key.reset(new InetTable::RequestKey(nlri, peer));
TASK_UTIL_EXPECT_NE(static_cast<BgpTable *>(NULL),
static_cast<BgpTable *>(
bgp_server_->database()->FindTable(instance_name + ".inet.0")));
BgpTable *table = static_cast<BgpTable *>(
bgp_server_->database()->FindTable(instance_name + ".inet.0"));
table->Enqueue(&request);
if (wait) task_util::WaitForIdle();
}
BgpRoute *VPNRouteLookup(const string &prefix) {
BgpTable *table = static_cast<BgpTable *>(
bgp_server_->database()->FindTable("bgp.l3vpn.0"));
EXPECT_TRUE(table != NULL);
if (table == NULL) {
return NULL;
}
boost::system::error_code error;
InetVpnPrefix nlri = InetVpnPrefix::FromString(prefix, &error);
EXPECT_FALSE(error);
InetVpnTable::RequestKey key(nlri, NULL);
BgpRoute *rt = static_cast<BgpRoute *>(table->Find(&key));
return rt;
}
BgpRoute *InetRouteLookup(const string &instance_name,
const string &prefix) {
BgpTable *table = static_cast<BgpTable *>(
bgp_server_->database()->FindTable(instance_name + ".inet.0"));
EXPECT_TRUE(table != NULL);
if (table == NULL) {
return NULL;
}
boost::system::error_code error;
Ip4Prefix nlri = Ip4Prefix::FromString(prefix, &error);
EXPECT_FALSE(error);
InetTable::RequestKey key(nlri, NULL);
BgpRoute *rt = static_cast<BgpRoute *>(table->Find(&key));
return rt;
}
void GenerateVrfs(VrfList &list_vrf, ConnectionMap &connections) {
uint32_t num_vrf_to_begin = min_vrf_ + rand() % max_vrf_;
for (uint32_t i = 0; i < num_vrf_to_begin; i++) {
stringstream oss;
oss << "vrf_" << i;
list_vrf.push_back(oss.str());
}
for (uint32_t i = 0; i < max_num_connections_; i++) {
uint32_t src = 0;
uint32_t dest = 0;
do {
do {
src = rand() % num_vrf_to_begin;
dest = rand() % num_vrf_to_begin;
} while (src == dest);
ConnectionMap::iterator it =
connections.find(list_vrf[src]);
while (it != connections.end() &&
(it->first == list_vrf[src])) {
if (it->second == list_vrf[dest]) {
break;
}
it++;
}
if (it != connections.end() && it->second == list_vrf[dest]) {
continue;
}
connections.insert(std::pair<string, string>(list_vrf[src],
list_vrf[dest]));
break;
} while (1);
}
}
void WalkDone(DBTableBase *table) {
}
bool TableVerify(BgpServer *server,
DBTablePartBase *root,
DBEntryBase *entry) {
BgpRoute *rt = static_cast<BgpRoute *> (entry);
BgpTable *table = static_cast<BgpTable *>(root->parent());
RoutePathReplicator *replicator = server->replicator(Address::INETVPN);
const RtReplicated *dbstate =
replicator->GetReplicationState(table, rt);
if (entry->IsDeleted()) {
assert(!dbstate);
return true;
}
for (Route::PathList::iterator path_it = rt->GetPathList().begin();
path_it != rt->GetPathList().end(); path_it++) {
BgpPath *path = static_cast<BgpPath *>(path_it.operator->());
if (path->IsReplicated()) {
const BgpSecondaryPath *secpath =
static_cast<const BgpSecondaryPath *>(path);
const BgpTable *pri_tbl = secpath->src_table();
const BgpRoute *pri_rt = secpath->src_rt();
BgpRoute *rt_to_check = NULL;
if (pri_tbl->family() == Address::INETVPN) {
// In this test the routes are added only to inet table,
// hence it is an assert to have primary route from VPN table
assert(0);
} else {
if (table->family() == Address::INETVPN) {
InetVpnRoute *vpn = static_cast<InetVpnRoute *>(rt);
Ip4Prefix prefix(vpn->GetPrefix().addr(),
vpn->GetPrefix().prefixlen());
RouteAddMap::iterator it =
routes_added_.find(prefix.ToString());
assert(it != routes_added_.end());
assert(it->second ==
pri_tbl->routing_instance()->name());
rt_to_check =
InetRouteLookup(pri_tbl->routing_instance()->name(),
prefix.ToString());
} else {
RouteAddMap::iterator it =
routes_added_.find(rt->ToString());
assert(it != routes_added_.end());
assert(it->second ==
pri_tbl->routing_instance()->name());
rt_to_check =
InetRouteLookup(pri_tbl->routing_instance()->name(),
rt->ToString());
}
}
assert(rt_to_check == pri_rt);
continue;
}
RoutingInstance *rtinstance = table->routing_instance();
assert(rtinstance);
RouteAddMap::iterator it = routes_added_.find(rt->ToString());
assert(it != routes_added_.end());
assert(it->second == rtinstance->name());
const ExtCommunity *ext_community = NULL;
ExtCommunityPtr new_ext_community(NULL);
const BgpAttr *attr = path->GetAttr();
if (table->family() != Address::INETVPN) {
ext_community = attr->ext_community();
ExtCommunity::ExtCommunityList export_list;
BOOST_FOREACH(RouteTarget rtarget, rtinstance->GetExportList()) {
export_list.push_back(rtarget.GetExtCommunity());
}
new_ext_community =
server->extcomm_db()->AppendAndLocate(ext_community,
export_list);
ext_community = new_ext_community.get();
} else {
// In this test the routes are added only to inet table,
// hence it is an assert to have primary route from VPN table
assert(0);
}
if (!ext_community) {
assert(!dbstate);
continue;
}
RtGroup::RtGroupMemberList super_set;
BOOST_FOREACH(const ExtCommunity::ExtCommunityValue &comm,
ext_community->communities()) {
RtGroup *rtgroup =
server->rtarget_group_mgr()->GetRtGroup(comm);
if (rtgroup) {
RtGroup::RtGroupMemberList import_list =
rtgroup->GetImportTables(replicator->family());
if (!import_list.empty())
super_set.insert(import_list.begin(),
import_list.end());
}
}
if (super_set.empty()) {
assert(!dbstate);
continue;
}
set<string> replicated_routes;
BOOST_FOREACH(BgpTable *dest, super_set) {
if (dest != table) {
BgpRoute *replicated_route = NULL;
if (dest->family() == Address::INETVPN) {
InetRoute *inet = static_cast<InetRoute *>(rt);
InetVpnPrefix vpn(*rtinstance->GetRD(),
inet->GetPrefix().ip4_addr(),
inet->GetPrefix().prefixlen());
replicated_route = VPNRouteLookup(vpn.ToString());
} else {
replicated_route =
InetRouteLookup(dest->routing_instance()->name(),
rt->ToString());
}
assert(replicated_route->FindSecondaryPath(rt,
path->GetSource(), path->GetPeer(),
path->GetPathId()));
string route_to_insert(dest->routing_instance()->name());
route_to_insert += ":";
route_to_insert += path->GetPeer()->ToString();
route_to_insert += ":";
route_to_insert += replicated_route->ToString();
replicated_routes.insert(route_to_insert);
}
}
// secondary routes which are no longer replicated
for (RtReplicated::ReplicatedRtPathList::iterator iter =
dbstate->GetList().begin();
iter != dbstate->GetList().end(); iter++) {
RtReplicated::SecondaryRouteInfo rinfo = *iter;
string route_to_find(rinfo.table_->routing_instance()->name());
route_to_find += ":";
route_to_find += rinfo.peer_->ToString();
route_to_find += ":";
route_to_find += rinfo.rt_->ToString();
set<string>::iterator it =
replicated_routes.find(route_to_find);
assert(it != replicated_routes.end());
replicated_routes.erase(it);
}
assert(replicated_routes.empty());
}
return true;
}
void DumpConnections() {
for(ConnectionMap::iterator con_verify_it = connections_.begin();
con_verify_it != connections_.end(); con_verify_it++) {
BGP_DEBUG_UT(con_verify_it->first << "<->"
<< con_verify_it->second);
}
}
bool VerifyConnection(string from_rt, string to_rt) {
if (from_rt == to_rt) {
return true;
}
for(ConnectionMap::iterator con_verify_it = connections_.begin();
con_verify_it != connections_.end(); con_verify_it++) {
if (((con_verify_it->first == from_rt) &&
(con_verify_it->second == to_rt)) ||
((con_verify_it->first == to_rt) &&
(con_verify_it->second == from_rt))) {
return true;
}
}
return false;
}
bool VerifyReplicationState() {
DBTableWalker::WalkCompleteFn walk_complete
= boost::bind(&ReplicationTest::WalkDone, this, _1);
DBTableWalker::WalkFn walker
= boost::bind(&ReplicationTest::TableVerify, this,
bgp_server_.get(), _1, _2);
DB *db = bgp_server_->database();
RoutingInstanceMgr *rtinst_mgr = bgp_server_->routing_instance_mgr();
for (RoutingInstanceMgr::RoutingInstanceIterator it =
rtinst_mgr->begin(); it != rtinst_mgr->end(); it++) {
BOOST_FOREACH(RouteTarget tgt, it->GetImportList()) {
const RoutingInstance *from_rt
= rtinst_mgr->GetInstanceByTarget(tgt);
assert(from_rt);
assert(VerifyConnection(from_rt->name(), it->name()));
}
BgpTable *table = it->GetTable(Address::INET);
if (table != NULL) {
db->GetWalker()->WalkTable(table, NULL, walker, walk_complete);
}
table = it->GetTable(Address::INETVPN);
if (table != NULL) {
db->GetWalker()->WalkTable(table, NULL, walker, walk_complete);
}
}
return true;
}
EventManager evm_;
DB config_db_;
DBGraph config_graph_;
boost::scoped_ptr<BgpServer> bgp_server_;
vector<BgpPeerMock *> peers_;
uint32_t min_vrf_;
uint32_t max_vrf_;
uint32_t max_num_connections_;
uint32_t max_iterations_;
RouteAddMap routes_added_;
VrfList vrfs_;
ConnectionMap connections_;
};
TEST_P(ReplicationTest, RandomTest) {
boost::system::error_code ec;
peers_.push_back(new BgpPeerMock(Ip4Address::from_string("192.168.0.1",
ec)));
GenerateVrfs(vrfs_, connections_);
NetworkConfig(vrfs_, connections_);
task_util::WaitForIdle();
// Start with random number of routes in VRFs
for (uint32_t num_iteration = 0;
num_iteration < max_iterations_;
num_iteration++) {
uint32_t vrf_index = rand() % vrfs_.size();
while(true) {
stringstream oss;
oss << "172.168.";
oss << (rand() % 255) << ".";
oss << (rand() % 255) << "/32";
// Add Route
pair<RouteAddMap::iterator, bool> ret =
routes_added_.insert(pair<string, string>(oss.str(),
vrfs_[vrf_index]));
if (ret.second == false) {
continue;
}
AddInetRoute(peers_[0], vrfs_[vrf_index], oss.str(), 100);
break;
}
}
task_util::WaitForIdle();
for (uint32_t num_iteration = 0;
num_iteration < max_iterations_;
num_iteration++) {
uint32_t vrf_index = 0;
do {
vrf_index = rand() % vrfs_.size();
} while(vrfs_[vrf_index] == "DELETED");
uint8_t vrf_or_route = rand() % 2;
if (vrf_or_route) {
// Play with VRF and connections
uint8_t vrf_or_connection = rand() % 2;
if (vrf_or_connection) {
// VRF
uint8_t add_or_del_vrf = rand() % 2;
if (add_or_del_vrf) {
// Add
stringstream oss;
oss << "vrf_" << vrfs_.size();
AddRoutingInstance(oss.str());
} else {
size_t count = count_if(vrfs_.begin(), vrfs_.end(),
(boost::lambda::_1 == "DELETED"));
if (count < (vrfs_.size() - 2)) {
DeleteRoutingInstance(vrfs_[vrf_index]);
}
}
} else {
// Connections
uint8_t add_or_del_link = rand() % 2;
if (add_or_del_link) {
// Add
uint32_t dest = 0;
do {
do {
dest = rand() % vrfs_.size();
} while ((vrfs_[dest] == "DELETED") ||
(vrf_index == dest));
ConnectionMap::iterator it =
connections_.find(vrfs_[vrf_index]);
while (it != connections_.end() &&
(it->first == vrfs_[vrf_index])) {
if (it->second == vrfs_[dest]) {
break;
}
it++;
}
if (it != connections_.end() &&
it->second == vrfs_[dest]) {
continue;
}
break;
} while (1);
AddConnection(vrfs_[vrf_index], vrfs_[dest]);
} else {
// Delete a Link
ConnectionMap::iterator it =
connections_.find(vrfs_[vrf_index]);
if (it != connections_.end()) {
RemoveConnection(it->first, it->second);
connections_.erase(it);
}
}
}
} else {
// Play with Routes
uint8_t adc_route = rand() % 3;
if (adc_route == 0) {
while(true) {
stringstream oss;
oss << "172.168.";
oss << (rand() % 255) << ".";
oss << (rand() % 255) << "/32";
// Add Route
pair<RouteAddMap::iterator, bool> ret =
routes_added_.insert(pair<string,
string>(oss.str(),
vrfs_[vrf_index]));
if (ret.second == false) {
continue;
}
AddInetRoute(peers_[0], vrfs_[vrf_index], oss.str(), 100);
break;
}
} else if (adc_route == 1) {
if (routes_added_.size() == 0) {
continue;
}
uint32_t at_index = rand() % routes_added_.size();
uint32_t count = 0;
// Delete Route
for(RouteAddMap::iterator it = routes_added_.begin();
it != routes_added_.end(); it++, count++) {
if (count == at_index) {
DeleteInetRoute(peers_[0], it->second, it->first);
routes_added_.erase(it);
break;
}
}
} else {
if (routes_added_.size() == 0) {
continue;
}
// Update Route
uint32_t at_index = rand() % routes_added_.size();
uint32_t count = 0;
// Delete Route
for(RouteAddMap::iterator it = routes_added_.begin();
it != routes_added_.end(); it++, count++) {
if (count == at_index) {
AddInetRoute(peers_[0], it->second, it->first, 10);
break;
}
}
}
}
task_util::WaitForIdle();
}
// Verify whether the routes are in consistent state
// Need to start multiple walks
VerifyReplicationState();
task_util::WaitForIdle();
BOOST_FOREACH(RouteAddMap::value_type mapref, routes_added_) {
DeleteInetRoute(peers_[0], mapref.second, mapref.first);
}
task_util::WaitForIdle();
}
class TestEnvironment : public ::testing::Environment {
virtual ~TestEnvironment() { }
};
static void SetUp() {
ControlNode::SetDefaultSchedulingPolicy();
BgpObjectFactory::Register<BgpConfigManager>(
boost::factory<BgpIfmapConfigManager *>());
}
static void TearDown() {
TaskScheduler *scheduler = TaskScheduler::GetInstance();
scheduler->Terminate();
}
static vector<int> n_vrfs = boost::assign::list_of(5)(10);
static vector<int> n_connections = boost::assign::list_of(5)(10);
static vector<int> n_iterations = boost::assign::list_of(5)(10);
static void process_command_line_args(int argc, char **argv) {
int vrfs = 1, connections = 1, iterations = 1;
options_description desc("Allowed options");
bool cmd_line_arg_set = false;
desc.add_options()
("help", "produce help message")
("vrfs", value<int>(), "set number of VRFs")
("connections", value<int>(), "set number of connectios")
("iterations", value<int>(), "set number of iterations")
;
variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
exit(1);
}
if (vm.count("vrfs")) {
vrfs = vm["vrfs"].as<int>();
cmd_line_arg_set = true;
}
if (vm.count("connections")) {
connections = vm["connections"].as<int>();
cmd_line_arg_set = true;
}
if (vm.count("iterations")) {
iterations = vm["iterations"].as<int>();
cmd_line_arg_set = true;
}
if (cmd_line_arg_set) {
n_vrfs.clear();
n_vrfs.push_back(vrfs);
n_connections.clear();
n_connections.push_back(connections);
n_iterations.clear();
n_iterations.push_back(iterations);
}
}
static vector<int> GetTestParam() {
static bool cmd_line_processed;
if (!cmd_line_processed) {
cmd_line_processed = true;
process_command_line_args(gargc, gargv);
}
return n_vrfs;
}
#define COMBINE_PARAMS \
Combine(ValuesIn(GetTestParam()), \
ValuesIn(n_connections), \
ValuesIn(n_iterations))
INSTANTIATE_TEST_CASE_P(ReplicatorRandomTestWithParams, ReplicationTest,
COMBINE_PARAMS);
int main(int argc, char **argv) {
bgp_log_test::init();
::testing::InitGoogleTest(&argc, argv);
::testing::AddGlobalTestEnvironment(new TestEnvironment());
SetUp();
int result = RUN_ALL_TESTS();
TearDown();
return result;
}
| 36.770975
| 81
| 0.522416
|
awesome-sdx
|
b4412ece324403b46722949334720c9e874a5185
| 5,862
|
hpp
|
C++
|
src/globalinclude/commonFunc/ThreadPool.hpp
|
tangtgithub/common_robotframe
|
f098d688bde1d2b2d5d6fac430c98b952621b7c1
|
[
"MIT"
] | 5
|
2021-07-21T11:38:09.000Z
|
2021-11-26T03:16:09.000Z
|
src/globalinclude/commonFunc/ThreadPool.hpp
|
tangtgithub/common_robotframe
|
f098d688bde1d2b2d5d6fac430c98b952621b7c1
|
[
"MIT"
] | null | null | null |
src/globalinclude/commonFunc/ThreadPool.hpp
|
tangtgithub/common_robotframe
|
f098d688bde1d2b2d5d6fac430c98b952621b7c1
|
[
"MIT"
] | null | null | null |
/** *******************************************************
* @brief :线程池类
* @author :tangt
* @date :2021-02-02
* @copyright :Copyright (C) 2021 - All Rights Reserved
* @note :对于返回值为void的function,只执行一次
* 对于返回值为int的function,一直执行直至返回值为0
* 对于返回值为bool的function,一直执行直至返回值为true
* 一直执行只是代表该function会被反复执行,其他function仍可正常得到调度
* todo:目前暂不支持指定执行失败后重新执行的时间
**********************************************************/
#ifndef __THREAD_POOL_NEW_H__
#define __THREAD_POOL_NEW_H__
#include <functional>
#include <deque>
#include <string>
#include <thread>
#include <mutex>
#include <iostream>
#include <assert.h>
#include <sys/prctl.h>
class ThreadPoolNew
{
public:
typedef std::function<void()> Task;
typedef std::function<int()> TaskI;
typedef std::function<bool()> TaskB;
public:
//实际会比threadNum多创建一个线程
explicit ThreadPoolNew(size_t threadNum = 10, std::string threadName = "ThreadPool")
: m_isRunning(true)
, m_threadsNum(threadNum)
, m_threadName(threadName)
, m_earlyTime(0)
{
createThreads();
}
~ThreadPoolNew()
{
stop();
}
public:
size_t addTask(const Task& task)
{
std::unique_lock<std::mutex> lock(m_mutex_msg);
m_taskQueue.push_back(task);
m_cvMsg.notify_one();
return sizeLockless();
}
size_t addTaskI(const TaskI& task)
{
std::unique_lock<std::mutex> lock(m_mutex_msg);
m_taskQueueI.push_back(task);
m_cvMsg.notify_one();
return sizeLockless();
}
size_t addTaskB(const TaskB& task)
{
std::unique_lock<std::mutex> lock(m_mutex_msg);
m_taskQueueB.push_back(task);
m_cvMsg.notify_one();
return sizeLockless();
}
private:
void createThreads()
{
for (size_t i = 0; i < m_threadsNum; ++i)
{
std::thread(&ThreadPoolNew::threadFunc, this).detach();
}
std::thread(&ThreadPoolNew::cacheHandler, this).detach();
}
void stop()
{
if (!m_isRunning) {
return;
}
m_isRunning = false;
m_cvMsg.notify_all();
}
void threadFunc()
{
prctl(PR_SET_NAME, m_threadName.c_str());
while (m_isRunning)
{
Task task;
TaskI taskI;
TaskB taskB;
take(task, taskI, taskB);
if (task)
task();
else if (taskI)
{
if (taskI() == 0)
continue;
std::unique_lock<std::mutex> lock(m_mutex_msg);
m_taskQueueICache.push_back(taskI);
if(m_earlyTime == 0)
m_earlyTime = time(nullptr);
}
else if (taskB)
{
if (taskB())
continue;
std::unique_lock<std::mutex> lock(m_mutex_msg);
m_taskQueueBCache.push_back(taskB);
if (m_earlyTime == 0)
m_earlyTime = time(nullptr);
}
}
}
void take(Task &task, TaskI &taskI, TaskB &taskB)
{
std::unique_lock<std::mutex> lock(m_mutex_msg);
while (sizeLockless()==0 && m_isRunning)
{
m_cvMsg.wait(lock);
}
if (!m_isRunning) {
return;
}
assert(sizeLockless() != 0);
if (m_taskQueue.size() != 0)
{
task = m_taskQueue.front();
m_taskQueue.pop_front();
}
else if (m_taskQueueI.size() != 0)
{
taskI = m_taskQueueI.front();
m_taskQueueI.pop_front();
}
else if (m_taskQueueB.size() != 0)
{
taskB = m_taskQueueB.front();
m_taskQueueB.pop_front();
}
}
size_t size()
{
std::unique_lock<std::mutex> lock(m_mutex_msg);
return m_taskQueue.size()+ m_taskQueueI.size()+ m_taskQueueB.size();
}
size_t sizeLockless()
{
return m_taskQueue.size() + m_taskQueueI.size() + m_taskQueueB.size();
}
void cacheHandler()
{
prctl(PR_SET_NAME, m_threadName.c_str());
while (1)
{
time_t now = time(nullptr);
if (now - m_earlyTime >= 5 && m_earlyTime != 0)
{
std::unique_lock<std::mutex> lock(m_mutex_msg);
m_taskQueue.insert(m_taskQueue.end(), m_taskQueueCache.begin(), m_taskQueueCache.end());
m_taskQueueI.insert(m_taskQueueI.end(), m_taskQueueICache.begin(), m_taskQueueICache.end());
m_taskQueueB.insert(m_taskQueueB.end(), m_taskQueueBCache.begin(), m_taskQueueBCache.end());
m_taskQueueCache.clear();
m_taskQueueICache.clear();
m_taskQueueBCache.clear();
m_earlyTime = 0;
m_cvMsg.notify_all();
}
else
std::this_thread::sleep_for(3s);
}
}
private:
ThreadPoolNew& operator=(const ThreadPoolNew&) = delete;
ThreadPoolNew(const ThreadPoolNew&) = delete;
private:
volatile bool m_isRunning;
size_t m_threadsNum;
std::string m_threadName;
//立即执行队列
std::deque<Task> m_taskQueue;
std::deque<TaskI> m_taskQueueI;
std::deque<TaskB> m_taskQueueB;
//缓存队列,执行失败的先放入缓存队列
std::deque<Task> m_taskQueueCache;
std::deque<TaskI> m_taskQueueICache;
std::deque<TaskB> m_taskQueueBCache;
time_t m_earlyTime;//第一次执行失败的时间
std::mutex m_mutex_msg;
std::condition_variable m_cvMsg;
};
#endif
| 28.318841
| 108
| 0.522518
|
tangtgithub
|
b441a906b48bed28e224b2435faf4287f5e342ec
| 3,034
|
cpp
|
C++
|
ai.cpp
|
Joeization/Othello
|
e61a19b0d8ea4a2967f6021ca6c7ac4cc346640e
|
[
"MIT"
] | null | null | null |
ai.cpp
|
Joeization/Othello
|
e61a19b0d8ea4a2967f6021ca6c7ac4cc346640e
|
[
"MIT"
] | null | null | null |
ai.cpp
|
Joeization/Othello
|
e61a19b0d8ea4a2967f6021ca6c7ac4cc346640e
|
[
"MIT"
] | null | null | null |
#include "ai.h"
ai *umikaze = new ai(0);
float sigmoid(float v){
return v/(abs(v)+1);
}
void ai::set_weight(){
for(int l=0;l<Layer;l++){
for(int fi=0;fi<8;fi++){
for(int fj=0;fj<8;fj++){
for(int ti=0;ti<8;ti++){
for(int tj=0;tj<8;tj++){
if(fi!=ti&&fj!=tj)
for(int p=0;p<acc;p++)
weight[l][fi][fj][ti][tj][p]=rand()%10;
}
}
}
}
}
}
ai::ai(bool init){
//init weight, there may be a better way.
if(init){
set_weight();
}
}
ai::~ai(){
//do nothing
}
void ai::set_value(game *v){
//init value for current map
int co = v->get_now_color();
for(int fi=0;fi<8;fi++){
for(int fj=0;fj<8;fj++){
if(v->get_pos(make_pair(fi,fj)) == co)
value[fi][fj] = 0.1;
else
value[fi][fj] = -0.1;
}
}
//compute
for(int l=0;l<Layer;l++){
memset(tmp,0,sizeof(tmp));
for(int fi=0;fi<8;fi++){
for(int fj=0;fj<8;fj++){
for(int ti=0;ti<8;ti++){
for(int tj=0;tj<8;tj++){
if(fi!=ti&&fj!=tj&&(abs(fi-ti)+abs(fj-tj))<dis){
float base=1;
float w=0;
for(int p=0;p<acc;p++){
w += base*weight[l][fi][fj][ti][tj][p];
base /= 10;
}
w -= 5;
tmp[ti][tj] += value[fi][fj]*w;
}
}
}
}
}
float stimu;
//stimulate
for(int i=0;i<8;i++)
for(int j=0;j<8;j++){
stimu = sigmoid(tmp[i][j]);
if(l < Layer-1){
if(abs(stimu) > threshold)
value[i][j] = stimu;
else
value[i][j] = 0;
}
else
value[i][j] = stimu;
}
}
}
bool ai::run(game *v, bool sh){
//testing
int color = v->get_now_color();
vector<pair<int, int> > s = v->can_drop(color);
if(s.size() > 0){
//bubble sort is enough for 64 elements
for(int i=0;i<s.size();i++)
for(int j=i+1;j<s.size();j++){
if(value[s[j].first][s[j].second]
>value[s[i].first][s[i].second])
iter_swap(s.begin()+i,s.begin()+j);
}
v->drop(s[0], color);
if(sh){
cout << value[s[0].first][s[0].second] << endl;
cout << "gap: " << value[s[0].first][s[0].second]
- value[s[s.size()-1].first][s[s.size()-1].second] << endl;
}
return true;
}
else{
cout << "not a valid move." << endl;
return false;
}
}
| 28.35514
| 75
| 0.359262
|
Joeization
|
b44410f9928fce7c9dfbdecb00203eff223c9f0d
| 22,827
|
cxx
|
C++
|
Modules/Filtering/DisplacementField/test/itkDisplacementFieldTransformTest.cxx
|
yjcchen0913/ITK
|
36c5bace788d84ab8f6de1e49ccfb88c0015ce5a
|
[
"Apache-2.0"
] | null | null | null |
Modules/Filtering/DisplacementField/test/itkDisplacementFieldTransformTest.cxx
|
yjcchen0913/ITK
|
36c5bace788d84ab8f6de1e49ccfb88c0015ce5a
|
[
"Apache-2.0"
] | 1
|
2017-08-18T19:28:52.000Z
|
2017-08-18T19:28:52.000Z
|
Modules/Filtering/DisplacementField/test/itkDisplacementFieldTransformTest.cxx
|
yjcchen0913/ITK
|
36c5bace788d84ab8f6de1e49ccfb88c0015ce5a
|
[
"Apache-2.0"
] | 1
|
2017-08-18T19:07:39.000Z
|
2017-08-18T19:07:39.000Z
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkDisplacementFieldTransform.h"
#include "itkCenteredAffineTransform.h"
#include "itkStdStreamStateSave.h"
#include "itkMath.h"
#include "itkNumericTraits.h"
#include "itkTestingMacros.h"
#include "itkVectorLinearInterpolateImageFunction.h"
template <typename TPoint>
bool samePoint( const TPoint & p1, const TPoint & p2, double epsilon = 1e-8 )
{
bool pass = true;
for( unsigned int i = 0; i < TPoint::PointDimension; i++ )
{
if( !itk::Math::FloatAlmostEqual( p1[i], p2[i], 10, epsilon ) )
{
std::cout << "Error at index [" << i << "]" << std::endl;
std::cout << "Expected: "
<< static_cast< typename itk::NumericTraits<
typename TPoint::ValueType >::PrintType >( p1[i] )
<< ", but got: "
<< static_cast< typename itk::NumericTraits<
typename TPoint::ValueType >::PrintType >( p2[i] )
<< std::endl;
pass = false;
}
}
return pass;
}
template <typename TVector>
bool sameVector( const TVector & v1, const TVector & v2, double epsilon = 1e-8 )
{
bool pass = true;
for( unsigned int i = 0; i < TVector::Dimension; i++ )
{
if( !itk::Math::FloatAlmostEqual( v1[i], v2[i], 10, epsilon ) )
{
std::cout << "Error at index [" << i << "]" << std::endl;
std::cout << "Expected: "
<< static_cast< typename itk::NumericTraits<
typename TVector::ValueType >::PrintType >( v1[i] )
<< ", but got: "
<< static_cast< typename itk::NumericTraits<
typename TVector::ValueType >::PrintType >( v2[i] )
<< std::endl;
pass = false;
}
}
return pass;
}
template <typename TVector>
bool sameVariableVector( const TVector & v1, const TVector & v2, double epsilon = 1e-8 )
{
bool pass = true;
const unsigned int D1 = v1.Size();
const unsigned int D2 = v2.Size();
if( D1 != D2 )
{
return false;
}
for( unsigned int i = 0; i < D1; i++ )
{
if( !itk::Math::FloatAlmostEqual( v1[i], v2[i], 10, epsilon ) )
{
std::cout << "Error at index [" << i << "]" << std::endl;
std::cout << "Expected: "
<< static_cast< typename itk::NumericTraits<
typename TVector::ValueType >::PrintType >( v1[i] )
<< ", but got: "
<< static_cast< typename itk::NumericTraits<
typename TVector::ValueType >::PrintType >( v2[i] )
<< std::endl;
pass = false;
}
}
return pass;
}
template <typename TTensor>
bool sameTensor( const TTensor & t1, const TTensor & t2, double epsilon = 1e-8 )
{
bool pass = true;
for( unsigned int i = 0; i < TTensor::InternalDimension; i++ )
{
if( !itk::Math::FloatAlmostEqual( t1[i], t2[i], 10, epsilon ) )
{
std::cout << "Error at index [" << i << "]" << std::endl;
std::cout << "Expected: "
<< static_cast< typename itk::NumericTraits<
typename TTensor::ValueType >::PrintType >( t1[i] )
<< ", but got: "
<< static_cast< typename itk::NumericTraits<
typename TTensor::ValueType >::PrintType >( t2[i] )
<< std::endl;
pass = false;
}
}
return pass;
}
template <typename TArray2D, typename TArray2D_ARG1>
bool sameArray2D( const TArray2D & a1, const TArray2D_ARG1 & a2, double epsilon = 1e-8 )
{
bool pass = true;
if( (a1.rows() != a2.rows() ) || (a1.cols() != a2.cols() ) )
{
return false;
}
for( unsigned int i = 0; i < a1.cols(); i++ )
{
for( unsigned int j = 0; j < a1.rows(); j++ )
{
if( !itk::Math::FloatAlmostEqual( a1(j, i), a2(j, i), 10, epsilon ) )
{
std::cout << "Error at index (" << j << ", " << i << ")" << std::endl;
std::cout << "Expected: "
<< static_cast< typename itk::NumericTraits<
typename TArray2D::element_type >::PrintType >( a1(j, i) )
<< ", but got: "
<< static_cast< typename itk::NumericTraits<
typename TArray2D_ARG1::element_type >::PrintType >( a2(j, i) )
<< std::endl;
pass = false;
}
}
}
return pass;
}
int itkDisplacementFieldTransformTest( int argc, char* argv[] )
{
if( argc < 3 )
{
std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv);
std::cerr << " coordinateTolerance directionTolerance";
std::cerr << std::endl;
return EXIT_FAILURE;
}
constexpr unsigned int Dimensions = 2;
using ParametersValueType = double;
using DisplacementTransformType =
itk::DisplacementFieldTransform< ParametersValueType, Dimensions >;
using ScalarType = DisplacementTransformType::ScalarType;
using FieldType = DisplacementTransformType::DisplacementFieldType;
using DisplacementFieldType = DisplacementTransformType::DisplacementFieldType;
// Save the format stream variables for std::cout
// They will be restored when coutState goes out of scope.
itk::StdStreamStateSave coutState(std::cout);
// Create a displacement field transform
DisplacementTransformType::Pointer displacementTransform =
DisplacementTransformType::New();
EXERCISE_BASIC_OBJECT_METHODS( displacementTransform,
DisplacementFieldTransform, Transform );
DisplacementTransformType::DisplacementFieldType::Pointer displacementField =
DisplacementTransformType::DisplacementFieldType::New();
displacementTransform->SetDisplacementField( displacementField );
TEST_SET_GET_VALUE( displacementField,
displacementTransform->GetDisplacementField() );
DisplacementTransformType::DisplacementFieldType::Pointer inverseDisplacementField =
DisplacementTransformType::DisplacementFieldType::New();
displacementTransform->SetInverseDisplacementField( inverseDisplacementField );
TEST_SET_GET_VALUE( inverseDisplacementField,
displacementTransform->GetInverseDisplacementField() );
using InterpolatorType = itk::VectorLinearInterpolateImageFunction<
DisplacementTransformType::DisplacementFieldType,
DisplacementTransformType::ScalarType>;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
displacementTransform->SetInterpolator( interpolator );
TEST_SET_GET_VALUE( interpolator,
displacementTransform->GetInterpolator() );
InterpolatorType::Pointer inverseInterpolator = InterpolatorType::New();
displacementTransform->SetInverseInterpolator( inverseInterpolator );
TEST_SET_GET_VALUE( inverseInterpolator,
displacementTransform->GetInverseInterpolator() );
double coordinateTolerance = std::stod( argv[1] );
displacementTransform->SetCoordinateTolerance( coordinateTolerance );
TEST_SET_GET_VALUE( coordinateTolerance,
displacementTransform->GetCoordinateTolerance() );
double directionTolerance = std::stod( argv[2] );
displacementTransform->SetDirectionTolerance( directionTolerance );
TEST_SET_GET_VALUE( directionTolerance,
displacementTransform->GetDirectionTolerance() );
FieldType::Pointer field = FieldType::New();
FieldType::SizeType size;
FieldType::IndexType start;
FieldType::RegionType region;
int dimLength = 20;
size.Fill( dimLength );
start.Fill( 0 );
region.SetSize( size );
region.SetIndex( start );
field->SetRegions( region );
field->Allocate();
DisplacementTransformType::OutputVectorType zeroVector;
zeroVector.Fill( 0 );
field->FillBuffer( zeroVector );
displacementTransform->SetDisplacementField( field );
TEST_SET_GET_VALUE( field, displacementTransform->GetDisplacementField() );
// Test the fixed parameters
DisplacementTransformType::ParametersType fixedParameters =
displacementTransform->GetFixedParameters();
displacementTransform->SetFixedParameters( fixedParameters );
TEST_SET_GET_VALUE( fixedParameters, displacementTransform->GetFixedParameters() );
DisplacementFieldType::SizeType size2 =
displacementTransform->GetDisplacementField()->GetLargestPossibleRegion().GetSize();
DisplacementFieldType::PointType origin2 =
displacementTransform->GetDisplacementField()->GetOrigin();
DisplacementFieldType::DirectionType direction2 =
displacementTransform->GetDisplacementField()->GetDirection();
DisplacementFieldType::SpacingType spacing2 =
displacementTransform->GetDisplacementField()->GetSpacing();
size = field->GetLargestPossibleRegion().GetSize();
DisplacementFieldType::PointType origin = field->GetOrigin();
DisplacementFieldType::DirectionType direction = field->GetDirection();
DisplacementFieldType::SpacingType spacing = field->GetSpacing();
if( size != size2 )
{
std::cerr << "Test failed!" << std::endl;
std::cerr << "Incorrect size from fixed parameters." << std::endl;
return EXIT_FAILURE;
}
if( origin != origin2 )
{
std::cerr << "Test failed!" << std::endl;
std::cerr << "Incorrect origin from fixed parameters." << std::endl;
return EXIT_FAILURE;
}
if( spacing != spacing2 )
{
std::cerr << "Test failed!" << std::endl;
std::cerr << "Incorrect spacing from fixed parameters." << std::endl;
return EXIT_FAILURE;
}
if( direction != direction2 )
{
std::cerr << "Test failed!" << std::endl;
std::cerr << "Incorrect direction from fixed parameters." << std::endl;
return EXIT_FAILURE;
}
// Initialize Affine transform and use it to create the displacement field
using AffineTransformType =
itk::CenteredAffineTransform< ParametersValueType, Dimensions >;
using AffineMatrixType = AffineTransformType::MatrixType;
AffineMatrixType affineMatrix;
affineMatrix( 0, 0 ) = 1.0;
affineMatrix( 1, 0 ) = 0.01;
affineMatrix( 0, 1 ) = 0.02;
affineMatrix( 1, 1 ) = 1.1;
AffineTransformType::Pointer affineTransform = AffineTransformType::New();
affineTransform->SetIdentity();
affineTransform->SetMatrix( affineMatrix );
DisplacementTransformType::JacobianType fieldJTruth;
fieldJTruth.SetSize( DisplacementTransformType::Dimension, DisplacementTransformType::Dimension );
fieldJTruth( 0, 0 ) = 1.0;
fieldJTruth( 1, 0 ) = 0.01;
fieldJTruth( 0, 1 ) = 0.02;
fieldJTruth( 1, 1 ) = 1.1;
itk::ImageRegionIteratorWithIndex< FieldType > it( field, field->GetLargestPossibleRegion() );
it.GoToBegin();
while( !it.IsAtEnd() )
{
FieldType::PointType pt;
field->TransformIndexToPhysicalPoint( it.GetIndex(), pt );
FieldType::PointType pt2 = affineTransform->TransformPoint( pt );
FieldType::PointType::VectorType vec = pt2 - pt;
FieldType::PixelType v;
v[0] = vec[0];
v[1] = vec[1];
field->SetPixel( it.GetIndex(), v );
++it;
}
displacementTransform->SetDisplacementField( field );
TEST_SET_GET_VALUE( field, displacementTransform->GetDisplacementField() );
DisplacementTransformType::InputPointType testPoint;
testPoint[0] = 10;
testPoint[1] = 8;
// Test LocalJacobian methods
DisplacementTransformType::JacobianPositionType jacobian;
displacementTransform->ComputeJacobianWithRespectToPosition( testPoint, jacobian );
double tolerance = 1e-6;
if( !sameArray2D( jacobian, fieldJTruth, tolerance ) )
{
std::cout << "Failed getting local Jacobian: "
<< "ComputeJacobianWithRespectToPosition(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
DisplacementTransformType::JacobianType invfieldJTruth;
invfieldJTruth.SetSize( DisplacementTransformType::Dimension,
DisplacementTransformType::Dimension);
invfieldJTruth( 0, 0 ) = affineTransform->GetInverseTransform()->GetParameters()[0];
invfieldJTruth( 1, 0 ) = affineTransform->GetInverseTransform()->GetParameters()[1];
invfieldJTruth( 0, 1 ) = affineTransform->GetInverseTransform()->GetParameters()[2];
invfieldJTruth( 1, 1 ) = affineTransform->GetInverseTransform()->GetParameters()[3];
displacementTransform->GetInverseJacobianOfForwardFieldWithRespectToPosition( testPoint, jacobian );
tolerance = 1e-1;
if( !sameArray2D( jacobian, invfieldJTruth, tolerance ) )
{
std::cout << "Error getting local inverse Jacobian: "
<< "GetInverseJacobianOfForwardFieldWithRespectToPosition(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
displacementTransform->GetInverseJacobianOfForwardFieldWithRespectToPosition( testPoint, jacobian, true );
if( !sameArray2D( jacobian, invfieldJTruth, tolerance ) )
{
std::cout << "Error getting local inverse Jacobian with SVD: "
<< "GetInverseJacobianOfForwardFieldWithRespectToPosition(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
// Test ComputeJacobianWithRespectToParameters: should return identity
DisplacementTransformType::JacobianType identity( Dimensions, Dimensions ), testIdentity;
identity.Fill( 0 );
for( unsigned int i = 0; i < Dimensions; i++ )
{
identity[i][i] = 1.0;
}
displacementTransform->ComputeJacobianWithRespectToParameters(
testPoint, testIdentity );
tolerance = 1e-10;
if( !sameArray2D( identity, testIdentity, tolerance ) )
{
std::cout << "Error returning identity for "
<< "ComputeJacobianWithRespectToParameters(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
DisplacementTransformType::IndexType testIndex;
testIdentity.SetSize( 1, 1 ); // make sure it gets resized properly
displacementTransform->ComputeJacobianWithRespectToParameters(
testIndex, testIdentity );
if( !sameArray2D( identity, testIdentity, tolerance ) )
{
std::cout << "Error returning identity for "
<< "ComputeJacobianWithRespectToParameters(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
// Test transforming of points
//
DisplacementTransformType::OutputPointType deformOutput, deformTruth;
// Test a point with non-zero displacement
FieldType::IndexType idx;
field->TransformPhysicalPointToIndex( testPoint, idx );
deformTruth = testPoint + field->GetPixel( idx );
deformOutput = displacementTransform->TransformPoint( testPoint );
if( !samePoint( deformOutput, deformTruth ) )
{
std::cout << "Error transforming point: TransformPoint(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
DisplacementTransformType::InputVectorType testVector;
DisplacementTransformType::OutputVectorType deformVector, deformVectorTruth;
testVector[0] = 0.5;
testVector[1] = 0.5;
deformVectorTruth = affineTransform->TransformVector( testVector );
deformVector = displacementTransform->TransformVector( testVector, testPoint );
tolerance = 1e-4;
if( !sameVector( deformVector, deformVectorTruth, tolerance ) )
{
std::cout << "Error transforming vector: TransformVector(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
TRY_EXPECT_EXCEPTION( deformVector =
displacementTransform->TransformVector( testVector ) );
// Test VectorTransform for variable length vector
DisplacementTransformType::InputVectorPixelType
testVVector( DisplacementTransformType::Dimension );
DisplacementTransformType::OutputVectorPixelType deformVVector,
deformVVectorTruth( DisplacementTransformType::Dimension );
testVVector[0] = 0.5;
testVVector[1] = 0.5;
deformVVectorTruth = affineTransform->TransformVector( testVVector );
deformVVector = displacementTransform->TransformVector( testVVector, testPoint );
if( !sameVariableVector( deformVVector, deformVVectorTruth, tolerance ) )
{
std::cout << "Error transforming variable length vector: "
<< "TransformVector(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
TRY_EXPECT_EXCEPTION( deformVVector =
displacementTransform->TransformVector( testVVector ) );
DisplacementTransformType::InputCovariantVectorType testcVector;
DisplacementTransformType::OutputCovariantVectorType deformcVector, deformcVectorTruth;
testcVector[0] = 0.5;
testcVector[1] = 0.5;
deformcVectorTruth = affineTransform->TransformCovariantVector( testcVector );
deformcVector = displacementTransform->TransformCovariantVector( testcVector, testPoint );
tolerance = 1e-1;
if( !sameVector( deformcVector, deformcVectorTruth, tolerance ) )
{
std::cout << "Error transforming covariant vector: "
<< "TransformCovariantVector(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
TRY_EXPECT_EXCEPTION( deformcVector =
displacementTransform->TransformCovariantVector( testcVector ) );
DisplacementTransformType::InputVectorPixelType
testcVVector( DisplacementTransformType::Dimension );
DisplacementTransformType::OutputVectorPixelType deformcVVector,
deformcVVectorTruth( DisplacementTransformType::Dimension );
testcVVector[0] = 0.5;
testcVVector[1] = 0.5;
deformcVVectorTruth = affineTransform->TransformCovariantVector( testcVVector );
deformcVVector = displacementTransform->TransformCovariantVector( testcVVector, testPoint );
if( !sameVariableVector( deformcVVector, deformcVVectorTruth, tolerance ) )
{
std::cout << "Error transforming variable length covariant vector: "
<< "TransformCovariantVector(...)" << std::endl;
std::cout << "Test failed!" << std::endl;
return EXIT_FAILURE;
}
TRY_EXPECT_EXCEPTION( deformcVVector =
displacementTransform->TransformCovariantVector( testcVVector ) );
DisplacementTransformType::InputDiffusionTensor3DType testTensor;
DisplacementTransformType::OutputDiffusionTensor3DType deformTensor,
deformTensorTruth;
testTensor[0] = 3;
testTensor[1] = 0.01;
testTensor[2] = 0.01;
testTensor[3] = 2;
testTensor[4] = 0.01;
testTensor[5] = 1;
// Pass thru functionality only for now
deformTensorTruth = affineTransform->TransformDiffusionTensor3D( testTensor );
deformTensor = displacementTransform->TransformDiffusionTensor3D(
testTensor, testPoint );
tolerance = 1e-4;
if( !sameTensor( deformTensor, deformTensorTruth, tolerance ) )
{
std::cout << "Error transforming tensor: TransformDiffusionTensor3D(...)"
<< std::endl;
std::cout << "Test failed!" << std::endl;
// ToDo
// Check this case. See
// https://insightsoftwareconsortium.atlassian.net/browse/ITK-3537
//return EXIT_FAILURE;
}
TRY_EXPECT_EXCEPTION( deformTensor =
displacementTransform->TransformDiffusionTensor( testTensor ) );
// Test setting parameters with wrong size
DisplacementTransformType::ParametersType paramsWrongSize( 1 );
paramsWrongSize.Fill( 0 );
TRY_EXPECT_EXCEPTION( displacementTransform->SetParameters( paramsWrongSize ) );
// Test UpdateTransformParameters
DisplacementTransformType::DerivativeType derivative(
displacementTransform->GetNumberOfParameters() );
DisplacementTransformType::DerivativeType updateTruth(
displacementTransform->GetNumberOfParameters() );
DisplacementTransformType::ParametersType params(
displacementTransform->GetNumberOfParameters() );
derivative.Fill( 1.2 );
ScalarType testFactor = 1.5;
for( unsigned int i = 0;
i < displacementTransform->GetNumberOfParameters(); i++ )
{
params[i] = i;
updateTruth[i] = params[i] + derivative[i] * testFactor;
}
displacementTransform->SetParameters( params );
displacementTransform->UpdateTransformParameters( derivative, testFactor );
params = displacementTransform->GetParameters();
for( unsigned int i = 0;
i < displacementTransform->GetNumberOfParameters(); i++ )
{
if( itk::Math::NotExactlyEquals( params[i], updateTruth[i] ) )
{
std::cout << "Test failed!" << std::endl;
std::cout << "Error in UpdateTransformParameters(...) at index ["
<< i << "]" << std::endl;
std::cout << "Expected: "
<< static_cast< itk::NumericTraits<
DisplacementTransformType::DerivativeType::ValueType >::PrintType >( updateTruth[i] )
<< ", but got: "
<< static_cast< itk::NumericTraits<
DisplacementTransformType::ParametersType::ValueType >::PrintType >( params[i] )
<< std::endl;
return EXIT_FAILURE;
}
}
// Test IsLinear(): should always return false
if( displacementTransform->IsLinear() )
{
std::cout << "DisplacementFieldTransform returned 'true' for IsLinear()."
<< " Expected 'false'." << std::endl;
return EXIT_FAILURE;
}
// Exercise other methods to improve coverage
//
std::cout << "DisplacementFieldSetTime: " <<
static_cast< itk::NumericTraits< itk::ModifiedTimeType >::PrintType >(
displacementTransform->GetDisplacementFieldSetTime() ) << std::endl;
// The inverse displacement field for the inverse displacement transform must
// have been set to nullptr when calling SetDisplacementField(), so
// 'false' should be returned here
DisplacementTransformType::Pointer inverseTransform = DisplacementTransformType::New();
if( displacementTransform->GetInverse( inverseTransform ) )
{
std::cout << "Test failed!" << std::endl;
std::cout << "Expected GetInverse() to return 'false'." << std::endl;
return EXIT_FAILURE;
}
// Set the inverse displacement field
displacementTransform->SetInverseDisplacementField( field );
displacementTransform->SetIdentity();
// Create a new one with null for both fields
displacementTransform = DisplacementTransformType::New();
displacementTransform->SetIdentity();
displacementTransform->SetDisplacementField( nullptr );
displacementTransform->SetInverseDisplacementField( nullptr );
// Check setting all zero for fixed parameters
displacementTransform = DisplacementTransformType::New();
fixedParameters = displacementTransform->GetFixedParameters();
fixedParameters.Fill( 0.0 );
displacementTransform->SetFixedParameters( fixedParameters );
std::cout << "Test finished." << std::endl;
return EXIT_SUCCESS;
}
| 34.429864
| 108
| 0.693389
|
yjcchen0913
|
b44482363780ee5e513c8c3f528e30e95abcbb16
| 845
|
cpp
|
C++
|
6. Polymorphism/3. Operator Overloading/5. Unary Operators/2.Negative.cpp
|
Imran4424/C-Plus-Plus-Object-Oriented
|
a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79
|
[
"MIT"
] | 3
|
2019-11-06T15:43:06.000Z
|
2020-06-05T10:47:28.000Z
|
6. Polymorphism/3. Operator Overloading/5. Unary Operators/2.Negative.cpp
|
Imran4424/C-Plus-Plus-Object-Oriented
|
a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79
|
[
"MIT"
] | null | null | null |
6. Polymorphism/3. Operator Overloading/5. Unary Operators/2.Negative.cpp
|
Imran4424/C-Plus-Plus-Object-Oriented
|
a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79
|
[
"MIT"
] | 1
|
2019-09-06T03:37:08.000Z
|
2019-09-06T03:37:08.000Z
|
#include <iostream>
using namespace std;
class Data
{
private: int x,y;
private: bool isPositive;
public: Data()
{
x = 0;
y = 0;
isPositive = true;
}
public: Data(int x, int y, bool isPositive)
{
this -> x = x;
this -> y = y;
this -> isPositive = isPositive;
}
public: void Show()
{
cout << "X = " << x << endl;
cout << "Y = " << y << endl;
cout << "Is Postivie = " << boolalpha << isPositive << endl << endl;
}
public: Data operator+()
{
return Data(abs(x), abs(y), true);
}
public: Data operator-()
{
return Data(-abs(x), -abs(y), false);
}
};
int main(int argc, char const *argv[])
{
Data red(-5, -8, false);
red.Show();
(+red).Show();
// (red+).Show(); // this statement will give you error
// because unary operators sits left of operands
(-red).Show();
return 0;
}
| 15.089286
| 70
| 0.556213
|
Imran4424
|
b448dc3d9c08d44b0fc12e01038a2cd5d34f4957
| 50,384
|
cpp
|
C++
|
sp/src/vgui2/vgui_controls/AnimationController.cpp
|
jarnar85/source-sdk-2013
|
8c279299883421fd78e7691545522ea863e0b646
|
[
"Unlicense"
] | null | null | null |
sp/src/vgui2/vgui_controls/AnimationController.cpp
|
jarnar85/source-sdk-2013
|
8c279299883421fd78e7691545522ea863e0b646
|
[
"Unlicense"
] | 8
|
2019-09-07T10:19:52.000Z
|
2020-03-31T19:44:45.000Z
|
sp/src/vgui2/vgui_controls/AnimationController.cpp
|
jarnar85/source-sdk-2013
|
8c279299883421fd78e7691545522ea863e0b646
|
[
"Unlicense"
] | null | null | null |
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#pragma warning( disable : 4244 ) // conversion from 'double' to 'float', possible loss of data
#include <vgui/IScheme.h>
#include <vgui/ISurface.h>
#include <vgui/ISystem.h>
#include <vgui/IVGui.h>
#include <KeyValues.h>
#include <vgui_controls/AnimationController.h>
#include "filesystem.h"
#include "filesystem_helpers.h"
#include <stdio.h>
#include <math.h>
#include "mempool.h"
#include "utldict.h"
#include "mathlib/mathlib.h"
#include "characterset.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/dbg.h>
// for SRC
#include <vstdlib/random.h>
#include <tier0/memdbgon.h>
using namespace vgui;
static CUtlSymbolTable g_ScriptSymbols(0, 128, true);
// singleton accessor for animation controller for use by the vgui controls
namespace vgui
{
AnimationController *GetAnimationController()
{
static AnimationController *s_pAnimationController = new AnimationController(NULL);
return s_pAnimationController;
}
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
AnimationController::AnimationController(Panel *parent) : BaseClass(parent, NULL)
{
m_hSizePanel = 0;
m_nScreenBounds[ 0 ] = m_nScreenBounds[ 1 ] = -1;
m_nScreenBounds[ 2 ] = m_nScreenBounds[ 3 ] = -1;
m_bAutoReloadScript = false;
// always invisible
SetVisible(false);
SetProportional(true);
// get the names of common types
m_sPosition = g_ScriptSymbols.AddString("position");
m_sSize = g_ScriptSymbols.AddString("size");
m_sFgColor = g_ScriptSymbols.AddString("fgcolor");
m_sBgColor = g_ScriptSymbols.AddString("bgcolor");
m_sXPos = g_ScriptSymbols.AddString("xpos");
m_sYPos = g_ScriptSymbols.AddString("ypos");
m_sWide = g_ScriptSymbols.AddString("wide");
m_sTall = g_ScriptSymbols.AddString("tall");
m_flCurrentTime = 0.0f;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
AnimationController::~AnimationController()
{
}
//-----------------------------------------------------------------------------
// Purpose: Sets which script file to use
//-----------------------------------------------------------------------------
bool AnimationController::SetScriptFile( VPANEL sizingPanel, const char *fileName, bool wipeAll /*=false*/ )
{
m_hSizePanel = sizingPanel;
if ( wipeAll )
{
// clear the current script
m_Sequences.RemoveAll();
m_ScriptFileNames.RemoveAll();
CancelAllAnimations();
}
// Store off this filename for reloading later on (if we don't have it already)
UtlSymId_t sFilename = g_ScriptSymbols.AddString( fileName );
if ( m_ScriptFileNames.Find( sFilename ) == m_ScriptFileNames.InvalidIndex() )
{
m_ScriptFileNames.AddToTail( sFilename );
}
UpdateScreenSize();
// load the new script file
return LoadScriptFile( fileName );
}
//-----------------------------------------------------------------------------
// Purpose: reloads the currently set script file
//-----------------------------------------------------------------------------
void AnimationController::ReloadScriptFile()
{
// Clear all current sequences
m_Sequences.RemoveAll();
UpdateScreenSize();
// Reload each file we've loaded
for ( int i = 0; i < m_ScriptFileNames.Count(); i++ )
{
const char *lpszFilename = g_ScriptSymbols.String( m_ScriptFileNames[i] );
if ( strlen( lpszFilename ) > 0)
{
if ( LoadScriptFile( lpszFilename ) == false )
{
Assert( 0 );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: loads a script file from disk
//-----------------------------------------------------------------------------
bool AnimationController::LoadScriptFile(const char *fileName)
{
FileHandle_t f = g_pFullFileSystem->Open(fileName, "rt");
if (!f)
{
Warning("Couldn't find script file %s\n", fileName);
return false;
}
// read the whole thing into memory
int size = g_pFullFileSystem->Size(f);
// read into temporary memory block
int nBufSize = size+1;
if ( IsXbox() )
{
nBufSize = AlignValue( nBufSize, 512 );
}
char *pMem = (char *)malloc(nBufSize);
int bytesRead = g_pFullFileSystem->ReadEx(pMem, nBufSize, size, f);
Assert(bytesRead <= size);
pMem[bytesRead] = 0;
g_pFullFileSystem->Close(f);
// parse
bool success = ParseScriptFile(pMem, bytesRead);
free(pMem);
return success;
}
AnimationController::RelativeAlignmentLookup AnimationController::g_AlignmentLookup[] =
{
{ AnimationController::a_northwest , "northwest" },
{ AnimationController::a_north , "north" },
{ AnimationController::a_northeast , "northeast" },
{ AnimationController::a_west , "west" },
{ AnimationController::a_center , "center" },
{ AnimationController::a_east , "east" },
{ AnimationController::a_southwest , "southwest" },
{ AnimationController::a_south , "south" },
{ AnimationController::a_southeast , "southeast" },
{ AnimationController::a_northwest , "nw" },
{ AnimationController::a_north , "n" },
{ AnimationController::a_northeast , "ne" },
{ AnimationController::a_west , "w" },
{ AnimationController::a_center , "c" },
{ AnimationController::a_east , "e" },
{ AnimationController::a_southwest , "sw" },
{ AnimationController::a_south , "s" },
{ AnimationController::a_southeast , "se" },
};
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
AnimationController::RelativeAlignment AnimationController::LookupAlignment( char const *token )
{
int c = ARRAYSIZE( g_AlignmentLookup );
for ( int i = 0; i < c; i++ )
{
if ( !Q_stricmp( token, g_AlignmentLookup[ i ].name ) )
{
return g_AlignmentLookup[ i ].align;
}
}
return AnimationController::a_northwest;
}
//-----------------------------------------------------------------------------
// Purpose: Parse position including right edge and center adjustment out of a
// token. This is relative to the screen
//-----------------------------------------------------------------------------
void AnimationController::SetupPosition( AnimCmdAnimate_t& cmd, float *output, char const *psz, int screendimension )
{
bool r = false, c = false;
int pos;
if ( psz[0] == '(' )
{
psz++;
if ( Q_strstr( psz, ")" ) )
{
char sz[ 256 ];
Q_strncpy( sz, psz, sizeof( sz ) );
char *colon = Q_strstr( sz, ":" );
if ( colon )
{
*colon = 0;
RelativeAlignment ra = LookupAlignment( sz );
colon++;
char *panelName = colon;
char *panelEnd = Q_strstr( panelName, ")" );
if ( panelEnd )
{
*panelEnd = 0;
if ( Q_strlen( panelName ) > 0 )
{
//
cmd.align.relativePosition = true;
cmd.align.alignPanel = g_ScriptSymbols.AddString(panelName);
cmd.align.alignment = ra;
}
}
}
psz = Q_strstr( psz, ")" ) + 1;
}
}
else if (psz[0] == 'r' || psz[0] == 'R')
{
r = true;
psz++;
}
else if (psz[0] == 'c' || psz[0] == 'C')
{
c = true;
psz++;
}
// get the number
pos = atoi(psz);
// scale the values
if (IsProportional())
{
pos = vgui::scheme()->GetProportionalScaledValueEx( GetScheme(), pos );
}
// adjust the positions
if (r)
{
pos = screendimension - pos;
}
if (c)
{
pos = (screendimension / 2) + pos;
}
// set the value
*output = static_cast<float>( pos );
}
//-----------------------------------------------------------------------------
// Purpose: parses a script into sequences
//-----------------------------------------------------------------------------
bool AnimationController::ParseScriptFile(char *pMem, int length)
{
// get the scheme (for looking up color names)
IScheme *scheme = vgui::scheme()->GetIScheme(GetScheme());
// get our screen size (for left/right/center alignment)
int screenWide = m_nScreenBounds[ 2 ];
int screenTall = m_nScreenBounds[ 3 ];
// start by getting the first token
char token[512];
pMem = ParseFile(pMem, token, NULL);
while (token[0])
{
bool bAccepted = true;
// should be 'event'
if (stricmp(token, "event"))
{
Warning("Couldn't parse script file: expected 'event', found '%s'\n", token);
return false;
}
// get the event name
pMem = ParseFile(pMem, token, NULL);
if (strlen(token) < 1)
{
Warning("Couldn't parse script file: expected <event name>, found nothing\n");
return false;
}
int seqIndex;
UtlSymId_t nameIndex = g_ScriptSymbols.AddString(token);
// Create a new sequence
seqIndex = m_Sequences.AddToTail();
AnimSequence_t &seq = m_Sequences[seqIndex];
seq.name = nameIndex;
seq.duration = 0.0f;
// get the open brace or a conditional
pMem = ParseFile(pMem, token, NULL);
if ( Q_stristr( token, "[$" ) )
{
bAccepted = EvaluateConditional( token );
// now get the open brace
pMem = ParseFile(pMem, token, NULL);
}
if (stricmp(token, "{"))
{
Warning("Couldn't parse script sequence '%s': expected '{', found '%s'\n", g_ScriptSymbols.String(seq.name), token);
return false;
}
// walk the commands
while (token[0])
{
// get the command type
pMem = ParseFile(pMem, token, NULL);
// skip out when we hit the end of the sequence
if (token[0] == '}')
break;
// create a new command
int cmdIndex = seq.cmdList.AddToTail();
AnimCommand_t &animCmd = seq.cmdList[cmdIndex];
memset(&animCmd, 0, sizeof(animCmd));
if (!stricmp(token, "animate"))
{
animCmd.commandType = CMD_ANIMATE;
// parse out the animation commands
AnimCmdAnimate_t &cmdAnimate = animCmd.cmdData.animate;
// panel to manipulate
pMem = ParseFile(pMem, token, NULL);
cmdAnimate.panel = g_ScriptSymbols.AddString(token);
// variable to change
pMem = ParseFile(pMem, token, NULL);
cmdAnimate.variable = g_ScriptSymbols.AddString(token);
// target value
pMem = ParseFile(pMem, token, NULL);
if (cmdAnimate.variable == m_sPosition)
{
// Get first token
SetupPosition( cmdAnimate, &cmdAnimate.target.a, token, screenWide );
// Get second token from "token"
char token2[32];
char *psz = ParseFile(token, token2, NULL);
psz = ParseFile(psz, token2, NULL);
psz = token2;
// Position Y goes into ".b"
SetupPosition( cmdAnimate, &cmdAnimate.target.b, psz, screenTall );
}
else if ( cmdAnimate.variable == m_sXPos )
{
// XPos and YPos both use target ".a"
SetupPosition( cmdAnimate, &cmdAnimate.target.a, token, screenWide );
}
else if ( cmdAnimate.variable == m_sYPos )
{
// XPos and YPos both use target ".a"
SetupPosition( cmdAnimate, &cmdAnimate.target.a, token, screenTall );
}
else
{
// parse the floating point values right out
if (0 == sscanf(token, "%f %f %f %f", &cmdAnimate.target.a, &cmdAnimate.target.b, &cmdAnimate.target.c, &cmdAnimate.target.d))
{
//=============================================================================
// HPE_BEGIN:
// [pfreese] Improved handling colors not defined in scheme
//=============================================================================
// could be referencing a value in the scheme file, lookup
Color default_invisible_black(0, 0, 0, 0);
Color col = scheme->GetColor(token, default_invisible_black);
// we don't have a way of seeing if the color is not declared in the scheme, so we use this
// silly method of trying again with a different default to see if we get the fallback again
if (col == default_invisible_black)
{
Color error_pink(255, 0, 255, 255); // make it extremely obvious if a scheme lookup fails
col = scheme->GetColor(token, error_pink);
// commented out for Soldier/Demo release...(getting spammed in console)
// we'll try to figure this out after the update is out
// if (col == error_pink)
// {
// Warning("Missing color in scheme: %s\n", token);
// }
}
//=============================================================================
// HPE_END
//=============================================================================
cmdAnimate.target.a = col[0];
cmdAnimate.target.b = col[1];
cmdAnimate.target.c = col[2];
cmdAnimate.target.d = col[3];
}
}
// fix up scale
if (cmdAnimate.variable == m_sSize)
{
if (IsProportional())
{
cmdAnimate.target.a = static_cast<float>( vgui::scheme()->GetProportionalScaledValueEx(GetScheme(), cmdAnimate.target.a) );
cmdAnimate.target.b = static_cast<float>( vgui::scheme()->GetProportionalScaledValueEx(GetScheme(), cmdAnimate.target.b) );
}
}
else if (cmdAnimate.variable == m_sWide ||
cmdAnimate.variable == m_sTall )
{
if (IsProportional())
{
// Wide and tall both use.a
cmdAnimate.target.a = static_cast<float>( vgui::scheme()->GetProportionalScaledValueEx(GetScheme(), cmdAnimate.target.a) );
}
}
// interpolation function
pMem = ParseFile(pMem, token, NULL);
if (!stricmp(token, "Accel"))
{
cmdAnimate.interpolationFunction = INTERPOLATOR_ACCEL;
}
else if (!stricmp(token, "Deaccel"))
{
cmdAnimate.interpolationFunction = INTERPOLATOR_DEACCEL;
}
else if ( !stricmp(token, "Spline"))
{
cmdAnimate.interpolationFunction = INTERPOLATOR_SIMPLESPLINE;
}
else if (!stricmp(token,"Pulse"))
{
cmdAnimate.interpolationFunction = INTERPOLATOR_PULSE;
// frequencey
pMem = ParseFile(pMem, token, NULL);
cmdAnimate.interpolationParameter = (float)atof(token);
}
else if ( !stricmp( token, "Flicker"))
{
cmdAnimate.interpolationFunction = INTERPOLATOR_FLICKER;
// noiseamount
pMem = ParseFile(pMem, token, NULL);
cmdAnimate.interpolationParameter = (float)atof(token);
}
else if (!stricmp(token, "Bounce"))
{
cmdAnimate.interpolationFunction = INTERPOLATOR_BOUNCE;
}
else
{
cmdAnimate.interpolationFunction = INTERPOLATOR_LINEAR;
}
// start time
pMem = ParseFile(pMem, token, NULL);
cmdAnimate.startTime = (float)atof(token);
// duration
pMem = ParseFile(pMem, token, NULL);
cmdAnimate.duration = (float)atof(token);
// check max duration
if (cmdAnimate.startTime + cmdAnimate.duration > seq.duration)
{
seq.duration = cmdAnimate.startTime + cmdAnimate.duration;
}
}
else if (!stricmp(token, "runevent"))
{
animCmd.commandType = CMD_RUNEVENT;
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.event = g_ScriptSymbols.AddString(token);
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.timeDelay = (float)atof(token);
}
else if (!stricmp(token, "stopevent"))
{
animCmd.commandType = CMD_STOPEVENT;
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.event = g_ScriptSymbols.AddString(token);
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.timeDelay = (float)atof(token);
}
else if (!stricmp(token, "StopPanelAnimations"))
{
animCmd.commandType = CMD_STOPPANELANIMATIONS;
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.event = g_ScriptSymbols.AddString(token);
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.timeDelay = (float)atof(token);
}
else if (!stricmp(token, "stopanimation"))
{
animCmd.commandType = CMD_STOPANIMATION;
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.event = g_ScriptSymbols.AddString(token);
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.variable = g_ScriptSymbols.AddString(token);
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.timeDelay = (float)atof(token);
}
else if ( !stricmp( token, "SetFont" ))
{
animCmd.commandType = CMD_SETFONT;
// Panel name
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.event = g_ScriptSymbols.AddString(token);
// Font parameter
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.variable = g_ScriptSymbols.AddString(token);
// Font name from scheme
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.variable2 = g_ScriptSymbols.AddString(token);
// Set time
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.timeDelay = (float)atof(token);
}
else if ( !stricmp( token, "SetTexture" ))
{
animCmd.commandType = CMD_SETTEXTURE;
// Panel name
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.event = g_ScriptSymbols.AddString(token);
// Texture Id
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.variable = g_ScriptSymbols.AddString(token);
// material name
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.variable2 = g_ScriptSymbols.AddString(token);
// Set time
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.timeDelay = (float)atof(token);
}
else if ( !stricmp( token, "SetString" ))
{
animCmd.commandType = CMD_SETSTRING;
// Panel name
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.event = g_ScriptSymbols.AddString(token);
// String variable name
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.variable = g_ScriptSymbols.AddString(token);
// String value to set
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.variable2 = g_ScriptSymbols.AddString(token);
// Set time
pMem = ParseFile(pMem, token, NULL);
animCmd.cmdData.runEvent.timeDelay = (float)atof(token);
}
else
{
Warning("Couldn't parse script sequence '%s': expected <anim command>, found '%s'\n", g_ScriptSymbols.String(seq.name), token);
return false;
}
// Look ahead one token for a conditional
char *peek = ParseFile(pMem, token, NULL);
if ( Q_stristr( token, "[$" ) )
{
if ( !EvaluateConditional( token ) )
{
seq.cmdList.Remove( cmdIndex );
}
pMem = peek;
}
}
if ( bAccepted )
{
// Attempt to find a collision in the sequences, replacing the old one if found
int seqIterator;
for ( seqIterator = 0; seqIterator < m_Sequences.Count()-1; seqIterator++ )
{
if ( m_Sequences[seqIterator].name == nameIndex )
{
// Get rid of it, we're overriding it
m_Sequences.Remove( seqIndex );
break;
}
}
}
else
{
// Dump the entire sequence
m_Sequences.Remove( seqIndex );
}
// get the next token, if any
pMem = ParseFile(pMem, token, NULL);
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: checks all posted animation events, firing if time
//-----------------------------------------------------------------------------
void AnimationController::UpdatePostedMessages(bool bRunToCompletion)
{
CUtlVector<RanEvent_t> eventsRanThisFrame;
// check all posted messages
for (int i = 0; i < m_PostedMessages.Count(); i++)
{
PostedMessage_t &msgRef = m_PostedMessages[i];
if (m_flCurrentTime < msgRef.startTime && !bRunToCompletion)
continue;
// take a copy of th message
PostedMessage_t msg = msgRef;
// remove the event
// do this before handling the message because the message queue may be messed with
m_PostedMessages.Remove(i);
// reset the count, start the whole queue again
i = -1;
// handle the event
switch (msg.commandType)
{
case CMD_RUNEVENT:
{
RanEvent_t curEvent;
curEvent.event = msg.event;
curEvent.pParent = msg.parent.Get();
// run the event, but only if we haven't already run it this frame, for this parent
if (!eventsRanThisFrame.HasElement(curEvent))
{
eventsRanThisFrame.AddToTail(curEvent);
RunCmd_RunEvent(msg);
}
}
break;
case CMD_STOPEVENT:
RunCmd_StopEvent(msg);
break;
case CMD_STOPPANELANIMATIONS:
RunCmd_StopPanelAnimations(msg);
break;
case CMD_STOPANIMATION:
RunCmd_StopAnimation(msg);
break;
case CMD_SETFONT:
RunCmd_SetFont(msg);
break;
case CMD_SETTEXTURE:
RunCmd_SetTexture(msg);
break;
case CMD_SETSTRING:
RunCmd_SetString( msg );
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: runs the current animations
//-----------------------------------------------------------------------------
void AnimationController::UpdateActiveAnimations(bool bRunToCompletion)
{
// iterate all the currently active animations
for (int i = 0; i < m_ActiveAnimations.Count(); i++)
{
ActiveAnimation_t &anim = m_ActiveAnimations[i];
// see if the anim is ready to start
if (m_flCurrentTime < anim.startTime && !bRunToCompletion)
continue;
if (!anim.panel.Get())
{
// panel is gone, remove the animation
m_ActiveAnimations.Remove(i);
--i;
continue;
}
if (!anim.started && !bRunToCompletion)
{
// start the animation from the current value
anim.startValue = GetValue(anim, anim.panel, anim.variable);
anim.started = true;
// Msg( "Starting animation of %s => %.2f (seq: %s) (%s)\n", g_ScriptSymbols.String(anim.variable), anim.endValue.a, g_ScriptSymbols.String(anim.seqName), anim.panel->GetName());
}
// get the interpolated value
Value_t val;
if (m_flCurrentTime >= anim.endTime || bRunToCompletion)
{
// animation is done, use the last value
val = anim.endValue;
}
else
{
// get the interpolated value
val = GetInterpolatedValue(anim.interpolator, anim.interpolatorParam, m_flCurrentTime, anim.startTime, anim.endTime, anim.startValue, anim.endValue);
}
// apply the new value to the panel
SetValue(anim, anim.panel, anim.variable, val);
// Msg( "Animate value: %s => %.2f for panel '%s'\n", g_ScriptSymbols.String(anim.variable), val.a, anim.panel->GetName());
// see if we can remove the animation
if (m_flCurrentTime >= anim.endTime || bRunToCompletion)
{
m_ActiveAnimations.Remove(i);
--i;
}
}
}
bool AnimationController::UpdateScreenSize()
{
// get our screen size (for left/right/center alignment)
int screenWide, screenTall;
int sx = 0, sy = 0;
if ( m_hSizePanel != 0 )
{
ipanel()->GetSize( m_hSizePanel, screenWide, screenTall );
ipanel()->GetPos( m_hSizePanel, sx, sy );
}
else
{
surface()->GetScreenSize(screenWide, screenTall);
}
bool changed = m_nScreenBounds[ 0 ] != sx ||
m_nScreenBounds[ 1 ] != sy ||
m_nScreenBounds[ 2 ] != screenWide ||
m_nScreenBounds[ 3 ] != screenTall;
m_nScreenBounds[ 0 ] = sx;
m_nScreenBounds[ 1 ] = sy;
m_nScreenBounds[ 2 ] = screenWide;
m_nScreenBounds[ 3 ] = screenTall;
return changed;
}
//-----------------------------------------------------------------------------
// Purpose: runs a frame of animation
//-----------------------------------------------------------------------------
void AnimationController::UpdateAnimations( float currentTime )
{
m_flCurrentTime = currentTime;
if ( UpdateScreenSize() && m_ScriptFileNames.Count() )
{
RunAllAnimationsToCompletion();
ReloadScriptFile();
}
UpdatePostedMessages(false);
UpdateActiveAnimations(false);
}
//-----------------------------------------------------------------------------
// Purpose: plays all animations to completion instantly
//-----------------------------------------------------------------------------
void AnimationController::RunAllAnimationsToCompletion()
{
// Msg( "AnimationController::RunAllAnimationsToCompletion()\n" );
UpdatePostedMessages(true);
UpdateActiveAnimations(true);
}
//-----------------------------------------------------------------------------
// Purpose: Stops all current animations
//-----------------------------------------------------------------------------
void AnimationController::CancelAllAnimations()
{
// Msg( "AnimationController::CancelAllAnimations()\n" );
m_ActiveAnimations.RemoveAll();
m_PostedMessages.RemoveAll();
}
//-----------------------------------------------------------------------------
// Purpose: produces an interpolated value
//-----------------------------------------------------------------------------
AnimationController::Value_t AnimationController::GetInterpolatedValue(int interpolator, float interpolatorParam, float currentTime, float startTime, float endTime, Value_t &startValue, Value_t &endValue)
{
// calculate how far we are into the animation
float pos = (currentTime - startTime) / (endTime - startTime);
// adjust the percentage through by the interpolation function
switch (interpolator)
{
case INTERPOLATOR_ACCEL:
pos *= pos;
break;
case INTERPOLATOR_DEACCEL:
pos = sqrtf(pos);
break;
case INTERPOLATOR_SIMPLESPLINE:
pos = SimpleSpline( pos );
break;
case INTERPOLATOR_PULSE:
// Make sure we end at 1.0, so use cosine
pos = 0.5f + 0.5f * ( cos( pos * 2.0f * M_PI * interpolatorParam ) );
break;
case INTERPOLATOR_FLICKER:
if ( RandomFloat( 0.0f, 1.0f ) < interpolatorParam )
{
pos = 1.0f;
}
else
{
pos = 0.0f;
}
break;
case INTERPOLATOR_BOUNCE:
{
// fall from startValue to endValue, bouncing a few times and settling out at endValue
const float hit1 = 0.33f;
const float hit2 = 0.67f;
const float hit3 = 1.0f;
if ( pos < hit1 )
{
pos = 1.0f - sin( M_PI * pos / hit1 );
}
else if ( pos < hit2 )
{
pos = 0.5f + 0.5f * ( 1.0f - sin( M_PI * ( pos - hit1 ) / ( hit2 - hit1 ) ) );
}
else
{
pos = 0.8f + 0.2f * ( 1.0f - sin( M_PI * ( pos - hit2 ) / ( hit3 - hit2 ) ) );
}
break;
}
case INTERPOLATOR_LINEAR:
default:
break;
}
// calculate the value
Value_t val;
val.a = ((endValue.a - startValue.a) * pos) + startValue.a;
val.b = ((endValue.b - startValue.b) * pos) + startValue.b;
val.c = ((endValue.c - startValue.c) * pos) + startValue.c;
val.d = ((endValue.d - startValue.d) * pos) + startValue.d;
return val;
}
//-----------------------------------------------------------------------------
// Purpose: sets that the script file should be reloaded each time a script is ran
// used for development
//-----------------------------------------------------------------------------
void AnimationController::SetAutoReloadScript(bool state)
{
m_bAutoReloadScript = state;
}
//-----------------------------------------------------------------------------
// Purpose: starts an animation sequence script
//-----------------------------------------------------------------------------
bool AnimationController::StartAnimationSequence(const char *sequenceName)
{
// We support calling an animation on elements that are not the calling
// panel's children. Use the base parent to start the search.
return StartAnimationSequence(GetParent(), sequenceName);
}
//-----------------------------------------------------------------------------
// Purpose: starts an animation sequence script
//-----------------------------------------------------------------------------
bool AnimationController::StartAnimationSequence(const char *sequenceName, const char *sequenceFallback)
{
if (!StartAnimationSequence(GetParent(), sequenceName))
return StartAnimationSequence(GetParent(), sequenceFallback);
return true;
}
//-----------------------------------------------------------------------------
// Purpose: starts an animation sequence script
//-----------------------------------------------------------------------------
bool AnimationController::StartAnimationSequence(Panel *pWithinParent, const char *sequenceName)
{
Assert( pWithinParent );
if (m_bAutoReloadScript)
{
// Reload the script files
ReloadScriptFile();
}
// lookup the symbol for the name
UtlSymId_t seqName = g_ScriptSymbols.Find(sequenceName);
if (seqName == UTL_INVAL_SYMBOL)
return false;
// Msg("Starting animation sequence %s\n", sequenceName);
// remove the existing command from the queue
RemoveQueuedAnimationCommands(seqName, pWithinParent);
// look through for the sequence
int i;
for (i = 0; i < m_Sequences.Count(); i++)
{
if (m_Sequences[i].name == seqName)
break;
}
if (i >= m_Sequences.Count())
return false;
// execute the sequence
for (int cmdIndex = 0; cmdIndex < m_Sequences[i].cmdList.Count(); cmdIndex++)
{
ExecAnimationCommand(seqName, m_Sequences[i].cmdList[cmdIndex], pWithinParent);
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Runs a custom command from code, not from a script file
//-----------------------------------------------------------------------------
void AnimationController::RunAnimationCommand(vgui::Panel *panel, const char *variable, float targetValue, float startDelaySeconds, float duration, Interpolators_e interpolator, float animParameter /* = 0 */ )
{
// clear any previous animations of this variable
UtlSymId_t var = g_ScriptSymbols.AddString(variable);
RemoveQueuedAnimationByType(panel, var, UTL_INVAL_SYMBOL);
// build a new animation
AnimCmdAnimate_t animateCmd;
memset(&animateCmd, 0, sizeof(animateCmd));
animateCmd.panel = 0;
animateCmd.variable = var;
animateCmd.target.a = targetValue;
animateCmd.interpolationFunction = interpolator;
animateCmd.interpolationParameter = animParameter;
animateCmd.startTime = startDelaySeconds;
animateCmd.duration = duration;
// start immediately
StartCmd_Animate(panel, 0, animateCmd);
}
//-----------------------------------------------------------------------------
// Purpose: Runs a custom command from code, not from a script file
//-----------------------------------------------------------------------------
void AnimationController::RunAnimationCommand(vgui::Panel *panel, const char *variable, Color targetValue, float startDelaySeconds, float duration, Interpolators_e interpolator, float animParameter /* = 0 */ )
{
// clear any previous animations of this variable
UtlSymId_t var = g_ScriptSymbols.AddString(variable);
RemoveQueuedAnimationByType(panel, var, UTL_INVAL_SYMBOL);
// build a new animation
AnimCmdAnimate_t animateCmd;
memset(&animateCmd, 0, sizeof(animateCmd));
animateCmd.panel = 0;
animateCmd.variable = var;
animateCmd.target.a = targetValue[0];
animateCmd.target.b = targetValue[1];
animateCmd.target.c = targetValue[2];
animateCmd.target.d = targetValue[3];
animateCmd.interpolationFunction = interpolator;
animateCmd.interpolationParameter = animParameter;
animateCmd.startTime = startDelaySeconds;
animateCmd.duration = duration;
// start immediately
StartCmd_Animate(panel, 0, animateCmd);
}
//-----------------------------------------------------------------------------
// Purpose: gets the length of an animation sequence, in seconds
//-----------------------------------------------------------------------------
float AnimationController::GetAnimationSequenceLength(const char *sequenceName)
{
// lookup the symbol for the name
UtlSymId_t seqName = g_ScriptSymbols.Find(sequenceName);
if (seqName == UTL_INVAL_SYMBOL)
return 0.0f;
// look through for the sequence
int i;
for (i = 0; i < m_Sequences.Count(); i++)
{
if (m_Sequences[i].name == seqName)
break;
}
if (i >= m_Sequences.Count())
return 0.0f;
// sequence found
return m_Sequences[i].duration;
}
//-----------------------------------------------------------------------------
// Purpose: removes an existing set of commands from the queue
//-----------------------------------------------------------------------------
void AnimationController::RemoveQueuedAnimationCommands(UtlSymId_t seqName, Panel *pWithinParent)
{
// Msg("Removing queued anims for sequence %s\n", g_ScriptSymbols.String(seqName));
// remove messages posted by this sequence
// if pWithinParent is specified, remove only messages under that parent
{for (int i = 0; i < m_PostedMessages.Count(); i++)
{
if ( ( m_PostedMessages[i].seqName == seqName ) &&
( !pWithinParent || ( m_PostedMessages[i].parent == pWithinParent ) ) )
{
m_PostedMessages.Remove(i);
--i;
}
}}
// remove all animations
// if pWithinParent is specified, remove only animations under that parent
for (int i = 0; i < m_ActiveAnimations.Count(); i++)
{
if ( m_ActiveAnimations[i].seqName != seqName )
continue;
// panel this anim is on, m_ActiveAnimations[i].panel
if ( pWithinParent )
{
Panel *animPanel = m_ActiveAnimations[i].panel;
if ( !animPanel )
continue;
Panel *foundPanel = pWithinParent->FindChildByName(animPanel->GetName(),true);
if ( foundPanel != animPanel )
continue;
}
m_ActiveAnimations.Remove(i);
--i;
}
}
//-----------------------------------------------------------------------------
// Purpose: removes the specified queued animation
//-----------------------------------------------------------------------------
void AnimationController::RemoveQueuedAnimationByType(vgui::Panel *panel, UtlSymId_t variable, UtlSymId_t sequenceToIgnore)
{
for (int i = 0; i < m_ActiveAnimations.Count(); i++)
{
if (m_ActiveAnimations[i].panel == panel && m_ActiveAnimations[i].variable == variable && m_ActiveAnimations[i].seqName != sequenceToIgnore)
{
// Msg("Removing queued anim %s::%s::%s\n", g_ScriptSymbols.String(m_ActiveAnimations[i].seqName), panel->GetName(), g_ScriptSymbols.String(variable));
m_ActiveAnimations.Remove(i);
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: runs a single line of the script
//-----------------------------------------------------------------------------
void AnimationController::ExecAnimationCommand(UtlSymId_t seqName, AnimCommand_t &animCommand, Panel *pWithinParent)
{
if (animCommand.commandType == CMD_ANIMATE)
{
StartCmd_Animate(seqName, animCommand.cmdData.animate, pWithinParent);
}
else
{
// post the command to happen at the specified time
PostedMessage_t &msg = m_PostedMessages[m_PostedMessages.AddToTail()];
msg.seqName = seqName;
msg.commandType = animCommand.commandType;
msg.event = animCommand.cmdData.runEvent.event;
msg.variable = animCommand.cmdData.runEvent.variable;
msg.variable2 = animCommand.cmdData.runEvent.variable2;
msg.startTime = m_flCurrentTime + animCommand.cmdData.runEvent.timeDelay;
msg.parent = pWithinParent;
}
}
//-----------------------------------------------------------------------------
// Purpose: starts a variable animation
//-----------------------------------------------------------------------------
void AnimationController::StartCmd_Animate(UtlSymId_t seqName, AnimCmdAnimate_t &cmd, Panel *pWithinParent)
{
Assert( pWithinParent );
if ( !pWithinParent )
return;
// make sure the child exists
Panel *panel = pWithinParent->FindChildByName(g_ScriptSymbols.String(cmd.panel),true);
if ( !panel )
{
// Check the parent
Panel *parent = GetParent();
if ( !Q_stricmp( parent->GetName(), g_ScriptSymbols.String(cmd.panel) ) )
{
panel = parent;
}
}
if (!panel)
return;
StartCmd_Animate(panel, seqName, cmd);
}
//-----------------------------------------------------------------------------
// Purpose: Starts an animation command for the specified panel
//-----------------------------------------------------------------------------
void AnimationController::StartCmd_Animate(Panel *panel, UtlSymId_t seqName, AnimCmdAnimate_t &cmd)
{
// build a command to add to the animation queue
ActiveAnimation_t &anim = m_ActiveAnimations[m_ActiveAnimations.AddToTail()];
anim.panel = panel;
anim.seqName = seqName;
anim.variable = cmd.variable;
anim.interpolator = cmd.interpolationFunction;
anim.interpolatorParam = cmd.interpolationParameter;
// timings
anim.startTime = m_flCurrentTime + cmd.startTime;
anim.endTime = anim.startTime + cmd.duration;
// values
anim.started = false;
anim.endValue = cmd.target;
anim.align = cmd.align;
}
//-----------------------------------------------------------------------------
// Purpose: a posted message to run another event
//-----------------------------------------------------------------------------
void AnimationController::RunCmd_RunEvent(PostedMessage_t &msg)
{
StartAnimationSequence(msg.parent.Get(), g_ScriptSymbols.String(msg.event));
}
//-----------------------------------------------------------------------------
// Purpose: a posted message to stop another event
//-----------------------------------------------------------------------------
void AnimationController::RunCmd_StopEvent(PostedMessage_t &msg)
{
RemoveQueuedAnimationCommands(msg.event, msg.parent);
}
//-----------------------------------------------------------------------------
// Purpose: a posted message to stop all animations relevant to a specified panel
//-----------------------------------------------------------------------------
void AnimationController::RunCmd_StopPanelAnimations(PostedMessage_t &msg)
{
Panel *panel = FindSiblingByName(g_ScriptSymbols.String(msg.event));
Assert(panel != NULL);
if (!panel)
return;
// loop through all the active animations cancelling any that
// are operating on said panel, except for the event specified
for (int i = 0; i < m_ActiveAnimations.Count(); i++)
{
if (m_ActiveAnimations[i].panel == panel && m_ActiveAnimations[i].seqName != msg.seqName)
{
m_ActiveAnimations.Remove(i);
--i;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: a posted message to stop animations of a specific type
//-----------------------------------------------------------------------------
void AnimationController::RunCmd_StopAnimation(PostedMessage_t &msg)
{
Panel *panel = FindSiblingByName(g_ScriptSymbols.String(msg.event));
Assert(panel != NULL);
if (!panel)
return;
RemoveQueuedAnimationByType(panel, msg.variable, msg.seqName);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void AnimationController::RunCmd_SetFont( PostedMessage_t &msg )
{
Panel *parent = msg.parent.Get();
if ( !parent )
{
parent = GetParent();
}
Panel *panel = parent->FindChildByName(g_ScriptSymbols.String(msg.event), true);
Assert(panel != NULL);
if (!panel)
return;
KeyValues *inputData = new KeyValues(g_ScriptSymbols.String(msg.variable));
inputData->SetString(g_ScriptSymbols.String(msg.variable), g_ScriptSymbols.String(msg.variable2));
if (!panel->SetInfo(inputData))
{
// Assert(!("Unhandlable var in AnimationController::SetValue())"));
}
inputData->deleteThis();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void AnimationController::RunCmd_SetTexture( PostedMessage_t &msg )
{
Panel *panel = FindSiblingByName(g_ScriptSymbols.String(msg.event));
Assert(panel != NULL);
if (!panel)
return;
KeyValues *inputData = new KeyValues(g_ScriptSymbols.String(msg.variable));
inputData->SetString(g_ScriptSymbols.String(msg.variable), g_ScriptSymbols.String(msg.variable2));
if (!panel->SetInfo(inputData))
{
// Assert(!("Unhandlable var in AnimationController::SetValue())"));
}
inputData->deleteThis();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void AnimationController::RunCmd_SetString( PostedMessage_t &msg )
{
Panel *panel = FindSiblingByName(g_ScriptSymbols.String(msg.event));
Assert(panel != NULL);
if (!panel)
return;
KeyValues *inputData = new KeyValues(g_ScriptSymbols.String(msg.variable));
inputData->SetString(g_ScriptSymbols.String(msg.variable), g_ScriptSymbols.String(msg.variable2));
if (!panel->SetInfo(inputData))
{
// Assert(!("Unhandlable var in AnimationController::SetValue())"));
}
inputData->deleteThis();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int AnimationController::GetRelativeOffset( AnimAlign_t& align, bool xcoord )
{
if ( !align.relativePosition )
return 0;
Panel *panel = GetParent()->FindChildByName(g_ScriptSymbols.String(align.alignPanel), true);
if ( !panel )
return 0;
int x, y, w, h;
panel->GetBounds( x, y, w, h );
int offset =0;
switch ( align.alignment )
{
default:
case a_northwest:
offset = xcoord ? x : y;
break;
case a_north:
offset = xcoord ? ( x + w ) / 2 : y;
break;
case a_northeast:
offset = xcoord ? ( x + w ) : y;
break;
case a_west:
offset = xcoord ? x : ( y + h ) / 2;
break;
case a_center:
offset = xcoord ? ( x + w ) / 2 : ( y + h ) / 2;
break;
case a_east:
offset = xcoord ? ( x + w ) : ( y + h ) / 2;
break;
case a_southwest:
offset = xcoord ? x : ( y + h );
break;
case a_south:
offset = xcoord ? ( x + w ) / 2 : ( y + h );
break;
case a_southeast:
offset = xcoord ? ( x + w ) : ( y + h );
break;
}
return offset;
}
//-----------------------------------------------------------------------------
// Purpose: Gets the specified value from a panel
//-----------------------------------------------------------------------------
AnimationController::Value_t AnimationController::GetValue(ActiveAnimation_t& anim, Panel *panel, UtlSymId_t var)
{
Value_t val = { 0, 0, 0, 0 };
if (var == m_sPosition)
{
int x, y;
panel->GetPos(x, y);
val.a = (float)(x - GetRelativeOffset( anim.align, true ) );
val.b = (float)(y - GetRelativeOffset( anim.align, false ) );
}
else if (var == m_sSize)
{
int w, t;
panel->GetSize(w, t);
val.a = (float)w;
val.b = (float)t;
}
else if (var == m_sFgColor)
{
Color col = panel->GetFgColor();
val.a = col[0];
val.b = col[1];
val.c = col[2];
val.d = col[3];
}
else if (var == m_sBgColor)
{
Color col = panel->GetBgColor();
val.a = col[0];
val.b = col[1];
val.c = col[2];
val.d = col[3];
}
else if ( var == m_sXPos )
{
int x, y;
panel->GetPos(x, y);
val.a = (float)( x - GetRelativeOffset( anim.align, true ) );
}
else if ( var == m_sYPos )
{
int x, y;
panel->GetPos(x, y);
val.a = (float)( y - GetRelativeOffset( anim.align, false ) );
}
else if ( var == m_sWide )
{
int w, h;
panel->GetSize(w, h);
val.a = (float)w;
}
else if ( var == m_sTall )
{
int w, h;
panel->GetSize(w, h);
val.a = (float)h;
}
else
{
KeyValues *outputData = new KeyValues(g_ScriptSymbols.String(var));
if (panel->RequestInfo(outputData))
{
// find the var and lookup it's type
KeyValues *kv = outputData->FindKey(g_ScriptSymbols.String(var));
if (kv && kv->GetDataType() == KeyValues::TYPE_FLOAT)
{
val.a = kv->GetFloat();
val.b = 0.0f;
val.c = 0.0f;
val.d = 0.0f;
}
else if (kv && kv->GetDataType() == KeyValues::TYPE_COLOR)
{
Color col = kv->GetColor();
val.a = col[0];
val.b = col[1];
val.c = col[2];
val.d = col[3];
}
}
else
{
// Assert(!("Unhandlable var in AnimationController::GetValue())"));
}
outputData->deleteThis();
}
return val;
}
//-----------------------------------------------------------------------------
// Purpose: Sets a value in a panel
//-----------------------------------------------------------------------------
void AnimationController::SetValue(ActiveAnimation_t& anim, Panel *panel, UtlSymId_t var, Value_t &value)
{
if (var == m_sPosition)
{
int x = (int)value.a + GetRelativeOffset( anim.align, true );
int y = (int)value.b + GetRelativeOffset( anim.align, false );
panel->SetPos(x, y);
}
else if (var == m_sSize)
{
panel->SetSize((int)value.a, (int)value.b);
}
else if (var == m_sFgColor)
{
Color col = panel->GetFgColor();
col[0] = (unsigned char)value.a;
col[1] = (unsigned char)value.b;
col[2] = (unsigned char)value.c;
col[3] = (unsigned char)value.d;
panel->SetFgColor(col);
}
else if (var == m_sBgColor)
{
Color col = panel->GetBgColor();
col[0] = (unsigned char)value.a;
col[1] = (unsigned char)value.b;
col[2] = (unsigned char)value.c;
col[3] = (unsigned char)value.d;
panel->SetBgColor(col);
}
else if (var == m_sXPos)
{
int newx = (int)value.a + GetRelativeOffset( anim.align, true );
int x, y;
panel->GetPos( x, y );
x = newx;
panel->SetPos(x, y);
}
else if (var == m_sYPos)
{
int newy = (int)value.a + GetRelativeOffset( anim.align, false );
int x, y;
panel->GetPos( x, y );
y = newy;
panel->SetPos(x, y);
}
else if (var == m_sWide)
{
int neww = (int)value.a;
int w, h;
panel->GetSize( w, h );
w = neww;
panel->SetSize(w, h);
}
else if (var == m_sTall)
{
int newh = (int)value.a;
int w, h;
panel->GetSize( w, h );
h = newh;
panel->SetSize(w, h);
}
else
{
KeyValues *inputData = new KeyValues(g_ScriptSymbols.String(var));
// set the custom value
if (value.b == 0.0f && value.c == 0.0f && value.d == 0.0f)
{
// only the first value is non-zero, so probably just a float value
inputData->SetFloat(g_ScriptSymbols.String(var), value.a);
}
else
{
// multivalue, set the color
Color col((unsigned char)value.a, (unsigned char)value.b, (unsigned char)value.c, (unsigned char)value.d);
inputData->SetColor(g_ScriptSymbols.String(var), col);
}
if (!panel->SetInfo(inputData))
{
// Assert(!("Unhandlable var in AnimationController::SetValue())"));
}
inputData->deleteThis();
}
}
// Hooks between panels and animation controller system
class CPanelAnimationDictionary
{
public:
CPanelAnimationDictionary() : m_PanelAnimationMapPool( 32 )
{
}
~CPanelAnimationDictionary()
{
m_PanelAnimationMapPool.Clear();
}
PanelAnimationMap *FindOrAddPanelAnimationMap( char const *className );
PanelAnimationMap *FindPanelAnimationMap( char const *className );
void PanelAnimationDumpVars( char const *className );
private:
struct PanelAnimationMapDictionaryEntry
{
PanelAnimationMap *map;
};
char const *StripNamespace( char const *className );
void PanelAnimationDumpMap( PanelAnimationMap *map, bool recursive );
CClassMemoryPool< PanelAnimationMap > m_PanelAnimationMapPool;
CUtlDict< PanelAnimationMapDictionaryEntry, int > m_AnimationMaps;
};
char const *CPanelAnimationDictionary::StripNamespace( char const *className )
{
if ( !Q_strnicmp( className, "vgui::", 6 ) )
{
return className + 6;
}
return className;
}
//-----------------------------------------------------------------------------
// Purpose: Find but don't add mapping
//-----------------------------------------------------------------------------
PanelAnimationMap *CPanelAnimationDictionary::FindPanelAnimationMap( char const *className )
{
int lookup = m_AnimationMaps.Find( StripNamespace( className ) );
if ( lookup != m_AnimationMaps.InvalidIndex() )
{
return m_AnimationMaps[ lookup ].map;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
PanelAnimationMap *CPanelAnimationDictionary::FindOrAddPanelAnimationMap( char const *className )
{
PanelAnimationMap *map = FindPanelAnimationMap( className );
if ( map )
return map;
Panel::InitPropertyConverters();
PanelAnimationMapDictionaryEntry entry;
entry.map = (PanelAnimationMap *)m_PanelAnimationMapPool.Alloc();
m_AnimationMaps.Insert( StripNamespace( className ), entry );
return entry.map;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPanelAnimationDictionary::PanelAnimationDumpMap( PanelAnimationMap *map, bool recursive )
{
if ( map->pfnClassName )
{
Msg( "%s\n", (*map->pfnClassName)() );
}
int c = map->entries.Count();
for ( int i = 0; i < c; i++ )
{
PanelAnimationMapEntry *e = &map->entries[ i ];
Msg( " %s %s\n", e->type(), e->name() );
}
if ( recursive && map->baseMap )
{
PanelAnimationDumpMap( map->baseMap, recursive );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPanelAnimationDictionary::PanelAnimationDumpVars( char const *className )
{
if ( className == NULL )
{
for ( int i = 0; i < (int)m_AnimationMaps.Count(); i++ )
{
PanelAnimationDumpMap( m_AnimationMaps[ i ].map, false );
}
}
else
{
PanelAnimationMap *map = FindPanelAnimationMap( className );
if ( map )
{
PanelAnimationDumpMap( map, true );
}
else
{
Msg( "No such Panel Animation class %s\n", className );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: singleton accessor
//-----------------------------------------------------------------------------
CPanelAnimationDictionary& GetPanelAnimationDictionary()
{
static CPanelAnimationDictionary dictionary;
return dictionary;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
PanelAnimationMap *FindOrAddPanelAnimationMap( char const *className )
{
return GetPanelAnimationDictionary().FindOrAddPanelAnimationMap( className );
}
//-----------------------------------------------------------------------------
// Purpose: Find but don't add mapping
//-----------------------------------------------------------------------------
PanelAnimationMap *FindPanelAnimationMap( char const *className )
{
return GetPanelAnimationDictionary().FindPanelAnimationMap( className );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PanelAnimationDumpVars( char const *className )
{
GetPanelAnimationDictionary().PanelAnimationDumpVars( className );
}
| 30.315283
| 209
| 0.585464
|
jarnar85
|
b449397db6699c587e98e79a0fad1215f948a4f3
| 6,476
|
cpp
|
C++
|
app/ioHandler.cpp
|
clueless-bachu/Human-Detector
|
0ec8ae9fb753607fc2e556ba2dcd23e9ebe1ba32
|
[
"MIT"
] | null | null | null |
app/ioHandler.cpp
|
clueless-bachu/Human-Detector
|
0ec8ae9fb753607fc2e556ba2dcd23e9ebe1ba32
|
[
"MIT"
] | null | null | null |
app/ioHandler.cpp
|
clueless-bachu/Human-Detector
|
0ec8ae9fb753607fc2e556ba2dcd23e9ebe1ba32
|
[
"MIT"
] | 1
|
2020-11-02T02:18:42.000Z
|
2020-11-02T02:18:42.000Z
|
/**
* @file ioHandler.cpp
* @author Vasista (clueless-bachu)
* @author Vishnuu (vishnuu95)
* @brief This file has all function definitions for IOHandler class
* @copyright MIT License (c) 2020 Vasista and Vishnuu.
*/
#include <bits/stdc++.h>
#include "opencv2/opencv.hpp"
#include <opencv2/tracking/tracker.hpp>
#include "ioHandler.hpp"
using vision::IOHandler;
/**
* @brief A constructor function for the IOHandler class
* @param None
* @return None
*/
IOHandler::IOHandler(string cfgPath) {
this->argParse(cfgPath);
}
/**
* @brief A destructor function for the IOHandler class
* @param None
* @return None
*/
IOHandler::~IOHandler() {
}
/**
* @brief parses the config file and assigns all its attributes to the appropriate value
* @param cfgPath - A path to the cfg file
* @return None
*/
void IOHandler::argParse(string cfgPath) {
std::ifstream cFile(cfgPath);
if (cFile.is_open()) {
std::string line;
while (getline(cFile, line)) {
line.erase(std::remove_if(line.begin(), line.end(), isspace),
line.end());
if (line[0] == '#' || line.empty())
continue;
auto delimiterPos = line.find("=");
string name = line.substr(0, delimiterPos);
string value = line.substr(delimiterPos + 1);
if (!name.compare("inPath")) {
this->inPath.assign(value); // = value.copy();
} else if (!name.compare("outPath")) {
this->outPath = value;
} else if (!name.compare("modelConfigPath")) {
this->modelConfigPath = value;
} else if (!name.compare("modelWeightsPath")) {
this->modelWeightsPath = value;
} else if (!name.compare("isImg") && !value.compare("true")) {
this->isImg = true;
} else if (!name.compare("ifVisualize") && !value.compare("true")) {
this->ifVisualize = true;
} else if (!name.compare("record") && !value.compare("true")) {
this->record = true;
} else if (!name.compare("humanHeight")) {
this->humanHeight = std::stod(value);
} else if (!name.compare("K")) {
auto newPos = value.find(",");
while (newPos != std::string::npos) {
this->intrinsicParams.push_back(
std::stod(value.substr(0, newPos)));
value = value.substr(newPos+1);
newPos = value.find(",");
}
this->intrinsicParams.push_back(std::stod(value));
} else if (!name.compare("transform")) {
auto newPos = value.find(",");
while (newPos != std::string::npos) {
this->transform.push_back
(std::stod(value.substr(0, newPos)));
value = value.substr(newPos+1);
newPos = value.find(",");
}
this->transform.push_back(std::stod(value));
} else if (!name.compare("imgWidth")) {
this->imgWidth = std::stoi(value);
} else if (!name.compare("imgHeight")) {
this->imgHeight = std::stoi(value);
}
}
} else {
std::cerr << "Couldn't open config file for reading.\n";
}
return;
}
/**
* @brief returns the input type: either image or video
* @param None
* @return a boolean, if true then type is image, if false then type is video
*/
bool IOHandler::getInputType() {
return this->isImg;
}
/**
* @brief returns condition to visualize data or not
* @param None
* @return bool
*/
bool IOHandler::isVisualize() {
return this->ifVisualize;
}
/**
* @brief returns condition to record to not
* @param none
* @return bool
*/
bool IOHandler::ifRecord() {
return this->record;
}
/**
* @brief returns the input image/video path
* @param None
* @return path - path to the data file
*/
string IOHandler::getInFilePath() {
return this->inPath;
}
/**
* @brief returns the image/video path where the output data should be stored
* @param None
* @return path - path to the data file
*/
string IOHandler::getOutFilePath() {
return this->outPath;
}
/**
* @brief returns the config file path of the DNN
* @param None
* @return path - path to the data file
*/
string IOHandler::getModelConfigPath() {
return this->modelConfigPath;
}
/**
* @brief returns the weightsfile path of the DNN
* @param None
* @return path - path to the data file
*/
string IOHandler::getModelWeightsPath() {
return this->modelWeightsPath;
}
/**
* @brief returns the average assumed human height
* @param None
* @return human height
*/
double IOHandler::getHumanHeight() {
return this->humanHeight;
}
/**
* @brief returns the camera intrinsics
* @param None
* @return Camera intrinsics
*/
vector<double> IOHandler::getIntrinsics() {
return this->intrinsicParams;
}
/**
* @brief returns the 4x4 matrix camera to robot transform as a flat vector
* @param None
* @return Camera intrinsics
*/
vector<double> IOHandler::getTransform() {
return this->transform;
}
/**
* @brief returns the image width
* @param None
* @return image width
*/
int IOHandler::getImgWidth() {
return this->imgWidth;
}
/**
* @brief returns the image height
* @param None
* @return image height
*/
int IOHandler::getImgHeight() {
return this->imgHeight;
}
/**
* @brief draws the bounding boxes over an image
* @param bb - a set of bounding boxes that needs to be drawn
* @param frame - the image on which the bounding boxes need to be drawn on
* @return None
*/
void IOHandler::drawBb
(vector<vector<int>> bbs, cv::Mat frame, vector<cv::Scalar> colors) {
for (unsigned int i = 0; i< bbs.size(); ++i) {
cv::Rect rect(bbs[i][0], bbs[i][1], bbs[i][2], bbs[i][3]);
cv::rectangle(frame, rect, colors[i], 3);
}
return;
}
/**
* @brief visualizes an image
* @param frame - the image on which the bounding boxes need to be drawn on
* @return None
*/
void IOHandler::seeImg(cv::Mat frame, int wait) {
cv::imshow("Human Tracking", frame);
cv::waitKey(wait);
return;
}
/**
* @brief save the image to a particular path
* @param path - The path where the image should be saved
* @param frame - the image to be saved
* @return None
*/
void IOHandler::saveImg(string path, cv::Mat frame) {
cv::imwrite(path, frame);
return;
}
| 26.983333
| 87
| 0.598981
|
clueless-bachu
|
b44cd2b7060a7301a125f0c607b04385e1e17205
| 2,090
|
cpp
|
C++
|
unit_tests/command_stream/create_command_stream_receiver_tests.cpp
|
FelipeMLopez/compute-runtime
|
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
|
[
"MIT"
] | null | null | null |
unit_tests/command_stream/create_command_stream_receiver_tests.cpp
|
FelipeMLopez/compute-runtime
|
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
|
[
"MIT"
] | null | null | null |
unit_tests/command_stream/create_command_stream_receiver_tests.cpp
|
FelipeMLopez/compute-runtime
|
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/execution_environment.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "core/unit_tests/helpers/ult_hw_config.h"
#include "runtime/command_stream/command_stream_receiver.h"
#include "runtime/command_stream/command_stream_receiver_with_aub_dump.h"
#include "runtime/memory_manager/os_agnostic_memory_manager.h"
#include "test.h"
#include "unit_tests/fixtures/mock_aub_center_fixture.h"
#include "unit_tests/helpers/execution_environment_helper.h"
#include "unit_tests/helpers/variable_backup.h"
#include "unit_tests/libult/create_command_stream.h"
using namespace NEO;
struct CreateCommandStreamReceiverTest : public ::testing::TestWithParam<CommandStreamReceiverType> {};
HWTEST_P(CreateCommandStreamReceiverTest, givenCreateCommandStreamWhenCsrIsSetToValidTypeThenTheFuntionReturnsCommandStreamReceiver) {
DebugManagerStateRestore stateRestorer;
HardwareInfo *hwInfo = nullptr;
ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1);
MockAubCenterFixture::setMockAubCenter(*executionEnvironment->rootDeviceEnvironments[0]);
CommandStreamReceiverType csrType = GetParam();
VariableBackup<UltHwConfig> backup(&ultHwConfig);
ultHwConfig.useHwCsr = true;
DebugManager.flags.SetCommandStreamReceiver.set(csrType);
auto csr = std::unique_ptr<CommandStreamReceiver>(createCommandStream(*executionEnvironment, 0));
if (csrType < CommandStreamReceiverType::CSR_TYPES_NUM) {
EXPECT_NE(nullptr, csr.get());
} else {
EXPECT_EQ(nullptr, csr.get());
}
EXPECT_NE(nullptr, executionEnvironment->memoryManager.get());
}
static CommandStreamReceiverType commandStreamReceiverTypes[] = {
CSR_HW,
CSR_AUB,
CSR_TBX,
CSR_HW_WITH_AUB,
CSR_TBX_WITH_AUB,
CSR_TYPES_NUM};
INSTANTIATE_TEST_CASE_P(
CreateCommandStreamReceiverTest_Create,
CreateCommandStreamReceiverTest,
testing::ValuesIn(commandStreamReceiverTypes));
| 36.666667
| 134
| 0.798086
|
FelipeMLopez
|
b450a5558325cf825441165bfda0e1bfba8c39d5
| 3,688
|
cpp
|
C++
|
src/Usb33Camera.cpp
|
TheImagingSource/tcam-firmware-update
|
a8feb157e73e36bf898bf4d6a025fef839df9584
|
[
"Apache-2.0"
] | null | null | null |
src/Usb33Camera.cpp
|
TheImagingSource/tcam-firmware-update
|
a8feb157e73e36bf898bf4d6a025fef839df9584
|
[
"Apache-2.0"
] | null | null | null |
src/Usb33Camera.cpp
|
TheImagingSource/tcam-firmware-update
|
a8feb157e73e36bf898bf4d6a025fef839df9584
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2017 The Imaging Source Europe GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Usb33Camera.h"
#include "33u/Firmware.h"
#include "33u/ReportProgress.h"
namespace tis
{
StdOutput::StdOutput(const std::function<void(int)>& callback) : progress(callback) {}
void StdOutput::report_percentage(int pct)
{
progress(pct);
}
void StdOutput::report_group(const std::string& /* msg */) {}
void StdOutput::report_step(const std::string& /* msg */) {}
void StdOutput::report_speed(float /* speed */, const std::string& /* unit */) {}
Usb33Camera::Usb33Camera(std::shared_ptr<UsbSession> session,
device_info dev,
unsigned int _interface)
: UsbCamera(session, dev, _interface),
device(std::make_shared<lib33u::driver_interface::libusb::ShowDevice>(session, dev)),
cam(device)
{
device->open();
}
Usb33Camera::~Usb33Camera() {}
int Usb33Camera::get_firmware_version()
{
return -1;
}
std::string Usb33Camera::get_firmware_version_string()
{
return std::to_string(cam.firmware_version());
}
int Usb33Camera::delete_firmware(std::function<void(int)> /* progress */)
{
return -1;
}
int Usb33Camera::download_firmware(std::vector<unsigned char>& /* firmware */,
std::function<void(int)> /* progress */)
{
return -1;
}
bool Usb33Camera::upload_firmware(const std::string& firmware_package,
const std::string& firmware,
std::function<void(int)> progress)
{
auto fw = lib33u::Firmware::load_package(firmware_package);
StdOutput out(progress);
if (!firmware.empty())
{
auto types = fw.device_types();
lib33u::firmware_update::DeviceTypeDesc type_desc;
for (auto& t : types)
{
if (t.description == firmware)
{
type_desc = t;
break;
}
}
fw.upload(cam, out, type_desc);
}
else
{
fw.upload(cam, out);
}
return true;
}
UVC_COMPLIANCE Usb33Camera::get_mode()
{
return UVC_COMPLIANCE::CAMERA_INTERFACE_MODE_UVC;
}
unsigned int Usb33Camera::get_eeprom_size()
{
return 0;
}
int Usb33Camera::set_mode(UVC_COMPLIANCE /* mode */)
{
return -1;
}
int Usb33Camera::write_eeprom(unsigned int /* addr */,
unsigned char* /* data */,
unsigned int /* size */)
{
return -1;
}
int Usb33Camera::read_eeprom(unsigned int /* addr */,
unsigned char* /* data */,
unsigned int /* size */)
{
return -1;
}
int Usb33Camera::erase_sector(unsigned int /* addr */)
{
return -1;
}
int Usb33Camera::erase_eeprom(std::function<void(int)> /* progress */)
{
return -1;
}
bool Usb33Camera::initialize_eeprom(std::vector<uint8_t>& /* firmware */)
{
return false;
}
int Usb33Camera::upload_firmware_file(std::vector<uint8_t> /* firmware */,
std::function<void(int)> /* progress */)
{
return -1;
}
} /* namespace tis */
| 21.44186
| 91
| 0.608731
|
TheImagingSource
|
b45126c4c9f9bac4d617ceb171c3a9beca596a8f
| 86,666
|
cpp
|
C++
|
igl/copyleft/cgal/remesh_intersections.cpp
|
ntg7creation/CG3DBasicEngine
|
4235dea17eab956e7dc5829618b5fe5642735ebc
|
[
"Apache-2.0"
] | 2
|
2022-03-28T14:10:50.000Z
|
2022-03-28T14:10:51.000Z
|
igl/copyleft/cgal/remesh_intersections.cpp
|
ntg7creation/CG3DBasicEngine
|
4235dea17eab956e7dc5829618b5fe5642735ebc
|
[
"Apache-2.0"
] | null | null | null |
igl/copyleft/cgal/remesh_intersections.cpp
|
ntg7creation/CG3DBasicEngine
|
4235dea17eab956e7dc5829618b5fe5642735ebc
|
[
"Apache-2.0"
] | 2
|
2022-03-23T10:33:10.000Z
|
2022-03-28T14:09:55.000Z
|
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2015 Qingnan Zhou <qnzhou@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
//
#include "remesh_intersections.h"
#include "assign_scalar.h"
#include "projected_cdt.h"
#include "../../get_seconds.h"
#include "../../parallel_for.h"
#include "../../LinSpaced.h"
#include "../../unique_rows.h"
#include <vector>
#include <map>
#include <queue>
#include <unordered_map>
#include <iostream>
//#define REMESH_INTERSECTIONS_TIMING
template <
typename DerivedV,
typename DerivedF,
typename Kernel,
typename DerivedVV,
typename DerivedFF,
typename DerivedJ,
typename DerivedIM>
IGL_INLINE void igl::copyleft::cgal::remesh_intersections(
const Eigen::MatrixBase<DerivedV> & V,
const Eigen::MatrixBase<DerivedF> & F,
const std::vector<CGAL::Triangle_3<Kernel> > & T,
const std::map<
typename DerivedF::Index,
std::vector<
std::pair<typename DerivedF::Index, CGAL::Object> > > & offending,
Eigen::PlainObjectBase<DerivedVV> & VV,
Eigen::PlainObjectBase<DerivedFF> & FF,
Eigen::PlainObjectBase<DerivedJ> & J,
Eigen::PlainObjectBase<DerivedIM> & IM)
{
// by default, no stitching
igl::copyleft::cgal::remesh_intersections(V,F,T,offending,false,VV,FF,J,IM);
}
template <
typename DerivedV,
typename DerivedF,
typename Kernel,
typename DerivedVV,
typename DerivedFF,
typename DerivedJ,
typename DerivedIM>
IGL_INLINE void igl::copyleft::cgal::remesh_intersections(
const Eigen::MatrixBase<DerivedV> & V,
const Eigen::MatrixBase<DerivedF> & F,
const std::vector<CGAL::Triangle_3<Kernel> > & T,
const std::map<
typename DerivedF::Index,
std::vector<
std::pair<typename DerivedF::Index, CGAL::Object> > > & offending,
bool stitch_all,
Eigen::PlainObjectBase<DerivedVV> & VV,
Eigen::PlainObjectBase<DerivedFF> & FF,
Eigen::PlainObjectBase<DerivedJ> & J,
Eigen::PlainObjectBase<DerivedIM> & IM)
{
#ifdef REMESH_INTERSECTIONS_TIMING
const auto & tictoc = []() -> double
{
static double t_start = igl::get_seconds();
double diff = igl::get_seconds()-t_start;
t_start += diff;
return diff;
};
const auto log_time = [&](const std::string& label) -> void {
std::cout << "remesh_intersections." << label << ": "
<< tictoc() << std::endl;
};
tictoc();
#endif
typedef CGAL::Point_3<Kernel> Point_3;
typedef CGAL::Segment_3<Kernel> Segment_3;
typedef CGAL::Plane_3<Kernel> Plane_3;
typedef CGAL::Triangulation_vertex_base_2<Kernel> TVB_2;
typedef CGAL::Constrained_triangulation_face_base_2<Kernel> CTFB_2;
typedef CGAL::Triangulation_data_structure_2<TVB_2,CTFB_2> TDS_2;
typedef CGAL::Exact_intersections_tag Itag;
typedef CGAL::Constrained_Delaunay_triangulation_2<Kernel,TDS_2,Itag>
CDT_2;
typedef CGAL::Constrained_triangulation_plus_2<CDT_2> CDT_plus_2;
typedef typename DerivedF::Index Index;
typedef std::pair<Index, Index> Edge;
struct EdgeHash {
size_t operator()(const Edge& e) const {
return (e.first * 805306457) ^ (e.second * 201326611);
}
};
typedef std::unordered_map<Edge, std::vector<Index>, EdgeHash > EdgeMap;
const size_t num_faces = F.rows();
const size_t num_base_vertices = V.rows();
assert(num_faces == T.size());
std::vector<bool> is_offending(num_faces, false);
for (const auto itr : offending)
{
const auto& fid = itr.first;
is_offending[fid] = true;
}
// Cluster overlaps so that co-planar clusters are resolved only once
std::unordered_map<Index, std::vector<Index> > intersecting_and_coplanar;
for (const auto itr : offending)
{
const auto& fi = itr.first;
const auto P = T[fi].supporting_plane();
assert(!P.is_degenerate());
for (const auto jtr : itr.second)
{
const auto& fj = jtr.first;
const auto& tj = T[fj];
if (P.has_on(tj[0]) && P.has_on(tj[1]) && P.has_on(tj[2]))
{
auto loc = intersecting_and_coplanar.find(fi);
if (loc == intersecting_and_coplanar.end())
{
intersecting_and_coplanar[fi] = {fj};
} else
{
loc->second.push_back(fj);
}
}
}
}
#ifdef REMESH_INTERSECTIONS_TIMING
log_time("overlap_analysis");
#endif
std::vector<std::vector<Index> > resolved_faces;
std::vector<Index> source_faces;
std::vector<Point_3> new_vertices;
EdgeMap edge_vertices;
// face_vertices: Given a face Index, find vertices inside the face
std::unordered_map<Index, std::vector<Index>> face_vertices;
// Run constraint Delaunay triangulation on the plane.
//
// Inputs:
// P plane to triangulate upone
// involved_faces #F list of indices into triangle of involved faces
// Outputs:
// vertices #V list of vertex positions of output triangulation
// faces #F list of face indices into vertices of output triangulation
//
auto delaunay_triangulation = [&offending, &T](
const Plane_3& P,
const std::vector<Index>& involved_faces,
std::vector<Point_3>& vertices,
std::vector<std::vector<Index> >& faces) -> void
{
std::vector<CGAL::Object> objects;
CDT_plus_2 cdt;
// insert each face into a common cdt
for (const auto& fid : involved_faces)
{
const auto itr = offending.find(fid);
const auto& triangle = T[fid];
objects.push_back(CGAL::make_object(triangle));
if (itr == offending.end())
{
continue;
}
for (const auto& index_obj : itr->second)
{
//const auto& ofid = index_obj.first;
const auto& obj = index_obj.second;
objects.push_back(obj);
}
}
projected_cdt(objects,P,vertices,faces);
};
// Given p on triangle indexed by ori_f, add point to list of vertices return index of p.
//
// Input:
// p point to search for
// ori_f index of triangle p is corner of
// Returns global index of vertex (dependent on whether stitch_all flag is
// set)
//
auto find_or_append_point = [&](
const Point_3& p,
const size_t ori_f) -> Index
{
if (stitch_all)
{
// No need to check if p shared by multiple triangles because all shared
// vertices would be merged later on.
const size_t index = num_base_vertices + new_vertices.size();
new_vertices.push_back(p);
return index;
} else
{
// Stitching triangles according to input connectivity.
// This step is potentially costly.
const auto& triangle = T[ori_f];
const auto& f = F.row(ori_f).eval();
// Check if p is one of the triangle corners.
for (size_t i=0; i<3; i++)
{
if (p == triangle[i]) return f[i];
}
// Check if p is on one of the edges.
for (size_t i=0; i<3; i++) {
const Point_3 curr_corner = triangle[i];
const Point_3 next_corner = triangle[(i+1)%3];
const Segment_3 edge(curr_corner, next_corner);
if (edge.has_on(p)) {
const Index curr = f[i];
const Index next = f[(i+1)%3];
Edge key;
key.first = curr<next?curr:next;
key.second = curr<next?next:curr;
auto itr = edge_vertices.find(key);
if (itr == edge_vertices.end()) {
const Index index =
num_base_vertices + new_vertices.size();
edge_vertices.insert({key, {index}});
new_vertices.push_back(p);
return index;
} else {
for (const auto vid : itr->second) {
if (p == new_vertices[vid - num_base_vertices]) {
return vid;
}
}
const size_t index = num_base_vertices + new_vertices.size();
new_vertices.push_back(p);
itr->second.push_back(index);
return index;
}
}
}
// p must be in the middle of the triangle.
auto & existing_face_vertices = face_vertices[ori_f];
for(const auto vid : existing_face_vertices) {
if (p == new_vertices[vid - num_base_vertices]) {
return vid;
}
}
const size_t index = num_base_vertices + new_vertices.size();
new_vertices.push_back(p);
existing_face_vertices.push_back(index);
return index;
}
};
// Determine the vertex indices for each corner of each output triangle.
//
// Inputs:
// vertices #V list of vertices of cdt
// faces #F list of list of face indices into vertices of cdt
// involved_faces list of involved faces on the plane of cdt
// Side effects:
// - add faces to resolved_faces
// - add corresponding original face to source_faces
// -
auto post_triangulation_process = [&](
const std::vector<Point_3>& vertices,
const std::vector<std::vector<Index> >& faces,
const std::vector<Index>& involved_faces) -> void
{
assert(involved_faces.size() > 0);
// for all faces of the cdt
for (const auto& f : faces)
{
const Point_3& v0 = vertices[f[0]];
const Point_3& v1 = vertices[f[1]];
const Point_3& v2 = vertices[f[2]];
Point_3 center(
(v0[0] + v1[0] + v2[0]) / 3.0,
(v0[1] + v1[1] + v2[1]) / 3.0,
(v0[2] + v1[2] + v2[2]) / 3.0);
if (involved_faces.size() == 1)
{
// If only there is only one involved face, all sub-triangles must
// belong to it and have the correct orientation.
const auto& ori_f = involved_faces[0];
std::vector<Index> corners(3);
corners[0] = find_or_append_point(v0, ori_f);
corners[1] = find_or_append_point(v1, ori_f);
corners[2] = find_or_append_point(v2, ori_f);
resolved_faces.emplace_back(corners);
source_faces.push_back(ori_f);
} else
{
for (const auto& ori_f : involved_faces)
{
const auto& triangle = T[ori_f];
const Plane_3 P = triangle.supporting_plane();
if (triangle.has_on(center)) {
std::vector<Index> corners(3);
corners[0] = find_or_append_point(v0, ori_f);
corners[1] = find_or_append_point(v1, ori_f);
corners[2] = find_or_append_point(v2, ori_f);
if (CGAL::orientation(
P.to_2d(v0), P.to_2d(v1), P.to_2d(v2))
== CGAL::RIGHT_TURN) {
std::swap(corners[0], corners[1]);
}
resolved_faces.emplace_back(corners);
source_faces.push_back(ori_f);
}
}
}
}
};
// Process un-touched faces.
for (size_t i=0; i<num_faces; i++)
{
if (!is_offending[i] && !T[i].is_degenerate())
{
resolved_faces.push_back( { F(i,0), F(i,1), F(i,2) } );
source_faces.push_back(i);
}
}
// Process self-intersecting faces.
std::vector<bool> processed(num_faces, false);
std::vector<std::pair<Plane_3, std::vector<Index> > > cdt_inputs;
for (const auto itr : offending)
{
const auto fid = itr.first;
if (processed[fid]) continue;
processed[fid] = true;
const auto loc = intersecting_and_coplanar.find(fid);
std::vector<Index> involved_faces;
if (loc == intersecting_and_coplanar.end())
{
involved_faces.push_back(fid);
} else
{
std::queue<Index> Q;
Q.push(fid);
while (!Q.empty())
{
const auto index = Q.front();
involved_faces.push_back(index);
Q.pop();
const auto overlapping_faces = intersecting_and_coplanar.find(index);
assert(overlapping_faces != intersecting_and_coplanar.end());
for (const auto other_index : overlapping_faces->second)
{
if (processed[other_index]) continue;
processed[other_index] = true;
Q.push(other_index);
}
}
}
Plane_3 P = T[fid].supporting_plane();
cdt_inputs.emplace_back(P, involved_faces);
}
#ifdef REMESH_INTERSECTIONS_TIMING
log_time("preprocess");
#endif
const size_t num_cdts = cdt_inputs.size();
std::vector<std::vector<Point_3> > cdt_vertices(num_cdts);
std::vector<std::vector<std::vector<Index> > > cdt_faces(num_cdts);
//// Not clear whether this is safe because of reference counting on Point_3
//// objects...
////
//// I tried it and got random segfaults (via MATLAB). Seems this is not
//// safe.
//igl::parallel_for(num_cdts,[&](int i)
for (size_t i=0; i<num_cdts; i++)
{
auto& vertices = cdt_vertices[i];
auto& faces = cdt_faces[i];
const auto& P = cdt_inputs[i].first;
const auto& involved_faces = cdt_inputs[i].second;
delaunay_triangulation(P, involved_faces, vertices, faces);
}
//,1000);
#ifdef REMESH_INTERSECTIONS_TIMING
log_time("cdt");
#endif
for (size_t i=0; i<num_cdts; i++)
{
const auto& vertices = cdt_vertices[i];
const auto& faces = cdt_faces[i];
const auto& involved_faces = cdt_inputs[i].second;
post_triangulation_process(vertices, faces, involved_faces);
}
#ifdef REMESH_INTERSECTIONS_TIMING
log_time("stitching");
#endif
// Output resolved mesh.
const size_t num_out_vertices = new_vertices.size() + num_base_vertices;
VV.resize(num_out_vertices, 3);
for (size_t i=0; i<num_base_vertices; i++)
{
assign_scalar(V(i,0), VV(i,0));
assign_scalar(V(i,1), VV(i,1));
assign_scalar(V(i,2), VV(i,2));
}
for (size_t i=num_base_vertices; i<num_out_vertices; i++)
{
assign_scalar(new_vertices[i-num_base_vertices][0], VV(i,0));
assign_scalar(new_vertices[i-num_base_vertices][1], VV(i,1));
assign_scalar(new_vertices[i-num_base_vertices][2], VV(i,2));
}
const size_t num_out_faces = resolved_faces.size();
FF.resize(num_out_faces, 3);
for (size_t i=0; i<num_out_faces; i++)
{
FF(i,0) = resolved_faces[i][0];
FF(i,1) = resolved_faces[i][1];
FF(i,2) = resolved_faces[i][2];
}
J.resize(num_out_faces);
std::copy(source_faces.begin(), source_faces.end(), J.data());
// Extract unique vertex indices.
const size_t VV_size = VV.rows();
IM.resize(VV_size,1);
DerivedVV unique_vv;
Eigen::VectorXi unique_to_vv, vv_to_unique;
// This is not stable... So even if offending is empty V != VV in
// general...
igl::unique_rows(VV, unique_vv, unique_to_vv, vv_to_unique);
if(stitch_all)
{
// Merge all vertices having the same coordinates into a single vertex
// and set IM to identity map.
VV = unique_vv;
std::transform(FF.data(), FF.data() + FF.rows()*FF.cols(),
FF.data(), [&vv_to_unique](const typename DerivedFF::Scalar& a)
{ return vv_to_unique[a]; });
IM.resize(unique_vv.rows());
// Have to use << instead of = because Eigen's PlainObjectBase is annoying
IM << igl::LinSpaced<
Eigen::Matrix<typename DerivedIM::Scalar, Eigen::Dynamic,1 >
>(unique_vv.rows(), 0, unique_vv.rows()-1);
}else
{
// Vertices with the same coordinates would be represented by one vertex.
// The IM value of a vertex is the index of the representative vertex.
for (Index v=0; v<(Index)VV_size; v++) {
IM(v) = unique_to_vv[vv_to_unique[v]];
}
}
#ifdef REMESH_INTERSECTIONS_TIMING
log_time("store_results");
#endif
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
// generated by autoexplicit.sh
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<long, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&);
// generated by autoexplicit.sh
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<long, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&);
// generated by autoexplicit.sh
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<float, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
// generated by autoexplicit.sh
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<float, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
// generated by autoexplicit.sh
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
// generated by autoexplicit.sh
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 1, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
// generated by autoexplicit.sh
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
// generated by autoexplicit.sh
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 1, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 1, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epick, Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epick, Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<long, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epeck, Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epeck, Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<long, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, 8, 3, 0, 8, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epick, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, 8, 3, 0, 8, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, 8, 3, 0, 8, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, 8, 3, 0, 8, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, CGAL::Epeck, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epeck, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epeck>, std::allocator<CGAL::Triangle_3<CGAL::Epeck> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::remesh_intersections<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, CGAL::Epick, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, std::vector<CGAL::Triangle_3<CGAL::Epick>, std::allocator<CGAL::Triangle_3<CGAL::Epick> > > const&, std::map<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > >, std::less<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index const, std::vector<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object>, std::allocator<std::pair<Eigen::Matrix<int, -1, 3, 0, -1, 3>::Index, CGAL::Object> > > > > > const&, bool, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
#ifdef WIN32
template void igl::copyleft::cgal::remesh_intersections<class Eigen::Matrix<float,-1,3,0,-1,3>,class Eigen::Matrix<int,-1,-1,0,-1,-1>,class CGAL::Epeck,class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>,-1,-1,0,-1,-1>,class Eigen::Matrix<int,-1,-1,0,-1,-1>,class Eigen::Matrix<__int64,-1,1,0,-1,1>,class Eigen::Matrix<int,-1,1,0,-1,1> >(class Eigen::MatrixBase<class Eigen::Matrix<float,-1,3,0,-1,3> > const &,class Eigen::MatrixBase<class Eigen::Matrix<int,-1,-1,0,-1,-1> > const &,class std::vector<class CGAL::Triangle_3<class CGAL::Epeck>,class std::allocator<class CGAL::Triangle_3<class CGAL::Epeck> > > const &,class std::map<__int64,class std::vector<struct std::pair<__int64,class CGAL::Object>,class std::allocator<struct std::pair<__int64,class CGAL::Object> > >,struct std::less<__int64>,class std::allocator<struct std::pair<__int64 const ,class std::vector<struct std::pair<__int64,class CGAL::Object>,class std::allocator<struct std::pair<__int64,class CGAL::Object> > > > > > const &,bool,class Eigen::PlainObjectBase<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>,-1,-1,0,-1,-1> > &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,-1,0,-1,-1> > &,class Eigen::PlainObjectBase<class Eigen::Matrix<__int64,-1,1,0,-1,1> > &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,1,0,-1,1> > &);
template void igl::copyleft::cgal::remesh_intersections<class Eigen::Matrix<float,-1,3,0,-1,3>,class Eigen::Matrix<int,-1,-1,0,-1,-1>,class CGAL::Epick,class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>,-1,-1,0,-1,-1>,class Eigen::Matrix<int,-1,-1,0,-1,-1>,class Eigen::Matrix<__int64,-1,1,0,-1,1>,class Eigen::Matrix<int,-1,1,0,-1,1> >(class Eigen::MatrixBase<class Eigen::Matrix<float,-1,3,0,-1,3> > const &,class Eigen::MatrixBase<class Eigen::Matrix<int,-1,-1,0,-1,-1> > const &,class std::vector<class CGAL::Triangle_3<class CGAL::Epick>,class std::allocator<class CGAL::Triangle_3<class CGAL::Epick> > > const &,class std::map<__int64,class std::vector<struct std::pair<__int64,class CGAL::Object>,class std::allocator<struct std::pair<__int64,class CGAL::Object> > >,struct std::less<__int64>,class std::allocator<struct std::pair<__int64 const ,class std::vector<struct std::pair<__int64,class CGAL::Object>,class std::allocator<struct std::pair<__int64,class CGAL::Object> > > > > > const &,bool,class Eigen::PlainObjectBase<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>,-1,-1,0,-1,-1> > &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,-1,0,-1,-1> > &,class Eigen::PlainObjectBase<class Eigen::Matrix<__int64,-1,1,0,-1,1> > &,class Eigen::PlainObjectBase<class Eigen::Matrix<int,-1,1,0,-1,1> > &);
template void igl::copyleft::cgal::remesh_intersections<class Eigen::Matrix<double, -1, 3, 0, -1, 3>, class Eigen::Matrix<int, -1, -1, 0, -1, -1>, class CGAL::Epeck, class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, -1, 0, -1, -1>, class Eigen::Matrix<int, -1, -1, 0, -1, -1>, class Eigen::Matrix<__int64, -1, 1, 0, -1, 1>, class Eigen::Matrix<int, -1, 1, 0, -1, 1>>(class Eigen::MatrixBase<class Eigen::Matrix<double, -1, 3, 0, -1, 3>> const &, class Eigen::MatrixBase<class Eigen::Matrix<int, -1, -1, 0, -1, -1>> const &, class std::vector<class CGAL::Triangle_3<class CGAL::Epeck>, class std::allocator<class CGAL::Triangle_3<class CGAL::Epeck>>> const &, class std::map<__int64, class std::vector<struct std::pair<__int64, class CGAL::Object>, class std::allocator<struct std::pair<__int64, class CGAL::Object>>>, struct std::less<__int64>, class std::allocator<struct std::pair<__int64 const, class std::vector<struct std::pair<__int64, class CGAL::Object>, class std::allocator<struct std::pair<__int64, class CGAL::Object>>>>>> const &, bool, class Eigen::PlainObjectBase<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, -1, 0, -1, -1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, -1, 0, -1, -1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<__int64, -1, 1, 0, -1, 1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, 1, 0, -1, 1>> &);
template void igl::copyleft::cgal::remesh_intersections<class Eigen::Matrix<double, -1, 3, 0, -1, 3>, class Eigen::Matrix<int, -1, -1, 0, -1, -1>, class CGAL::Epick, class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, -1, 0, -1, -1>, class Eigen::Matrix<int, -1, -1, 0, -1, -1>, class Eigen::Matrix<__int64, -1, 1, 0, -1, 1>, class Eigen::Matrix<int, -1, 1, 0, -1, 1>>(class Eigen::MatrixBase<class Eigen::Matrix<double, -1, 3, 0, -1, 3>> const &, class Eigen::MatrixBase<class Eigen::Matrix<int, -1, -1, 0, -1, -1>> const &, class std::vector<class CGAL::Triangle_3<class CGAL::Epick>, class std::allocator<class CGAL::Triangle_3<class CGAL::Epick>>> const &, class std::map<__int64, class std::vector<struct std::pair<__int64, class CGAL::Object>, class std::allocator<struct std::pair<__int64, class CGAL::Object>>>, struct std::less<__int64>, class std::allocator<struct std::pair<__int64 const, class std::vector<struct std::pair<__int64, class CGAL::Object>, class std::allocator<struct std::pair<__int64, class CGAL::Object>>>>>> const &, bool, class Eigen::PlainObjectBase<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, -1, 0, -1, -1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, -1, 0, -1, -1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<__int64, -1, 1, 0, -1, 1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, 1, 0, -1, 1>> &);
template void igl::copyleft::cgal::remesh_intersections<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, 3, 0, -1, 3>, class Eigen::Matrix<int, -1, -1, 0, -1, -1>, class CGAL::Epeck, class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, -1, 0, -1, -1>, class Eigen::Matrix<int, -1, -1, 0, -1, -1>, class Eigen::Matrix<__int64, -1, 1, 0, -1, 1>, class Eigen::Matrix<int, -1, 1, 0, -1, 1>>(class Eigen::MatrixBase<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, 3, 0, -1, 3>> const &, class Eigen::MatrixBase<class Eigen::Matrix<int, -1, -1, 0, -1, -1>> const &, class std::vector<class CGAL::Triangle_3<class CGAL::Epeck>, class std::allocator<class CGAL::Triangle_3<class CGAL::Epeck>>> const &, class std::map<__int64, class std::vector<struct std::pair<__int64, class CGAL::Object>, class std::allocator<struct std::pair<__int64, class CGAL::Object>>>, struct std::less<__int64>, class std::allocator<struct std::pair<__int64 const, class std::vector<struct std::pair<__int64, class CGAL::Object>, class std::allocator<struct std::pair<__int64, class CGAL::Object>>>>>> const &, bool, class Eigen::PlainObjectBase<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, -1, 0, -1, -1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, -1, 0, -1, -1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<__int64, -1, 1, 0, -1, 1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, 1, 0, -1, 1>> &);
template void igl::copyleft::cgal::remesh_intersections<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, 3, 0, -1, 3>, class Eigen::Matrix<int, -1, -1, 0, -1, -1>, class CGAL::Epick, class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, -1, 0, -1, -1>, class Eigen::Matrix<int, -1, -1, 0, -1, -1>, class Eigen::Matrix<__int64, -1, 1, 0, -1, 1>, class Eigen::Matrix<int, -1, 1, 0, -1, 1>>(class Eigen::MatrixBase<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, 3, 0, -1, 3>> const &, class Eigen::MatrixBase<class Eigen::Matrix<int, -1, -1, 0, -1, -1>> const &, class std::vector<class CGAL::Triangle_3<class CGAL::Epick>, class std::allocator<class CGAL::Triangle_3<class CGAL::Epick>>> const &, class std::map<__int64, class std::vector<struct std::pair<__int64, class CGAL::Object>, class std::allocator<struct std::pair<__int64, class CGAL::Object>>>, struct std::less<__int64>, class std::allocator<struct std::pair<__int64 const, class std::vector<struct std::pair<__int64, class CGAL::Object>, class std::allocator<struct std::pair<__int64, class CGAL::Object>>>>>> const &, bool, class Eigen::PlainObjectBase<class Eigen::Matrix<class CGAL::Lazy_exact_nt<class CGAL::Gmpq>, -1, -1, 0, -1, -1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, -1, 0, -1, -1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<__int64, -1, 1, 0, -1, 1>> &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, 1, 0, -1, 1>> &);
#endif
#endif
| 158.728938
| 1,491
| 0.618836
|
ntg7creation
|
b455871a0f4904c49088fb10fd8a0ebb76021166
| 2,073
|
hpp
|
C++
|
MPAGSCipher/PlayfairCipher.hpp
|
tomlatham/mpags-day-4-dbradders-1
|
35ba61b1c124796e4ad55b108e8bed7ac4e50c48
|
[
"MIT"
] | null | null | null |
MPAGSCipher/PlayfairCipher.hpp
|
tomlatham/mpags-day-4-dbradders-1
|
35ba61b1c124796e4ad55b108e8bed7ac4e50c48
|
[
"MIT"
] | null | null | null |
MPAGSCipher/PlayfairCipher.hpp
|
tomlatham/mpags-day-4-dbradders-1
|
35ba61b1c124796e4ad55b108e8bed7ac4e50c48
|
[
"MIT"
] | null | null | null |
#ifndef MPAGSCIPHER_PLAYFAIRCIPHER_HPP
#define MPAGSCIPHER_PLAYFAIRCIPHER_HPP
#include <map>
#include <string>
#include <vector>
#include "CipherMode.hpp"
/**
* \file PlayfairCipher.hpp
* \brief Contains the declaration of the PlayfairCipher class
*/
/**
* \class PlayfairCipher
* \brief Encrypt or decrypt text using the Playfair cipher with the given key
*/
class PlayfairCipher {
public:
/**
* Create a new PlayfairCipher with the given key
*
* \param key the key to use in the cipher
*/
explicit PlayfairCipher(const std::string& key );
/**
* Apply the cipher to the provided text
*
* \param inputText the text to encrypt or decrypt
* \param cipherMode whether to encrypt or decrypt the input text
* \return the result of applying the cipher to the input text
*/
std::string applyCipher(const std::string& inputText, const CipherMode cipherMode) const;
private:
/// The cipher key
std::string key_{""};
/**
* Set the key to be used for the encryption/decryption
*
* \param key the key to use in the cipher
*/
void setKey(const std::string& key);
/// Define the nested alphabet type
struct Alphabet{
/// The alphabet itself
const std::string alphabet{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
/// The alphabet size
const std::vector<char>::size_type alphabetSize = alphabet.size();
};
/// Our alphabet instance
Alphabet alphabet_;
/// The grid dimension
const int gridDim_{5};
// Lookup tables generated from the key
/// Type definition for the coordinates in the 5x5 table
using Coords = std::pair<int,int>;
/// Type definition for the map from letter to coordinates in the 5x5 table
using Char2Coords = std::map<char, Coords>;
/// Type definition for the map from coordinates in the 5x5 table to letter
using Coords2Char = std::map<Coords, char>;
/// Lookup table to go from the character to the coordinates
Char2Coords letterToCoords_;
/// Lookup table to go from the coordinates to the character
Coords2Char coordsToLetter_;
};
#endif
| 24.975904
| 91
| 0.705258
|
tomlatham
|
b455b52c2f5d5ea9edb2e475d613720e8e545935
| 35,390
|
cpp
|
C++
|
projects/examples/ex_image_readback/src/renderer/readback_benchmark.cpp
|
Nyran/schism
|
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
|
[
"BSD-3-Clause"
] | 10
|
2015-09-17T06:01:03.000Z
|
2019-10-23T07:10:20.000Z
|
projects/examples/ex_image_readback/src/renderer/readback_benchmark.cpp
|
Nyran/schism
|
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
|
[
"BSD-3-Clause"
] | 5
|
2015-01-06T14:11:32.000Z
|
2016-12-12T10:26:53.000Z
|
projects/examples/ex_image_readback/src/renderer/readback_benchmark.cpp
|
Nyran/schism
|
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
|
[
"BSD-3-Clause"
] | 15
|
2015-01-29T20:56:13.000Z
|
2020-07-02T19:03:20.000Z
|
// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com>
// Distributed under the Modified BSD License, see license.txt.
#include "readback_benchmark.h"
#include <exception>
#include <stdexcept>
#include <sstream>
#include <string>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/assign/list_of.hpp>
#include <cuda.h>
#include <cuda_runtime_api.h>
#include <scm/core/platform/windows.h>
#include <cuda_gl_interop.h>
#include <scm/core/time/time_types.h>
#include <scm/gl_core/math.h>
#include <scm/gl_core/frame_buffer_objects.h>
#include <scm/gl_core/query_objects.h>
#include <scm/gl_core/render_device.h>
#include <scm/gl_core/shader_objects.h>
#include <scm/gl_core/state_objects.h>
#include <scm/gl_core/sync_objects.h>
#include <scm/gl_core/texture_objects.h>
#include <scm/gl_core/window_management/context.h>
#include <scm/gl_core/window_management/surface.h>
#include <scm/gl_util/font/font_face.h>
#include <scm/gl_util/font/text.h>
#include <scm/gl_util/font/text_renderer.h>
#include <scm/gl_util/primitives/wavefront_obj.h>
#include <scm/gl_util/utilities/accum_timer_query.h>
#include <scm/gl_util/utilities/texture_output.h>
#include <scm/gl_util/viewer/camera.h>
#include <scm/gl_util/viewer/camera_uniform_block.h>
//#include <scm/large_data/virtual_texture/vtexture.h>
//#include <scm/large_data/virtual_texture/vtexture_context.h>
//#include <scm/large_data/virtual_texture/vtexture_system.h>
#include <scm/core/platform/windows.h>
#define SCM_TEST_READPIXELS 1
//#undef SCM_TEST_READPIXELS
#define SCM_TEST_TEXTURE_IMAGE_STORE 1
#undef SCM_TEST_TEXTURE_IMAGE_STORE
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE
# define SCM_TEST_TEXTURE_IMAGE_STORE_READBACK
# undef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK
# define SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_THREADED
# undef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_THREADED
# define SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_CUDA
# undef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_CUDA
#endif // SCM_TEST_TEXTURE_IMAGE_STORE
namespace {
const int SCM_FEEDBACK_BUFFER_REDUCTION = 1;
}
namespace scm {
namespace data {
readback_benchmark::readback_benchmark(const gl::render_device_ptr& device,
const gl::wm::context_cptr& gl_context,
const gl::wm::surface_cptr& gl_surface,
const math::vec2ui& viewport_size,
const std::string& model_file)
: _viewport_size(viewport_size)
, _color_format(gl::FORMAT_BGRA_8)
, _capture_enabled(true)
{
using namespace scm;
using namespace scm::gl;
using namespace scm::math;
using boost::assign::list_of;
using boost::lexical_cast;
camera_uniform_block::add_block_include_string(device);
_camera_block.reset(new gl::camera_uniform_block(device));
// state objects //////////////////////////////////////////////////////////////////////////////
_bstate = device->create_blend_state(false, FUNC_ONE, FUNC_ZERO, FUNC_ONE, FUNC_ZERO);
_dstate = device->create_depth_stencil_state(true, true, COMPARISON_LESS);
_rstate = device->create_rasterizer_state(FILL_SOLID, CULL_BACK, ORIENT_CCW, true);
_sstate = device->create_sampler_state(FILTER_MIN_MAG_LINEAR, WRAP_CLAMP_TO_EDGE);
if ( !_bstate
|| !_dstate
|| !_rstate
|| !_sstate) {
throw std::runtime_error("readback_benchmark::readback_benchmark(): error creating state objects");
}
// ray casting program ////////////////////////////////////////////////////////////////////////
_vtexture_program = device->create_program(list_of(device->create_shader_from_file(STAGE_VERTEX_SHADER,
"../../../src/renderer/shaders/vtexture_model.glslv"))
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE
(device->create_shader_from_file(STAGE_FRAGMENT_SHADER,
"../../../src/renderer/shaders/vtexture_model.glslf",
shader_macro_array("SCM_TEST_TEXTURE_IMAGE_STORE", "1")
("SCM_FEEDBACK_BUFFER_REDUCTION", lexical_cast<std::string>(SCM_FEEDBACK_BUFFER_REDUCTION)))),
#else
(device->create_shader_from_file(STAGE_FRAGMENT_SHADER, "../../../src/renderer/shaders/vtexture_model.glslf")),
#endif // SCM_TEST_TEXTURE_IMAGE_STORE
"readback_benchmark::vtexture_program");
if (!_vtexture_program) {
throw std::runtime_error("readback_benchmark::readback_benchmark(): error creating vtexture_program");
}
_vtexture_program->uniform_buffer("camera_matrices", 0);
// framebuffer ////////////////////////////////////////////////////////////////////////////////
out() << "_viewport_size " << _viewport_size << log::end;
//_color_buffer = device->create_render_buffer(_viewport_size, _color_format);
//_depth_buffer = device->create_render_buffer(_viewport_size, FORMAT_D24_S8);
_color_buffer = device->create_texture_2d(_viewport_size, _color_format);
_depth_buffer = device->create_texture_2d(_viewport_size, FORMAT_D24_S8);
if ( !_color_buffer
|| !_depth_buffer) {
throw std::runtime_error("readback_benchmark::readback_benchmark(): error creating textures");
}
_framebuffer = device->create_frame_buffer();
if (!_framebuffer) {
throw std::runtime_error("readback_benchmark::readback_benchmark(): error creating framebuffers");
}
_framebuffer->attach_color_buffer(0, _color_buffer);
_framebuffer->attach_depth_stencil_buffer(_depth_buffer);
// capture ////////////////////////////////////////////////////////////////////////////////////
vec2ui capture_size = _viewport_size / SCM_FEEDBACK_BUFFER_REDUCTION;
size_t copy_buffer_size = capture_size.x * capture_size.y * size_of_format(_color_format);
_copy_framebuffer = device->create_frame_buffer();
_copy_texture_color_buffer = device->create_texture_buffer(_color_format, USAGE_STATIC_COPY/*USAGE_STATIC_DRAW*/, copy_buffer_size);
_copy_color_buffer = device->create_texture_2d(capture_size, _color_format);
_copy_depth_buffer = device->create_texture_2d(capture_size, FORMAT_R_32UI);
_copy_lock_buffer = device->create_texture_2d(capture_size, FORMAT_R_32UI);
_copy_buffer_0 = device->create_buffer(BIND_PIXEL_PACK_BUFFER, USAGE_STREAM_READ, copy_buffer_size);
_copy_buffer_1 = _copy_buffer_0;//device->create_buffer(BIND_PIXEL_PACK_BUFFER, USAGE_STREAM_READ, copy_buffer_size);
//SYSTEM_INFO sys_info;
//::GetSystemInfo(&sys_info);
//out() << "system page size: " << sys_info.dwPageSize << "B." << log::end;
//_copy_memory.reset(static_cast<uint8*>(VirtualAlloc(0, copy_buffer_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)),
// boost::bind<BOOL>(VirtualFree, _1, 0, MEM_RELEASE));
_copy_memory.reset(new uint8[copy_buffer_size]);
if ( !_copy_framebuffer
|| !_copy_texture_color_buffer
|| !_copy_color_buffer
|| !_copy_lock_buffer
|| !_copy_depth_buffer
|| !_copy_buffer_0
|| !_copy_buffer_1) {
throw std::runtime_error("readback_benchmark::readback_benchmark(): error creating copy buffer or texture");
}
_copy_framebuffer->attach_color_buffer(0, _copy_color_buffer);
_copy_framebuffer->attach_color_buffer(1, _copy_depth_buffer);
_copy_framebuffer->attach_color_buffer(2, _copy_lock_buffer);
// timing /////////////////////////////////////////////////////////////////////////////////////
_gpu_timer_draw = make_shared<accum_timer_query>(device);
_gpu_timer_read = make_shared<accum_timer_query>(device);
_gpu_timer_copy = make_shared<accum_timer_query>(device);
_gpu_timer_tex = make_shared<accum_timer_query>(device);
if ( !_gpu_timer_draw
|| !_gpu_timer_read
|| !_gpu_timer_copy
|| !_gpu_timer_tex) {
throw std::runtime_error("readback_benchmark::readback_benchmark(): error creating timer queries");
}
try {
_texture_output = make_shared<texture_output>(device);
_model = scm::make_shared<wavefront_obj_geometry>(device, model_file);
// text
font_face_ptr output_font(new font_face(device, "../../../res/fonts/Consola.ttf", 12, 0, font_face::smooth_lcd));
_text_renderer = make_shared<text_renderer>(device);
_output_text = make_shared<text>(device, output_font, font_face::style_regular, "sick, sad world...");
mat4f fs_projection = make_ortho_matrix(0.0f, static_cast<float>(_viewport_size.x),
0.0f, static_cast<float>(_viewport_size.y), -1.0f, 1.0f);
_text_renderer->projection_matrix(fs_projection);
_output_text->text_color(math::vec4f(1.0f, 1.0f, 0.0f, 1.0f));
_output_text->text_kerning(true);
}
catch(const std::exception& e) {
throw std::runtime_error(std::string("readback_benchmark::readback_benchmark(): ") + e.what());
}
_frame_number = 0;
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_THREADED
// readback thread
_readback_buffer_count = 2;
try {
_readback_thread_gl_context.reset(new gl::wm::context(gl_surface, gl_context->context_attributes(), gl_context));
}
catch (std::exception& e) {
err() << "readback_benchmark::readback_benchmark() "
<< "error creating gl context resources (" << e.what() << ")" << log::end;
throw std::runtime_error(std::string("readback_benchmark::readback_benchmark(): ") + e.what());
}
for (int rbi = 0; rbi < _readback_buffer_count; ++rbi) {
_readback_draw_end.push_back(gl::sync_ptr());
_readback_draw_end_valid.push_back(sync_event());
_readback_readback_end.push_back(gl::sync_ptr());
_readback_readback_end_valid.push_back(sync_event());
_readback_textures.push_back(device->create_texture_2d(capture_size, _color_format));
}
_readback_thread_running = true;
_readback_thread.reset(new boost::thread(boost::bind(&readback_benchmark::readback_thread_entry, this, device, gl_context, gl_surface, viewport_size)));
// get everything rolling
for (int rbi = 0; rbi < _readback_buffer_count; ++rbi) {
_readback_readback_end[rbi] = device->main_context()->insert_fence_sync();
_readback_readback_end_valid[rbi].signal();
}
#endif
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_CUDA
cudaError cu_err = cudaSuccess;
const int max_cugl_devices = 10;
unsigned cugl_dev_count = 0;
int cugl_devices[max_cugl_devices];
cu_err = cudaGLGetDevices(&cugl_dev_count, cugl_devices, max_cugl_devices, cudaGLDeviceListCurrentFrame);
if (cudaSuccess != cu_err) {
err() << log::fatal
<< "readback_benchmark::readback_benchmark() "
<< "error acquiring cuda-gl devices (" << cudaGetErrorString(cu_err) << ")." << log::end;
throw std::runtime_error(std::string("readback_benchmark::readback_benchmark()..."));
}
if (cugl_dev_count < 1) {
err() << log::fatal
<< "readback_benchmark::readback_benchmark() "
<< "error acquiring cuda-gl devices (no CUDA devices returned)." << log::end;
throw std::runtime_error(std::string("readback_benchmark::readback_benchmark()..."));
}
cu_err = cudaGLSetGLDevice(cugl_devices[0]);
if (cudaSuccess != cu_err) {
err() << log::fatal
<< "readback_benchmark::readback_benchmark() "
<< "error setting cuda-gl device " << cugl_devices[0] << " (" << cudaGetErrorString(cu_err) << ")." << log::end;
throw std::runtime_error(std::string("readback_benchmark::readback_benchmark()..."));
}
cu_err = cudaStreamCreate(&_cuda_stream);
if (cudaSuccess != cu_err) {
err() << log::fatal
<< "readback_benchmark::readback_benchmark() "
<< "error creating cuda stream (" << cudaGetErrorString(cu_err) << ")." << log::end;
throw std::runtime_error(std::string("readback_benchmark::readback_benchmark()..."));
}
size_t fb_size = copy_buffer_size;
_cuda_copy_memory_size = copy_buffer_size;
uint8* cu_copy_data = 0;
cu_err = cudaHostAlloc(reinterpret_cast<void**>(&cu_copy_data), _cuda_copy_memory_size, cudaHostAllocDefault);
if (cudaSuccess != cu_err) {
err() << log::fatal
<< "readback_benchmark::readback_benchmark() "
<< "error allocating cuda host pinned memory (" << cudaGetErrorString(cu_err) << ")." << log::end;
throw std::runtime_error(std::string("readback_benchmark::readback_benchmark()..."));
}
else {
_cuda_copy_memory.reset(cu_copy_data, boost::bind<cudaError>(cudaFreeHost, _1));
}
cudaGraphicsResource* cu_fb_resource = 0;
cu_err = cudaGraphicsGLRegisterImage(&cu_fb_resource, _copy_color_buffer->object_id(), _copy_color_buffer->object_target(), cudaGraphicsRegisterFlagsReadOnly);
if (cudaSuccess != cu_err) {
err() << log::fatal
<< "readback_benchmark::readback_benchmark() "
<< "error registering color texture as cuda graphics resource (" << cudaGetErrorString(cu_err) << ")." << log::end;
throw std::runtime_error(std::string("readback_benchmark::readback_benchmark()..."));
}
else {
_cuda_gfx_res.reset(cu_fb_resource, boost::bind<cudaError>(cudaGraphicsUnregisterResource, _1));
}
#endif // SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_CUDA
}
readback_benchmark::~readback_benchmark()
{
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_THREADED
_readback_thread_running = false;
//}
//_requests_wait_condition.notify_one();
_readback_thread->join();
_readback_thread.reset();
#endif
_texture_output.reset();
_model.reset();
_text_renderer.reset();
_output_text.reset();
_gpu_timer_draw.reset();
_gpu_timer_read.reset();
_gpu_timer_copy.reset();
_gpu_timer_tex.reset();
_vtexture_program.reset();
_camera_block.reset();
_copy_buffer_0.reset();
_copy_buffer_1.reset();
_copy_texture_color_buffer.reset();
_copy_texture_depth_buffer.reset();
_copy_lock_buffer.reset();
_copy_color_buffer.reset();
_copy_depth_buffer.reset();
_copy_memory.reset();
_color_buffer.reset();
_depth_buffer.reset();
_framebuffer.reset();
_dstate.reset();
_bstate.reset();
_rstate.reset();
_sstate.reset();
}
bool
readback_benchmark::capture_enabled() const
{
return _capture_enabled;
}
void
readback_benchmark::capture_enabled(bool e)
{
_capture_enabled = e;
out() << "readback_benchmark::capture_enabled(): " << (_capture_enabled ? "true" : "false") << log::end;
}
void
readback_benchmark::draw_model(const gl::render_context_ptr& context)
{
using namespace scm;
using namespace scm::gl;
using namespace scm::math;
mat4f model_matrix = make_translation(vec3f(0.0, 0.0, -2.0f));//mat4f::identity();//make_scale(0.01f, 0.01f, 0.01f);
_gpu_timer_draw->start(context); { // draw
context_framebuffer_guard cfg(context);
context_program_guard cpg(context);
context_state_objects_guard csg(context);
context_texture_units_guard ctg(context);
context_image_units_guard cig(context);
context_uniform_buffer_guard cug(context);
_vtexture_program->uniform("model_matrix", model_matrix);
context->clear_color_buffer(_framebuffer, 0, vec4f(0.3f, 0.3f, 0.3f, 1.0f));
context->clear_depth_stencil_buffer(_framebuffer);
context->set_frame_buffer(_framebuffer);
context->bind_uniform_buffer(_camera_block->block().block_buffer(), 0);
context->bind_program(_vtexture_program);
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE
//vec2i capture_size = vec2i(_viewport_size) / SCM_FEEDBACK_BUFFER_REDUCTION;
context->clear_color_buffer(_copy_framebuffer, 0, vec4f(0.3f, 0.3f, 0.3f, 1.0f));
context->clear_color_buffer(_copy_framebuffer, 1, vec4ui(0u));
context->clear_color_buffer(_copy_framebuffer, 2, vec4ui(0u));
//_vtexture_program->uniform("output_res", capture_size);
// we are on 4.2, so we do not need to set these
//_vtexture_program->uniform("output_image", 0);
//_vtexture_program->uniform("depth_image", 1);
//_vtexture_program->uniform("lock_image", 2);
//_vtexture_program->uniform("output_buffer", 3);
context->bind_image(_copy_color_buffer, FORMAT_RGBA_8, ACCESS_WRITE_ONLY, 0);
context->bind_image(_copy_depth_buffer, FORMAT_R_32UI, ACCESS_READ_WRITE, 1);
context->bind_image(_copy_lock_buffer, FORMAT_R_32UI, ACCESS_READ_WRITE, 2);
context->bind_image(_copy_texture_color_buffer, FORMAT_RGBA_8, ACCESS_WRITE_ONLY, 3);
#endif // SCM_TEST_TEXTURE_IMAGE_STORE
context->set_rasterizer_state(_rstate);
context->set_depth_stencil_state(_dstate);
context->set_blend_state(_bstate);
//context->apply();
//context->sync();
_model->draw_raw(context);
//context->sync();
} _gpu_timer_draw->stop();
}
void
readback_benchmark::draw(const gl::render_context_ptr& context)
{
using namespace scm;
using namespace scm::gl;
using namespace scm::math;
++_frame_number;
static int current_draw_texture = 0;
static int last_draw_texture = 0;// not used
_cpu_timer_frame.start(); {
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_THREADED
if (_capture_enabled) {
// wait for the sync object to signal the end of the readback on the current texture
// wait for the sync object
_readback_readback_end_valid[current_draw_texture].wait();
context->sync_client_wait(_readback_readback_end[current_draw_texture]);
//out() << "draw: " << current_draw_texture;
_readback_readback_end_valid[current_draw_texture].reset();
_readback_readback_end[current_draw_texture].reset();
_framebuffer->attach_color_buffer(0, _readback_textures[current_draw_texture]);
draw_model(context);
context->clear_frame_buffer_color_attachments(_framebuffer);
_readback_draw_end[current_draw_texture] = context->insert_fence_sync();
_readback_draw_end_valid[current_draw_texture].signal();
current_draw_texture = (current_draw_texture + 1) % _readback_buffer_count;
last_draw_texture = (last_draw_texture + 1) % _readback_buffer_count;
}
else {
_framebuffer->attach_color_buffer(0, _readback_textures[current_draw_texture]);
draw_model(context);
context->clear_frame_buffer_color_attachments(_framebuffer);
}
#else // SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_THREADED
draw_model(context);
#endif // SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_THREADED
//context->sync();
#ifdef SCM_TEST_READPIXELS
{ // readback
size_t data_size = _viewport_size.x * _viewport_size.y * size_of_format(_color_format);
void* data = 0;
_cpu_timer_read.start();
_gpu_timer_read->start(context); {
context->orphane_buffer(_copy_buffer_0);
context->capture_color_buffer(_framebuffer, 0,
texture_region(vec3ui(0), _viewport_size),
_color_format,
//FORMAT_BGRA_8,
_copy_buffer_0);
} _gpu_timer_read->stop();
_cpu_timer_read.stop();
#if 1
_cpu_timer_copy.start();
_gpu_timer_copy->start(context); {
if (data = context->map_buffer(_copy_buffer_1, ACCESS_READ_ONLY)) {
::memcpy(_copy_memory.get(), data, data_size);
}
context->unmap_buffer(_copy_buffer_1);
} _gpu_timer_copy->stop();
_cpu_timer_copy.stop();
_cpu_timer_tex.start();
_gpu_timer_tex->start(context); {
context->update_sub_texture(_copy_color_buffer, texture_region(vec3ui(0), vec3ui(_viewport_size, 1)), 0, _color_format, _copy_memory.get());
} _gpu_timer_tex->stop();
_cpu_timer_tex.stop();
#else
_cpu_timer_tex.start();
_gpu_timer_tex->start(context); {
context->bind_unpack_buffer(_copy_buffer_0);
context->update_sub_texture(_copy_color_buffer, texture_region(vec3ui(0), vec3ui(_viewport_size, 1)), 0, _color_format, size_t(0));
context->bind_unpack_buffer(buffer_ptr());
} _gpu_timer_tex->stop(context);
_cpu_timer_tex.stop();
#endif
std::swap(_copy_buffer_0, _copy_buffer_1);
}
#endif // SCM_TEST_READPIXELS
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK
{
vec2ui capture_size = _viewport_size / SCM_FEEDBACK_BUFFER_REDUCTION;
size_t data_size = capture_size.x * capture_size.y * size_of_format(_color_format);
void* data = 0;
if (!_capture_finished) {
_cpu_timer_read.start();
_gpu_timer_read->start(context); {
context->orphane_buffer(_copy_buffer_0);
context->capture_color_buffer(_copy_framebuffer, 0,
texture_region(vec3ui(0), capture_size),
_color_format,
//FORMAT_BGRA_8,
_copy_buffer_0);
_capture_finished = context->insert_fence_sync();
_capture_start_frame = _frame_number;
} _gpu_timer_read->stop(context);
_cpu_timer_read.stop();
}
//context->sync();
//_cpu_timer_copy.start();
//_gpu_timer_copy->start(context); {
// if (data = context->map_buffer(_copy_buffer_1, ACCESS_READ_ONLY)) {
// ::memcpy(_copy_memory.get(), data, data_size);
// }
// context->unmap_buffer(_copy_buffer_1);
//} _gpu_timer_copy->stop(context);
//_cpu_timer_copy.stop();
if (context->sync_signal_status(_capture_finished) == SYNC_SIGNALED) {
int64 fdelay = _frame_number - _capture_start_frame;
//out() << "capture delay: " << fdelay << log::end;
context->sync_server_wait(_capture_finished);
//_gpu_timer_copy->start(context); {
#if 1
if (data = context->map_buffer(_copy_buffer_1, ACCESS_READ_ONLY)) {
_cpu_timer_copy.start();
::CopyMemory(_copy_memory.get(), data, data_size);
//::memcpy(_copy_memory.get(), data, data_size);
_cpu_timer_copy.stop();
}
context->unmap_buffer(_copy_buffer_1);
//} _gpu_timer_copy->stop(context);
#else
{
context_unpack_buffer_guard upbg(context);
context->bind_unpack_buffer(_copy_buffer_0);
_gpu_timer_copy->start(context);
context->update_sub_texture(_copy_color_buffer, texture_region(vec3ui(0), vec3ui(capture_size, 1)), 0, _color_format, static_cast<size_t>(0));
_gpu_timer_copy->stop(context);
}
#endif
//_cpu_timer_tex.start();
//_gpu_timer_tex->start(context); {
// context->update_sub_texture(_copy_color_buffer, texture_region(vec3ui(0), vec3ui(capture_size, 1)), 0, _color_format, _copy_memory.get());
//} _gpu_timer_tex->stop(context);
//_cpu_timer_tex.stop();
_capture_finished.reset();
std::swap(_copy_buffer_0, _copy_buffer_1);
}
}
#endif // SCM_TEST_TEXTURE_IMAGE_STORE
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_CUDA
{
if (_capture_enabled) {
const vec2ui buf_dim = _viewport_size;// / SCM_FEEDBACK_BUFFER_REDUCTION;
const double buf_size = static_cast<double>(buf_dim.x * buf_dim.y * size_of_format(_color_format)) / (1024.0 * 1024.0); // MiB
cudaEvent_t cu_start;
cudaEvent_t cu_stop;
cudaError cu_err = cudaSuccess;
cu_err = cudaEventCreate(&cu_start);
cu_err = cudaEventCreate(&cu_stop);
cudaArray* cu_array = 0;
cudaGraphicsResource_t cu_gfx_res = _cuda_gfx_res.get();
cu_err = cudaEventRecord(cu_start, _cuda_stream);
cu_err = cudaGraphicsMapResources(1, &cu_gfx_res, _cuda_stream);
cu_err = cudaGraphicsSubResourceGetMappedArray(&cu_array, cu_gfx_res, 0, 0);
cu_err = cudaMemcpyFromArrayAsync(_cuda_copy_memory.get(), cu_array, 0, 0, _cuda_copy_memory_size, cudaMemcpyDeviceToHost, _cuda_stream);
cu_err = cudaGraphicsUnmapResources(1, &cu_gfx_res, _cuda_stream);
cu_err = cudaEventRecord(cu_stop, _cuda_stream);
cu_err = cudaStreamSynchronize(_cuda_stream);
float cu_copy_time = 0.0f;
cu_err = cudaEventElapsedTime(&cu_copy_time, cu_start, cu_stop);
if (_frame_number % 1000 == 0) {
const double copy_bw = buf_size * 1000.0 / cu_copy_time; // MiB/s
std::stringstream os;
os << std::fixed << std::setprecision(3)
<< "image size: " << buf_dim << ", color_format: " << format_string(_color_format) << ", size(color_format): " << size_of_format(_color_format) << "B, buffer size: " << buf_size << "MiB" << std::endl
<< "cuda_copy: " << cu_copy_time << "ms, " << copy_bw << "MiB/s" << std::endl;
out() << os.str();
}
}
}
#endif // SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_CUDA
#ifdef SCM_TEST_TEXTURE_IMAGE_STORE_READBACK_THREADED
_texture_output->draw_texture_2d(context, _readback_textures[current_draw_texture], vec2ui(0, _viewport_size.y / 2), _viewport_size / 2);
#else
_texture_output->draw_texture_2d(context, _color_buffer, vec2ui(0, _viewport_size.y / 2), _viewport_size / 2);
#endif
_texture_output->draw_texture_2d(context, _depth_buffer, vec2ui(0, 0), _viewport_size / 2);
_texture_output->draw_texture_2d(context, _copy_color_buffer, _viewport_size / 2, _viewport_size / 2);
//_texture_output->draw_texture_2d(context, _copy_depth_buffer, vec2ui(_viewport_size.x / 2, 0), _viewport_size / 2);
_texture_output->draw_texture_2d_uint(context, _copy_depth_buffer, vec4f(100.0f / 0x00EFFFFFF), vec2ui(_viewport_size.x / 2, 0), _viewport_size / 2);
//_texture_output->draw_texture_2d(context, _color_buffer, vec2ui(0, 0), _viewport_size);
//_texture_output->draw_texture_2d(context, _copy_color_buffer, vec2ui(0, 0), _viewport_size);
_text_renderer->draw_shadowed(context, vec2i(5, _viewport_size.y - 15), _output_text);
} _cpu_timer_frame.stop();
}
void
readback_benchmark::readback_thread_entry(const gl::render_device_ptr& device,
const gl::wm::context_cptr& gl_context,
const gl::wm::surface_cptr& gl_surface,
const math::vec2ui& viewport_size)
{
using namespace scm;
using namespace scm::gl;
using namespace scm::math;
out() << "thread startup..." << log::end;
#if 1
_readback_thread_gl_context->make_current(gl_surface, true);
gl::render_context_ptr context = device->create_context();
context->apply();
vec2ui capture_size = viewport_size / SCM_FEEDBACK_BUFFER_REDUCTION;
size_t capture_data_size = capture_size.x * capture_size.y * size_of_format(_color_format);
gl::frame_buffer_ptr readback_fbo = device->create_frame_buffer();
std::vector<gl::buffer_ptr> readback_buffers;
for (int rbi = 0; rbi < _readback_buffer_count; ++rbi) {
readback_buffers.push_back(device->create_buffer(BIND_PIXEL_PACK_BUFFER, USAGE_STREAM_READ, capture_data_size));
}
// query objects not sharable, so we create our own here
_gpu_timer_read = make_shared<accum_timer_query>(device);
int current_rb_buffer = 0;//_readback_buffer_count / 2;
int last_rb_buffer = current_rb_buffer + 1;
//std::stringstream os;
//device->print_device_informations(os);
//out() << os.str() << log::end;
context->set_frame_buffer(readback_fbo);
context->apply();
while (_readback_thread_running) {
if (_capture_enabled) {
// wait for the sync object to signal the end of the rendering frame
// wait for the sync object
_cpu_timer_copy.start();
_readback_draw_end_valid[current_rb_buffer].wait();
context->sync_client_wait(_readback_draw_end[current_rb_buffer]);
//out() << "read: " << current_rb_buffer;
_readback_draw_end_valid[current_rb_buffer].reset();
_readback_draw_end[current_rb_buffer].reset();
_cpu_timer_copy.stop();
// read framebuffer content to PBO
readback_fbo->attach_color_buffer(0, _readback_textures[current_rb_buffer]);
context->orphane_buffer(readback_buffers[current_rb_buffer]);
//context->sync();
_cpu_timer_read.start();
_gpu_timer_read->start(context);
context->capture_color_buffer(readback_fbo, 0,
texture_region(vec3ui(0), capture_size),
_color_format,
readback_buffers[current_rb_buffer]);
_gpu_timer_read->stop();
//context->sync();
_cpu_timer_read.stop();
context->clear_frame_buffer_color_attachments(readback_fbo);
// signal end of readback operation
_readback_readback_end[current_rb_buffer] = context->insert_fence_sync();
_readback_readback_end_valid[current_rb_buffer].signal();
_cpu_timer_tex.start();
void* data = 0;
if (data = context->map_buffer(readback_buffers[last_rb_buffer], ACCESS_READ_ONLY)) {
::memcpy(_copy_memory.get(), data, capture_data_size);
}
context->unmap_buffer(readback_buffers[last_rb_buffer]);
_cpu_timer_tex.stop();
current_rb_buffer = (current_rb_buffer + 1) % _readback_buffer_count;
last_rb_buffer = (last_rb_buffer + 1) % _readback_buffer_count;
}
}
#endif
out() << "thread shutdown..." << log::end;
}
void
readback_benchmark::update(const gl::render_context_ptr& context,
const gl::camera& cam)
{
using namespace scm;
using namespace scm::gl;
using namespace scm::math;
_camera_block->update(context, cam);
_gpu_timer_draw->collect();
_gpu_timer_read->collect();
_gpu_timer_copy->collect();
_gpu_timer_tex->collect();
const vec2ui buf_dim = _viewport_size / SCM_FEEDBACK_BUFFER_REDUCTION;
const double buf_size = static_cast<double>(buf_dim.x * buf_dim.y * size_of_format(_color_format)) / (1024.0 * 1024.0); // MiB
static double draw_time = 0.0;
static double read_time = 0.0;
static double read_tp = 0.0;
static double copy_time = 0.0;
static double copy_tp = 0.0;
static double tex_time = 0.0;
static double tex_tp = 0.0;
static double frame_time_cpu = 0.0;
static double read_time_cpu = 0.0;
static double read_tp_cpu = 0.0;
static double copy_time_cpu = 0.0;
static double copy_tp_cpu = 0.0;
static double tex_time_cpu = 0.0;
static double tex_tp_cpu = 0.0;
if (time::to_milliseconds(_cpu_timer_frame.accumulated_duration()) > 500.0) {
_gpu_timer_draw->update(0);
_gpu_timer_read->update(0);
_gpu_timer_copy->update(0);
_gpu_timer_tex->update(0);
draw_time = _gpu_timer_draw->average_time(time::time_io::msec);
read_time = _gpu_timer_read->average_time(time::time_io::msec);
read_tp = buf_size * 1000.0 / read_time; // MiB/s
copy_time = _gpu_timer_copy->average_time(time::time_io::msec);
copy_tp = buf_size * 1000.0 / copy_time; // MiB/s
tex_time = _gpu_timer_tex->average_time(time::time_io::msec);
tex_tp = buf_size * 1000.0 / tex_time; // MiB/s
frame_time_cpu = time::to_milliseconds(_cpu_timer_frame.average_duration());
read_time_cpu = time::to_milliseconds(_cpu_timer_read.average_duration());
read_tp_cpu = buf_size * 1000.0 / read_time_cpu; // MiB/s
copy_time_cpu = time::to_milliseconds(_cpu_timer_copy.average_duration());
copy_tp_cpu = buf_size * 1000.0 / copy_time_cpu; // MiB/s
tex_time_cpu = time::to_milliseconds(_cpu_timer_tex.average_duration());
tex_tp_cpu = buf_size * 1000.0 / tex_time_cpu; // MiB/s
_gpu_timer_read->reset();
_gpu_timer_copy->reset();
_gpu_timer_tex->reset();
_cpu_timer_frame.reset();
_cpu_timer_read.reset();
_cpu_timer_copy.reset();
_cpu_timer_tex.reset();
std::stringstream os;
os << std::fixed << std::setprecision(3)
<< "image size: " << buf_dim << ", color_format: " << format_string(_color_format) << ", size(color_format): " << size_of_format(_color_format) << "B, buffer size: " << buf_size << "MiB" << std::endl
<< "draw: gpu " << draw_time << "ms" << std::endl
<< "read: gpu " << read_time << "ms, " << read_tp << "MiB/s - cpu: " << read_time_cpu << "ms, " << read_tp_cpu << "MiB/s" << std::endl
<< "copy: gpu " << copy_time << "ms, " << copy_tp << "MiB/s - cpu: " << copy_time_cpu << "ms, " << copy_tp_cpu << "MiB/s" << std::endl
<< "tex_update: gpu " << tex_time << "ms, " << tex_tp << "MiB/s - cpu: " << tex_time_cpu << "ms, " << tex_tp_cpu << "MiB/s" << std::endl
<< "frame_time: cpu " << frame_time_cpu << "ms" << std::endl;
_output_text->text_string(os.str());
}
}
} // namespace data
} // namespace scm
| 42.845036
| 222
| 0.632184
|
Nyran
|
b45962421bee00eacdccf001b0467d55a11c7e40
| 2,625
|
cpp
|
C++
|
OGDF/src/ogdf/basic/Math.cpp
|
shahnidhi/MetaCarvel
|
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
|
[
"MIT"
] | 13
|
2017-12-21T03:35:41.000Z
|
2022-01-31T13:45:25.000Z
|
OGDF/src/ogdf/basic/Math.cpp
|
shahnidhi/MetaCarvel
|
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
|
[
"MIT"
] | 7
|
2017-09-13T01:31:24.000Z
|
2021-12-14T00:31:50.000Z
|
OGDF/src/ogdf/basic/Math.cpp
|
shahnidhi/MetaCarvel
|
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
|
[
"MIT"
] | 15
|
2017-09-07T18:28:55.000Z
|
2022-01-18T14:17:43.000Z
|
/** \file
* \brief Implementation of mathematical constants, functions.
*
* \author Carsten Gutwenger
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.txt in the root directory of the OGDF installation for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* \see http://www.gnu.org/copyleft/gpl.html
***************************************************************/
#include <ogdf/basic/Math.h>
namespace ogdf {
const double Math::pi = 3.14159265358979323846;
const double Math::pi_2 = 1.57079632679489661923;
const double Math::pi_4 = 0.785398163397448309616;
const double Math::two_pi = 2*3.14159265358979323846;
const double Math::e = 2.71828182845904523536;
const double Math::log_of_2 = log(2.0);
const double Math::log_of_4 = log(4.0);
int factorials[13] = {
1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880,
3628800, 39916800, 479001600
};
double factorials_d[20] = {
1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
1307674368000.0, 20922789888000.0, 355687428096000.0,
6402373705728000.0, 121645100408832000.0
};
int Math::binomial(int n, int k)
{
if(k>n/2) k = n-k;
if(k == 0) return 1;
int r = n;
for(int i = 2; i<=k; ++i)
r = (r * (n+1-i))/i;
return r;
}
double Math::binomial_d(int n, int k)
{
if(k>n/2) k = n-k;
if(k == 0) return 1.0;
double r = n;
for(int i = 2; i<=k; ++i)
r = (r * (n+1-i))/i;
return r;
}
int Math::factorial(int n)
{
if(n < 0) return 1;
if(n > 12) return numeric_limits<int>::max(); // not representable by int
return factorials[n];
}
double Math::factorial_d(int n)
{
if(n < 0) return 1.0;
double f = 1.0;
for(; n > 19; --n)
f *= n;
return f * factorials_d[n];
}
} // namespace ogdf
| 25.240385
| 77
| 0.645333
|
shahnidhi
|
b45b4aecfce3e36a32657608eebf8ef96cfaccd0
| 16,273
|
cpp
|
C++
|
piel/gavcquery.cpp
|
diakovliev/pie
|
eb957a5e44496ba802d8b4fcace64ad48be16871
|
[
"BSD-3-Clause"
] | null | null | null |
piel/gavcquery.cpp
|
diakovliev/pie
|
eb957a5e44496ba802d8b4fcace64ad48be16871
|
[
"BSD-3-Clause"
] | null | null | null |
piel/gavcquery.cpp
|
diakovliev/pie
|
eb957a5e44496ba802d8b4fcace64ad48be16871
|
[
"BSD-3-Clause"
] | 1
|
2017-12-28T11:37:42.000Z
|
2017-12-28T11:37:42.000Z
|
/*
* Copyright (c) 2017, Dmytro Iakovliev daemondzk@gmail.com
* 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 <organization> 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 Dmytro Iakovliev daemondzk@gmail.com ''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 Dmytro Iakovliev daemondzk@gmail.com 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 <gavcquery.h>
#include <logging.h>
#include <gavcconstants.h>
#include <algorithm>
#include <boost/format.hpp>
#include <boost/bind.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/split.hpp>
#include <gavcversionsfilter.h>
#include <gavcversionsrangefilter.h>
//! Versions based queries
//
// '*' - all
// '+' - latest
// '-' - oldest
//
// prefix(+|-|*\.)+suffix
// - calculation from left to right
// (+|-|*\.)(+|-) == (+|-) (single element)
// (+|-|*\.)* == * (set)
//
// Pairs conversion matrix:
// -------------
// | + | - | * |
// -----------------
// | + | + | - | + |
// -----------------
// | - | - | - | - |
// -----------------
// | * | + | - | * |
// -----------------
BOOST_FUSION_ADAPT_STRUCT(
art::lib::gavc::gavc_data,
(std::string, group)
(std::string, name)
(std::string, version)
(std::string, classifier)
(std::string, extension)
)
BOOST_FUSION_ADAPT_STRUCT(
art::lib::gavc::gavc_versions_range_data,
(std::string, left)
(std::string, right)
)
namespace art { namespace lib {
namespace gavc {
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
template<typename Iterator>
struct gavc_version_ops_grammar: qi::grammar<Iterator, std::vector<OpType>(), ascii::space_type> {
gavc_version_ops_grammar(): gavc_version_ops_grammar::base_type(_ops)
{
using qi::char_;
using qi::as_string;
_op = ops;
_const = as_string[ +( char_ - _op - GavcConstants::left_include_braket - GavcConstants::left_exclude_braket ) ];
_ops = *( (_op >> !_op) | _const );
}
private:
struct ops_: qi::symbols<char,OpType> {
ops_()
{
add_sym(GavcConstants::all_versions, Op_all);
add_sym(GavcConstants::latest_version, Op_latest);
add_sym(GavcConstants::oldest_version, Op_oldest);
}
void add_sym(const std::string& sym, Ops op)
{
add(sym, OpType(op, sym));
}
void add_sym(char ch, Ops op)
{
std::string sym;
sym.push_back(ch);
add(sym, OpType(op, sym));
}
} ops;
qi::rule<Iterator, OpType()> _op; //!< Operation.
qi::rule<Iterator, std::string()> _const; //!< Constanst.
qi::rule<Iterator, std::vector<OpType>(), ascii::space_type> _ops;
};
// req :req :opt :opt @opt
// <group.spec>:<name-spec>[:][<version.spec>[:{[classifier][@][extension]}]]
template<typename Iterator>
struct gavc_grammar: qi::grammar<Iterator, gavc_data(), ascii::space_type> {
gavc_grammar(): gavc_grammar::base_type(_gavc)
{
using qi::char_;
using qi::skip;
_body = +( char_ - GavcConstants::delimiter );
_group = _body > skip[ GavcConstants::delimiter ];
_name = _body > -( skip[ GavcConstants::delimiter ] );
_version = _body > -( skip[ GavcConstants::delimiter ] );
_classifier = +( char_ - GavcConstants::extension_prefix ) > -( skip[ GavcConstants::extension_prefix ] );
_extension = +( char_ );
_gavc = _group
> _name
> -_version
> -_classifier
> -_extension
;
}
private:
qi::rule<Iterator, std::string()> _body; //!< Helper.
qi::rule<Iterator, std::string()> _group; //!< Consumer is gavc_data.group .
qi::rule<Iterator, std::string()> _name; //!< Consumer is gavc_data.name .
qi::rule<Iterator, std::string()> _version; //!< Consumer is gavc_data.version .
qi::rule<Iterator, std::string()> _classifier; //!< Consumer is gavc_data.classifier .
qi::rule<Iterator, std::string()> _extension; //!< Consumer is gavc_data.extension .
qi::rule<Iterator, gavc_data(), ascii::space_type> _gavc; //!< Consumer is gavc_data.
};
// <[|(><left>,<right><]|(>
template<typename Iterator>
struct gavc_versions_range_grammar: qi::grammar<Iterator, gavc_versions_range_data()> {
gavc_versions_range_grammar()
: gavc_versions_range_grammar::base_type(_data)
, _flags(RangeFlags_exclude_all)
{
using qi::char_;
using qi::skip;
using qi::lit;
using qi::lexeme;
using qi::as_string;
_left_braket = lexeme[
lit(GavcConstants::left_include_braket)
[
boost::bind(&gavc_versions_range_grammar::include_left, this)
]
| lit(GavcConstants::left_exclude_braket)
];
_right_braket = lexeme[
lit(GavcConstants::right_include_braket)
[
boost::bind(&gavc_versions_range_grammar::include_right, this)
]
| lit(GavcConstants::right_exclude_braket)
];
_left = as_string[ +( char_ - GavcConstants::range_separator ) ];
_right = as_string[ +( char_ - _right_braket )];
_data = _left_braket > _left > GavcConstants::range_separator > _right > _right_braket;
}
unsigned char flags() const {
return _flags;
}
void include_left() {
_flags |= RangeFlags_include_left;
}
void include_right() {
_flags |= RangeFlags_include_right;
}
private:
qi::rule<Iterator> _left_braket;
qi::rule<Iterator> _right_braket;
qi::rule<Iterator, std::string()> _left;
qi::rule<Iterator, std::string()> _right;
qi::rule<Iterator, gavc_versions_range_data()> _data;
unsigned char _flags;
};
} // namespace gavc
GavcQuery::GavcQuery()
: data_()
{
}
GavcQuery::~GavcQuery()
{
}
boost::optional<GavcQuery> GavcQuery::parse(const std::string& gavc_str)
{
if (gavc_str.empty())
return boost::none;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
GavcQuery result;
gavc::gavc_grammar<std::string::const_iterator> grammar;
try {
qi::phrase_parse( gavc_str.begin(), gavc_str.end(), grammar, ascii::space, result.data_ );
} catch (...) {
return boost::none;
}
LOGT << "group: " << result.group() << ELOG;
LOGT << "name: " << result.name() << ELOG;
LOGT << "version: " << result.version() << ELOG;
LOGT << "classifier: " << result.classifier() << ELOG;
LOGT << "extension: " << result.extension() << ELOG;
// Attempt to parse versions query
boost::optional<std::vector<gavc::OpType> > ops = result.query_version_ops();
if (!ops) {
return boost::none;
}
return result;
}
boost::optional<std::vector<gavc::OpType> > GavcQuery::query_version_ops() const
{
return query_version_ops(data_.version);
}
std::pair<
boost::optional<std::vector<gavc::OpType> >,
boost::optional<gavc::gavc_versions_range_data>
> GavcQuery::query_version_data() const {
return query_version_data(data_.version);
}
boost::optional<gavc::gavc_versions_range_data> GavcQuery::query_versions_range() const
{
return query_versions_range(data_.version);
}
/* static */
std::pair<
boost::optional<std::vector<gavc::OpType> >,
boost::optional<gavc::gavc_versions_range_data>
> GavcQuery::query_version_data(const std::string& version) {
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
std::vector<gavc::OpType> ops;
gavc::gavc_versions_range_data range;
if (version.empty()) {
ops.push_back(gavc::OpType(gavc::Op_all, GavcConstants::all_versions));
return std::make_pair(ops, boost::none);
}
gavc::gavc_version_ops_grammar<std::string::const_iterator> version_ops_grammar;
gavc::gavc_versions_range_grammar<std::string::const_iterator> version_range_grammar;
bool range_found = false;
auto range_callback = [&]() { range_found = true; };
try {
bool matched = qi::phrase_parse(
version.begin(),
version.end(),
version_ops_grammar > -version_range_grammar[ range_callback ],
ascii::space,
ops, range);
if (!matched)
return std::make_pair(boost::none, boost::none);
if (range_found)
range.flags = version_range_grammar.flags();
} catch (...) {
return std::make_pair(boost::none, boost::none);
}
if (!version.empty() & ops.empty())
{
LOGE << "version query: " << version << " has wrong syntax!" << ELOG;
return std::make_pair(boost::none, boost::none);
}
std::for_each(ops.begin(), ops.end(), [&](auto i) {
{
LOGT << "version query op: " << i.second << ELOG;
}
});
if (!range_found)
return std::make_pair(ops, boost::none);
LOGT << "versions range left: " << range.left << ELOG;
LOGT << "versions range right: " << range.right << ELOG;
LOGT << "versions range flags: " << int(range.flags) << ELOG;
return std::make_pair(ops, range);
}
/* static */ boost::optional<std::vector<gavc::OpType> > GavcQuery::query_version_ops(const std::string& version)
{
return query_version_data(version).first;
}
/* static */ boost::optional<gavc::gavc_versions_range_data> GavcQuery::query_versions_range(const std::string& version)
{
return query_version_data(version).second;
}
struct QueryOpsFinder_exact_version_query {
bool operator()(const gavc::OpType& op) {
return op.first > gavc::Op_const;
}
};
bool GavcQuery::is_exact_version_query() const
{
return is_exact_version_query(data_.version);
}
/* static */ bool GavcQuery::is_exact_version_query(const std::string& version)
{
auto range = query_versions_range(version);
if (range) return false;
auto pops = query_version_ops(version);
if (!pops) return false;
return std::find_if(pops->begin(), pops->end(), QueryOpsFinder_exact_version_query()) == pops->end();
}
bool GavcQuery::is_single_version_query() const
{
return is_single_version_query(data_.version);
}
/* static */ bool GavcQuery::is_single_version_query(const std::string& version)
{
auto range = query_versions_range(version);
if (range) return false;
auto pops = query_version_ops(version);
if (!pops) return false;
bool is_last_op_all = false;
std::for_each(pops->begin(), pops->end(), [&](auto i)
{
if (i.first != gavc::Op_const)
is_last_op_all = i.first == gavc::Op_all;
});
return !is_last_op_all;
}
std::string GavcQuery::to_string() const
{
std::ostringstream result;
if (!group().empty())
{
result << group();
}
if (!name().empty())
{
result << GavcConstants::delimiter;
result << name();
}
if (!version().empty())
{
result << GavcConstants::delimiter;
result << version();
}
if (!classifier().empty())
{
result << GavcConstants::delimiter;
result << classifier();
}
if (!extension().empty())
{
result << GavcConstants::extension_prefix;
result << extension();
}
LOGT << result.str() << ELOG;
return result.str();
}
std::string GavcQuery::group_path() const
{
std::string g = group();
std::vector<std::string> parts;
boost::split(parts, g, boost::is_any_of("."));
return boost::join(parts, "/");
}
std::string GavcQuery::format_maven_metadata_url(const std::string& server_url, const std::string& repository) const
{
LOGT << "Build url for maven metadata. server_url: " << server_url << " repository: " << repository << ELOG;
std::string group_path = group();
std::replace(group_path.begin(), group_path.end(), GavcConstants::group_delimiter, GavcConstants::path_delimiter);
std::string result = boost::str(boost::format( "%2$s%1$c%3$s%1$c%4$s%1$c%5$s%1$c%6$s" )
% GavcConstants::path_delimiter % server_url % repository % group_path % name() % GavcConstants::maven_metadata_filename);
LOGT << "Maven metadata url: " << result << ELOG;
return result;
}
std::string GavcQuery::format_maven_metadata_path(const std::string& repository) const
{
LOGT << "Build path for maven metadata. repository: " << repository << ELOG;
std::string group_path = group();
std::replace(group_path.begin(), group_path.end(), GavcConstants::group_delimiter, GavcConstants::path_delimiter);
std::string result = boost::str(boost::format( "%1$c%2$s%1$c%3$s%1$c%4$s" )
% GavcConstants::path_delimiter % repository % group_path % name());
LOGT << "Cache path to metadata url: " << result << ELOG;
return result;
}
std::vector<std::string> GavcQuery::filter(const std::vector<std::string>& versions) const {
std::vector<std::string> result = versions;
auto data = query_version_data();
if (data.first && data.second) {
auto ops = data.first;
auto range = data.second;
GavcVersionsRangeFilter filter(*ops, range->left, range->right, range->flags);
return filter.filtered(result);
} else if (data.first) {
auto ops = data.first;
if (!ops) {
LOGT << "Unable to get query operations list." << ELOG;
return result;
}
GavcVersionsFilter filter(*ops);
return filter.filtered(result);
}
return result;
}
} } // namespace art::lib
| 32.676707
| 130
| 0.584834
|
diakovliev
|
b45d56b0fbcc0c1c57ca6644d8c1f10b640d670b
| 579
|
cpp
|
C++
|
unicode_back/character_categories/punctuation_connector.cpp
|
do-m-en/random_regex_string
|
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
|
[
"BSL-1.0"
] | null | null | null |
unicode_back/character_categories/punctuation_connector.cpp
|
do-m-en/random_regex_string
|
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
|
[
"BSL-1.0"
] | null | null | null |
unicode_back/character_categories/punctuation_connector.cpp
|
do-m-en/random_regex_string
|
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
|
[
"BSL-1.0"
] | null | null | null |
#include "punctuation_connector.hpp"
namespace {
static const std::vector<char32_t> characters
{
0x5F,
0x203F,
0x2040,
0x2054,
0xFE33,
0xFE34,
0xFE4D,
0xFE4E,
0xFE4F,
0xFF3F
};
}
/*
Character Name
U+005F LOW LINE
U+203F UNDERTIE
U+2040 CHARACTER TIE
U+2054 INVERTED UNDERTIE
U+FE33 PRESENTATION FORM FOR VERTICAL LOW LINE
U+FE34 PRESENTATION FORM FOR VERTICAL WAVY LOW LINE
U+FE4D DASHED LOW LINE
U+FE4E CENTRELINE LOW LINE
U+FE4F WAVY LOW LINE
U+FF3F FULLWIDTH LOW LINE
*/
| 16.542857
| 54
| 0.64076
|
do-m-en
|
b45f97391080ce46eebdff3aef796ce39dcd3d1c
| 544
|
hpp
|
C++
|
shapes/Bat.hpp
|
PabloMorenoUm/Projekt
|
ebd5b4bfbd5da0e86ade850ce0cd701e8eff2e83
|
[
"MIT"
] | null | null | null |
shapes/Bat.hpp
|
PabloMorenoUm/Projekt
|
ebd5b4bfbd5da0e86ade850ce0cd701e8eff2e83
|
[
"MIT"
] | 9
|
2021-06-30T14:58:40.000Z
|
2021-08-22T22:36:31.000Z
|
shapes/Bat.hpp
|
PabloMorenoUm/Projekt
|
ebd5b4bfbd5da0e86ade850ce0cd701e8eff2e83
|
[
"MIT"
] | null | null | null |
//
// Created by Pablo Moreno Um on 19.07.21.
//
#ifndef PROJEKT_BAT_HPP
#define PROJEKT_BAT_HPP
#include "BallBat.hpp"
#include "Direction.hpp"
#include "WindowSize.hpp"
class Bat: public BallBat {
Direction m_RightPressed{};
Direction m_LeftPressed{};
WindowSize m_WindowSize;
void moveLeft(const float &elapsedTime);
void moveRight(const float &elapsedTime);
public:
Bat(const float &startX, const float &startY);
void input();
void update(const float &elapsedTime) override;
};
#endif //PROJEKT_BAT_HPP
| 20.923077
| 51
| 0.720588
|
PabloMorenoUm
|
b46f0d870f4d04be3313b7187a7b89db7e9c9d20
| 4,973
|
hpp
|
C++
|
modules/dnn/src/cuda4dnn/primitives/eltwise.hpp
|
xipingyan/opencv
|
39c3334147ec02761b117f180c9c4518be18d1fa
|
[
"Apache-2.0"
] | 56,632
|
2016-07-04T16:36:08.000Z
|
2022-03-31T18:38:14.000Z
|
modules/dnn/src/cuda4dnn/primitives/eltwise.hpp
|
yusufm423/opencv
|
6a2077cbd8a8a0d8cbd3e0e8c3ca239f17e6c067
|
[
"Apache-2.0"
] | 13,593
|
2016-07-04T13:59:03.000Z
|
2022-03-31T21:04:51.000Z
|
modules/dnn/src/cuda4dnn/primitives/eltwise.hpp
|
yusufm423/opencv
|
6a2077cbd8a8a0d8cbd3e0e8c3ca239f17e6c067
|
[
"Apache-2.0"
] | 54,986
|
2016-07-04T14:24:38.000Z
|
2022-03-31T22:51:18.000Z
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_DNN_SRC_CUDA4DNN_PRIMITIVES_ELTWISE_HPP
#define OPENCV_DNN_SRC_CUDA4DNN_PRIMITIVES_ELTWISE_HPP
#include "../../op_cuda.hpp"
#include "../csl/stream.hpp"
#include "../csl/tensor.hpp"
#include "../csl/tensor_ops.hpp"
#include "../kernels/eltwise_ops.hpp"
#include <opencv2/core.hpp>
#include <cstddef>
#include <vector>
#include <utility>
namespace cv { namespace dnn { namespace cuda4dnn {
enum class EltwiseOpType {
MAX,
SUM,
PRODUCT,
DIV,
MIN,
};
class EltwiseOpBase : public CUDABackendNode {
public:
EltwiseOpBase(csl::Stream stream_, EltwiseOpType op_, std::vector<float> coeffs_)
: stream(std::move(stream_)), op(op_), coeffs(std::move(coeffs_))
{
}
protected:
csl::Stream stream;
public:
EltwiseOpType op;
std::vector<float> coeffs;
};
template <class T>
class EltwiseOp final : public EltwiseOpBase {
public:
using wrapper_type = GetCUDABackendWrapperType<T>;
EltwiseOp(csl::Stream stream_, EltwiseOpType op_, std::vector<float> coeffs_)
: EltwiseOpBase(std::move(stream_), op_, std::move(coeffs_))
{
}
void forward(
const std::vector<cv::Ptr<BackendWrapper>>& inputs,
const std::vector<cv::Ptr<BackendWrapper>>& outputs,
csl::Workspace& workspace) override
{
CV_Assert(inputs.size() >= 2);
CV_Assert(outputs.size() == 1);
CV_Assert(coeffs.size() == 0 || op == EltwiseOpType::SUM);
CV_Assert(coeffs.size() == 0 || inputs.size() == coeffs.size());
auto output_wrapper = outputs[0].dynamicCast<wrapper_type>();
auto output = output_wrapper->getSpan();
if (inputs.size() == 2)
{
auto input_wrapper_x = inputs[0].dynamicCast<wrapper_type>();
auto input_x = input_wrapper_x->getView();
auto input_wrapper_y = inputs[1].dynamicCast<wrapper_type>();
auto input_y = input_wrapper_y->getView();
switch (op)
{
case EltwiseOpType::MAX: kernels::eltwise_max_2<T>(stream, output, input_x, input_y); break;
case EltwiseOpType::MIN: kernels::eltwise_min_2<T>(stream, output, input_x, input_y); break;
case EltwiseOpType::PRODUCT: kernels::eltwise_prod_2<T>(stream, output, input_x, input_y); break;
case EltwiseOpType::DIV: kernels::eltwise_div_2<T>(stream, output, input_x, input_y); break;
case EltwiseOpType::SUM:
if (coeffs.empty() || (coeffs[0] == 1 && coeffs[1] == 1))
kernels::eltwise_sum_2<T>(stream, output, input_x, input_y);
else
kernels::eltwise_sum_coeff_2<T>(stream, output, coeffs[0], input_x, coeffs[1], input_y);
break;
}
}
else
{
auto input_wrapper_0 = inputs[0].dynamicCast<wrapper_type>();
auto input_0 = input_wrapper_0->getView();
/* we first make a copy and then apply EltwiseOp cumulatively */
csl::tensor_ops::copy(stream, output, input_0);
for (int i = 1; i < inputs.size(); i++)
{
auto input_wrapper = inputs[i].dynamicCast<wrapper_type>();
auto input = input_wrapper->getView();
switch (op)
{
case EltwiseOpType::MAX: kernels::eltwise_max_2<T>(stream, output, output, input); break;
case EltwiseOpType::MIN: kernels::eltwise_min_2<T>(stream, output, output, input); break;
case EltwiseOpType::PRODUCT: kernels::eltwise_prod_2<T>(stream, output, output, input); break;
case EltwiseOpType::DIV: kernels::eltwise_div_2<T>(stream, output, output, input); break;
case EltwiseOpType::SUM:
if (coeffs.empty() || coeffs[i] == 1)
kernels::eltwise_sum_2<T>(stream, output, output, input);
else
{
/* if this is the first op, we must scale output too */
T coeff_x = (i == 1) ? coeffs[0] : 1.0;
kernels::eltwise_sum_coeff_2<T>(stream, output, coeff_x, output, coeffs[i], input);
}
break;
}
}
}
}
};
}}} /* namespace cv::dnn::cuda4dnn */
#endif /* OPENCV_DNN_SRC_CUDA4DNN_PRIMITIVES_ELTWISE_HPP */
| 37.961832
| 114
| 0.550975
|
xipingyan
|
b47ba741388e0adbfb595f50a2a0fa54f6319696
| 3,224
|
cpp
|
C++
|
contracts/amax.bootdao/src/bootdao.cpp
|
armoniax/amax.contracts
|
adb2a30fd7ed0ab6d3952efe4d73bb13f8d224e1
|
[
"MIT"
] | null | null | null |
contracts/amax.bootdao/src/bootdao.cpp
|
armoniax/amax.contracts
|
adb2a30fd7ed0ab6d3952efe4d73bb13f8d224e1
|
[
"MIT"
] | null | null | null |
contracts/amax.bootdao/src/bootdao.cpp
|
armoniax/amax.contracts
|
adb2a30fd7ed0ab6d3952efe4d73bb13f8d224e1
|
[
"MIT"
] | null | null | null |
#include <amax.token.hpp>
#include "bootdao.hpp"
#include <amax.system/amax.system.hpp>
#include <chrono>
using namespace wasm;
using namespace eosiosystem;
static constexpr name AMAX_BANK = "amax.token"_n;
static constexpr symbol AMAX = symbol(symbol_code("AMAX"), 8);
static constexpr eosio::name active_permission{"active"_n};
using undelegatebw_action = eosio::action_wrapper<"undelegatebw"_n, &system_contract::undelegatebw>;
#define FORCE_TRANSFER(bank, from, to, quantity, memo) \
token::transfer_action( bank, {{_self, active_perm}})\
.send( from, to, quantity, memo );
#define UNDELEGATE_BW(from, receiver, unstate_net, unstate_cpu) \
system_contract::undelegatebw_action( "amax"_n, {{get_self(), active_permission}}) \
.send( from, receiver, unstate_net, unstate_cpu );
#define SELL_RAM(from, rambytes) \
system_contract::sellram_action( "amax"_n, {{get_self(), active_permission}}) \
.send( from, rambytes );
[[eosio::action]]
void bootdao::init() {
auto& acct = _gstate.whitelist_accounts;
acct.insert("amax.custody"_n);
acct.insert("armoniaadmin"_n);
acct.insert("amax.satoshi"_n);
acct.insert("dragonmaster"_n);
acct.insert("armonia1"_n);
acct.insert("armonia2"_n);
acct.insert("armonia3"_n);
acct.insert("amax.ram"_n);
acct.insert("amax.stake"_n);
acct.insert("masteraychen"_n);
}
void bootdao::recycle(const vector<name>& accounts) {
require_auth(get_self());
for( auto& account: accounts ){
recycle_account( account );
}
}
void bootdao::recycle_account(const name& account) {
check( _gstate.whitelist_accounts.find(account) == _gstate.whitelist_accounts.end(), "whitelisted" );
user_resources_table userres( "amax"_n, account.value );
auto res_itr = userres.find( account.value );
check( res_itr != userres.end(), "account res not found: " + account.to_string() );
auto net_bw = asset(200000, SYS_SYMB);
auto cpu_bw = asset(200000, SYS_SYMB);
if ( res_itr->net_weight > net_bw ) {
//undelegate net
net_bw = res_itr->net_weight - net_bw;
} else
net_bw.amount = 0;
if( res_itr->cpu_weight > cpu_bw ){
//undelegate cpu
cpu_bw = res_itr->cpu_weight - cpu_bw;
} else
cpu_bw.amount = 0;
// check(false, "net_bw: " + net_bw.to_string() + ", cpu_bw: " + cpu_bw.to_string() );
//undelegate net or cpu
if( net_bw.amount > 0 || cpu_bw.amount > 0 )
UNDELEGATE_BW( account, account, net_bw, cpu_bw )
//sell RAM
auto rambytes = res_itr->ram_bytes;
if( rambytes > 4000 )
SELL_RAM( account, rambytes - 4000 )
//reverse amax from balance
auto amax_bal = get_balance(SYS_BANK, AMAX, account);
// check(false, "amax bal: " + amax_bal.to_string() );
if (amax_bal.amount > 0)
FORCE_TRANSFER( AMAX_BANK, account, "amax"_n, amax_bal, "" )
}
asset bootdao::get_balance(const name& bank, const symbol& symb, const name& account) {
tbl_accounts tmp(bank, account.value);
auto itr = tmp.find(symb.code().raw());
if (itr != tmp.end())
return itr->balance;
else
return asset(0, symb);
}
| 31.920792
| 105
| 0.654467
|
armoniax
|
b47cb71adf240a1df4078e85604c536636abd2d1
| 2,504
|
cpp
|
C++
|
src/Oscilloscope.cpp
|
kometbomb/oscilloscoper
|
7a0e4fce9b0074e9675bce55e97272c57c517dd0
|
[
"MIT"
] | 20
|
2016-08-04T15:20:29.000Z
|
2022-03-22T00:24:15.000Z
|
src/Oscilloscope.cpp
|
kometbomb/oscilloscoper
|
7a0e4fce9b0074e9675bce55e97272c57c517dd0
|
[
"MIT"
] | null | null | null |
src/Oscilloscope.cpp
|
kometbomb/oscilloscoper
|
7a0e4fce9b0074e9675bce55e97272c57c517dd0
|
[
"MIT"
] | 2
|
2017-11-16T15:52:15.000Z
|
2018-06-19T04:19:09.000Z
|
#include "Oscilloscope.hpp"
#include "Wave.hpp"
#include "SDL.h"
#include <algorithm>
Oscilloscope::Oscilloscope(const Wave& wave, int windowSizeMs, float yScale)
: mWave(wave), mResolution(0), mYScale(yScale), mFilterEnabled(false), mFilterCenterFreq(400), mFilterBandwidth(50)
{
mWindowSize = (float)wave.getSampleRate() * windowSizeMs / 1000;
mResolution = mWindowSize;
mFilterBuffer = new float[mWindowSize * 2];
}
Oscilloscope::~Oscilloscope()
{
delete [] mFilterBuffer;
}
void Oscilloscope::draw(int position, SDL_Renderer *renderer, const SDL_Rect& area)
{
int maxLookback = mWindowSize;
int lookback = 0;
int bufferPosition = mWindowSize;
if (mFilterEnabled)
{
for (int i = 0 ; i < mWindowSize * 2 ; ++i)
mFilterBuffer[i] = mWave.get(position + i - mResolution / 2);
mFilter.process(mWindowSize * 2, &mFilterBuffer);
float orig = mFilterBuffer[mWindowSize];
while (lookback < maxLookback - 1)
{
if (orig > 0)
{
--position;
--bufferPosition;
if (mFilterBuffer[bufferPosition] < 0)
break;
}
else
{
++position;
++bufferPosition;
if (mFilterBuffer[bufferPosition] > 0)
break;
}
lookback++;
}
}
else
{
int orig = mWave.get(position);
while (lookback < maxLookback)
{
if (orig > 0)
{
--position;
if (mWave.get(position) < 0)
break;
}
else
{
++position;
if (mWave.get(position) > 0)
break;
}
lookback++;
}
}
int amp, prevAmp = mWave.get(position - mResolution / 2) * mYScale * (area.h / 2) / 32768 + area.h / 2;
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
for (int x = 0 ; x < area.w ; ++x)
{
//amp = mFilterBuffer[x * mResolution / area.w + bufferPosition - mResolution / 2] * mYScale * (area.h / 2) / 32768 + area.h / 2;
amp = mWave.get(position - mResolution / 2 + x * mResolution / area.w) * mYScale * (area.h / 2) / 32768 + area.h / 2;
SDL_Rect rect = {x + area.x, std::min(prevAmp, amp) - 4 + area.y, 2, abs(prevAmp - amp) + 8};
SDL_RenderFillRect(renderer, &rect);
//SDL_RenderDrawLine(renderer, x - 1 + area.x, prevAmp + area.y, x + area.x, amp + area.y);
prevAmp = amp;
}
}
const Wave& Oscilloscope::getWave() const
{
return mWave;
}
void Oscilloscope::setFilter(float centerFreq, float bandwidth)
{
mFilterEnabled = true;
mFilterCenterFreq = centerFreq;
mFilterBandwidth = bandwidth;
mFilter.setup(3, mWave.getSampleRate(), mFilterCenterFreq, mFilterBandwidth, 1);
}
| 22.159292
| 132
| 0.641374
|
kometbomb
|
b47e32a1acb6b3d749f1ea8d337b77fad81869b2
| 3,245
|
inl
|
C++
|
external/gli/gli/core/generate_mipmaps.inl
|
cloudqiu1110/tinype
|
de289d45fca89a4ba964ae2577ac9d82784fadd0
|
[
"BSD-3-Clause"
] | 143
|
2017-01-03T15:26:44.000Z
|
2022-03-28T01:00:52.000Z
|
external/gli/gli/core/generate_mipmaps.inl
|
cloudqiu1110/tinype
|
de289d45fca89a4ba964ae2577ac9d82784fadd0
|
[
"BSD-3-Clause"
] | 4
|
2017-01-09T23:02:46.000Z
|
2020-10-14T07:20:51.000Z
|
external/gli/gli/core/generate_mipmaps.inl
|
cloudqiu1110/tinype
|
de289d45fca89a4ba964ae2577ac9d82784fadd0
|
[
"BSD-3-Clause"
] | 47
|
2017-01-30T11:56:35.000Z
|
2022-02-20T23:35:12.000Z
|
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Image (gli.g-truc.net)
///
/// Copyright (c) 2008 - 2013 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// @ref core
/// @file gli/core/generate_mipmaps.inl
/// @date 2010-09-27 / 2013-01-12
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////
namespace gli{
namespace detail
{
}//namespace detail
template <>
inline texture2D generate_mipmaps(texture2D & Texture)
{
texture2D Result(Texture.format(), Texture.dimensions());
texture2D::size_type const Components(gli::component_count(Result.format()));
for(texture2D::size_type Level = Texture.base_level(); Level < Texture.max_level(); ++Level)
{
// Src
std::size_t BaseWidth = Result[Level].dimensions().x;
void * DataSrc = Result[Level + 0].data();
// Dst
texture2D::dim_type LevelDimensions = texture2D::dim_type(Result[Level].dimensions()) >> texture2D::dim_type(1);
LevelDimensions = glm::max(LevelDimensions, texture2D::dim_type(1));
void * DataDst = Result[Level + 1].data();
for(std::size_t j = 0; j < LevelDimensions.y; ++j)
for(std::size_t i = 0; i < LevelDimensions.x; ++i)
for(std::size_t c = 0; c < Components; ++c)
{
std::size_t x = (i << 1);
std::size_t y = (j << 1);
std::size_t Index00 = ((x + 0) + (y + 0) * BaseWidth) * Components + c;
std::size_t Index01 = ((x + 0) + (y + 1) * BaseWidth) * Components + c;
std::size_t Index11 = ((x + 1) + (y + 1) * BaseWidth) * Components + c;
std::size_t Index10 = ((x + 1) + (y + 0) * BaseWidth) * Components + c;
glm::u32 Data00 = reinterpret_cast<glm::byte *>(DataSrc)[Index00];
glm::u32 Data01 = reinterpret_cast<glm::byte *>(DataSrc)[Index01];
glm::u32 Data11 = reinterpret_cast<glm::byte *>(DataSrc)[Index11];
glm::u32 Data10 = reinterpret_cast<glm::byte *>(DataSrc)[Index10];
std::size_t IndexDst = (x + y * LevelDimensions.x) * Components + c;
*(reinterpret_cast<glm::byte *>(DataDst) + IndexDst) = (Data00 + Data01 + Data11 + Data10) >> 2;
}
}
return Result;
}
}//namespace gli
| 41.075949
| 115
| 0.643451
|
cloudqiu1110
|
b47eb7c94ebf483f58f62de5e1ef48d1958af23f
| 167
|
hpp
|
C++
|
src/cpp/wasm.hpp
|
semious/layout
|
63c8be60855051fd886f8c6ecc1c85c5423473af
|
[
"MIT"
] | null | null | null |
src/cpp/wasm.hpp
|
semious/layout
|
63c8be60855051fd886f8c6ecc1c85c5423473af
|
[
"MIT"
] | 1
|
2021-12-11T10:35:10.000Z
|
2021-12-11T10:35:10.000Z
|
src/cpp/wasm.hpp
|
semious/layout
|
63c8be60855051fd886f8c6ecc1c85c5423473af
|
[
"MIT"
] | null | null | null |
#ifndef SPIDERJS_H_
#define SPIDERJS_H_
#include <cstddef>
#include <cstdint>
namespace graph_algo
{
namespace wasm
{
extern "C"
{
}
}
}
#endif
| 8.35
| 20
| 0.634731
|
semious
|
b4803b637ac0dc6e2bb41382710270a85eb71922
| 24,697
|
hpp
|
C++
|
include/System/Collections/CollectionBase.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | null | null | null |
include/System/Collections/CollectionBase.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | null | null | null |
include/System/Collections/CollectionBase.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | 1
|
2022-03-30T21:07:35.000Z
|
2022-03-30T21:07:35.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Collections.IList
#include "System/Collections/IList.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: ArrayList
class ArrayList;
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Array
class Array;
}
// Completed forward declares
// Type namespace: System.Collections
namespace System::Collections {
// Forward declaring type: CollectionBase
class CollectionBase;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Collections::CollectionBase);
DEFINE_IL2CPP_ARG_TYPE(::System::Collections::CollectionBase*, "System.Collections", "CollectionBase");
// Type namespace: System.Collections
namespace System::Collections {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: System.Collections.CollectionBase
// [TokenAttribute] Offset: FFFFFFFF
// [ComVisibleAttribute] Offset: 686A1C
class CollectionBase : public ::Il2CppObject/*, public ::System::Collections::IList*/ {
public:
public:
// private System.Collections.ArrayList list
// Size: 0x8
// Offset: 0x10
::System::Collections::ArrayList* list;
// Field size check
static_assert(sizeof(::System::Collections::ArrayList*) == 0x8);
public:
// Creating interface conversion operator: operator ::System::Collections::IList
operator ::System::Collections::IList() noexcept {
return *reinterpret_cast<::System::Collections::IList*>(this);
}
// Creating conversion operator: operator ::System::Collections::ArrayList*
constexpr operator ::System::Collections::ArrayList*() const noexcept {
return list;
}
// Get instance field reference: private System.Collections.ArrayList list
[[deprecated("Use field access instead!")]] ::System::Collections::ArrayList*& dyn_list();
// protected System.Collections.ArrayList get_InnerList()
// Offset: 0xE392A0
::System::Collections::ArrayList* get_InnerList();
// protected System.Collections.IList get_List()
// Offset: 0xE39308
::System::Collections::IList* get_List();
// public System.Int32 get_Count()
// Offset: 0xE3930C
int get_Count();
// private System.Boolean System.Collections.IList.get_IsReadOnly()
// Offset: 0xE39580
bool System_Collections_IList_get_IsReadOnly();
// private System.Boolean System.Collections.IList.get_IsFixedSize()
// Offset: 0xE395A8
bool System_Collections_IList_get_IsFixedSize();
// private System.Object System.Collections.ICollection.get_SyncRoot()
// Offset: 0xE395D0
::Il2CppObject* System_Collections_ICollection_get_SyncRoot();
// private System.Object System.Collections.IList.get_Item(System.Int32 index)
// Offset: 0xE39638
::Il2CppObject* System_Collections_IList_get_Item(int index);
// private System.Void System.Collections.IList.set_Item(System.Int32 index, System.Object value)
// Offset: 0xE39700
void System_Collections_IList_set_Item(int index, ::Il2CppObject* value);
// public System.Void Clear()
// Offset: 0xE39328
void Clear();
// public System.Void RemoveAt(System.Int32 index)
// Offset: 0xE39384
void RemoveAt(int index);
// private System.Void System.Collections.ICollection.CopyTo(System.Array array, System.Int32 index)
// Offset: 0xE395F8
void System_Collections_ICollection_CopyTo(::System::Array* array, int index);
// private System.Boolean System.Collections.IList.Contains(System.Object value)
// Offset: 0xE3990C
bool System_Collections_IList_Contains(::Il2CppObject* value);
// private System.Int32 System.Collections.IList.Add(System.Object value)
// Offset: 0xE39944
int System_Collections_IList_Add(::Il2CppObject* value);
// private System.Void System.Collections.IList.Remove(System.Object value)
// Offset: 0xE39AAC
void System_Collections_IList_Remove(::Il2CppObject* value);
// private System.Int32 System.Collections.IList.IndexOf(System.Object value)
// Offset: 0xE39C6C
int System_Collections_IList_IndexOf(::Il2CppObject* value);
// private System.Void System.Collections.IList.Insert(System.Int32 index, System.Object value)
// Offset: 0xE39CA4
void System_Collections_IList_Insert(int index, ::Il2CppObject* value);
// public System.Collections.IEnumerator GetEnumerator()
// Offset: 0xE39E80
::System::Collections::IEnumerator* GetEnumerator();
// protected System.Void OnSet(System.Int32 index, System.Object oldValue, System.Object newValue)
// Offset: 0xE39EA8
void OnSet(int index, ::Il2CppObject* oldValue, ::Il2CppObject* newValue);
// protected System.Void OnInsert(System.Int32 index, System.Object value)
// Offset: 0xE39EAC
void OnInsert(int index, ::Il2CppObject* value);
// protected System.Void OnClear()
// Offset: 0xE39EB0
void OnClear();
// protected System.Void OnRemove(System.Int32 index, System.Object value)
// Offset: 0xE39EB4
void OnRemove(int index, ::Il2CppObject* value);
// protected System.Void OnValidate(System.Object value)
// Offset: 0xE39EB8
void OnValidate(::Il2CppObject* value);
// protected System.Void OnSetComplete(System.Int32 index, System.Object oldValue, System.Object newValue)
// Offset: 0xE39F14
void OnSetComplete(int index, ::Il2CppObject* oldValue, ::Il2CppObject* newValue);
// protected System.Void OnInsertComplete(System.Int32 index, System.Object value)
// Offset: 0xE39F18
void OnInsertComplete(int index, ::Il2CppObject* value);
// protected System.Void OnClearComplete()
// Offset: 0xE39F1C
void OnClearComplete();
// protected System.Void OnRemoveComplete(System.Int32 index, System.Object value)
// Offset: 0xE39F20
void OnRemoveComplete(int index, ::Il2CppObject* value);
// protected System.Void .ctor()
// Offset: 0xE39238
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static CollectionBase* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<CollectionBase*, creationType>()));
}
}; // System.Collections.CollectionBase
#pragma pack(pop)
static check_size<sizeof(CollectionBase), 16 + sizeof(::System::Collections::ArrayList*)> __System_Collections_CollectionBaseSizeCheck;
static_assert(sizeof(CollectionBase) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Collections::CollectionBase::get_InnerList
// Il2CppName: get_InnerList
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::ArrayList* (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::get_InnerList)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "get_InnerList", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::get_List
// Il2CppName: get_List
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IList* (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::get_List)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "get_List", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::get_Count
// Il2CppName: get_Count
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::get_Count)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "get_Count", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_IList_get_IsReadOnly
// Il2CppName: System.Collections.IList.get_IsReadOnly
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::System_Collections_IList_get_IsReadOnly)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.IList.get_IsReadOnly", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_IList_get_IsFixedSize
// Il2CppName: System.Collections.IList.get_IsFixedSize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::System_Collections_IList_get_IsFixedSize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.IList.get_IsFixedSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_ICollection_get_SyncRoot
// Il2CppName: System.Collections.ICollection.get_SyncRoot
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::System_Collections_ICollection_get_SyncRoot)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.ICollection.get_SyncRoot", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_IList_get_Item
// Il2CppName: System.Collections.IList.get_Item
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Collections::CollectionBase::*)(int)>(&System::Collections::CollectionBase::System_Collections_IList_get_Item)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.IList.get_Item", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_IList_set_Item
// Il2CppName: System.Collections.IList.set_Item
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(int, ::Il2CppObject*)>(&System::Collections::CollectionBase::System_Collections_IList_set_Item)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.IList.set_Item", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::Clear
// Il2CppName: Clear
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::Clear)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "Clear", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::RemoveAt
// Il2CppName: RemoveAt
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(int)>(&System::Collections::CollectionBase::RemoveAt)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "RemoveAt", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_ICollection_CopyTo
// Il2CppName: System.Collections.ICollection.CopyTo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(::System::Array*, int)>(&System::Collections::CollectionBase::System_Collections_ICollection_CopyTo)> {
static const MethodInfo* get() {
static auto* array = &::il2cpp_utils::GetClassFromName("System", "Array")->byval_arg;
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.ICollection.CopyTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{array, index});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_IList_Contains
// Il2CppName: System.Collections.IList.Contains
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Collections::CollectionBase::*)(::Il2CppObject*)>(&System::Collections::CollectionBase::System_Collections_IList_Contains)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.IList.Contains", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_IList_Add
// Il2CppName: System.Collections.IList.Add
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Collections::CollectionBase::*)(::Il2CppObject*)>(&System::Collections::CollectionBase::System_Collections_IList_Add)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.IList.Add", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_IList_Remove
// Il2CppName: System.Collections.IList.Remove
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(::Il2CppObject*)>(&System::Collections::CollectionBase::System_Collections_IList_Remove)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.IList.Remove", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_IList_IndexOf
// Il2CppName: System.Collections.IList.IndexOf
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Collections::CollectionBase::*)(::Il2CppObject*)>(&System::Collections::CollectionBase::System_Collections_IList_IndexOf)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.IList.IndexOf", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::System_Collections_IList_Insert
// Il2CppName: System.Collections.IList.Insert
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(int, ::Il2CppObject*)>(&System::Collections::CollectionBase::System_Collections_IList_Insert)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "System.Collections.IList.Insert", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::GetEnumerator
// Il2CppName: GetEnumerator
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::GetEnumerator)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "GetEnumerator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::OnSet
// Il2CppName: OnSet
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(int, ::Il2CppObject*, ::Il2CppObject*)>(&System::Collections::CollectionBase::OnSet)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* oldValue = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* newValue = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "OnSet", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, oldValue, newValue});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::OnInsert
// Il2CppName: OnInsert
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(int, ::Il2CppObject*)>(&System::Collections::CollectionBase::OnInsert)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "OnInsert", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::OnClear
// Il2CppName: OnClear
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::OnClear)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "OnClear", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::OnRemove
// Il2CppName: OnRemove
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(int, ::Il2CppObject*)>(&System::Collections::CollectionBase::OnRemove)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "OnRemove", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::OnValidate
// Il2CppName: OnValidate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(::Il2CppObject*)>(&System::Collections::CollectionBase::OnValidate)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "OnValidate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::OnSetComplete
// Il2CppName: OnSetComplete
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(int, ::Il2CppObject*, ::Il2CppObject*)>(&System::Collections::CollectionBase::OnSetComplete)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* oldValue = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* newValue = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "OnSetComplete", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, oldValue, newValue});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::OnInsertComplete
// Il2CppName: OnInsertComplete
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(int, ::Il2CppObject*)>(&System::Collections::CollectionBase::OnInsertComplete)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "OnInsertComplete", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::OnClearComplete
// Il2CppName: OnClearComplete
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)()>(&System::Collections::CollectionBase::OnClearComplete)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "OnClearComplete", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::OnRemoveComplete
// Il2CppName: OnRemoveComplete
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::CollectionBase::*)(int, ::Il2CppObject*)>(&System::Collections::CollectionBase::OnRemoveComplete)> {
static const MethodInfo* get() {
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Collections::CollectionBase*), "OnRemoveComplete", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value});
}
};
// Writing MetadataGetter for method: System::Collections::CollectionBase::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 62.366162
| 218
| 0.752197
|
v0idp
|
b4812d1abb4a1c7d68f00493ef92e290429e6497
| 3,085
|
cpp
|
C++
|
aws-cpp-sdk-macie2/source/model/CreateClassificationJobRequest.cpp
|
orinem/aws-sdk-cpp
|
f38413cc1f278689ef14e9ebdd74a489a48776be
|
[
"Apache-2.0"
] | 1
|
2020-07-16T19:02:58.000Z
|
2020-07-16T19:02:58.000Z
|
aws-cpp-sdk-macie2/source/model/CreateClassificationJobRequest.cpp
|
novaquark/aws-sdk-cpp
|
a0969508545bec9ae2864c9e1e2bb9aff109f90c
|
[
"Apache-2.0"
] | null | null | null |
aws-cpp-sdk-macie2/source/model/CreateClassificationJobRequest.cpp
|
novaquark/aws-sdk-cpp
|
a0969508545bec9ae2864c9e1e2bb9aff109f90c
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/macie2/model/CreateClassificationJobRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Macie2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreateClassificationJobRequest::CreateClassificationJobRequest() :
m_clientToken(Aws::Utils::UUID::RandomUUID()),
m_clientTokenHasBeenSet(true),
m_customDataIdentifierIdsHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_initialRun(false),
m_initialRunHasBeenSet(false),
m_jobType(JobType::NOT_SET),
m_jobTypeHasBeenSet(false),
m_nameHasBeenSet(false),
m_s3JobDefinitionHasBeenSet(false),
m_samplingPercentage(0),
m_samplingPercentageHasBeenSet(false),
m_scheduleFrequencyHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
Aws::String CreateClassificationJobRequest::SerializePayload() const
{
JsonValue payload;
if(m_clientTokenHasBeenSet)
{
payload.WithString("clientToken", m_clientToken);
}
if(m_customDataIdentifierIdsHasBeenSet)
{
Array<JsonValue> customDataIdentifierIdsJsonList(m_customDataIdentifierIds.size());
for(unsigned customDataIdentifierIdsIndex = 0; customDataIdentifierIdsIndex < customDataIdentifierIdsJsonList.GetLength(); ++customDataIdentifierIdsIndex)
{
customDataIdentifierIdsJsonList[customDataIdentifierIdsIndex].AsString(m_customDataIdentifierIds[customDataIdentifierIdsIndex]);
}
payload.WithArray("customDataIdentifierIds", std::move(customDataIdentifierIdsJsonList));
}
if(m_descriptionHasBeenSet)
{
payload.WithString("description", m_description);
}
if(m_initialRunHasBeenSet)
{
payload.WithBool("initialRun", m_initialRun);
}
if(m_jobTypeHasBeenSet)
{
payload.WithString("jobType", JobTypeMapper::GetNameForJobType(m_jobType));
}
if(m_nameHasBeenSet)
{
payload.WithString("name", m_name);
}
if(m_s3JobDefinitionHasBeenSet)
{
payload.WithObject("s3JobDefinition", m_s3JobDefinition.Jsonize());
}
if(m_samplingPercentageHasBeenSet)
{
payload.WithInteger("samplingPercentage", m_samplingPercentage);
}
if(m_scheduleFrequencyHasBeenSet)
{
payload.WithObject("scheduleFrequency", m_scheduleFrequency.Jsonize());
}
if(m_tagsHasBeenSet)
{
JsonValue tagsJsonMap;
for(auto& tagsItem : m_tags)
{
tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
}
payload.WithObject("tags", std::move(tagsJsonMap));
}
return payload.View().WriteReadable();
}
| 25.286885
| 157
| 0.757212
|
orinem
|
b485041ec667ac5ffba8ff136d314a4e97077f23
| 32,428
|
cpp
|
C++
|
tests/XINTOUTTests.cpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
tests/XINTOUTTests.cpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
tests/XINTOUTTests.cpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | 1
|
2021-07-21T06:48:19.000Z
|
2021-07-21T06:48:19.000Z
|
// Copyright (c) 2020 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)
#include <ovk/extras/XINTOUT.hpp>
#include "tests/MPITest.hpp"
#include "tests/fixtures/Interface.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <ovk/core/Array.hpp>
#include <ovk/core/Cart.hpp>
#include <ovk/core/Comm.hpp>
#include <ovk/core/ConnectivityComponent.hpp>
#include <ovk/core/ConnectivityM.hpp>
#include <ovk/core/ConnectivityN.hpp>
#include <ovk/core/Domain.hpp>
#include <ovk/core/Exchanger.hpp>
#include <ovk/core/Grid.hpp>
#include <ovk/core/Range.hpp>
#include <ovk/core/Tuple.hpp>
#include <mpi.h>
using testing::ElementsAre;
using testing::ElementsAreArray;
class XINTOUTTests : public tests::mpi_test {};
using tests::Interface2D;
using tests::Interface3D;
TEST_F(XINTOUTTests, ImportStandard2D) {
ovk::comm Comm = CreateSubsetComm(TestComm(), TestComm().Rank() < 16);
if (Comm) {
ovk::domain Domain = Interface2D(Comm, {{-1.,-1.,0.}, {1.,1.,0.}}, {32,32,1}, {false, false,
false}, ovk::periodic_storage::UNIQUE);
Domain.CreateComponent<ovk::connectivity_component>(4);
ovk::ImportXINTOUT(Domain, 4, "data/XINTOUTTests/XINTOUT_Standard2D.HO.2D",
"data/XINTOUTTests/XINTOUT_Standard2D.X.2D", 0, MPI_INFO_NULL);
bool Grid1IsLocal = Domain.GridIsLocal(1);
bool Grid2IsLocal = Domain.GridIsLocal(2);
ovk::exchanger Exchanger = ovk::CreateExchanger(Domain.SharedContext());
Exchanger.Bind(Domain, ovk::exchanger::bindings()
.SetConnectivityComponentID(4)
);
auto &ConnectivityComponent = Domain.Component<ovk::connectivity_component>(4);
if (Grid1IsLocal) {
const ovk::grid &Grid = Domain.Grid(1);
const ovk::range &GlobalRange = Grid.GlobalRange();
const ovk::range &LocalRange = Grid.LocalRange();
bool HasInterface = LocalRange.End(1) == GlobalRange.End(1);
const ovk::connectivity_m &ConnectivityM = ConnectivityComponent.ConnectivityM({1,2});
const ovk::connectivity_n &ConnectivityN = ConnectivityComponent.ConnectivityN({2,1});
if (HasInterface) {
long long NumDonors = ConnectivityM.Size();
EXPECT_EQ(NumDonors, LocalRange.Size(0));
const ovk::array<int,3> &Extents = ConnectivityM.Extents();
const ovk::array<double,2> &Coords = ConnectivityM.Coords();
const ovk::array<double,3> &InterpCoefs = ConnectivityM.InterpCoefs();
const ovk::array<int,2> &Destinations = ConnectivityM.Destinations();
ovk::array<int,3> ExpectedExtents({{2,ovk::MAX_DIMS,NumDonors}});
ovk::array<double,2> ExpectedCoords({{ovk::MAX_DIMS,NumDonors}});
ovk::array<double,3> ExpectedInterpCoefs({{ovk::MAX_DIMS,1,NumDonors}});
ovk::array<int,2> ExpectedDestinations({{ovk::MAX_DIMS,NumDonors}});
long long iDonor = 0;
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedExtents(0,0,iDonor) = i;
ExpectedExtents(0,1,iDonor) = GlobalRange.End(1)-2;
ExpectedExtents(0,2,iDonor) = 0;
ExpectedExtents(1,0,iDonor) = ExpectedExtents(0,0,iDonor)+1;
ExpectedExtents(1,1,iDonor) = ExpectedExtents(0,1,iDonor)+1;
ExpectedExtents(1,2,iDonor) = 1;
ExpectedCoords(0,iDonor) = 0.;
ExpectedCoords(1,iDonor) = 0.;
ExpectedCoords(2,iDonor) = 0.;
ExpectedInterpCoefs(0,0,iDonor) = 1.;
ExpectedInterpCoefs(1,0,iDonor) = 1.;
ExpectedInterpCoefs(2,0,iDonor) = 1.;
ExpectedDestinations(0,iDonor) = i;
ExpectedDestinations(1,iDonor) = 0;
ExpectedDestinations(2,iDonor) = 0;
++iDonor;
}
EXPECT_THAT(Extents, ElementsAreArray(ExpectedExtents));
EXPECT_THAT(Coords, ElementsAreArray(ExpectedCoords));
EXPECT_THAT(InterpCoefs, ElementsAreArray(ExpectedInterpCoefs));
EXPECT_THAT(Destinations, ElementsAreArray(ExpectedDestinations));
long long NumReceivers = ConnectivityN.Size();
EXPECT_EQ(NumReceivers, LocalRange.Size(0));
const ovk::array<int,2> &Points = ConnectivityN.Points();
const ovk::array<int,2> &Sources = ConnectivityN.Sources();
ovk::array<int,2> ExpectedPoints({{ovk::MAX_DIMS,NumReceivers}});
ovk::array<int,2> ExpectedSources({{ovk::MAX_DIMS,NumReceivers}});
long long iReceiver = 0;
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedPoints(0,iReceiver) = i;
ExpectedPoints(1,iReceiver) = GlobalRange.End(1)-1;
ExpectedPoints(2,iReceiver) = 0;
ExpectedSources(0,iReceiver) = i;
ExpectedSources(1,iReceiver) = 1;
ExpectedSources(2,iReceiver) = 0;
++iReceiver;
}
EXPECT_THAT(Points, ElementsAreArray(Points));
EXPECT_THAT(Sources, ElementsAreArray(Sources));
} else {
EXPECT_EQ(ConnectivityM.Size(), 0);
EXPECT_EQ(ConnectivityN.Size(), 0);
}
}
if (Grid2IsLocal) {
const ovk::grid &Grid = Domain.Grid(2);
const ovk::range &GlobalRange = Grid.GlobalRange();
const ovk::range &LocalRange = Grid.LocalRange();
bool HasInterface = LocalRange.Begin(1) == GlobalRange.Begin(1);
const ovk::connectivity_m &ConnectivityM = ConnectivityComponent.ConnectivityM({2,1});
const ovk::connectivity_n &ConnectivityN = ConnectivityComponent.ConnectivityN({1,2});
if (HasInterface) {
long long NumDonors = ConnectivityM.Size();
EXPECT_EQ(NumDonors, LocalRange.Size(0));
const ovk::array<int,3> &Extents = ConnectivityM.Extents();
const ovk::array<double,2> &Coords = ConnectivityM.Coords();
const ovk::array<double,3> &InterpCoefs = ConnectivityM.InterpCoefs();
const ovk::array<int,2> &Destinations = ConnectivityM.Destinations();
ovk::array<int,3> ExpectedExtents({{2,ovk::MAX_DIMS,NumDonors}});
ovk::array<double,2> ExpectedCoords({{ovk::MAX_DIMS,NumDonors}});
ovk::array<double,3> ExpectedInterpCoefs({{ovk::MAX_DIMS,1,NumDonors}});
ovk::array<int,2> ExpectedDestinations({{ovk::MAX_DIMS,NumDonors}});
long long iDonor = 0;
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedExtents(0,0,iDonor) = i;
ExpectedExtents(0,1,iDonor) = 1;
ExpectedExtents(0,2,iDonor) = 0;
ExpectedExtents(1,0,iDonor) = ExpectedExtents(0,0,iDonor)+1;
ExpectedExtents(1,1,iDonor) = ExpectedExtents(0,1,iDonor)+1;
ExpectedExtents(1,2,iDonor) = 1;
ExpectedCoords(0,iDonor) = 0.;
ExpectedCoords(1,iDonor) = 0.;
ExpectedCoords(2,iDonor) = 0.;
ExpectedInterpCoefs(0,0,iDonor) = 1.;
ExpectedInterpCoefs(1,0,iDonor) = 1.;
ExpectedInterpCoefs(2,0,iDonor) = 1.;
ExpectedDestinations(0,iDonor) = i;
ExpectedDestinations(1,iDonor) = Domain.GridInfo(1).GlobalRange().End(1)-1;
ExpectedDestinations(2,iDonor) = 0;
++iDonor;
}
EXPECT_THAT(Extents, ElementsAreArray(ExpectedExtents));
EXPECT_THAT(Coords, ElementsAreArray(ExpectedCoords));
EXPECT_THAT(InterpCoefs, ElementsAreArray(ExpectedInterpCoefs));
EXPECT_THAT(Destinations, ElementsAreArray(ExpectedDestinations));
long long NumReceivers = ConnectivityN.Size();
EXPECT_EQ(NumReceivers, LocalRange.Size(0));
const ovk::array<int,2> &Points = ConnectivityN.Points();
const ovk::array<int,2> &Sources = ConnectivityN.Sources();
ovk::array<int,2> ExpectedPoints({{ovk::MAX_DIMS,NumReceivers}});
ovk::array<int,2> ExpectedSources({{ovk::MAX_DIMS,NumReceivers}});
long long iReceiver = 0;
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedPoints(0,iReceiver) = i;
ExpectedPoints(1,iReceiver) = 0;
ExpectedPoints(2,iReceiver) = 0;
ExpectedSources(0,iReceiver) = i;
ExpectedSources(1,iReceiver) = Domain.GridInfo(1).GlobalRange().End(1)-2;
ExpectedSources(2,iReceiver) = 0;
++iReceiver;
}
EXPECT_THAT(Points, ElementsAreArray(Points));
EXPECT_THAT(Sources, ElementsAreArray(Sources));
} else {
EXPECT_EQ(ConnectivityM.Size(), 0);
EXPECT_EQ(ConnectivityN.Size(), 0);
}
}
}
}
TEST_F(XINTOUTTests, ImportStandard3D) {
ovk::comm Comm = CreateSubsetComm(TestComm(), TestComm().Rank() < 64);
if (Comm) {
ovk::domain Domain = Interface3D(Comm, {{-1.,-1.,-1}, {1.,1.,1.}}, {32,32,32}, {false, false,
false}, ovk::periodic_storage::UNIQUE);
Domain.CreateComponent<ovk::connectivity_component>(4);
ovk::ImportXINTOUT(Domain, 4, "data/XINTOUTTests/XINTOUT_Standard3D.HO.2D",
"data/XINTOUTTests/XINTOUT_Standard3D.X.2D", 0, MPI_INFO_NULL);
bool Grid1IsLocal = Domain.GridIsLocal(1);
bool Grid2IsLocal = Domain.GridIsLocal(2);
ovk::exchanger Exchanger = ovk::CreateExchanger(Domain.SharedContext());
Exchanger.Bind(Domain, ovk::exchanger::bindings()
.SetConnectivityComponentID(4)
);
auto &ConnectivityComponent = Domain.Component<ovk::connectivity_component>(4);
if (Grid1IsLocal) {
const ovk::grid &Grid = Domain.Grid(1);
const ovk::range &GlobalRange = Grid.GlobalRange();
const ovk::range &LocalRange = Grid.LocalRange();
bool HasInterface = LocalRange.End(2) == GlobalRange.End(2);
const ovk::connectivity_m &ConnectivityM = ConnectivityComponent.ConnectivityM({1,2});
const ovk::connectivity_n &ConnectivityN = ConnectivityComponent.ConnectivityN({2,1});
if (HasInterface) {
long long NumDonors = ConnectivityM.Size();
EXPECT_EQ(NumDonors, LocalRange.Size(0)*LocalRange.Size(1));
const ovk::array<int,3> &Extents = ConnectivityM.Extents();
const ovk::array<double,2> &Coords = ConnectivityM.Coords();
const ovk::array<double,3> &InterpCoefs = ConnectivityM.InterpCoefs();
const ovk::array<int,2> &Destinations = ConnectivityM.Destinations();
ovk::array<int,3> ExpectedExtents({{2,ovk::MAX_DIMS,NumDonors}});
ovk::array<double,2> ExpectedCoords({{ovk::MAX_DIMS,NumDonors}});
ovk::array<double,3> ExpectedInterpCoefs({{ovk::MAX_DIMS,1,NumDonors}});
ovk::array<int,2> ExpectedDestinations({{ovk::MAX_DIMS,NumDonors}});
long long iDonor = 0;
for (int j = LocalRange.Begin(1); j < LocalRange.End(1); ++j) {
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedExtents(0,0,iDonor) = i;
ExpectedExtents(0,1,iDonor) = j;
ExpectedExtents(0,2,iDonor) = GlobalRange.End(2)-2;
ExpectedExtents(1,0,iDonor) = ExpectedExtents(0,0,iDonor)+1;
ExpectedExtents(1,1,iDonor) = ExpectedExtents(0,1,iDonor)+1;
ExpectedExtents(1,2,iDonor) = ExpectedExtents(0,2,iDonor)+1;
ExpectedCoords(0,iDonor) = 0.;
ExpectedCoords(1,iDonor) = 0.;
ExpectedCoords(2,iDonor) = 0.;
ExpectedInterpCoefs(0,0,iDonor) = 1.;
ExpectedInterpCoefs(1,0,iDonor) = 1.;
ExpectedInterpCoefs(2,0,iDonor) = 1.;
ExpectedDestinations(0,iDonor) = i;
ExpectedDestinations(1,iDonor) = j;
ExpectedDestinations(2,iDonor) = 0;
++iDonor;
}
}
EXPECT_THAT(Extents, ElementsAreArray(ExpectedExtents));
EXPECT_THAT(Coords, ElementsAreArray(ExpectedCoords));
EXPECT_THAT(InterpCoefs, ElementsAreArray(ExpectedInterpCoefs));
EXPECT_THAT(Destinations, ElementsAreArray(ExpectedDestinations));
long long NumReceivers = ConnectivityN.Size();
EXPECT_EQ(NumReceivers, LocalRange.Size(0)*LocalRange.Size(1));
const ovk::array<int,2> &Points = ConnectivityN.Points();
const ovk::array<int,2> &Sources = ConnectivityN.Sources();
ovk::array<int,2> ExpectedPoints({{ovk::MAX_DIMS,NumReceivers}});
ovk::array<int,2> ExpectedSources({{ovk::MAX_DIMS,NumReceivers}});
long long iReceiver = 0;
for (int j = LocalRange.Begin(1); j < LocalRange.End(1); ++j) {
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedPoints(0,iReceiver) = i;
ExpectedPoints(1,iReceiver) = j;
ExpectedPoints(2,iReceiver) = GlobalRange.End(2)-1;
ExpectedSources(0,iReceiver) = i;
ExpectedSources(1,iReceiver) = j;
ExpectedSources(2,iReceiver) = 1;
++iReceiver;
}
}
EXPECT_THAT(Points, ElementsAreArray(Points));
EXPECT_THAT(Sources, ElementsAreArray(Sources));
} else {
EXPECT_EQ(ConnectivityM.Size(), 0);
EXPECT_EQ(ConnectivityN.Size(), 0);
}
}
if (Grid2IsLocal) {
const ovk::grid &Grid = Domain.Grid(2);
const ovk::range &GlobalRange = Grid.GlobalRange();
const ovk::range &LocalRange = Grid.LocalRange();
bool HasInterface = LocalRange.Begin(2) == GlobalRange.Begin(2);
const ovk::connectivity_m &ConnectivityM = ConnectivityComponent.ConnectivityM({2,1});
const ovk::connectivity_n &ConnectivityN = ConnectivityComponent.ConnectivityN({1,2});
if (HasInterface) {
long long NumDonors = ConnectivityM.Size();
EXPECT_EQ(NumDonors, LocalRange.Size(0)*LocalRange.Size(1));
const ovk::array<int,3> &Extents = ConnectivityM.Extents();
const ovk::array<double,2> &Coords = ConnectivityM.Coords();
const ovk::array<double,3> &InterpCoefs = ConnectivityM.InterpCoefs();
const ovk::array<int,2> &Destinations = ConnectivityM.Destinations();
ovk::array<int,3> ExpectedExtents({{2,ovk::MAX_DIMS,NumDonors}});
ovk::array<double,2> ExpectedCoords({{ovk::MAX_DIMS,NumDonors}});
ovk::array<double,3> ExpectedInterpCoefs({{ovk::MAX_DIMS,1,NumDonors}});
ovk::array<int,2> ExpectedDestinations({{ovk::MAX_DIMS,NumDonors}});
long long iDonor = 0;
for (int j = LocalRange.Begin(1); j < LocalRange.End(1); ++j) {
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedExtents(0,0,iDonor) = i;
ExpectedExtents(0,1,iDonor) = j;
ExpectedExtents(0,2,iDonor) = 1;
ExpectedExtents(1,0,iDonor) = ExpectedExtents(0,0,iDonor)+1;
ExpectedExtents(1,1,iDonor) = ExpectedExtents(0,1,iDonor)+1;
ExpectedExtents(1,2,iDonor) = ExpectedExtents(0,2,iDonor)+1;
ExpectedCoords(0,iDonor) = 0.;
ExpectedCoords(1,iDonor) = 0.;
ExpectedCoords(2,iDonor) = 0.;
ExpectedInterpCoefs(0,0,iDonor) = 1.;
ExpectedInterpCoefs(1,0,iDonor) = 1.;
ExpectedInterpCoefs(2,0,iDonor) = 1.;
ExpectedDestinations(0,iDonor) = i;
ExpectedDestinations(1,iDonor) = j;
ExpectedDestinations(2,iDonor) = Domain.GridInfo(1).GlobalRange().End(2)-1;
++iDonor;
}
}
EXPECT_THAT(Extents, ElementsAreArray(ExpectedExtents));
EXPECT_THAT(Coords, ElementsAreArray(ExpectedCoords));
EXPECT_THAT(InterpCoefs, ElementsAreArray(ExpectedInterpCoefs));
EXPECT_THAT(Destinations, ElementsAreArray(ExpectedDestinations));
long long NumReceivers = ConnectivityN.Size();
EXPECT_EQ(NumReceivers, LocalRange.Size(0)*LocalRange.Size(1));
const ovk::array<int,2> &Points = ConnectivityN.Points();
const ovk::array<int,2> &Sources = ConnectivityN.Sources();
ovk::array<int,2> ExpectedPoints({{ovk::MAX_DIMS,NumReceivers}});
ovk::array<int,2> ExpectedSources({{ovk::MAX_DIMS,NumReceivers}});
long long iReceiver = 0;
for (int j = LocalRange.Begin(1); j < LocalRange.End(1); ++j) {
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedPoints(0,iReceiver) = i;
ExpectedPoints(1,iReceiver) = j;
ExpectedPoints(2,iReceiver) = 0;
ExpectedSources(0,iReceiver) = i;
ExpectedSources(1,iReceiver) = j;
ExpectedSources(2,iReceiver) = Domain.GridInfo(1).GlobalRange().End(2)-2;
++iReceiver;
}
}
EXPECT_THAT(Points, ElementsAreArray(Points));
EXPECT_THAT(Sources, ElementsAreArray(Sources));
} else {
EXPECT_EQ(ConnectivityM.Size(), 0);
EXPECT_EQ(ConnectivityN.Size(), 0);
}
}
}
}
TEST_F(XINTOUTTests, ImportExtended2D) {
ovk::comm Comm = CreateSubsetComm(TestComm(), TestComm().Rank() < 16);
if (Comm) {
ovk::domain Domain = Interface2D(Comm, {{-1.,-1.,0.}, {1.,1.,0.}}, {32,32,1}, {false, false,
false}, ovk::periodic_storage::UNIQUE);
Domain.CreateComponent<ovk::connectivity_component>(4);
ovk::ImportXINTOUT(Domain, 4, "data/XINTOUTTests/XINTOUT_Extended2D.HO.2D",
"data/XINTOUTTests/XINTOUT_Extended2D.X.2D", 0, MPI_INFO_NULL);
bool Grid1IsLocal = Domain.GridIsLocal(1);
bool Grid2IsLocal = Domain.GridIsLocal(2);
ovk::exchanger Exchanger = ovk::CreateExchanger(Domain.SharedContext());
Exchanger.Bind(Domain, ovk::exchanger::bindings()
.SetConnectivityComponentID(4)
);
auto &ConnectivityComponent = Domain.Component<ovk::connectivity_component>(4);
if (Grid1IsLocal) {
const ovk::grid &Grid = Domain.Grid(1);
const ovk::range &GlobalRange = Grid.GlobalRange();
const ovk::range &LocalRange = Grid.LocalRange();
bool HasInterface = LocalRange.End(1) == GlobalRange.End(1);
const ovk::connectivity_m &ConnectivityM = ConnectivityComponent.ConnectivityM({1,2});
const ovk::connectivity_n &ConnectivityN = ConnectivityComponent.ConnectivityN({2,1});
if (HasInterface) {
long long NumDonors = ConnectivityM.Size();
EXPECT_EQ(NumDonors, LocalRange.Size(0));
const ovk::array<int,3> &Extents = ConnectivityM.Extents();
const ovk::array<double,2> &Coords = ConnectivityM.Coords();
const ovk::array<double,3> &InterpCoefs = ConnectivityM.InterpCoefs();
const ovk::array<int,2> &Destinations = ConnectivityM.Destinations();
ovk::array<int,3> ExpectedExtents({{2,ovk::MAX_DIMS,NumDonors}});
ovk::array<double,2> ExpectedCoords({{ovk::MAX_DIMS,NumDonors}});
ovk::array<double,3> ExpectedInterpCoefs({{ovk::MAX_DIMS,1,NumDonors}});
ovk::array<int,2> ExpectedDestinations({{ovk::MAX_DIMS,NumDonors}});
long long iDonor = 0;
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedExtents(0,0,iDonor) = i;
ExpectedExtents(0,1,iDonor) = GlobalRange.End(1)-2;
ExpectedExtents(0,2,iDonor) = 0;
ExpectedExtents(1,0,iDonor) = ExpectedExtents(0,0,iDonor)+1;
ExpectedExtents(1,1,iDonor) = ExpectedExtents(0,1,iDonor)+1;
ExpectedExtents(1,2,iDonor) = 1;
ExpectedCoords(0,iDonor) = 0.;
ExpectedCoords(1,iDonor) = 0.;
ExpectedCoords(2,iDonor) = 0.;
ExpectedInterpCoefs(0,0,iDonor) = 1.;
ExpectedInterpCoefs(1,0,iDonor) = 1.;
ExpectedInterpCoefs(2,0,iDonor) = 1.;
ExpectedDestinations(0,iDonor) = i;
ExpectedDestinations(1,iDonor) = 0;
ExpectedDestinations(2,iDonor) = 0;
++iDonor;
}
EXPECT_THAT(Extents, ElementsAreArray(ExpectedExtents));
EXPECT_THAT(Coords, ElementsAreArray(ExpectedCoords));
EXPECT_THAT(InterpCoefs, ElementsAreArray(ExpectedInterpCoefs));
EXPECT_THAT(Destinations, ElementsAreArray(ExpectedDestinations));
long long NumReceivers = ConnectivityN.Size();
EXPECT_EQ(NumReceivers, LocalRange.Size(0));
const ovk::array<int,2> &Points = ConnectivityN.Points();
const ovk::array<int,2> &Sources = ConnectivityN.Sources();
ovk::array<int,2> ExpectedPoints({{ovk::MAX_DIMS,NumReceivers}});
ovk::array<int,2> ExpectedSources({{ovk::MAX_DIMS,NumReceivers}});
long long iReceiver = 0;
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedPoints(0,iReceiver) = i;
ExpectedPoints(1,iReceiver) = GlobalRange.End(1)-1;
ExpectedPoints(2,iReceiver) = 0;
ExpectedSources(0,iReceiver) = i;
ExpectedSources(1,iReceiver) = 1;
ExpectedSources(2,iReceiver) = 0;
++iReceiver;
}
EXPECT_THAT(Points, ElementsAreArray(Points));
EXPECT_THAT(Sources, ElementsAreArray(Sources));
} else {
EXPECT_EQ(ConnectivityM.Size(), 0);
EXPECT_EQ(ConnectivityN.Size(), 0);
}
}
if (Grid2IsLocal) {
const ovk::grid &Grid = Domain.Grid(2);
const ovk::range &GlobalRange = Grid.GlobalRange();
const ovk::range &LocalRange = Grid.LocalRange();
bool HasInterface = LocalRange.Begin(1) == GlobalRange.Begin(1);
const ovk::connectivity_m &ConnectivityM = ConnectivityComponent.ConnectivityM({2,1});
const ovk::connectivity_n &ConnectivityN = ConnectivityComponent.ConnectivityN({1,2});
if (HasInterface) {
long long NumDonors = ConnectivityM.Size();
EXPECT_EQ(NumDonors, LocalRange.Size(0));
const ovk::array<int,3> &Extents = ConnectivityM.Extents();
const ovk::array<double,2> &Coords = ConnectivityM.Coords();
const ovk::array<double,3> &InterpCoefs = ConnectivityM.InterpCoefs();
const ovk::array<int,2> &Destinations = ConnectivityM.Destinations();
ovk::array<int,3> ExpectedExtents({{2,ovk::MAX_DIMS,NumDonors}});
ovk::array<double,2> ExpectedCoords({{ovk::MAX_DIMS,NumDonors}});
ovk::array<double,3> ExpectedInterpCoefs({{ovk::MAX_DIMS,1,NumDonors}});
ovk::array<int,2> ExpectedDestinations({{ovk::MAX_DIMS,NumDonors}});
long long iDonor = 0;
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedExtents(0,0,iDonor) = i;
ExpectedExtents(0,1,iDonor) = 1;
ExpectedExtents(0,2,iDonor) = 0;
ExpectedExtents(1,0,iDonor) = ExpectedExtents(0,0,iDonor)+1;
ExpectedExtents(1,1,iDonor) = ExpectedExtents(0,1,iDonor)+1;
ExpectedExtents(1,2,iDonor) = 1;
ExpectedCoords(0,iDonor) = 0.;
ExpectedCoords(1,iDonor) = 0.;
ExpectedCoords(2,iDonor) = 0.;
ExpectedInterpCoefs(0,0,iDonor) = 1.;
ExpectedInterpCoefs(1,0,iDonor) = 1.;
ExpectedInterpCoefs(2,0,iDonor) = 1.;
ExpectedDestinations(0,iDonor) = i;
ExpectedDestinations(1,iDonor) = Domain.GridInfo(1).GlobalRange().End(1)-1;
ExpectedDestinations(2,iDonor) = 0;
++iDonor;
}
EXPECT_THAT(Extents, ElementsAreArray(ExpectedExtents));
EXPECT_THAT(Coords, ElementsAreArray(ExpectedCoords));
EXPECT_THAT(InterpCoefs, ElementsAreArray(ExpectedInterpCoefs));
EXPECT_THAT(Destinations, ElementsAreArray(ExpectedDestinations));
long long NumReceivers = ConnectivityN.Size();
EXPECT_EQ(NumReceivers, LocalRange.Size(0));
const ovk::array<int,2> &Points = ConnectivityN.Points();
const ovk::array<int,2> &Sources = ConnectivityN.Sources();
ovk::array<int,2> ExpectedPoints({{ovk::MAX_DIMS,NumReceivers}});
ovk::array<int,2> ExpectedSources({{ovk::MAX_DIMS,NumReceivers}});
long long iReceiver = 0;
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedPoints(0,iReceiver) = i;
ExpectedPoints(1,iReceiver) = 0;
ExpectedPoints(2,iReceiver) = 0;
ExpectedSources(0,iReceiver) = i;
ExpectedSources(1,iReceiver) = Domain.GridInfo(1).GlobalRange().End(1)-2;
ExpectedSources(2,iReceiver) = 0;
++iReceiver;
}
EXPECT_THAT(Points, ElementsAreArray(Points));
EXPECT_THAT(Sources, ElementsAreArray(Sources));
} else {
EXPECT_EQ(ConnectivityM.Size(), 0);
EXPECT_EQ(ConnectivityN.Size(), 0);
}
}
}
}
TEST_F(XINTOUTTests, ImportExtended3D) {
ovk::comm Comm = CreateSubsetComm(TestComm(), TestComm().Rank() < 64);
if (Comm) {
ovk::domain Domain = Interface3D(Comm, {{-1.,-1.,-1}, {1.,1.,1.}}, {32,32,32}, {false, false,
false}, ovk::periodic_storage::UNIQUE);
Domain.CreateComponent<ovk::connectivity_component>(4);
ovk::ImportXINTOUT(Domain, 4, "data/XINTOUTTests/XINTOUT_Extended3D.HO.2D",
"data/XINTOUTTests/XINTOUT_Extended3D.X.2D", 0, MPI_INFO_NULL);
bool Grid1IsLocal = Domain.GridIsLocal(1);
bool Grid2IsLocal = Domain.GridIsLocal(2);
ovk::exchanger Exchanger = ovk::CreateExchanger(Domain.SharedContext());
Exchanger.Bind(Domain, ovk::exchanger::bindings()
.SetConnectivityComponentID(4)
);
auto &ConnectivityComponent = Domain.Component<ovk::connectivity_component>(4);
if (Grid1IsLocal) {
const ovk::grid &Grid = Domain.Grid(1);
const ovk::range &GlobalRange = Grid.GlobalRange();
const ovk::range &LocalRange = Grid.LocalRange();
bool HasInterface = LocalRange.End(2) == GlobalRange.End(2);
const ovk::connectivity_m &ConnectivityM = ConnectivityComponent.ConnectivityM({1,2});
const ovk::connectivity_n &ConnectivityN = ConnectivityComponent.ConnectivityN({2,1});
if (HasInterface) {
long long NumDonors = ConnectivityM.Size();
EXPECT_EQ(NumDonors, LocalRange.Size(0)*LocalRange.Size(1));
const ovk::array<int,3> &Extents = ConnectivityM.Extents();
const ovk::array<double,2> &Coords = ConnectivityM.Coords();
const ovk::array<double,3> &InterpCoefs = ConnectivityM.InterpCoefs();
const ovk::array<int,2> &Destinations = ConnectivityM.Destinations();
ovk::array<int,3> ExpectedExtents({{2,ovk::MAX_DIMS,NumDonors}});
ovk::array<double,2> ExpectedCoords({{ovk::MAX_DIMS,NumDonors}});
ovk::array<double,3> ExpectedInterpCoefs({{ovk::MAX_DIMS,1,NumDonors}});
ovk::array<int,2> ExpectedDestinations({{ovk::MAX_DIMS,NumDonors}});
long long iDonor = 0;
for (int j = LocalRange.Begin(1); j < LocalRange.End(1); ++j) {
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedExtents(0,0,iDonor) = i;
ExpectedExtents(0,1,iDonor) = j;
ExpectedExtents(0,2,iDonor) = GlobalRange.End(2)-2;
ExpectedExtents(1,0,iDonor) = ExpectedExtents(0,0,iDonor)+1;
ExpectedExtents(1,1,iDonor) = ExpectedExtents(0,1,iDonor)+1;
ExpectedExtents(1,2,iDonor) = ExpectedExtents(0,2,iDonor)+1;
ExpectedCoords(0,iDonor) = 0.;
ExpectedCoords(1,iDonor) = 0.;
ExpectedCoords(2,iDonor) = 0.;
ExpectedInterpCoefs(0,0,iDonor) = 1.;
ExpectedInterpCoefs(1,0,iDonor) = 1.;
ExpectedInterpCoefs(2,0,iDonor) = 1.;
ExpectedDestinations(0,iDonor) = i;
ExpectedDestinations(1,iDonor) = j;
ExpectedDestinations(2,iDonor) = 0;
++iDonor;
}
}
EXPECT_THAT(Extents, ElementsAreArray(ExpectedExtents));
EXPECT_THAT(Coords, ElementsAreArray(ExpectedCoords));
EXPECT_THAT(InterpCoefs, ElementsAreArray(ExpectedInterpCoefs));
EXPECT_THAT(Destinations, ElementsAreArray(ExpectedDestinations));
long long NumReceivers = ConnectivityN.Size();
EXPECT_EQ(NumReceivers, LocalRange.Size(0)*LocalRange.Size(1));
const ovk::array<int,2> &Points = ConnectivityN.Points();
const ovk::array<int,2> &Sources = ConnectivityN.Sources();
ovk::array<int,2> ExpectedPoints({{ovk::MAX_DIMS,NumReceivers}});
ovk::array<int,2> ExpectedSources({{ovk::MAX_DIMS,NumReceivers}});
long long iReceiver = 0;
for (int j = LocalRange.Begin(1); j < LocalRange.End(1); ++j) {
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedPoints(0,iReceiver) = i;
ExpectedPoints(1,iReceiver) = j;
ExpectedPoints(2,iReceiver) = GlobalRange.End(2)-1;
ExpectedSources(0,iReceiver) = i;
ExpectedSources(1,iReceiver) = j;
ExpectedSources(2,iReceiver) = 1;
++iReceiver;
}
}
EXPECT_THAT(Points, ElementsAreArray(Points));
EXPECT_THAT(Sources, ElementsAreArray(Sources));
} else {
EXPECT_EQ(ConnectivityM.Size(), 0);
EXPECT_EQ(ConnectivityN.Size(), 0);
}
}
if (Grid2IsLocal) {
const ovk::grid &Grid = Domain.Grid(2);
const ovk::range &GlobalRange = Grid.GlobalRange();
const ovk::range &LocalRange = Grid.LocalRange();
bool HasInterface = LocalRange.Begin(2) == GlobalRange.Begin(2);
const ovk::connectivity_m &ConnectivityM = ConnectivityComponent.ConnectivityM({2,1});
const ovk::connectivity_n &ConnectivityN = ConnectivityComponent.ConnectivityN({1,2});
if (HasInterface) {
long long NumDonors = ConnectivityM.Size();
EXPECT_EQ(NumDonors, LocalRange.Size(0)*LocalRange.Size(1));
const ovk::array<int,3> &Extents = ConnectivityM.Extents();
const ovk::array<double,2> &Coords = ConnectivityM.Coords();
const ovk::array<double,3> &InterpCoefs = ConnectivityM.InterpCoefs();
const ovk::array<int,2> &Destinations = ConnectivityM.Destinations();
ovk::array<int,3> ExpectedExtents({{2,ovk::MAX_DIMS,NumDonors}});
ovk::array<double,2> ExpectedCoords({{ovk::MAX_DIMS,NumDonors}});
ovk::array<double,3> ExpectedInterpCoefs({{ovk::MAX_DIMS,1,NumDonors}});
ovk::array<int,2> ExpectedDestinations({{ovk::MAX_DIMS,NumDonors}});
long long iDonor = 0;
for (int j = LocalRange.Begin(1); j < LocalRange.End(1); ++j) {
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedExtents(0,0,iDonor) = i;
ExpectedExtents(0,1,iDonor) = j;
ExpectedExtents(0,2,iDonor) = 1;
ExpectedExtents(1,0,iDonor) = ExpectedExtents(0,0,iDonor)+1;
ExpectedExtents(1,1,iDonor) = ExpectedExtents(0,1,iDonor)+1;
ExpectedExtents(1,2,iDonor) = ExpectedExtents(0,2,iDonor)+1;
ExpectedCoords(0,iDonor) = 0.;
ExpectedCoords(1,iDonor) = 0.;
ExpectedCoords(2,iDonor) = 0.;
ExpectedInterpCoefs(0,0,iDonor) = 1.;
ExpectedInterpCoefs(1,0,iDonor) = 1.;
ExpectedInterpCoefs(2,0,iDonor) = 1.;
ExpectedDestinations(0,iDonor) = i;
ExpectedDestinations(1,iDonor) = j;
ExpectedDestinations(2,iDonor) = Domain.GridInfo(1).GlobalRange().End(2)-1;
++iDonor;
}
}
EXPECT_THAT(Extents, ElementsAreArray(ExpectedExtents));
EXPECT_THAT(Coords, ElementsAreArray(ExpectedCoords));
EXPECT_THAT(InterpCoefs, ElementsAreArray(ExpectedInterpCoefs));
EXPECT_THAT(Destinations, ElementsAreArray(ExpectedDestinations));
long long NumReceivers = ConnectivityN.Size();
EXPECT_EQ(NumReceivers, LocalRange.Size(0)*LocalRange.Size(1));
const ovk::array<int,2> &Points = ConnectivityN.Points();
const ovk::array<int,2> &Sources = ConnectivityN.Sources();
ovk::array<int,2> ExpectedPoints({{ovk::MAX_DIMS,NumReceivers}});
ovk::array<int,2> ExpectedSources({{ovk::MAX_DIMS,NumReceivers}});
long long iReceiver = 0;
for (int j = LocalRange.Begin(1); j < LocalRange.End(1); ++j) {
for (int i = LocalRange.Begin(0); i < LocalRange.End(0); ++i) {
ExpectedPoints(0,iReceiver) = i;
ExpectedPoints(1,iReceiver) = j;
ExpectedPoints(2,iReceiver) = 0;
ExpectedSources(0,iReceiver) = i;
ExpectedSources(1,iReceiver) = j;
ExpectedSources(2,iReceiver) = Domain.GridInfo(1).GlobalRange().End(2)-2;
++iReceiver;
}
}
EXPECT_THAT(Points, ElementsAreArray(Points));
EXPECT_THAT(Sources, ElementsAreArray(Sources));
} else {
EXPECT_EQ(ConnectivityM.Size(), 0);
EXPECT_EQ(ConnectivityN.Size(), 0);
}
}
}
}
| 42.500655
| 97
| 0.636888
|
gyzhangqm
|
b48d06518c9e25279987caa3c4e84ff5b6713f4a
| 196
|
cpp
|
C++
|
src/MathHelper.cpp
|
ThalissonMelo/IDJ-Game
|
3d31722479b75151a6e1f328c6b71ec7b1022168
|
[
"MIT"
] | null | null | null |
src/MathHelper.cpp
|
ThalissonMelo/IDJ-Game
|
3d31722479b75151a6e1f328c6b71ec7b1022168
|
[
"MIT"
] | null | null | null |
src/MathHelper.cpp
|
ThalissonMelo/IDJ-Game
|
3d31722479b75151a6e1f328c6b71ec7b1022168
|
[
"MIT"
] | null | null | null |
#include "MathHelper.h"
#define PI 3.141592653589793
float MathHelper::Cos(float angle){
return cos(angle * (PI/180));
}
float MathHelper::Sin(float angle){
return sin(angle * (PI/180));
}
| 19.6
| 35
| 0.693878
|
ThalissonMelo
|
b48d9f37d406b6c69134759aa874c526d13d3194
| 8,830
|
cpp
|
C++
|
core/string_db.cpp
|
masoudbh/godot
|
c731dd1ba68604ff7e97915e2b9d3011e818ca03
|
[
"CC-BY-3.0",
"MIT"
] | 33
|
2015-01-01T23:34:59.000Z
|
2020-10-30T02:22:39.000Z
|
core/string_db.cpp
|
masoudbh/godot
|
c731dd1ba68604ff7e97915e2b9d3011e818ca03
|
[
"CC-BY-3.0",
"MIT"
] | null | null | null |
core/string_db.cpp
|
masoudbh/godot
|
c731dd1ba68604ff7e97915e2b9d3011e818ca03
|
[
"CC-BY-3.0",
"MIT"
] | 5
|
2015-03-05T01:19:50.000Z
|
2020-05-11T05:49:30.000Z
|
/*************************************************************************/
/* string_db.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "string_db.h"
#include "print_string.h"
#include "os/os.h"
StaticCString StaticCString::create(const char *p_ptr) {
StaticCString scs; scs.ptr=p_ptr; return scs;
}
StringName::_Data *StringName::_table[STRING_TABLE_LEN];
StringName _scs_create(const char *p_chr) {
return (p_chr[0]?StringName(StaticCString::create(p_chr)):StringName());
}
bool StringName::configured=false;
void StringName::setup() {
ERR_FAIL_COND(configured);
for(int i=0;i<STRING_TABLE_LEN;i++) {
_table[i]=NULL;
}
configured=true;
}
void StringName::cleanup() {
_global_lock();
int lost_strings=0;
for(int i=0;i<STRING_TABLE_LEN;i++) {
while(_table[i]) {
_Data*d=_table[i];
lost_strings++;
if (OS::get_singleton()->is_stdout_verbose()) {
if (d->cname) {
print_line("Orphan StringName: "+String(d->cname));
} else {
print_line("Orphan StringName: "+String(d->name));
}
}
_table[i]=_table[i]->next;
memdelete(d);
}
}
if (OS::get_singleton()->is_stdout_verbose() && lost_strings) {
print_line("StringName: "+itos(lost_strings)+" unclaimed string names at exit.");
}
_global_unlock();
}
void StringName::unref() {
ERR_FAIL_COND(!configured);
if (_data && _data->refcount.unref()) {
_global_lock();
if (_data->prev) {
_data->prev->next=_data->next;
} else {
if (_table[_data->idx]!=_data) {
ERR_PRINT("BUG!");
}
_table[_data->idx]=_data->next;
}
if (_data->next) {
_data->next->prev=_data->prev;
}
memdelete(_data);
_global_unlock();
}
_data=NULL;
}
bool StringName::operator==(const String& p_name) const {
if (!_data) {
return (p_name.length()==0);
}
return (_data->get_name()==p_name);
}
bool StringName::operator==(const char* p_name) const {
if (!_data) {
return (p_name[0]==0);
}
return (_data->get_name()==p_name);
}
bool StringName::operator!=(const String& p_name) const {
return !(operator==(p_name));
}
bool StringName::operator!=(const StringName& p_name) const {
// the real magic of all this mess happens here.
// this is why path comparisons are very fast
return _data!=p_name._data;
}
void StringName::operator=(const StringName& p_name) {
if (this==&p_name)
return;
unref();
if (p_name._data && p_name._data->refcount.ref()) {
_data = p_name._data;
}
}
/* was inlined
StringName::operator String() const {
if (_data)
return _data->get_name();
return "";
}
*/
StringName::StringName(const StringName& p_name) {
ERR_FAIL_COND(!configured);
_data=NULL;
if (p_name._data && p_name._data->refcount.ref()) {
_data = p_name._data;
}
}
StringName::StringName(const char *p_name) {
_data=NULL;
ERR_FAIL_COND(!configured);
ERR_FAIL_COND( !p_name || !p_name[0]);
_global_lock();
uint32_t hash = String::hash(p_name);
uint32_t idx=hash&STRING_TABLE_MASK;
_data=_table[idx];
while(_data) {
// compare hash first
if (_data->hash==hash && _data->get_name()==p_name)
break;
_data=_data->next;
}
if (_data) {
if (_data->refcount.ref()) {
// exists
_global_unlock();
return;
} else {
}
}
_data = memnew( _Data );
_data->name=p_name;
_data->refcount.init();
_data->hash=hash;
_data->idx=idx;
_data->cname=NULL;
_data->next=_table[idx];
_data->prev=NULL;
if (_table[idx])
_table[idx]->prev=_data;
_table[idx]=_data;
_global_unlock();
}
StringName::StringName(const StaticCString& p_static_string) {
_data=NULL;
ERR_FAIL_COND(!configured);
ERR_FAIL_COND( !p_static_string.ptr || !p_static_string.ptr[0]);
_global_lock();
uint32_t hash = String::hash(p_static_string.ptr);
uint32_t idx=hash&STRING_TABLE_MASK;
_data=_table[idx];
while(_data) {
// compare hash first
if (_data->hash==hash && _data->get_name()==p_static_string.ptr)
break;
_data=_data->next;
}
if (_data) {
if (_data->refcount.ref()) {
// exists
_global_unlock();
return;
} else {
}
}
_data = memnew( _Data );
_data->refcount.init();
_data->hash=hash;
_data->idx=idx;
_data->cname=p_static_string.ptr;
_data->next=_table[idx];
_data->prev=NULL;
if (_table[idx])
_table[idx]->prev=_data;
_table[idx]=_data;
_global_unlock();
}
StringName::StringName(const String& p_name) {
_data=NULL;
ERR_FAIL_COND(!configured);
_global_lock();
uint32_t hash = p_name.hash();
uint32_t idx=hash&STRING_TABLE_MASK;
_data=_table[idx];
while(_data) {
if (_data->hash==hash && _data->get_name()==p_name)
break;
_data=_data->next;
}
if (_data) {
if (_data->refcount.ref()) {
// exists
_global_unlock();
return;
} else {
}
}
_data = memnew( _Data );
_data->name=p_name;
_data->refcount.init();
_data->hash=hash;
_data->idx=idx;
_data->cname=NULL;
_data->next=_table[idx];
_data->prev=NULL;
if (_table[idx])
_table[idx]->prev=_data;
_table[idx]=_data;
_global_unlock();
}
StringName StringName::search(const char *p_name) {
ERR_FAIL_COND_V(!configured,StringName());
ERR_FAIL_COND_V( !p_name, StringName() );
if (!p_name[0])
return StringName();
_global_lock();
uint32_t hash = String::hash(p_name);
uint32_t idx=hash&STRING_TABLE_MASK;
_Data *_data=_table[idx];
while(_data) {
// compare hash first
if (_data->hash==hash && _data->get_name()==p_name)
break;
_data=_data->next;
}
if (_data && _data->refcount.ref()) {
_global_unlock();
return StringName(_data);
}
_global_unlock();
return StringName(); //does not exist
}
StringName StringName::search(const CharType *p_name) {
ERR_FAIL_COND_V(!configured,StringName());
ERR_FAIL_COND_V( !p_name, StringName() );
if (!p_name[0])
return StringName();
_global_lock();
uint32_t hash = String::hash(p_name);
uint32_t idx=hash&STRING_TABLE_MASK;
_Data *_data=_table[idx];
while(_data) {
// compare hash first
if (_data->hash==hash && _data->get_name()==p_name)
break;
_data=_data->next;
}
if (_data && _data->refcount.ref()) {
_global_unlock();
return StringName(_data);
}
_global_unlock();
return StringName(); //does not exist
}
StringName StringName::search(const String &p_name) {
ERR_FAIL_COND_V( p_name=="", StringName() );
_global_lock();
uint32_t hash = p_name.hash();
uint32_t idx=hash&STRING_TABLE_MASK;
_Data *_data=_table[idx];
while(_data) {
// compare hash first
if (_data->hash==hash && p_name==_data->get_name())
break;
_data=_data->next;
}
if (_data && _data->refcount.ref()) {
_global_unlock();
return StringName(_data);
}
_global_unlock();
return StringName(); //does not exist
}
StringName::StringName() {
_data=NULL;
}
StringName::~StringName() {
unref();
}
| 19.753915
| 83
| 0.602945
|
masoudbh
|
b48f70e4362a96809995518884ee0393657d91ec
| 1,284
|
cpp
|
C++
|
tests/0021_merge_two_sorted_lists_test.cpp
|
paulo-erichsen/leetcode
|
78543363f7f938bdbda75de9cdab645daa29466a
|
[
"MIT"
] | null | null | null |
tests/0021_merge_two_sorted_lists_test.cpp
|
paulo-erichsen/leetcode
|
78543363f7f938bdbda75de9cdab645daa29466a
|
[
"MIT"
] | null | null | null |
tests/0021_merge_two_sorted_lists_test.cpp
|
paulo-erichsen/leetcode
|
78543363f7f938bdbda75de9cdab645daa29466a
|
[
"MIT"
] | null | null | null |
#include "0021_merge_two_sorted_lists.cpp"
#include <doctest/doctest.h>
TEST_CASE("mergeTwoListsTest1")
{
auto l = list::make_list({1, 2, 4});
auto r = list::make_list({1, 3, 4});
Solution s = Solution();
auto* result = s.mergeTwoLists(l[0].get(), r[0].get());
// result = 1->1->2->3->4->4
REQUIRE(list::same_values(result, {1, 1, 2, 3, 4, 4}));
}
TEST_CASE("mergeTwoListsTest2")
{
auto l = list::make_list({2, 3, 4});
auto r = list::make_list({1, 2, 5});
Solution s = Solution();
auto* result = s.mergeTwoLists(l[0].get(), r[0].get());
// result = 1->2->2->3->4->5
REQUIRE(list::same_values(result, {1, 2, 2, 3, 4, 5}));
}
TEST_CASE("mergeTwoListsTest3")
{
auto l = list::make_list({2, 3, 4});
auto r = list::make_list({5, 6, 7});
Solution s = Solution();
auto* result = s.mergeTwoLists(l[0].get(), r[0].get());
// result = 2->3->4->5->6->7
REQUIRE(list::same_values(result, {2, 3, 4, 5, 6, 7}));
}
TEST_CASE("mergeTwoListsTest4")
{
auto l = list::make_list({4, 5, 6});
auto r = list::make_list({1, 2, 3});
Solution s = Solution();
auto* result = s.mergeTwoLists(l[0].get(), r[0].get());
// result = 1->2->3->4->5->6
REQUIRE(list::same_values(result, {1, 2, 3, 4, 5, 6}));
}
| 25.176471
| 59
| 0.563084
|
paulo-erichsen
|
b49358cf2eb205141320ee34c63caa91b7dd2fa1
| 1,006
|
cpp
|
C++
|
code/world/props/book.cpp
|
DamianoOriti/Escape-Room
|
0a5612492bf261f13dc5e98c5b786b241d3a1cf2
|
[
"MIT"
] | 1
|
2018-10-10T08:58:40.000Z
|
2018-10-10T08:58:40.000Z
|
code/world/props/book.cpp
|
DamianoOriti/Escape-Room
|
0a5612492bf261f13dc5e98c5b786b241d3a1cf2
|
[
"MIT"
] | null | null | null |
code/world/props/book.cpp
|
DamianoOriti/Escape-Room
|
0a5612492bf261f13dc5e98c5b786b241d3a1cf2
|
[
"MIT"
] | null | null | null |
#include "book.h"
#include "../../game.h"
Book::Book(const char* bodyFilename, const char* modelFilename, const Vector3f& position,
const Vector3f& rotationAxis, float rotationAngle) :
flag_(false),
pDiaryEntry_(nullptr),
Prop(bodyFilename, modelFilename, true, true, position, rotationAxis, rotationAngle)
{
pDiaryEntry_ = new Diary::Entry(
"../EscapeRoom/data/models/book.mdl",
"I have found a book which has been printed in\n1888 and is entitled 'The Eight Knights'"
);
pDiaryEntry_->getShadedModel3D()->position_.y = 0.0f;
pDiaryEntry_->getShadedModel3D()->scale_ = 0.5f;
}
Book::~Book()
{
if (pDiaryEntry_ != nullptr)
{
delete pDiaryEntry_;
pDiaryEntry_ = nullptr;
}
}
bool Book::use(Prop* pOtherProp)
{
if (!flag_)
{
Game::getInstance().playVideo(
"../EscapeRoom/data/videos/book_animation.mkv",
std::bind(
&Book::onVideoEnd,
this
)
);
flag_ = true;
}
return false;
}
void Book::onVideoEnd()
{
Game::getInstance().addEntryInDiary(pDiaryEntry_);
}
| 20.530612
| 91
| 0.696819
|
DamianoOriti
|
b4994c1e278c133e0185ecdd2803f310edb95ebd
| 6,580
|
h++
|
C++
|
include/nonius/go.h++
|
jtippet/nonius
|
8c1c2ce24c702bb9a7ec2f0a1bdf7cc52aee6424
|
[
"CC0-1.0"
] | 238
|
2015-02-15T09:09:08.000Z
|
2022-03-06T03:35:13.000Z
|
include/nonius/go.h++
|
jtippet/nonius
|
8c1c2ce24c702bb9a7ec2f0a1bdf7cc52aee6424
|
[
"CC0-1.0"
] | 66
|
2015-01-28T10:52:28.000Z
|
2016-09-02T11:06:48.000Z
|
benchmark/nonius/go.h++
|
Trick-17/FMath
|
7c67597e0c725784bd82a62d40762dffd3f81529
|
[
"MIT"
] | 36
|
2016-09-05T10:10:53.000Z
|
2022-01-25T13:39:17.000Z
|
// Nonius - C++ benchmarking tool
//
// Written in 2014- by the nonius contributors <nonius@rmf.io>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
// Runner entry point
#ifndef NONIUS_GO_HPP
#define NONIUS_GO_HPP
#include <nonius/clock.h++>
#include <nonius/benchmark.h++>
#include <nonius/configuration.h++>
#include <nonius/environment.h++>
#include <nonius/reporter.h++>
#include <nonius/reporters/standard_reporter.h++>
#include <nonius/detail/estimate_clock.h++>
#include <nonius/detail/analyse.h++>
#include <nonius/detail/complete_invoke.h++>
#include <nonius/detail/noexcept.h++>
#include <algorithm>
#include <set>
#include <exception>
#include <utility>
#include <regex>
namespace nonius {
namespace detail {
template <typename Clock>
environment<FloatDuration<Clock>> measure_environment(reporter& rep) {
rep.warmup_start();
auto iters = detail::warmup<Clock>();
rep.warmup_end(iters);
rep.estimate_clock_resolution_start();
auto resolution = detail::estimate_clock_resolution<Clock>(iters);
rep.estimate_clock_resolution_complete(resolution);
rep.estimate_clock_cost_start();
auto cost = detail::estimate_clock_cost<Clock>(resolution.mean);
rep.estimate_clock_cost_complete(cost);
return { resolution, cost };
}
} // namespace detail
struct benchmark_user_error : virtual std::exception {
char const* what() const NONIUS_NOEXCEPT override {
return "a benchmark failed to run successfully";
}
};
template <typename Fun>
detail::CompleteType<detail::ResultOf<Fun()>> user_code(reporter& rep, Fun&& fun) {
try {
return detail::complete_invoke(std::forward<Fun>(fun));
} catch(...) {
rep.benchmark_failure(std::current_exception());
throw benchmark_user_error();
}
}
inline std::vector<parameters> generate_params(param_configuration cfg) {
auto params = global_param_registry().defaults().merged(cfg.map);
if (!cfg.run) {
return {params};
} else {
using operation_t = std::function<param(param, param)>;
auto&& run = *cfg.run;
auto step = run.step;
auto oper = std::unordered_map<std::string, operation_t> {
{"+", std::plus<param>{}},
{"*", std::multiplies<param>{}},
}.at(run.op);
auto r = std::vector<parameters>{};
auto next = run.init;
std::generate_n(std::back_inserter(r), std::max(run.count, std::size_t{1}), [&] {
auto last = next;
next = oper(next, step);
return params.merged(parameters{{run.name, last}});
});
return r;
}
}
template <typename Iterator>
std::vector<benchmark> filter_benchmarks(Iterator first, Iterator last, std::string pattern) {
auto r = std::vector<benchmark>{};
auto matcher = std::regex{pattern};
std::copy_if(first, last, std::back_inserter(r), [&] (benchmark const& b) {
return std::regex_match(b.name, matcher);
});
return r;
}
template <typename Clock = default_clock, typename Iterator>
void go(configuration cfg, Iterator first, Iterator last, reporter& rep) {
rep.configure(cfg);
auto env = detail::measure_environment<Clock>(rep);
rep.suite_start();
auto benchmarks = filter_benchmarks(first, last, cfg.filter_pattern);
auto all_params = generate_params(cfg.params);
for (auto&& params : all_params) {
rep.params_start(params);
for (auto&& bench : benchmarks) {
rep.benchmark_start(bench.name);
auto plan = user_code(rep, [&]{
return bench.template prepare<Clock>(cfg, params, env);
});
rep.measurement_start(plan);
auto samples = user_code(rep, [&]{
return plan.template run<Clock>(cfg, env);
});
rep.measurement_complete(std::vector<fp_seconds>(samples.begin(), samples.end()));
if(!cfg.no_analysis) {
rep.analysis_start();
auto analysis = detail::analyse(cfg, env, samples.begin(), samples.end());
rep.analysis_complete(analysis);
}
rep.benchmark_complete();
}
rep.params_complete();
}
rep.suite_complete();
}
struct duplicate_benchmarks : virtual std::exception {
char const* what() const NONIUS_NOEXCEPT override {
return "two or more benchmarks with the same name were registered";
}
};
template <typename Clock = default_clock, typename Iterator>
void validate_benchmarks(Iterator first, Iterator last) {
struct strings_lt_through_pointer {
bool operator()(std::string* a, std::string* b) const { return *a < *b; };
};
std::set<std::string*, strings_lt_through_pointer> names;
for(; first != last; ++first) {
if(!names.insert(&first->name).second)
throw duplicate_benchmarks();
}
}
template <typename Clock = default_clock, typename Iterator>
void go(configuration cfg, Iterator first, Iterator last, reporter&& rep) {
go<Clock>(cfg, first, last, rep);
}
struct no_such_reporter : virtual std::exception {
char const* what() const NONIUS_NOEXCEPT override {
return "reporter could not be found";
}
};
template <typename Clock = default_clock>
void go(configuration cfg, benchmark_registry& benchmarks = global_benchmark_registry(), reporter_registry& reporters = global_reporter_registry()) {
auto it = reporters.find(cfg.reporter);
if(it == reporters.end()) throw no_such_reporter();
validate_benchmarks<Clock>(benchmarks.begin(), benchmarks.end());
go<Clock>(cfg, benchmarks.begin(), benchmarks.end(), *it->second);
}
} // namespace nonius
#endif // NONIUS_GO_HPP
| 36.759777
| 153
| 0.609726
|
jtippet
|
a3348dbf24676dc416428296e587705b3d69f5b9
| 2,788
|
cpp
|
C++
|
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcAirTerminalTypeEnum.cpp
|
vjeranc/ifcplusplus
|
215859fb84d5be484d454c2767571dd168612329
|
[
"MIT"
] | null | null | null |
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcAirTerminalTypeEnum.cpp
|
vjeranc/ifcplusplus
|
215859fb84d5be484d454c2767571dd168612329
|
[
"MIT"
] | 1
|
2019-03-06T08:59:24.000Z
|
2019-03-06T08:59:24.000Z
|
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcAirTerminalTypeEnum.cpp
|
Imerso3D/ifcplusplus
|
84d1a5f58db232e07f4f3d233a9efb035f3babd2
|
[
"MIT"
] | 1
|
2021-04-26T14:56:09.000Z
|
2021-04-26T14:56:09.000Z
|
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4/include/IfcAirTerminalTypeEnum.h"
// TYPE IfcAirTerminalTypeEnum = ENUMERATION OF (DIFFUSER ,GRILLE ,LOUVRE ,REGISTER ,USERDEFINED ,NOTDEFINED);
shared_ptr<BuildingObject> IfcAirTerminalTypeEnum::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcAirTerminalTypeEnum> copy_self( new IfcAirTerminalTypeEnum() );
copy_self->m_enum = m_enum;
return copy_self;
}
void IfcAirTerminalTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCAIRTERMINALTYPEENUM("; }
switch( m_enum )
{
case ENUM_DIFFUSER: stream << ".DIFFUSER."; break;
case ENUM_GRILLE: stream << ".GRILLE."; break;
case ENUM_LOUVRE: stream << ".LOUVRE."; break;
case ENUM_REGISTER: stream << ".REGISTER."; break;
case ENUM_USERDEFINED: stream << ".USERDEFINED."; break;
case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break;
}
if( is_select_type ) { stream << ")"; }
}
const std::wstring IfcAirTerminalTypeEnum::toString() const
{
switch( m_enum )
{
case ENUM_DIFFUSER: return L"DIFFUSER";
case ENUM_GRILLE: return L"GRILLE";
case ENUM_LOUVRE: return L"LOUVRE";
case ENUM_REGISTER: return L"REGISTER";
case ENUM_USERDEFINED: return L"USERDEFINED";
case ENUM_NOTDEFINED: return L"NOTDEFINED";
}
return L"";
}
shared_ptr<IfcAirTerminalTypeEnum> IfcAirTerminalTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcAirTerminalTypeEnum>(); }
if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcAirTerminalTypeEnum>(); }
shared_ptr<IfcAirTerminalTypeEnum> type_object( new IfcAirTerminalTypeEnum() );
if( boost::iequals( arg, L".DIFFUSER." ) )
{
type_object->m_enum = IfcAirTerminalTypeEnum::ENUM_DIFFUSER;
}
else if( boost::iequals( arg, L".GRILLE." ) )
{
type_object->m_enum = IfcAirTerminalTypeEnum::ENUM_GRILLE;
}
else if( boost::iequals( arg, L".LOUVRE." ) )
{
type_object->m_enum = IfcAirTerminalTypeEnum::ENUM_LOUVRE;
}
else if( boost::iequals( arg, L".REGISTER." ) )
{
type_object->m_enum = IfcAirTerminalTypeEnum::ENUM_REGISTER;
}
else if( boost::iequals( arg, L".USERDEFINED." ) )
{
type_object->m_enum = IfcAirTerminalTypeEnum::ENUM_USERDEFINED;
}
else if( boost::iequals( arg, L".NOTDEFINED." ) )
{
type_object->m_enum = IfcAirTerminalTypeEnum::ENUM_NOTDEFINED;
}
return type_object;
}
| 36.207792
| 161
| 0.712697
|
vjeranc
|
a334b10273bee22fca8052cc67822adc7d8d6ab4
| 4,534
|
cpp
|
C++
|
Tool/kvsconv/UcdConv.cpp
|
X1aoyueyue/KVS
|
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
|
[
"BSD-3-Clause"
] | 42
|
2015-07-24T23:05:07.000Z
|
2022-03-16T01:31:04.000Z
|
Tool/kvsconv/UcdConv.cpp
|
X1aoyueyue/KVS
|
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
|
[
"BSD-3-Clause"
] | 4
|
2015-03-17T05:42:49.000Z
|
2020-08-09T15:21:45.000Z
|
Tool/kvsconv/UcdConv.cpp
|
X1aoyueyue/KVS
|
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
|
[
"BSD-3-Clause"
] | 29
|
2015-01-03T05:56:32.000Z
|
2021-10-05T15:28:33.000Z
|
/*****************************************************************************/
/**
* @file UcdConv.cpp
* @author Naohisa Sakamoto
* @brief AVS UCD Data Converter
*/
/*****************************************************************************/
#include "UcdConv.h"
#include <memory>
#include <string>
#include <kvs/File>
#include <kvs/AVSUcd>
#include <kvs/UnstructuredVolumeObject>
#include <kvs/UnstructuredVolumeImporter>
namespace kvsconv
{
namespace UcdConv
{
/*===========================================================================*/
/**
* @brief Constructs a new Argument class for a ucd2kvsml.
* @param argc [in] argument count
* @param argv [in] argument values
*/
/*===========================================================================*/
Argument::Argument( int argc, char** argv ):
kvsconv::Argument::Common( argc, argv, UcdConv::CommandName )
{
addOption( UcdConv::CommandName, UcdConv::Description, 0 );
addOption( "e", "External data file. (optional)", 0, false );
addOption( "b", "Data file as binary. (optional)", 0, false );
}
/*===========================================================================*/
/**
* @brief Returns a input filename.
* @return input filename
*/
/*===========================================================================*/
std::string Argument::inputFilename()
{
return this->value<std::string>();
}
/*===========================================================================*/
/**
* @brief Returns a output filename.
* @param filename [in] input filename
* @return output filename.
*/
/*===========================================================================*/
std::string Argument::outputFilename( const std::string& filename )
{
if ( this->hasOption("output") )
{
return this->optionValue<std::string>("output");
}
else
{
// Default output filename: <basename_of_filename>.kvsml
// e.g) avs_data.inp -> avs_data.kvsml
const std::string basename = kvs::File( filename ).baseName();
const std::string extension = "kvsml";
return basename + "." + extension;
}
}
/*===========================================================================*/
/**
* @brief Returns a writing data type (ascii/external ascii/external binary).
* @return writing data type
*/
/*===========================================================================*/
kvs::KVSMLUnstructuredVolumeObject::WritingDataType Argument::writingDataType()
{
if ( this->hasOption("b") )
{
return kvs::KVSMLUnstructuredVolumeObject::ExternalBinary;
}
else
{
if ( this->hasOption("e") )
{
return kvs::KVSMLUnstructuredVolumeObject::ExternalAscii;
}
}
return kvs::KVSMLUnstructuredVolumeObject::Ascii;
}
/*===========================================================================*/
/**
* @brief Executes main process.
*/
/*===========================================================================*/
bool Main::exec()
{
// Parse specified arguments.
UcdConv::Argument arg( m_argc, m_argv );
if( !arg.parse() ) { return false; }
// Set a input filename and a output filename.
m_input_name = arg.inputFilename();
m_output_name = arg.outputFilename( m_input_name );
// Check input data file.
if ( m_input_name.empty() )
{
kvsMessageError() << "Input file is not specified." << std::endl;
return false;
}
kvs::File file( m_input_name );
if ( !file.exists() )
{
kvsMessageError() << m_input_name << " is not found." << std::endl;
return false;
}
// Read AVS UCD data file.
auto* data = new kvs::AVSUcd( m_input_name );
if ( data->isFailure() )
{
kvsMessageError() << "Cannot read " << m_input_name << "." << std::endl;
delete data;
return false;
}
// Import AVS UCD data as unstructured volume object.
auto* object = new kvs::UnstructuredVolumeImporter( data );
if ( !object )
{
kvsMessageError() << "Cannot import " << m_input_name << "." << std::endl;
delete data;
return false;
}
delete data;
// Write the unstructured volume object to a file in KVSML format.
const bool ascii = !arg.hasOption("b");
const bool external = arg.hasOption("e");
object->write( m_output_name, ascii, external );
delete object;
return true;
}
} // end of namespace UcdConv
} // end of namespace kvsconv
| 29.251613
| 82
| 0.491839
|
X1aoyueyue
|
a33972565473414158d984e6937b1fab7b00d09b
| 1,288
|
cpp
|
C++
|
EXAMPLES/WebSnap/LocateFileService/mainpg.cpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | 1
|
2022-01-13T01:03:55.000Z
|
2022-01-13T01:03:55.000Z
|
EXAMPLES/WebSnap/LocateFileService/mainpg.cpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null |
EXAMPLES/WebSnap/LocateFileService/mainpg.cpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null |
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <WebReq.hpp>
#include <WebCntxt.hpp>
#include <WebFact.hpp>
#include <WebInit.h>
#include "MainPg.h"
#include "ResourceLocator.h"
USEADDITIONALFILES("*.html");
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TMainPage *MainPage()
{
return (TMainPage*)WebContext()->FindModuleClass(__classid (TMainPage));
}
static TWebPageAccess PageAccess;
static TWebAppPageInit WebInit(__classid(TMainPage), caCache,
PageAccess << wpPublished /* << wpLoginRequired */, ".html", "", "", "", "");
void __fastcall TMainPage::LocateFileService1FindStream(TObject *ASender,
TComponent *AComponent, const AnsiString AFileName,
TStream *&AFoundStream, bool &AOwned, bool &AHandled)
{
// After dropping down the LocateFileService component,
// I double clicked on the OnFindStream event. This event will
// get fired anytime a template is located, or an include file is requested.
AHandled = TemplateFileStreamFromResource(AFileName, AFoundStream);
}
//---------------------------------------------------------------------------
| 29.953488
| 80
| 0.582298
|
earthsiege2
|
a339cdb5c14e6e4c8d427ddb4d9260b62ce90e1a
| 3,217
|
cpp
|
C++
|
Source/GUI/VCL_New/GUI_Main_Easy.cpp
|
buckmelanoma/MediaInfo
|
cf38b0e3d0e6ee2565f49276f423a5792ed62962
|
[
"BSD-2-Clause"
] | 743
|
2015-01-13T23:16:53.000Z
|
2022-03-31T22:56:27.000Z
|
Source/GUI/VCL_New/GUI_Main_Easy.cpp
|
buckmelanoma/MediaInfo
|
cf38b0e3d0e6ee2565f49276f423a5792ed62962
|
[
"BSD-2-Clause"
] | 317
|
2015-07-28T17:50:14.000Z
|
2022-03-08T02:41:19.000Z
|
Source/GUI/VCL_New/GUI_Main_Easy.cpp
|
buckmelanoma/MediaInfo
|
cf38b0e3d0e6ee2565f49276f423a5792ed62962
|
[
"BSD-2-Clause"
] | 134
|
2015-01-30T05:33:51.000Z
|
2022-03-21T09:39:38.000Z
|
/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Common/Core.h"
#include "GUI/VCL_New/GUI_Main_Easy.h"
//---------------------------------------------------------------------------
//***************************************************************************
// Constructor/Destructor
//***************************************************************************
//---------------------------------------------------------------------------
GUI_Main_Easy::GUI_Main_Easy(Core* Core_, TWinControl* Owner)
: GUI_Main_Common_Core(Core_)
{
//VCL
VCL=new TPanel(Owner);
VCL->Parent=Owner;
//Creation - Select
Select=new TComboBox(Owner);
Select->Parent=Owner;
//Update
GUI_Refresh();
}
//---------------------------------------------------------------------------
GUI_Main_Easy::~GUI_Main_Easy()
{
delete VCL; //VCL=NULL
}
//***************************************************************************
// Actions
//***************************************************************************
//---------------------------------------------------------------------------
void GUI_Main_Easy::GUI_Refresh()
{
//The choice list
/*
Select->Clear();
size_t FilesCount=FilesCount_Get();
for (File_Pos=0; File_Pos<FilesCount; File_Pos++)
Select->Append(FileName_Get());
File_Pos=0;
Select->SetSelection(File_Pos);
*/
GUI_Refresh_Partial();
}
//---------------------------------------------------------------------------
void GUI_Main_Easy::GUI_Refresh_Partial()
{
/*
//For each box
for (size_t StreamPos=0; StreamPos<Stream_Max; StreamPos++)
for (size_t Pos=0; Pos<Boxes[StreamPos].size(); Pos++)
Boxes[StreamPos][Pos]->GUI_Refresh();
*/
//Resize some boxes if needed
GUI_Resize_Partial();
}
//---------------------------------------------------------------------------
void GUI_Main_Easy::GUI_Resize()
{
//Global and Select
VCL->Left=0;
VCL->Top=0;
VCL->Width=VCL->Parent->ClientWidth;
VCL->Height=VCL->Parent->ClientHeight;
Select->Left=0;
Select->Top=0;
Select->Width=Select->Parent->ClientWidth;
Select->Height=20;
//Other
GUI_Resize_Partial();
}
//---------------------------------------------------------------------------
void GUI_Main_Easy::GUI_Resize_Partial()
{
/*
//For each box
for (size_t StreamPos=0; StreamPos<Stream_Max; StreamPos++)
for (size_t Pos=0; Pos<Boxes[StreamPos].size(); Pos++)
Boxes[StreamPos][Pos]->GUI_Resize();
*/
}
//***************************************************************************
// Events
//***************************************************************************
/*
void GUI_Main_Easy::OnChoice(wxCommandEvent& event)
{
File_Pos=Select->GetSelection();
GUI_Refresh_Partial();
}
*/
| 28.219298
| 78
| 0.412496
|
buckmelanoma
|
a33b0cd8ccfcbf54e99f80f7a4a3a1e8a324cb75
| 498
|
cpp
|
C++
|
docs/mfc/reference/codesnippet/CPP/ctreectrl-class_46.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 965
|
2017-06-25T23:57:11.000Z
|
2022-03-31T14:17:32.000Z
|
docs/mfc/reference/codesnippet/CPP/ctreectrl-class_46.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 3,272
|
2017-06-24T00:26:34.000Z
|
2022-03-31T22:14:07.000Z
|
docs/mfc/reference/codesnippet/CPP/ctreectrl-class_46.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 951
|
2017-06-25T12:36:14.000Z
|
2022-03-26T22:49:06.000Z
|
// Sort the item in reverse alphabetical order.
int CALLBACK MyCompareProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
// lParamSort contains a pointer to the tree control.
// The lParam of an item is just its handle,
// as specified with SetItemData
CTreeCtrl* pmyTreeCtrl = (CTreeCtrl*)lParamSort;
CString strItem1 = pmyTreeCtrl->GetItemText((HTREEITEM)lParam1);
CString strItem2 = pmyTreeCtrl->GetItemText((HTREEITEM)lParam2);
return strItem2.Compare(strItem1);
}
| 41.5
| 77
| 0.757028
|
bobbrow
|
a3409799027660eb7bb433e0d4591d4afee0847a
| 3,593
|
cpp
|
C++
|
src/renderer/vulkan/BackendResources.cpp
|
Ryp/reaper
|
da7b3aa4a69b95ced2496214e5cea4eb7823593a
|
[
"MIT"
] | 10
|
2018-08-16T05:32:46.000Z
|
2022-02-04T09:55:54.000Z
|
src/renderer/vulkan/BackendResources.cpp
|
Ryp/reaper
|
da7b3aa4a69b95ced2496214e5cea4eb7823593a
|
[
"MIT"
] | null | null | null |
src/renderer/vulkan/BackendResources.cpp
|
Ryp/reaper
|
da7b3aa4a69b95ced2496214e5cea4eb7823593a
|
[
"MIT"
] | 1
|
2019-05-13T17:56:35.000Z
|
2019-05-13T17:56:35.000Z
|
////////////////////////////////////////////////////////////////////////////////
/// Reaper
///
/// Copyright (c) 2015-2021 Thibault Schueller
/// This file is distributed under the MIT License
////////////////////////////////////////////////////////////////////////////////
#include "BackendResources.h"
#include "Backend.h"
#include "common/Log.h"
namespace Reaper
{
void create_backend_resources(ReaperRoot& root, VulkanBackend& backend)
{
backend.resources = new BackendResources;
BackendResources& resources = *backend.resources;
// Create command buffer
VkCommandPoolCreateInfo poolCreateInfo = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, nullptr,
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
backend.physicalDeviceInfo.graphicsQueueFamilyIndex};
Assert(vkCreateCommandPool(backend.device, &poolCreateInfo, nullptr, &resources.graphicsCommandPool) == VK_SUCCESS);
log_debug(root, "vulkan: created command pool with handle: {}", static_cast<void*>(resources.graphicsCommandPool));
VkCommandBufferAllocateInfo cmdBufferAllocInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, nullptr,
resources.graphicsCommandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY,
1};
Assert(vkAllocateCommandBuffers(backend.device, &cmdBufferAllocInfo, &resources.gfxCmdBuffer.handle) == VK_SUCCESS);
log_debug(
root, "vulkan: created command buffer with handle: {}", static_cast<void*>(resources.gfxCmdBuffer.handle));
const glm::uvec2 swapchain_extent(backend.presentInfo.surfaceExtent.width,
backend.presentInfo.surfaceExtent.height);
resources.mesh_cache = create_mesh_cache(root, backend);
resources.material_resources = create_material_resources(root, backend);
resources.cull_resources = create_culling_resources(root, backend);
resources.shadow_map_resources = create_shadow_map_resources(root, backend);
resources.main_pass_resources = create_main_pass_resources(root, backend, swapchain_extent);
resources.histogram_pass_resources = create_histogram_pass_resources(root, backend);
resources.swapchain_pass_resources = create_swapchain_pass_resources(root, backend, swapchain_extent);
resources.frame_sync_resources = create_frame_sync_resources(root, backend);
resources.audio_resources = create_audio_resources(root, backend);
}
void destroy_backend_resources(VulkanBackend& backend)
{
BackendResources& resources = *backend.resources;
destroy_swapchain_pass_resources(backend, resources.swapchain_pass_resources);
destroy_histogram_pass_resources(backend, resources.histogram_pass_resources);
destroy_main_pass_resources(backend, resources.main_pass_resources);
destroy_shadow_map_resources(backend, resources.shadow_map_resources);
destroy_culling_resources(backend, resources.cull_resources);
destroy_material_resources(backend, resources.material_resources);
destroy_mesh_cache(backend, resources.mesh_cache);
destroy_frame_sync_resources(backend, resources.frame_sync_resources);
destroy_audio_resources(backend, resources.audio_resources);
vkFreeCommandBuffers(backend.device, resources.graphicsCommandPool, 1, &resources.gfxCmdBuffer.handle);
vkDestroyCommandPool(backend.device, resources.graphicsCommandPool, nullptr);
delete backend.resources;
backend.resources = nullptr;
}
} // namespace Reaper
| 49.219178
| 120
| 0.719733
|
Ryp
|
a34190411a8ccfb55344da4576c4110b7c56c757
| 1,262
|
cpp
|
C++
|
algorithms/cpp/Problems 601-700/_637_AverageOfLevelsInBinaryTree.cpp
|
shivamacs/LeetCode
|
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
|
[
"MIT"
] | null | null | null |
algorithms/cpp/Problems 601-700/_637_AverageOfLevelsInBinaryTree.cpp
|
shivamacs/LeetCode
|
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
|
[
"MIT"
] | null | null | null |
algorithms/cpp/Problems 601-700/_637_AverageOfLevelsInBinaryTree.cpp
|
shivamacs/LeetCode
|
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
|
[
"MIT"
] | null | null | null |
/* Source - https://leetcode.com/problems/average-of-levels-in-binary-tree/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int data;
TreeNode* left, *right;
TreeNode (int x) {
data = x;
left = right = NULL;
}
};
vector<double> averageOfLevels (TreeNode* root) {
queue<TreeNode*> tq;
TreeNode *front = NULL;
int size, sum, count;
vector<double> avgs;
tq.push(root);
while (!tq.empty()) {
size = tq.size();
sum = count = 0;
while (size-- > 0) {
front = tq.front();
tq.pop();
sum += front->data;
count++;
if (front->left) tq.push(front->left);
if (front->right) tq.push(front->right);
}
avgs.push_back(double(sum)/double(count));
}
return avgs;
}
int main()
{
TreeNode* root = NULL;
root = new TreeNode(4);
root->left = new TreeNode(2);
root->right = new TreeNode(9);
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(5);
root->right->right = new TreeNode(7);
vector<double> avgs = averageOfLevels(root);
for (int i=0;i<avgs.size();i++) cout<<avgs[i]<<" ";
cout<<endl;
}
| 22.535714
| 75
| 0.541997
|
shivamacs
|
a3434d77afccd8c702984f68364c298e98e9e5e8
| 13,829
|
cpp
|
C++
|
serverplugin/dbp/tinysap/AvenueSmoothMessage.cpp
|
shrewdlin/BPE
|
cf29647479b1b8ed53afadaf70557387f4c07e16
|
[
"BSD-3-Clause"
] | 1
|
2016-07-12T06:00:37.000Z
|
2016-07-12T06:00:37.000Z
|
serverplugin/dbp/tinysap/AvenueSmoothMessage.cpp
|
shrewdlin/BPE
|
cf29647479b1b8ed53afadaf70557387f4c07e16
|
[
"BSD-3-Clause"
] | null | null | null |
serverplugin/dbp/tinysap/AvenueSmoothMessage.cpp
|
shrewdlin/BPE
|
cf29647479b1b8ed53afadaf70557387f4c07e16
|
[
"BSD-3-Clause"
] | 2
|
2016-09-06T07:59:09.000Z
|
2020-12-12T03:25:24.000Z
|
#include "AvenueSmoothMessage.h"
#include <boost/asio.hpp>
#include "Cipher.h"
#include <boost/thread/mutex.hpp>
#include <string>
using std::string;
using sdo::dbp::CCipher;
namespace sdo{
namespace commonsdk{
static boost::mutex s_mutexSequence;
unsigned int CAvenueSmoothEncoder::sm_dwSeq=0;
CAvenueSmoothEncoder::CAvenueSmoothEncoder()
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
pHeader->byContext=0;
pHeader->byPrio=0;
pHeader->byBodyType=0;
pHeader->byCharset=0;
pHeader->byHeadLen=sizeof(SAvenueMsgHeader);
pHeader->dwPacketLen=htonl(sizeof(SAvenueMsgHeader));
pHeader->byVersion=0x01;
pHeader->byM=0xFF;
pHeader->dwCode=0;
memset(pHeader->bySignature,0,16);
m_buffer.reset_loc(sizeof(SAvenueMsgHeader));
}
CAvenueSmoothEncoder::CAvenueSmoothEncoder(unsigned char byIdentifer,unsigned int dwServiceId,unsigned int dwMsgId,unsigned int dwCode)
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
pHeader->byContext=0;
pHeader->byPrio=0;
pHeader->byBodyType=0;
pHeader->byCharset=0;
pHeader->byHeadLen=sizeof(SAvenueMsgHeader);
pHeader->dwPacketLen=htonl(sizeof(SAvenueMsgHeader));
pHeader->byVersion=0x01;
pHeader->byM=0xFF;
pHeader->dwCode=0;
memset(pHeader->bySignature,0,16);
m_buffer.reset_loc(sizeof(SAvenueMsgHeader));
pHeader->byIdentifer=byIdentifer;
pHeader->dwServiceId=htonl(dwServiceId);
pHeader->dwMsgId=htonl(dwMsgId);
pHeader->dwCode=htonl(dwCode);
}
void CAvenueSmoothEncoder::Reset()
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
pHeader->byContext=0;
pHeader->byPrio=0;
pHeader->byBodyType=0;
pHeader->byCharset=0;
pHeader->byHeadLen=sizeof(SAvenueMsgHeader);
pHeader->dwPacketLen=htonl(sizeof(SAvenueMsgHeader));
pHeader->byVersion=0x01;
pHeader->byM=0xFF;
pHeader->dwCode=0;
memset(pHeader->bySignature,0,16);
m_buffer.reset_loc(sizeof(SAvenueMsgHeader));
}
void CAvenueSmoothEncoder::SetService(unsigned char byIdentifer,unsigned int dwServiceId,unsigned int dwMsgId,unsigned int dwCode)
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
pHeader->byIdentifer=byIdentifer;
pHeader->dwServiceId=htonl(dwServiceId);
pHeader->dwMsgId=htonl(dwMsgId);
pHeader->dwCode=htonl(dwCode);
}
unsigned int CAvenueSmoothEncoder::CreateAndSetSequence()
{
unsigned int dwSequnece;
{
boost::lock_guard<boost::mutex> guard(s_mutexSequence);
if(++sm_dwSeq==0)
sm_dwSeq++;
dwSequnece=sm_dwSeq;
}
SetSequence(dwSequnece);
return dwSequnece;
}
void CAvenueSmoothEncoder::SetSequence(unsigned int dwSequence)
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
pHeader->dwSequence=htonl(dwSequence);
}
void CAvenueSmoothEncoder::SetMsgOption(unsigned int dwOption)
{
// SDK_XLOG(XLOG_DEBUG, "CAvenueSmoothEncoder::%s\n",__FUNCTION__);
unsigned char * pOption=(unsigned char *)(&dwOption);
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
pHeader->byContext=pOption[0];
pHeader->byPrio=pOption[1];
pHeader->byBodyType=pOption[2];
pHeader->byCharset=pOption[3];
}
void CAvenueSmoothEncoder::SetExtHeader(const void *pBuffer, unsigned int nLen)
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
pHeader->byHeadLen=sizeof(SAvenueMsgHeader)+nLen;
memcpy(m_buffer.top(),pBuffer,nLen);
m_buffer.inc_loc(nLen);
pHeader->dwPacketLen=htonl(m_buffer.len());
}
void CAvenueSmoothEncoder::SetBody(const void *pBuffer, unsigned int nLen)
{
if(m_buffer.capacity()<nLen)
{
m_buffer.add_capacity(SAP_ALIGN(nLen-m_buffer.capacity()));
}
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
memcpy(m_buffer.top(),pBuffer,nLen);
m_buffer.inc_loc(nLen);
pHeader->dwPacketLen=htonl(m_buffer.len());
}
void CAvenueSmoothEncoder::AesEnc(unsigned char abyKey[16])
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
unsigned int nLeft=0x10-(m_buffer.len()-pHeader->byHeadLen)&0x0f;
if(m_buffer.capacity()<nLeft)
{
m_buffer.add_capacity(SAP_ALIGN(nLeft-m_buffer.capacity()));
}
pHeader=(SAvenueMsgHeader *)m_buffer.base();
memset(m_buffer.top(),0,nLeft);
m_buffer.inc_loc(nLeft);
unsigned char *pbyInBlk=(unsigned char *)m_buffer.base()+pHeader->byHeadLen;
CCipher::AesEnc(abyKey,pbyInBlk,m_buffer.len()-pHeader->byHeadLen,pbyInBlk);
pHeader->dwPacketLen=htonl(m_buffer.len());
}
void CAvenueSmoothEncoder::SetSignature(const char * szKey, unsigned int nLen)
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
int nMin=(nLen<16?nLen:16);
memcpy(pHeader->bySignature,szKey,nMin);
CCipher::Md5(m_buffer.base(),m_buffer.len(),pHeader->bySignature);
}
void CAvenueSmoothEncoder::SetValue(unsigned short wKey,const void* pValue,unsigned int nValueLen)
{
unsigned int nFactLen=((nValueLen&0x03)!=0?((nValueLen>>2)+1)<<2:nValueLen);
if(m_buffer.capacity()<nFactLen+4)
{
m_buffer.add_capacity(SAP_ALIGN(nFactLen+4-m_buffer.capacity()));
}
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
SAvenueMsgAttribute *pAtti=(SAvenueMsgAttribute *)m_buffer.top();
pAtti->wType=htons(wKey);
pAtti->wLength=htons(nValueLen+sizeof(SAvenueMsgAttribute));
memcpy(pAtti->acValue,pValue,nValueLen);
memset(pAtti->acValue+nValueLen,0,nFactLen-nValueLen);
m_buffer.inc_loc(sizeof(SAvenueMsgAttribute)+nFactLen);
pHeader->dwPacketLen=htonl(m_buffer.len());
}
void CAvenueSmoothEncoder::SetValue(unsigned short wKey, const string &strValue)
{
SetValue(wKey,strValue.c_str(),strValue.length());
}
void CAvenueSmoothEncoder::SetValue(unsigned short wKey, unsigned int wValue)
{
int nNetValue=htonl(wValue);
SetValue(wKey,&nNetValue,4);
}
void CAvenueSmoothEncoder::BeginValue(unsigned short wType)
{
if(m_buffer.capacity()<sizeof(SAvenueMsgAttribute))
{
m_buffer.add_capacity(SAP_ALIGN(sizeof(SAvenueMsgAttribute)-m_buffer.capacity()));
}
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
SAvenueMsgAttribute * pAttri=(SAvenueMsgAttribute *)m_buffer.top();
pAttri->wType=htons(wType);
m_buffer.inc_loc(sizeof(SAvenueMsgAttribute));
pHeader->dwPacketLen=htonl(m_buffer.len());
pAttriBlock=(unsigned char *)pAttri;
}
void CAvenueSmoothEncoder::AddValueBloc(const void *pData,unsigned int nLen)
{
unsigned int nFactLen=((nLen&0x03)!=0?((nLen>>2)+1)<<2:nLen);
if(m_buffer.capacity()<nFactLen)
{
m_buffer.add_capacity(SAP_ALIGN(nFactLen-m_buffer.capacity()));
}
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_buffer.base();
memcpy(m_buffer.top(),pData,nLen);
memset(m_buffer.top()+nLen,0,nFactLen-nLen);
m_buffer.inc_loc(nFactLen);
pHeader->dwPacketLen=htonl(m_buffer.len());
}
void CAvenueSmoothEncoder::EndValue(unsigned short dwLen)
{
if(dwLen!=0)
((SAvenueMsgAttribute *)pAttriBlock)->wLength=htons(dwLen);
else
((SAvenueMsgAttribute *)pAttriBlock)->wLength=htons(m_buffer.top()-pAttriBlock);
}
CAvenueSmoothDecoder::CAvenueSmoothDecoder(const void *pBuffer,int nLen)
{
m_pBuffer=(void *)pBuffer;
m_nLen=nLen;
}
CAvenueSmoothDecoder::CAvenueSmoothDecoder()
{
m_pBuffer=0;
m_nLen=0;
}
void CAvenueSmoothDecoder::Reset(const void *pBuffer,int nLen)
{
m_pBuffer=(void *)pBuffer;
m_nLen=nLen;
}
int CAvenueSmoothDecoder::VerifySignature(const char * szKey, unsigned int nLen)
{
unsigned char arSignature[16];
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
memcpy(arSignature,pHeader->bySignature,16);
int nMin=(nLen<16?nLen:16);
memset(pHeader->bySignature,0,16);
memcpy(pHeader->bySignature,szKey,nMin);
CCipher::Md5((const unsigned char *)m_pBuffer,m_nLen,pHeader->bySignature);
return memcmp(arSignature,pHeader->bySignature,16);
}
void CAvenueSmoothDecoder::AesDec(unsigned char abyKey[16])
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
unsigned char *ptrLoc=(unsigned char *)m_pBuffer+pHeader->byHeadLen;
CCipher::AesDec(abyKey,ptrLoc,m_nLen-pHeader->byHeadLen,ptrLoc);
}
void CAvenueSmoothDecoder::GetService(unsigned char * pIdentifer,unsigned int * pServiceId,unsigned int * pMsgId,unsigned int * pdwCode)
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
*pIdentifer=pHeader->byIdentifer;
*pServiceId=ntohl(pHeader->dwServiceId);
*pMsgId=ntohl(pHeader->dwMsgId);
*pdwCode=ntohl(pHeader->dwCode);
}
unsigned char CAvenueSmoothDecoder::GetIdentifier()
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
return pHeader->byIdentifer;
}
unsigned int CAvenueSmoothDecoder::GetServiceId()
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
return ntohl(pHeader->dwServiceId);
}
unsigned int CAvenueSmoothDecoder::GetMsgId()
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
return ntohl(pHeader->dwMsgId);
}
unsigned int CAvenueSmoothDecoder::GetCode()
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
return ntohl(pHeader->dwCode);
}
unsigned int CAvenueSmoothDecoder::GetSequence()
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
return ntohl(pHeader->dwSequence);
}
unsigned int CAvenueSmoothDecoder::GetMsgOption()
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
return *((int *)(&pHeader->byContext));
}
void CAvenueSmoothDecoder::GetExtHeader(void **ppBuffer, int * pLen)
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;
*ppBuffer=(unsigned char *)m_pBuffer+sizeof(SAvenueMsgHeader);
*pLen=pHeader->byHeadLen-sizeof(SAvenueMsgHeader);
}
void CAvenueSmoothDecoder::GetBody(void **ppBuffer, unsigned int * pLen)
{
SAvenueMsgHeader *pHeader=(SAvenueMsgHeader *)m_pBuffer;;
*ppBuffer=(unsigned char *)m_pBuffer+pHeader->byHeadLen;
*pLen=ntohl(pHeader->dwPacketLen)-pHeader->byHeadLen;
}
void CAvenueSmoothDecoder::DecodeBodyAsTLV()
{
void * pBody;
unsigned int nBodyLen;
GetBody(&pBody,&nBodyLen);
unsigned char *ptrLoc=(unsigned char *)pBody;
while(ptrLoc<(unsigned char *)pBody+nBodyLen)
{
SAvenueMsgAttribute *pAtti=(SAvenueMsgAttribute *)ptrLoc;
unsigned short nLen=ntohs(pAtti->wLength);
if(nLen==0)
{
break;
}
m_mapMultiAttri.insert(AttriMultiMap::value_type(ntohs(pAtti->wType),ptrLoc));
int nFactLen=((nLen&0x03)!=0?((nLen>>2)+1)<<2:nLen);
ptrLoc+=nFactLen;
}
}
int CAvenueSmoothDecoder::GetValue(unsigned short wKey,void** pValue, unsigned int * pValueLen)
{
AttriMultiMap::const_iterator itr=m_mapMultiAttri.find(wKey);
if(itr==m_mapMultiAttri.end())
{
return -1;
}
const unsigned char *ptrLoc=itr->second;
SAvenueMsgAttribute *pAtti=(SAvenueMsgAttribute *)ptrLoc;
*pValueLen=ntohs(pAtti->wLength)-sizeof(SAvenueMsgAttribute);
*pValue=pAtti->acValue;
return 0;
}
int CAvenueSmoothDecoder::GetValue(unsigned short wKey,string & strValue)
{
void *pData=NULL;
unsigned int nLen=0;
if(GetValue(wKey,&pData,&nLen)==-1||nLen<0)
{
return -1;
}
strValue=string((const char *)pData,nLen);
return 0;
}
int CAvenueSmoothDecoder::GetValue(unsigned short wKey, unsigned int * pValue)
{
void *pData=NULL;
unsigned int nLen=0;
if(GetValue(wKey,&pData,&nLen)==-1||nLen!=4)
{
return -1;
}
*pValue=ntohl(*(int *)pData);
return 0;
}
void CAvenueSmoothDecoder::GetValues(unsigned short wKey,vector<SAvenueValueNode> &vecValues)
{
std::pair<AttriMultiMap::const_iterator, AttriMultiMap::const_iterator> itr_pair = m_mapMultiAttri.equal_range(wKey);
AttriMultiMap::const_iterator itr;
for(itr=itr_pair.first; itr!=itr_pair.second;itr++)
{
const unsigned char *ptrLoc=itr->second;
SAvenueMsgAttribute *pAtti=(SAvenueMsgAttribute *)ptrLoc;
SAvenueValueNode tmp;
tmp.nLen=ntohs(pAtti->wLength)-sizeof(SAvenueMsgAttribute);
tmp.pLoc=pAtti->acValue;
vecValues.push_back(tmp);
}
}
void CAvenueSmoothDecoder::GetValues(unsigned short wKey,vector<string> &vecValues)
{
std::pair<AttriMultiMap::const_iterator, AttriMultiMap::const_iterator> itr_pair = m_mapMultiAttri.equal_range(wKey);
AttriMultiMap::const_iterator itr;
for(itr=itr_pair.first; itr!=itr_pair.second;itr++)
{
const unsigned char *ptrLoc=itr->second;
SAvenueMsgAttribute *pAtti=(SAvenueMsgAttribute *)ptrLoc;
int nLen=ntohs(pAtti->wLength)-sizeof(SAvenueMsgAttribute);
if(nLen>0)
{
string strValue=string((const char *)pAtti->acValue,nLen);
vecValues.push_back(strValue);
}
}
}
void CAvenueSmoothDecoder::GetValues(unsigned short wKey,vector<unsigned int> &vecValues)
{
std::pair<AttriMultiMap::const_iterator, AttriMultiMap::const_iterator> itr_pair = m_mapMultiAttri.equal_range(wKey);
AttriMultiMap::const_iterator itr;
for(itr=itr_pair.first; itr!=itr_pair.second;itr++)
{
const unsigned char *ptrLoc=itr->second;
SAvenueMsgAttribute *pAtti=(SAvenueMsgAttribute *)ptrLoc;
if(ntohs(pAtti->wLength)-sizeof(SAvenueMsgAttribute)==4)
{
vecValues.push_back(ntohl(*(unsigned int *)pAtti->acValue));
}
}
}
}
}
| 33.977887
| 137
| 0.701786
|
shrewdlin
|
a3449aa51756b99f36e7ab6d80f5b945d75b53d1
| 2,075
|
cpp
|
C++
|
Source/PluginAiState_Misc1/CAiState_FindEnemy.cpp
|
shanefarris/CoreGameEngine
|
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
|
[
"MIT"
] | 3
|
2019-04-12T15:22:53.000Z
|
2022-01-05T02:59:56.000Z
|
Source/PluginAiState_Misc1/CAiState_FindEnemy.cpp
|
shanefarris/CoreGameEngine
|
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
|
[
"MIT"
] | null | null | null |
Source/PluginAiState_Misc1/CAiState_FindEnemy.cpp
|
shanefarris/CoreGameEngine
|
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
|
[
"MIT"
] | 2
|
2019-04-10T22:46:21.000Z
|
2020-05-27T16:21:37.000Z
|
#include "CAiState_FindEnemy.h"
#include "CPlayer.h"
#include "CGameObjectManager.h"
#include "Ai/CFpsVehicle.h"
#include "Ai/Obstacle.h"
#include "CTextOutput.h"
#include "CCharacterStateManager.h"
#include "IO/CoreLogging.h"
using namespace Core;
using namespace Core::Plugin;
CAiState_FindEnemy::CAiState_FindEnemy(CPlayer* Player) : CCharacterState(Player)
{
m_State = WORKING;
m_StateType = EPS_FIND_ENEMY;
m_StateLabel = "FindEnemy";
m_Level = 1;
m_CheckCount = 0;
m_GameObjectManager = CGameObjectManager::Instance();
}
Core::AI::E_CHARACTER_STATE_OUTCOME CAiState_FindEnemy::Update(f32 elapsedTime)
{
CCharacterStateManager::Instance()->Search(m_Player, elapsedTime);
CORE_TEXT("CharacterState_FindEnemy", "looking for an enemy");
if(m_CheckCount >= 10)
{
m_CheckCount = 0;
CPlayer* target_player = nullptr;
Vector<CPlayer*> players;
m_GameObjectManager->GetAllPlayers(players);
for(u32 i = 0; i < players.size(); i++)
{
CPlayer* target = players[i];
// Check the team
if(target->GetPlayerTeam() != m_Player->GetPlayerTeam())
{
// Can we see them
if(m_Player->CanSee(target->GetPosition()) && target->GetHealth() > 0)
{
if(target)
{
f32 d = Vec3Utilities::distance (m_Player->GetPosition(), target->GetPosition());
if(d < m_Player->GetViewRange())
{
// Found a target, we are done
m_Player->SetAiTarget(target->GetAiVehicle());
m_State = SUCCESS;
#ifdef _DEBUG
CORE_TEXT("CharacterState_FindEnemy", "Found an enemy");
String msg = "CharacterState_FindEnemy success for player: " + String(m_Player->GetName());
CORE_LOG(msg.c_str());
#endif
}
}
}
}
}
}
m_CheckCount++;
return m_State;
}
CAiState_FindEnemyFactory::CAiState_FindEnemyFactory()
{
LabelName = "FindEnemy";
Type = EPS_FIND_ENEMY;
Level = 0;
}
CAiState_FindEnemyFactory::~CAiState_FindEnemyFactory()
{
}
Core::AI::CCharacterState* CAiState_FindEnemyFactory::GetCharacterState(CPlayer* Player)
{
return new CAiState_FindEnemy(Player);
}
| 25.304878
| 99
| 0.697349
|
shanefarris
|
a345389a92cadf8e10b26bf9c132db109e688859
| 26,442
|
cxx
|
C++
|
src/main.cxx
|
bwvdnbro/VELOCIraptor-STF
|
9c4a07eee20309152bcde40602029315c8bd50ca
|
[
"MIT"
] | 4
|
2020-08-28T11:29:09.000Z
|
2021-10-16T20:17:54.000Z
|
src/main.cxx
|
bwvdnbro/VELOCIraptor-STF
|
9c4a07eee20309152bcde40602029315c8bd50ca
|
[
"MIT"
] | 118
|
2019-05-06T11:46:28.000Z
|
2022-03-14T17:14:37.000Z
|
src/main.cxx
|
bwvdnbro/VELOCIraptor-STF
|
9c4a07eee20309152bcde40602029315c8bd50ca
|
[
"MIT"
] | 4
|
2020-10-01T05:22:31.000Z
|
2021-07-26T13:07:42.000Z
|
/*! \file main.cxx
* \brief Main program
This code initialize MPI (if necessary) and reads parameters from the user input (see \ref ui.cxx)
loads particle data from a N-body output (see \ref io.cxx) into an array of \ref NBody::Particle,
analyzes the system, searches for structures then substructures (see \ref search.cxx),
outputs the group ids (in two different fashions see \ref io.cxx) and can also analyze the structures
(see \ref substructureproperties.cxx and \ref io.cxx).
\todo remove array mpi_idlist and mpi_indexlist as these arrays are unnecessary
\todo alter unbinding/sortbybindingenergy calls since seems a waste of cpu cycles
*/
#include <algorithm>
#include <iterator>
#include <set>
#include <sstream>
#include <unistd.h>
#include "compilation_info.h"
#include "ioutils.h"
#include "stf.h"
#include "logging.h"
#include "timer.h"
using namespace std;
using namespace Math;
using namespace NBody;
using namespace velociraptor;
void finish_vr(Options &opt)
{
//get memory useage
LOG(info) << "Finished running VR";
MEMORY_USAGE_REPORT(info, opt);
#ifdef USEMPI
#ifdef USEADIOS
adios_finalize(ThisTask);
#endif
MPI_Finalize();
#endif
}
void show_version_info(int argc, char *argv[])
{
LOG_RANK0(info) << "VELOCIraptor git version: " << git_sha1();
LOG_RANK0(info) << "VELOCIraptor compiled with: " << vr::get_cxx_flags() << " " << vr::get_macros();
LOG_RANK0(info) << "VELOCIraptor was built on: " << vr::get_compilation_date();
char cwd[PATH_MAX];
std::ostringstream os;
LOG_RANK0(info) << "VELOCIraptor running at: " << getcwd(cwd, PATH_MAX);
std::copy(argv, argv + argc, std::ostream_iterator<char *>(os, " "));
LOG_RANK0(info) << "VELOCIraptor started with command line: " << os.str();
// MPI/OpenMP information
std::ostringstream mpi_info;
mpi_info << "VELOCIratptor MPI support: ";
#ifdef USEMPI
mpi_info << "yes, " << NProcs << " MPI ranks";
char hostname[HOST_NAME_MAX + 1];
::gethostname(hostname, HOST_NAME_MAX);
std::vector<char> all_hostnames;
if (ThisTask == 0) {
all_hostnames.resize((HOST_NAME_MAX + 1)* NProcs);
}
MPI_Gather(hostname, HOST_NAME_MAX + 1, MPI_CHAR, all_hostnames.data(), HOST_NAME_MAX + 1, MPI_CHAR, 0, MPI_COMM_WORLD);
if (ThisTask == 0) {
std::vector<std::string> proper_hostnames;
for (int rank = 0; rank != NProcs; rank++) {
proper_hostnames.emplace_back(all_hostnames.data() + (HOST_NAME_MAX + 1) * rank);
}
mpi_info << " running in " << std::set<std::string>(proper_hostnames.begin(), proper_hostnames.end()).size() << " nodes: ";
mpi_info << vr::printable_range(proper_hostnames);
}
#else
mpi_info << "no";
#endif
LOG_RANK0(info) << "VELOCIratptor MPI support: " << mpi_info.str();
LOG_RANK0(info) << "VELOCIratptor OpenMP support: "
#ifdef USEOPENMP
<< "yes, " << omp_get_max_threads() << " OpenMP threads, OpenMP version " << _OPENMP;
#else
<< "no";
#endif
}
int main(int argc,char **argv)
{
#ifdef USEMPI
//start MPI
#ifdef USEOPENMP
//if using hybrid then need to check that threads are available and use the correct initialization
//Each thread will call MPI routines, but these calls will be coordinated to occur only one at a time within a process.
int required=MPI_THREAD_FUNNELED; // Required level of MPI threading support
int provided; // Provided level of MPI threading support
MPI_Init_thread(&argc, &argv, required, &provided);
#else
MPI_Init(&argc,&argv);
#endif
//find out how big the SPMD world is
MPI_Comm_size(MPI_COMM_WORLD,&NProcs);
//and this processes' rank is
MPI_Comm_rank(MPI_COMM_WORLD,&ThisTask);
#ifdef USEOPENMP
// Check the threading support level
if (provided < required)
{
// Insufficient support, degrade to 1 thread and warn the user
if (ThisTask == 0) cout << "Warning: This MPI implementation provides insufficient threading support. Required was " <<required<<" but provided was "<<provided<<endl;
omp_set_num_threads(1);
MPI_Finalize();
exit(9);
}
#endif
#else
int ThisTask=0,NProcs=1;
Int_t Nlocal,Ntotal;
Int_t Ntotalbaryon[NBARYONTYPES], Nlocalbaryon[NBARYONTYPES];
#endif
int nthreads;
#ifdef USEOPENMP
nthreads = omp_get_max_threads();
#else
nthreads=1;
#endif
show_version_info(argc, argv);
#ifdef SWIFTINTERFACE
cout<<"Built with SWIFT interface enabled when running standalone VELOCIraptor. Should only be enabled when running VELOCIraptor as a library from SWIFT. Exiting..."<<endl;
exit(0);
#endif
gsl_set_error_handler_off();
Options opt;
//get arguments
GetArgs(argc, argv, opt);
cout.precision(10);
#ifdef USEMPI
MPIInitWriteComm();
#ifdef USEADIOS
//init adios
adios_init_noxml(MPI_COMM_WORLD);
//specify the buffer size (use the tot particle buffer size in bytes and convert to MB)
adios_set_max_buffer_size(opt.mpiparticletotbufsize/1024/1024);
#endif
#endif
InitMemUsageLog(opt);
//variables
//number of particles, (also number of baryons if use dm+baryon search)
//to store (point to) particle data
Int_t nbodies,nbaryons,ndark;
vector<Particle> Part;
Particle *Pbaryons;
KDTree *tree;
//number in subset, number of grids used if iSingleHalo==0;
Int_t nsubset, ngrid;
//number of groups, temp num groups, and number of halos
Int_t ngroup, ng, nhalos;
//to store group value (pfof), and also arrays to parse particles
//vector<Int_t> pfof, pfofbaryons;
Int_t *pfof, *pfofbaryons;;
Int_t *numingroup,**pglist;
Int_t *pfofall;
//to store information about the group
PropData *pdata=NULL,*pdatahalos=NULL;
//to store time and output time taken
vr::Timer total_timer;
Coordinate cm,cmvel;
Double_t Mtot;
char fname1[1000],fname4[1000];
#ifdef USEMPI
mpi_nlocal=new Int_t[NProcs];
mpi_domain=new MPI_Domain[NProcs];
mpi_nsend=new Int_t[NProcs*NProcs];
mpi_ngroups=new Int_t[NProcs];
mpi_nhalos=new Int_t[NProcs];
//store MinSize as when using mpi prior to stitching use min of 2;
MinNumMPI=2;
//if single halo, use minsize to initialize the old minimum number
//else use the halominsize since if mpi and not single halo, halos localized to mpi domain for substructure search
if (opt.iSingleHalo) MinNumOld=opt.MinSize;
else MinNumOld=opt.HaloMinSize;
#endif
//read particle information and allocate memory
vr::Timer loading_timer;
//for MPI determine total number of particles AND the number of particles assigned to each processor
if (ThisTask==0) {
LOG(info) << "Reading header";
nbodies=ReadHeader(opt);
if (opt.iBaryonSearch>0) {
for (int i=0;i<NBARYONTYPES;i++) Ntotalbaryon[i]=Nlocalbaryon[i]=0;
nbaryons=0;
int pstemp=opt.partsearchtype;
opt.partsearchtype=PSTGAS;
nbaryons+=ReadHeader(opt);
if (opt.iusestarparticles) {
opt.partsearchtype=PSTSTAR;
nbaryons+=ReadHeader(opt);
}
if (opt.iusesinkparticles) {
opt.partsearchtype=PSTBH;
nbaryons+=ReadHeader(opt);
}
opt.partsearchtype=pstemp;
}
else nbaryons=0;
}
#ifdef USEMPI
MPI_Bcast(&nbodies,1, MPI_Int_t,0,MPI_COMM_WORLD);
//if MPI, possible desired particle types not present in file so update used particle types
MPIUpdateUseParticleTypes(opt);
if (opt.iBaryonSearch>0) MPI_Bcast(&nbaryons,1, MPI_Int_t,0,MPI_COMM_WORLD);
//initial estimate need for memory allocation assuming that work balance is not greatly off
#endif
LOG_RANK0(info) << "There are " << nbodies << " particles in total that require " << vr::memory_amount(nbodies * sizeof(Particle));
if (opt.iBaryonSearch > 0) {
LOG_RANK0(info) << "There are " << nbaryons << " baryon particles in total that require " << vr::memory_amount(nbaryons * sizeof(Particle));
}
//note that for nonmpi particle array is a contiguous block of memory regardless of whether a separate baryon search is required
#ifndef USEMPI
Nlocal=nbodies;
if (opt.iBaryonSearch>0 && opt.partsearchtype!=PSTALL) {
Part.resize(nbodies+nbaryons);
Pbaryons=&(Part.data()[nbodies]);
Nlocalbaryon[0]=nbaryons;
}
else {
Part.resize(nbodies);
Pbaryons=NULL;
nbaryons=0;
}
#else
//for mpi however, it is not possible to have a simple contiguous block of memory IFF a separate baryon search is required.
//for the simple reason that the local number of particles changes to ensure large fof groups are local to an mpi domain
//however, when reading data, it is much simplier to have a contiguous block of memory, sort that memory (if necessary)
//and then split afterwards the dm particles and the baryons
if (NProcs==1) {Nlocal=Nmemlocal=nbodies;NExport=NImport=1;}
else {
#ifdef MPIREDUCEMEM
//if allocating reasonable amounts of memory, use MPIREDUCEMEM
//this determines number of particles in the mpi domains
MPINumInDomain(opt);
LOG(info) << "There are " << Nlocal << " particles and have allocated enough memory for "
<< Nmemlocal << " requiring " << vr::memory_amount(Nmemlocal * sizeof(Particle));
if (opt.iBaryonSearch > 0) {
LOG(info) << "There are " << Nlocalbaryon[0] << " baryon particles and have allocated enough memory for "
<< Nmemlocalbaryon << " requiring " << vr::memory_amount(Nmemlocalbaryon * sizeof(Particle));
}
#else
//otherwise just base on total number of particles * some factor and initialise the domains
MPIDomainExtent(opt);
MPIDomainDecomposition(opt);
Nlocal=nbodies/NProcs*MPIProcFac;
Nmemlocal=Nlocal;
Nlocalbaryon[0]=nbaryons/NProcs*MPIProcFac;
Nmemlocalbaryon=Nlocalbaryon[0];
NExport=NImport=Nlocal*MPIExportFac;
LOG(info) << "Have allocated enough memory for " << Nmemlocal << " requiring "
<< vr::memory_amount(Nmemlocal * sizeof(Particle));
if (opt.iBaryonSearch > 0) {
LOG(info) << "Have allocated enough memory for " << Nmemlocalbaryon << " baryons particles requiring "
<< vr::memory_amount(Nmemlocalbaryon * sizeof(Particle));
}
#endif
}
LOG(info) << "Will also require additional memory for FOF algorithms and substructure search. "
<< "Largest mem needed for preliminary FOF search. Rough estimate is " << vr::memory_amount(Nlocal * sizeof(Int_tree_t) * 8);
if (opt.iBaryonSearch>0 && opt.partsearchtype!=PSTALL) {
Part.resize(Nmemlocal+Nmemlocalbaryon);
Pbaryons=&(Part.data()[Nlocal]);
nbaryons=Nlocalbaryon[0];
}
else {
Part.resize(Nmemlocal);
Pbaryons=NULL;
nbaryons=0;
}
#endif
//now read particle data
ReadData(opt, Part, nbodies, Pbaryons, nbaryons);
#ifdef USEMPI
//if mpi and want separate baryon search then once particles are loaded into contigous block of memory and sorted according to type order,
//allocate memory for baryons
if (opt.iBaryonSearch>0 && opt.partsearchtype!=PSTALL) {
Pbaryons=new Particle[Nmemlocalbaryon];
nbaryons=Nlocalbaryon[0];
for (Int_t i=0;i<Nlocalbaryon[0];i++) Pbaryons[i]=Part[i+Nlocal];
Part.resize(Nlocal);
}
#endif
#ifdef USEMPI
Ntotal=nbodies;
nbodies=Nlocal;
NExport=NImport=Nlocal*MPIExportFac;
mpi_period=opt.p;
MPI_Allgather(&nbodies, 1, MPI_Int_t, mpi_nlocal, 1, MPI_Int_t, MPI_COMM_WORLD);
MPI_Allreduce(&nbodies, &Ntotal, 1, MPI_Int_t, MPI_SUM, MPI_COMM_WORLD);
LOG(info) << Nlocal << '/' << Ntotal << " particles loaded in " << loading_timer;
#else
LOG(info) << nbodies << " particles loaded in " << loading_timer;
#endif
//write out the configuration used by velociraptor having read in the data (as input data can contain cosmological information)
WriteVELOCIraptorConfig(opt);
WriteSimulationInfo(opt);
WriteUnitInfo(opt);
//set filenames if they have been passed
#ifdef USEMPI
if (opt.smname!=NULL) sprintf(fname4,"%s.%d",opt.smname,ThisTask);
#else
if (opt.smname!=NULL) sprintf(fname4,"%s",opt.smname);
#endif
//read local velocity data or calculate it
//(and if STRUCDEN flag or HALOONLYDEN is set then only calculate the velocity density function for objects within a structure
//as found by SearchFullSet)
#if defined (STRUCDEN) || defined (HALOONLYDEN)
#else
if (opt.iSubSearch==1) {
vr::Timer timer;
if(FileExists(fname4)) ReadLocalVelocityDensity(opt, nbodies,Part);
else {
GetVelocityDensity(opt, nbodies, Part.data());
WriteLocalVelocityDensity(opt, nbodies,Part);
}
LOG(info) << "Local velocity density read/analised for " << Nlocal << " particles with "
<< nthreads << " threads in " << timer;
}
#endif
//here adjust Efrac to Omega_cdm/Omega_m from what it was before if baryonic search is separate
if (opt.iBaryonSearch>0 && opt.partsearchtype!=PSTALL) opt.uinfo.Eratio*=opt.Omega_cdm/opt.Omega_m;
//From here can either search entire particle array for "Halos" or if a single halo is loaded, then can just search for substructure
if (!opt.iSingleHalo) {
vr::Timer timer;
#ifndef USEMPI
pfof=SearchFullSet(opt,nbodies,Part,ngroup);
nhalos=ngroup;
#else
//nbodies=Ntotal;
///\todo Communication Buffer size determination and allocation. For example, eventually need something like FoFDataIn = (struct fofdata_in *) CommBuffer;
///At the moment just using NExport
NExport=Nlocal*MPIExportFac;
//Now when MPI invoked this returns pfof after local linking and linking across and also reorders groups
//according to size and localizes the particles belong to the same group to the same mpi thread.
//after this is called Nlocal is adjusted to the local subset where groups are localized to a given mpi thread.
pfof=SearchFullSet(opt,Nlocal,Part,ngroup);
nbodies=Nlocal;
nhalos=ngroup;
#endif
LOG(info) << "Search over " << nbodies << " with " << nthreads << " took " << timer;
//if compiled to determine inclusive halo masses, then for simplicity, I assume halo id order NOT rearranged!
//this is not necessarily true if baryons are searched for separately.
if (opt.iInclusiveHalo > 0 && opt.iInclusiveHalo < 3) {
pdatahalos=new PropData[nhalos+1];
Int_t *numinhalos=BuildNumInGroup(nbodies, nhalos, pfof);
Int_t *sortvalhalos=new Int_t[nbodies];
Int_t *originalID=new Int_t[nbodies];
for (Int_t i=0;i<nbodies;i++) {sortvalhalos[i]=pfof[i]*(pfof[i]>0)+nbodies*(pfof[i]==0);originalID[i]=Part[i].GetID();Part[i].SetID(i);}
Int_t *noffsethalos=BuildNoffset(nbodies, Part.data(), nhalos, numinhalos, sortvalhalos);
///here if inclusive halo flag is 3, then S0 masses are calculated after substructures are found for field objects
///and only calculate FOF masses. Otherwise calculate inclusive masses at this moment.
GetInclusiveMasses(opt, nbodies, Part.data(), nhalos, pfof, numinhalos, pdatahalos, noffsethalos);
qsort(Part.data(),nbodies,sizeof(Particle),IDCompare);
//sort(Part.begin(), Part.end(), IDCompareVec);
delete[] numinhalos;
delete[] sortvalhalos;
delete[] noffsethalos;
for (Int_t i=0;i<nbodies;i++) Part[i].SetID(originalID[i]);
delete[] originalID;
}
}
else {
Coordinate *gvel;
Matrix *gveldisp;
GridCell *grid;
///\todo Scaling is still not MPI compatible
if (opt.iScaleLengths) ScaleLinkingLengths(opt,nbodies,Part.data(),cm,cmvel,Mtot);
opt.Ncell=opt.Ncellfac*nbodies;
//build grid using leaf nodes of tree (which is guaranteed to be adaptive and have maximum number of particles in cell of tree bucket size)
tree=InitializeTreeGrid(opt,nbodies,Part.data());
ngrid=tree->GetNumLeafNodes();
LOG(info) << "Given " << nbodies << " particles, and max cell size of " << opt.Ncell
<< " there are " << ngrid << " leaf nodes or grid cells, with each node containing ~"
<< nbodies / ngrid << " particles";
grid=new GridCell[ngrid];
//note that after this system is back in original order as tree has been deleted.
FillTreeGrid(opt, nbodies, ngrid, tree, Part.data(), grid);
//calculate cell quantities to get mean field
gvel=GetCellVel(opt,nbodies,Part.data(),ngrid,grid);
gveldisp=GetCellVelDisp(opt,nbodies,Part.data(),ngrid,grid,gvel);
opt.HaloSigmaV=0;for (int j=0;j<ngrid;j++) opt.HaloSigmaV+=pow(gveldisp[j].Det(),1./3.);opt.HaloSigmaV/=(double)ngrid;
//now that have the grid cell volume quantities and local volume density
//can determine the logarithmic ratio between the particle velocity density and that predicted by the background velocity distribution
GetDenVRatio(opt,nbodies,Part.data(),ngrid,grid,gvel,gveldisp);
//WriteDenVRatio(opt,nbodies,Part);
//and then determine how much of an outlier it is
nsubset=GetOutliersValues(opt,nbodies,Part.data());
//save the normalized denvratio and also determine how many particles lie above the threshold.
//nsubset=WriteOutlierValues(opt, nbodies,Part);
//Now check if any particles are above the threshold
if (nsubset==0) {
LOG(info) << "No particles found above threshold of " << opt.ellthreshold;
LOG(info) << "Exiting";
return 0;
}
else {
LOG(info) << nsubset << " particles above threshold of " << opt.ellthreshold << " to be searched";
}
#ifndef USEMPI
pfof=SearchSubset(opt,nbodies,nbodies,Part.data(),ngroup);
#else
//nbodies=Ntotal;
///\todo Communication Buffer size determination and allocation. For example, eventually need something like FoFDataIn = (struct fofdata_in *) CommBuffer;
///At the moment just using NExport
NExport=Nlocal*MPIExportFac;
mpi_foftask=MPISetTaskID(nbodies);
//Now when MPI invoked this returns pfof after local linking and linking across and also reorders groups
//according to size and localizes the particles belong to the same group to the same mpi thread.
//after this is called Nlocal is adjusted to the local subset where groups are localized to a given mpi thread.
pfof=SearchSubset(opt,Nlocal,Nlocal,Part.data(),ngroup);
nbodies=Nlocal;
#endif
}
if (opt.iSubSearch) {
LOG(info) << "Searching subset";
vr::Timer timer;
//if groups have been found (and localized to single MPI thread) then proceed to search for subsubstructures
SearchSubSub(opt, nbodies, Part, pfof,ngroup,nhalos, pdatahalos);
LOG(info) << "Search for substructures " << Nlocal << " with " << nthreads
<< " threads finished in " << timer;
}
pdata=new PropData[ngroup+1];
//if inclusive halo mass required
if (opt.iInclusiveHalo > 0 && opt.iInclusiveHalo < 3 && ngroup>0) {
CopyMasses(opt,nhalos,pdatahalos,pdata);
delete[] pdatahalos;
}
//if only searching initially for dark matter groups, once found, search for associated baryonic structures if requried
if (opt.iBaryonSearch>0) {
vr::Timer timer;
if (opt.partsearchtype==PSTDARK) {
pfofall=SearchBaryons(opt, nbaryons, Pbaryons, nbodies, Part, pfof, ngroup,nhalos,opt.iseparatefiles,opt.iInclusiveHalo,pdata);
pfofbaryons=&pfofall[nbodies];
}
//if FOF search overall particle types then running sub search over just dm and need to associate baryons to just dm particles must determine number of baryons, sort list, run search, etc
//but only need to run search if substructure has been searched
else if (opt.iSubSearch==1){
nbaryons=0;
ndark=0;
for (Int_t i=0;i<nbodies;i++) {
if (Part[i].GetType()==DARKTYPE)ndark++;
else nbaryons++;
}
Pbaryons=NULL;
SearchBaryons(opt, nbaryons, Pbaryons, ndark, Part, pfof, ngroup,nhalos,opt.iseparatefiles,opt.iInclusiveHalo,pdata);
}
LOG(info) << "Baryon search with " << nthreads << " threads finished in " << timer;
}
//get mpi local hierarchy
Int_t *nsub,*parentgid, *uparentgid,*stype;
nsub=new Int_t[ngroup+1];
parentgid=new Int_t[ngroup+1];
uparentgid=new Int_t[ngroup+1];
stype=new Int_t[ngroup+1];
Int_t nhierarchy=GetHierarchy(opt,ngroup,nsub,parentgid,uparentgid,stype);
CopyHierarchy(opt,pdata,ngroup,nsub,parentgid,uparentgid,stype);
//if a separate baryon search has been run, now just place all particles together
if (opt.iBaryonSearch>0 && opt.partsearchtype!=PSTALL) {
delete[] pfof;
pfof=&pfofall[0];
nbodies+=nbaryons;
Nlocal=nbodies;
}
//output results
//if want to ignore any information regard particles themselves as particle PIDS are meaningless
//which might be useful for runs where not interested in tracking just halo catalogues (save for
//approximate methods like PICOLA. Here it writes desired output and exits
if(opt.inoidoutput){
numingroup=BuildNumInGroup(Nlocal, ngroup, pfof);
CalculateHaloProperties(opt,Nlocal,Part.data(),ngroup,pfof,numingroup,pdata);
WriteProperties(opt,ngroup,pdata);
if (opt.iprofilecalc) WriteProfiles(opt, ngroup, pdata);
delete[] numingroup;
delete[] pdata;
finish_vr(opt);
}
//if want a simple tipsy still array listing particles group ids in input order
if(opt.iwritefof) {
#ifdef USEMPI
if (ThisTask==0) {
mpi_pfof=new Int_t[Ntotal];
//since pfof is a local subset, not all pfof values have been set, thus initialize them to zero.
for (Int_t i=0;i<Ntotal;i++) mpi_pfof[i]=0;
}
MPICollectFOF(Ntotal, pfof);
if (ThisTask==0) WriteFOF(opt,Ntotal,mpi_pfof);
#else
WriteFOF(opt,nbodies,pfof);
#endif
}
numingroup=BuildNumInGroup(Nlocal, ngroup, pfof);
//if separate files explicitly save halos, associated baryons, and subhalos separately
if (opt.iseparatefiles) {
if (nhalos>0) {
pglist=SortAccordingtoBindingEnergy(opt,Nlocal,Part.data(),nhalos,pfof,numingroup,pdata);//alters pglist so most bound particles first
WriteProperties(opt,nhalos,pdata);
WriteGroupCatalog(opt, nhalos, numingroup, pglist, Part,ngroup-nhalos);
//if baryons have been searched output related gas baryon catalogue
if (opt.partsearchtype==PSTALL){
WriteGroupPartType(opt, nhalos, numingroup, pglist, Part);
}
WriteHierarchy(opt,ngroup,nhierarchy,psldata->nsinlevel,nsub,parentgid,stype);
for (Int_t i=1;i<=nhalos;i++) delete[] pglist[i];
delete[] pglist;
}
else {
#ifdef USEMPI
//if calculating inclusive masses at end, must call SortAccordingtoBindingEnergy if
//MPI as domain, despite having no groups might need to exchange particles
if (opt.iInclusiveHalo==3) SortAccordingtoBindingEnergy(opt,Nlocal,Part.data(),nhalos,pfof,numingroup,pdata);
#endif
WriteGroupCatalog(opt,nhalos,numingroup,NULL,Part);
WriteHierarchy(opt,nhalos,nhierarchy,psldata->nsinlevel,nsub,parentgid,stype);
if (opt.partsearchtype==PSTALL){
WriteGroupPartType(opt, nhalos, numingroup, NULL, Part);
}
}
}
Int_t indexii=0;
ng=ngroup;
//if separate files, alter offsets
if (opt.iseparatefiles) {
sprintf(fname1,"%s.sublevels",opt.outname);
sprintf(opt.outname,"%s",fname1);
//alter index point to just output sublevels (assumes no reordering and assumes no change in nhalos as a result of unbinding in SubSubSearch)
indexii=nhalos;
ng=ngroup-nhalos;
}
if (ng>0) {
pglist=SortAccordingtoBindingEnergy(opt,Nlocal,Part.data(),ng,pfof,&numingroup[indexii],&pdata[indexii],indexii);//alters pglist so most bound particles first
WriteProperties(opt,ng,&pdata[indexii]);
WriteGroupCatalog(opt, ng, &numingroup[indexii], pglist, Part);
if (opt.iseparatefiles) WriteHierarchy(opt,ngroup,nhierarchy,psldata->nsinlevel,nsub,parentgid,stype,1);
else WriteHierarchy(opt,ngroup,nhierarchy,psldata->nsinlevel,nsub,parentgid,stype,-1);
if (opt.partsearchtype==PSTALL){
WriteGroupPartType(opt, ng, &numingroup[indexii], pglist, Part);
}
for (Int_t i=1;i<=ng;i++) delete[] pglist[i];
delete[] pglist;
}
else {
#ifdef USEMPI
//if calculating inclusive masses at end, must call SortAccordingtoBindingEnergy if
//MPI as domain, despite having no groups might need to exchange particles
if (opt.iInclusiveHalo==3) SortAccordingtoBindingEnergy(opt,Nlocal,Part.data(),ng,pfof,numingroup,pdata);
#endif
WriteProperties(opt,ng,NULL);
WriteGroupCatalog(opt,ng,&numingroup[indexii],NULL,Part);
if (opt.iseparatefiles) WriteHierarchy(opt,ngroup,nhierarchy,psldata->nsinlevel,nsub,parentgid,stype,1);
else WriteHierarchy(opt,ngroup,nhierarchy,psldata->nsinlevel,nsub,parentgid,stype,-1);
if (opt.partsearchtype==PSTALL){
WriteGroupPartType(opt, ng, &numingroup[indexii], NULL, Part);
}
}
if (opt.iprofilecalc) WriteProfiles(opt, ngroup, pdata);
#ifdef EXTENDEDHALOOUTPUT
if (opt.iExtendedOutput) WriteExtendedOutput (opt, ngroup, Nlocal, pdata, Part, pfof);
#endif
delete[] pfof;
delete[] numingroup;
delete[] pdata;
delete psldata;
delete[] nsub;
delete[] parentgid;
delete[] uparentgid;
delete[] stype;
LOG(info) << "VELOCIraptor finished in " << total_timer;
finish_vr(opt);
return 0;
}
| 42.511254
| 195
| 0.668482
|
bwvdnbro
|
a346417a88b0a515620618a3a54dd55742791c16
| 8,039
|
cpp
|
C++
|
example/frame/ipc/ipcserialization.cpp
|
joydit/solidframe
|
0539b0a1e77663ac4c701a88f56723d3e3688e8c
|
[
"BSL-1.0"
] | null | null | null |
example/frame/ipc/ipcserialization.cpp
|
joydit/solidframe
|
0539b0a1e77663ac4c701a88f56723d3e3688e8c
|
[
"BSL-1.0"
] | null | null | null |
example/frame/ipc/ipcserialization.cpp
|
joydit/solidframe
|
0539b0a1e77663ac4c701a88f56723d3e3688e8c
|
[
"BSL-1.0"
] | null | null | null |
#include "system/debug.hpp"
#include "system/thread.hpp"
#include "system/timespec.hpp"
#include "utility/dynamicpointer.hpp"
#include "utility/dynamictype.hpp"
#include "utility/queue.hpp"
#include "frame/ipc/ipcmessage.hpp"
#include "serialization/binary.hpp"
#include "serialization/idtypemapper.hpp"
#include "boost/program_options.hpp"
#include <string>
#include <iostream>
using namespace std;
using namespace solid;
struct Params{
string dbg_levels;
string dbg_modules;
string dbg_addr;
string dbg_port;
bool dbg_console;
bool dbg_buffered;
bool log;
uint32 repeat_count;
uint32 message_count;
uint32 min_size;
uint32 max_size;
};
struct MessageUid{
MessageUid(
const uint32 _idx = 0xffffffff,
const uint32 _uid = 0xffffffff
):idx(_idx), uid(_uid){}
uint32 idx;
uint32 uid;
};
struct FirstMessage: Dynamic<FirstMessage, DynamicShared<frame::ipc::Message> >{
uint32 state;
uint32 sec;
uint32 nsec;
std::string str;
MessageUid msguid;
FirstMessage();
~FirstMessage();
uint32 size()const{
return sizeof(state) + sizeof(sec) + sizeof(nsec) + sizeof(msguid) + sizeof(uint32) + str.size();
}
/*virtual*/ void ipcOnReceive(frame::ipc::ConnectionContext const &_rctx, MessagePointerT &_rmsgptr);
/*virtual*/ uint32 ipcOnPrepare(frame::ipc::ConnectionContext const &_rctx);
/*virtual*/ void ipcOnComplete(frame::ipc::ConnectionContext const &_rctx, int _err);
template <class S>
void serialize(S &_s){
_s.push(state, "state").push(sec, "seconds").push(nsec, "nanoseconds").push(str, "data");
_s.push(msguid.idx, "msguid.idx").push(msguid.uid,"msguid.uid");
}
};
FirstMessage* create_message(uint32_t _idx, const bool _incremental = false);
namespace{
Params p;
}
//------------------------------------------------------------------
typedef DynamicSharedPointer<FirstMessage> FirstMessageSharedPointerT;
typedef Queue<FirstMessageSharedPointerT> FirstMessageSharedPointerQueueT;
typedef serialization::binary::Serializer<> BinSerializerT;
typedef serialization::binary::Deserializer<> BinDeserializerT;
typedef serialization::IdTypeMapper<BinSerializerT, BinDeserializerT, uint16> UInt16TypeMapperT;
struct Context{
enum{
BufferCapacity = 4 * 1024
};
Context(): ser(tm), des(tm), bufcp(BufferCapacity){}
UInt16TypeMapperT tm;
BinSerializerT ser;
BinDeserializerT des;
const size_t bufcp;
char buf[BufferCapacity];
};
void execute_messages(FirstMessageSharedPointerQueueT &_rmsgq, Context &_ctx);
bool parseArguments(Params &_par, int argc, char *argv[]);
int main(int argc, char *argv[]){
if(parseArguments(p, argc, argv)) return 0;
Thread::init();
#ifdef UDEBUG
{
string dbgout;
Debug::the().levelMask(p.dbg_levels.c_str());
Debug::the().moduleMask(p.dbg_modules.c_str());
if(p.dbg_addr.size() && p.dbg_port.size()){
Debug::the().initSocket(
p.dbg_addr.c_str(),
p.dbg_port.c_str(),
p.dbg_buffered,
&dbgout
);
}else if(p.dbg_console){
Debug::the().initStdErr(
p.dbg_buffered,
&dbgout
);
}else{
Debug::the().initFile(
*argv[0] == '.' ? argv[0] + 2 : argv[0],
p.dbg_buffered,
3,
1024 * 1024 * 64,
&dbgout
);
}
cout<<"Debug output: "<<dbgout<<endl;
dbgout.clear();
Debug::the().moduleNames(dbgout);
cout<<"Debug modules: "<<dbgout<<endl;
}
#endif
FirstMessageSharedPointerQueueT msgq;
Context ctx;
ctx.tm.insert<FirstMessage>();
for(uint32 i = 0; i < p.message_count; ++i){
DynamicSharedPointer<FirstMessage> msgptr(create_message(i));
msgq.push(msgptr);
}
TimeSpec begintime(TimeSpec::createRealTime());
for(uint32 i = 0; i < p.repeat_count; ++i){
execute_messages(msgq, ctx);
}
TimeSpec endtime(TimeSpec::createRealTime());
endtime -= begintime;
uint64 duration = endtime.seconds() * 1000;
duration += endtime.nanoSeconds() / 1000000;
cout<<"Duration(msec) = "<<duration<<endl;
Thread::waitAll();
return 0;
}
//------------------------------------------------------------------
bool parseArguments(Params &_par, int argc, char *argv[]){
using namespace boost::program_options;
try{
options_description desc("SolidFrame ipc stress test");
desc.add_options()
("help,h", "List program options")
("debug_levels,L", value<string>(&_par.dbg_levels)->default_value("view"),"Debug logging levels")
("debug_modules,M", value<string>(&_par.dbg_modules),"Debug logging modules")
("debug_address,A", value<string>(&_par.dbg_addr), "Debug server address (e.g. on linux use: nc -l 9999)")
("debug_port,P", value<string>(&_par.dbg_port)->default_value("9999"), "Debug server port (e.g. on linux use: nc -l 9999)")
("debug_console,C", value<bool>(&_par.dbg_console)->implicit_value(true)->default_value(false), "Debug console")
("debug_unbuffered,S", value<bool>(&_par.dbg_buffered)->implicit_value(false)->default_value(true), "Debug unbuffered")
("use_log,L", value<bool>(&_par.log)->implicit_value(true)->default_value(false), "Debug buffered")
("repeat_count", value<uint32_t>(&_par.repeat_count)->default_value(10), "Per message trip count")
("message_count", value<uint32_t>(&_par.message_count)->default_value(1000), "Message count")
("min_size", value<uint32_t>(&_par.min_size)->default_value(10), "Min message data size")
("max_size", value<uint32_t>(&_par.max_size)->default_value(500000), "Max message data size")
;
variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return true;
}
return false;
}catch(exception& e){
cout << e.what() << "\n";
return true;
}
}
//------------------------------------------------------
// FirstMessage
//------------------------------------------------------
FirstMessage::FirstMessage():state(-1){
idbg("CREATE ---------------- "<<(void*)this);
}
FirstMessage::~FirstMessage(){
idbg("DELETE ---------------- "<<(void*)this);
}
/*virtual*/ void FirstMessage::ipcOnReceive(frame::ipc::ConnectionContext const &_rctx, FirstMessage::MessagePointerT &_rmsgptr){
++state;
idbg("EXECUTE ---------------- "<<state);
}
/*virtual*/ uint32 FirstMessage::ipcOnPrepare(frame::ipc::ConnectionContext const &_rctx){
return 0;
}
/*virtual*/ void FirstMessage::ipcOnComplete(frame::ipc::ConnectionContext const &_rctx, int _err){
if(!_err){
idbg("SUCCESS ----------------");
}else{
idbg("ERROR ------------------");
}
}
string create_string(){
string s;
for(char c = '0'; c <= '9'; ++c){
s += c;
}
for(char c = 'a'; c <= 'z'; ++c){
s += c;
}
for(char c = 'A'; c <= 'Z'; ++c){
s += c;
}
return s;
}
FirstMessage* create_message(uint32_t _idx, const bool _incremental){
static const string s(create_string());
FirstMessage *pmsg = new FirstMessage;
pmsg->state = 0;
if(!_incremental){
_idx = p.message_count - 1 - _idx;
}
const uint32_t size = (p.min_size * (p.message_count - _idx - 1) + _idx * p.max_size) / (p.message_count - 1);
idbg("create message with size "<<size);
pmsg->str.resize(size);
for(uint32_t i = 0; i < size; ++i){
pmsg->str[i] = s[i % s.size()];
}
TimeSpec crttime(TimeSpec::createRealTime());
pmsg->sec = crttime.seconds();
pmsg->nsec = crttime.nanoSeconds();
return pmsg;
}
void execute_messages(FirstMessageSharedPointerQueueT &_rmsgq, Context &_rctx){
const uint32 sz = _rmsgq.size();
for(uint32 i = 0; i < sz; ++i){
FirstMessageSharedPointerT frmsgptr = _rmsgq.front();
FirstMessageSharedPointerT tomsgptr(new FirstMessage);
_rmsgq.pop();
_rctx.ser.push(*frmsgptr, "msgptr");
_rctx.des.push(*tomsgptr, "msgptr");
int rv;
while((rv = _rctx.ser.run(_rctx.buf, _rctx.bufcp)) == _rctx.bufcp){
_rctx.des.run(_rctx.buf, rv);
}
if(rv > 0){
_rctx.des.run(_rctx.buf, rv);
}
_rmsgq.push(tomsgptr);
}
}
| 28.108392
| 129
| 0.641373
|
joydit
|
a347f6d78d60e19f405ed3e9924d5beeb3fe14bd
| 6,653
|
hpp
|
C++
|
include/libpmemobj++/detail/common.hpp
|
skygyh/libpmemobj-cpp
|
fbe4025fd37beec6ba1374b4b32b0e83bc9e2204
|
[
"BSD-3-Clause"
] | null | null | null |
include/libpmemobj++/detail/common.hpp
|
skygyh/libpmemobj-cpp
|
fbe4025fd37beec6ba1374b4b32b0e83bc9e2204
|
[
"BSD-3-Clause"
] | null | null | null |
include/libpmemobj++/detail/common.hpp
|
skygyh/libpmemobj-cpp
|
fbe4025fd37beec6ba1374b4b32b0e83bc9e2204
|
[
"BSD-3-Clause"
] | 2
|
2021-01-19T08:22:32.000Z
|
2021-01-19T08:23:32.000Z
|
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/**
* @file
* Commonly used functionality.
*/
#ifndef LIBPMEMOBJ_CPP_COMMON_HPP
#define LIBPMEMOBJ_CPP_COMMON_HPP
#include <libpmemobj++/pexceptions.hpp>
#include <libpmemobj/tx_base.h>
#include <string>
#include <typeinfo>
#if _MSC_VER
#include <intrin.h>
#include <windows.h>
#endif
#if defined(__GNUC__) || defined(__clang__)
#define POBJ_CPP_DEPRECATED __attribute__((deprecated))
#elif defined(_MSC_VER)
#define POBJ_CPP_DEPRECATED __declspec(deprecated)
#else
#define POBJ_CPP_DEPRECATED
#endif
#if LIBPMEMOBJ_CPP_VG_ENABLED
#undef LIBPMEMOBJ_CPP_VG_PMEMCHECK_ENABLED
#undef LIBPMEMOBJ_CPP_VG_MEMCHECK_ENABLED
#undef LIBPMEMOBJ_CPP_VG_HELGRIND_ENABLED
#undef LIBPMEMOBJ_CPP_VG_DRD_ENABLED
#define LIBPMEMOBJ_CPP_VG_PMEMCHECK_ENABLED 1
#define LIBPMEMOBJ_CPP_VG_MEMCHECK_ENABLED 1
#define LIBPMEMOBJ_CPP_VG_HELGRIND_ENABLED 1
#define LIBPMEMOBJ_CPP_VG_DRD_ENABLED 1
#endif
#if LIBPMEMOBJ_CPP_VG_PMEMCHECK_ENABLED || \
LIBPMEMOBJ_CPP_VG_MEMCHECK_ENABLED || \
LIBPMEMOBJ_CPP_VG_HELGRIND_ENABLED || LIBPMEMOBJ_CPP_VG_DRD_ENABLED
#define LIBPMEMOBJ_CPP_ANY_VG_TOOL_ENABLED 1
#endif
#if LIBPMEMOBJ_CPP_ANY_VG_TOOL_ENABLED
#include <valgrind.h>
#endif
#if LIBPMEMOBJ_CPP_VG_PMEMCHECK_ENABLED
#include <pmemcheck.h>
#endif
#if LIBPMEMOBJ_CPP_VG_MEMCHECK_ENABLED
#include <memcheck.h>
#endif
#if LIBPMEMOBJ_CPP_VG_HELGRIND_ENABLED
#include <helgrind.h>
#endif
#if LIBPMEMOBJ_CPP_VG_DRD_ENABLED
#include <drd.h>
#endif
/*
* Workaround for missing "is_trivially_copyable" in gcc < 5.0.
* Be aware of a difference between __has_trivial_copy and is_trivially_copyable
* e.g. for deleted copy constructors __has_trivial_copy(A) returns 1 in clang
* and 0 in gcc. It means that for gcc < 5 LIBPMEMOBJ_CPP_IS_TRIVIALLY_COPYABLE
* is more restrictive than is_trivially_copyable.
*/
#if !defined(LIBPMEMOBJ_CPP_USE_HAS_TRIVIAL_COPY)
#if !defined(__clang__) && defined(__GNUG__) && __GNUC__ < 5
#define LIBPMEMOBJ_CPP_USE_HAS_TRIVIAL_COPY 1
#else
#define LIBPMEMOBJ_CPP_USE_HAS_TRIVIAL_COPY 0
#endif
#endif
#if LIBPMEMOBJ_CPP_USE_HAS_TRIVIAL_COPY
#define LIBPMEMOBJ_CPP_IS_TRIVIALLY_COPYABLE(T) __has_trivial_copy(T)
#else
#define LIBPMEMOBJ_CPP_IS_TRIVIALLY_COPYABLE(T) \
std::is_trivially_copyable<T>::value
#endif
/*! \namespace pmem
* \brief Persistent memory namespace.
*
* It is a common namespace for all persistent memory C++ libraries
* For more information about pmem goto: https://pmem.io
*/
namespace pmem
{
/*! \namespace pmem::obj
* \brief Main libpmemobj namespace.
*
* It contains all libpmemobj's public types, enums, classes with their
* functions and members. It is located within pmem namespace.
*/
namespace obj
{
template <typename T>
class persistent_ptr;
/*! \namespace pmem::obj::experimental
* \brief Experimental implementations.
*
* It contains implementations, which are not yet ready to be used in
* production. They may be not finished, not fully tested or still in
* discussion. It is located within pmem::obj namespace.
*/
namespace experimental
{
}
}
/*! \namespace pmem::detail
* \brief Implementation details.
*
* It contains libpmemobj's implementation details, not needed in public
* headers. It is located within pmem namespace.
*/
namespace detail
{
/*
* Conditionally add 'count' objects to a transaction.
*
* Adds count objects starting from `that` to the transaction if '*that' is
* within a pmemobj pool and there is an active transaction.
* Does nothing otherwise.
*
* @param[in] that pointer to the first object being added to the transaction.
* @param[in] count number of elements to be added to the transaction.
* @param[in] flags is a bitmask of values which are described in libpmemobj
* manpage (pmemobj_tx_xadd_range method)
*/
template <typename T>
inline void
conditional_add_to_tx(const T *that, std::size_t count = 1, uint64_t flags = 0)
{
if (count == 0)
return;
if (pmemobj_tx_stage() != TX_STAGE_WORK)
return;
/* 'that' is not in any open pool */
if (!pmemobj_pool_by_ptr(that))
return;
if (pmemobj_tx_xadd_range_direct(that, sizeof(*that) * count, flags)) {
if (errno == ENOMEM)
throw pmem::transaction_out_of_memory(
"Could not add object(s) to the transaction.")
.with_pmemobj_errormsg();
else
throw pmem::transaction_error(
"Could not add object(s) to the transaction.")
.with_pmemobj_errormsg();
}
}
/*
* Return type number for given type.
*/
template <typename T>
uint64_t
type_num()
{
return typeid(T).hash_code();
}
/**
* Round up to the next lowest power of 2. Overload for uint64_t argument.
*/
inline uint64_t
next_pow_2(uint64_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
++v;
return v + (v == 0);
}
/**
* Round up to the next lowest power of 2. Overload for uint32_t argument.
*/
inline uint64_t
next_pow_2(uint32_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
++v;
return v + (v == 0);
}
#if _MSC_VER
static inline int
Log2(uint64_t x)
{
unsigned long j;
_BitScanReverse64(&j, x);
return static_cast<int>(j);
}
#elif __GNUC__ || __clang__
static inline int
Log2(uint64_t x)
{
// __builtin_clz builtin count _number_ of leading zeroes
return 8 * int(sizeof(x)) - __builtin_clzll(x) - 1;
}
#else
static inline int
Log2(uint64_t x)
{
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
x |= (x >> 32);
static const int table[64] = {
0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3, 61,
51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4, 62,
57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21, 56,
45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5, 63};
return table[(x * 0x03f6eaf2cd271461) >> 58];
}
#endif
#ifndef _MSC_VER
/** Returns index of most significant set bit */
static inline uint8_t
mssb_index64(unsigned long long value)
{
return ((uint8_t)(63 - __builtin_clzll(value)));
}
/** Returns index of most significant set bit */
static inline uint8_t
mssb_index(unsigned int value)
{
return ((uint8_t)(31 - __builtin_clz(value)));
}
#else
static __inline uint8_t
mssb_index(unsigned long value)
{
unsigned long ret;
_BitScanReverse(&ret, value);
return (uint8_t)ret;
}
static __inline uint8_t
mssb_index64(uint64_t value)
{
unsigned long ret;
_BitScanReverse64(&ret, value);
return (uint8_t)ret;
}
#endif
} /* namespace detail */
} /* namespace pmem */
#endif /* LIBPMEMOBJ_CPP_COMMON_HPP */
| 23.100694
| 80
| 0.712461
|
skygyh
|
a34ae6b8e84d95ee3e323a9d68f1eb61eb7aeaa4
| 4,646
|
hpp
|
C++
|
tpls/pressio/include/pressio/WIP/rom/galerkin/impl/continuous_time_api/policies/rom_galerkin_fom_apply_jacobian_policy.hpp
|
fnrizzi/pressio-demoapps
|
6ff10bbcf4d526610580940753c9620725bff1ba
|
[
"BSD-3-Clause"
] | 29
|
2019-11-11T13:17:57.000Z
|
2022-03-16T01:31:31.000Z
|
tpls/pressio/include/pressio/WIP/rom/galerkin/impl/continuous_time_api/policies/rom_galerkin_fom_apply_jacobian_policy.hpp
|
fnrizzi/pressio-demoapps
|
6ff10bbcf4d526610580940753c9620725bff1ba
|
[
"BSD-3-Clause"
] | 303
|
2019-09-30T10:15:41.000Z
|
2022-03-30T08:24:04.000Z
|
tpls/pressio/include/pressio/WIP/rom/galerkin/impl/continuous_time_api/policies/rom_galerkin_fom_apply_jacobian_policy.hpp
|
fnrizzi/pressio-demoapps
|
6ff10bbcf4d526610580940753c9620725bff1ba
|
[
"BSD-3-Clause"
] | 4
|
2020-07-07T03:32:36.000Z
|
2022-03-10T05:21:42.000Z
|
/*
//@HEADER
// ************************************************************************
//
// rom_galerkin_fom_apply_jacobian_policy.hpp
// Pressio
// Copyright 2019
// National Technology & Engineering Solutions of Sandia, LLC (NTESS)
//
// Under the terms of Contract DE-NA0003525 with NTESS, the
// U.S. Government retains certain rights in this software.
//
// Pressio is licensed under BSD-3-Clause terms of use:
//
// 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.
//
// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef ROM_GALERKIN_IMPL_CONTINUOUS_TIME_API_POLICIES_ROM_GALERKIN_FOM_APPLY_JACOBIAN_POLICY_HPP_
#define ROM_GALERKIN_IMPL_CONTINUOUS_TIME_API_POLICIES_ROM_GALERKIN_FOM_APPLY_JACOBIAN_POLICY_HPP_
namespace pressio{ namespace rom{ namespace galerkin{ namespace impl{
template <class fom_states_manager_t, class fom_apply_jac_type, class decoder_type>
class FomApplyJacobianPolicy
{
public:
using data_type = fom_apply_jac_type;
private:
std::reference_wrapper<fom_states_manager_t> fomStatesMngr_;
std::reference_wrapper<const typename decoder_type::jacobian_type> phi_;
mutable fom_apply_jac_type fomApplyJac_ = {};
public:
FomApplyJacobianPolicy() = delete;
FomApplyJacobianPolicy(const FomApplyJacobianPolicy &) = default;
FomApplyJacobianPolicy & operator=(const FomApplyJacobianPolicy &) = delete;
FomApplyJacobianPolicy(FomApplyJacobianPolicy &&) = default;
FomApplyJacobianPolicy & operator=(FomApplyJacobianPolicy &&) = delete;
~FomApplyJacobianPolicy() = default;
template<typename fom_system_t>
FomApplyJacobianPolicy(const fom_system_t & fomSystemObj,
fom_states_manager_t & fomStatesMngr,
const decoder_type & decoder)
: fomStatesMngr_(fomStatesMngr),
phi_(decoder.jacobianCRef()),
fomApplyJac_(fomSystemObj.createApplyJacobianResult(*phi_.get().data()))
{}
public:
template<class galerkin_state_t, typename fom_system_t, typename scalar_t>
void compute(const galerkin_state_t & galerkinState,
const fom_system_t & fomSystemObj,
const scalar_t & evaluationTime) const
{
#ifdef PRESSIO_ENABLE_TEUCHOS_TIMERS
auto timer = Teuchos::TimeMonitor::getStackedTimer();
timer->start("galerkin apply fom jacobian");
#endif
/* here we assume that current FOM state has been reconstructd
by the residual policy. So we do not recompute the FOM state.
Maybe we should find a way to ensure this is the case.
*/
const auto & fomState = fomStatesMngr_.get().fomStateAt(::pressio::ode::nPlusOne());
// call applyJacobian on the fom object
fomSystemObj.applyJacobian(*fomState.data(),
*phi_.get().data(),
evaluationTime,
*fomApplyJac_.data());
#ifdef PRESSIO_ENABLE_TEUCHOS_TIMERS
timer->stop("galerkin apply fom jacobian");
#endif
}
const fom_apply_jac_type & get() const{ return fomApplyJac_; }
};
}}}}//end namespace pressio::rom::galerkin::impl
#endif // ROM_GALERKIN_IMPL_CONTINUOUS_TIME_API_POLICIES_ROM_GALERKIN_FOM_APPLY_JACOBIAN_POLICY_HPP_
| 40.754386
| 101
| 0.735041
|
fnrizzi
|
a34ca64e771d98dca9beb1129ef1fed5277ab2c4
| 675
|
cpp
|
C++
|
chapters/11/ex11_03.cpp
|
yG620/cpp_primer_5th_solutions
|
68fdb2e5167228a3d31ac31c221c1055c2500b91
|
[
"Apache-2.0"
] | null | null | null |
chapters/11/ex11_03.cpp
|
yG620/cpp_primer_5th_solutions
|
68fdb2e5167228a3d31ac31c221c1055c2500b91
|
[
"Apache-2.0"
] | null | null | null |
chapters/11/ex11_03.cpp
|
yG620/cpp_primer_5th_solutions
|
68fdb2e5167228a3d31ac31c221c1055c2500b91
|
[
"Apache-2.0"
] | null | null | null |
//
// ex11_00.cpp
// Exercise 11.00
//
// Created by yG620 on 20/9/13
//
// @Brief > A classic example that relies on associative arrays is a
// word-counting program.
// @KeyPoint
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main(int argc, char const *argv[]) {
map<string, size_t> word_count; // empty map from string to size_t
set<string> exclude = {"i", "world"};
string word;
while (cin >> word) {
if (exclude.find(word) == exclude.end()) ++word_count[word];
}
for (const auto &w : word_count) {
cout << w.first << " occurs " << w.second << " times" << endl;
}
return 0;
}
| 20.454545
| 74
| 0.591111
|
yG620
|
a35228b89a27bbc8e52a05cf12d8e9b9a3477804
| 2,739
|
hpp
|
C++
|
Extensions/Editor/AnimationTrackView.hpp
|
RachelWilSingh/ZeroCore
|
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
|
[
"MIT"
] | 52
|
2018-09-11T17:18:35.000Z
|
2022-03-13T15:28:21.000Z
|
Extensions/Editor/AnimationTrackView.hpp
|
RachelWilSingh/ZeroCore
|
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
|
[
"MIT"
] | 1,409
|
2018-09-19T18:03:43.000Z
|
2021-06-09T08:33:33.000Z
|
Extensions/Editor/AnimationTrackView.hpp
|
RachelWilSingh/ZeroCore
|
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
|
[
"MIT"
] | 26
|
2018-09-11T17:16:32.000Z
|
2021-11-22T06:21:19.000Z
|
///////////////////////////////////////////////////////////////////////////////
///
/// \file AnimationEditor.hpp
/// Declaration of AnimationEditor Composite
///
/// Authors: Joshua Claeys
/// Copyright 2013, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Zero
{
// Typedefs
class Animation;
class AnimationEditor;
class TreeView;
class AnimationTrackSource;
struct TrackSelection;
class RichAnimation;
class TrackNode;
class TreeEvent;
class DataEvent;
class AnimationEditorData;
class TrackEvent;
void RegisterAnimationTrackViewEditors();
//--------------------------------------------------------- Animation Track View
class AnimationTrackView : public Composite
{
public:
/// Meta Initialization.
ZilchDeclareType(TypeCopyMode::ReferenceType);
/// Constructor.
AnimationTrackView(Composite* parent, AnimationEditor* editor);
/// Composite interface.
void UpdateTransform() override;
/// Builds the tree view from the given animation info.
void SetAnimationEditorData(AnimationEditorData* editorData);
/// Sets the selection.
void SetSelection(Array<TrackNode*>& selection);
/// Open all
void FocusOnObject(TrackNode* track);
/// Hides all data relevant to the animation being edited, but retains
/// the data in attempt to avoid re-allocations.
void Hide();
/// Re-Displays all hidden information.
void Show();
private:
void UpdateToolTip();
void OnAnimatorDeactivated(Event* event);
/// We want to know when the selection is modified outside of the tree view.
void OnSelectionModified(Event* e);
/// Focus on the track when double clicked.
void OnDataActivated(DataEvent* e);
/// We want to bring up a context menu when they right click on a row.
void OnTreeRightClick(TreeEvent* e);
/// Renaming object tracks.
void OnRename(Event* e);
/// Enable / Disable through the right click menu.
void OnToggleEnable(Event* e);
/// Clears all key frames on the track.
void OnClearKeys(Event* e);
/// When the delete option is pressed in the context menu.
void OnDeleteTrack(Event* e);
/// Called when the selection on the tree has changed.
void OnTracksSelected(Event* e);
/// We want to focus on the track that was added.
void OnTrackAdded(TrackEvent* e);
TreeView* mTree;
AnimationTrackSource* mSource;
Element* mBackground;
/// Context row.
DataIndex mCommandIndex;
/// Text displayed when the animation is empty.
HandleOf<ToolTip> mToolTip;
AnimationEditor* mEditor;
AnimationEditorData* mEditorData;
};
}//namespace Zero
| 25.839623
| 81
| 0.650602
|
RachelWilSingh
|
a352cc60dbe9cd41acb85742098d5eef24c4d147
| 9,470
|
cpp
|
C++
|
libc/src/time/mktime.cpp
|
kubamracek/llvm-project
|
f7ff1869cdd487d4baaf009380901e5469d8344d
|
[
"Apache-2.0"
] | null | null | null |
libc/src/time/mktime.cpp
|
kubamracek/llvm-project
|
f7ff1869cdd487d4baaf009380901e5469d8344d
|
[
"Apache-2.0"
] | null | null | null |
libc/src/time/mktime.cpp
|
kubamracek/llvm-project
|
f7ff1869cdd487d4baaf009380901e5469d8344d
|
[
"Apache-2.0"
] | null | null | null |
//===-- Implementation of mktime function ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "src/time/mktime.h"
#include "src/__support/common.h"
#include "src/time/time_utils.h"
#include <limits.h>
namespace __llvm_libc {
using __llvm_libc::time_utils::TimeConstants;
static constexpr int NonLeapYearDaysInMonth[] = {31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
// Returns number of years from (1, year).
static constexpr int64_t getNumOfLeapYearsBefore(int64_t year) {
return (year / 4) - (year / 100) + (year / 400);
}
// Returns True if year is a leap year.
static constexpr bool isLeapYear(const int64_t year) {
return (((year) % 4) == 0 && (((year) % 100) != 0 || ((year) % 400) == 0));
}
static int64_t computeRemainingYears(int64_t daysPerYears,
int64_t quotientYears,
int64_t *remainingDays) {
int64_t years = *remainingDays / daysPerYears;
if (years == quotientYears)
years--;
*remainingDays -= years * daysPerYears;
return years;
}
// Update the "tm" structure's year, month, etc. members from seconds.
// "total_seconds" is the number of seconds since January 1st, 1970.
//
// First, divide "total_seconds" by the number of seconds in a day to get the
// number of days since Jan 1 1970. The remainder will be used to calculate the
// number of Hours, Minutes and Seconds.
//
// Then, adjust that number of days by a constant to be the number of days
// since Mar 1 2000. Year 2000 is a multiple of 400, the leap year cycle. This
// makes it easier to count how many leap years have passed using division.
//
// While calculating numbers of years in the days, the following algorithm
// subdivides the days into the number of 400 years, the number of 100 years and
// the number of 4 years. These numbers of cycle years are used in calculating
// leap day. This is similar to the algorithm used in getNumOfLeapYearsBefore()
// and isLeapYear(). Then compute the total number of years in days from these
// subdivided units.
//
// Compute the number of months from the remaining days. Finally, adjust years
// to be 1900 and months to be from January.
static int64_t updateFromSeconds(int64_t total_seconds, struct tm *tm) {
// Days in month starting from March in the year 2000.
static const char daysInMonth[] = {31 /* Mar */, 30, 31, 30, 31, 31,
30, 31, 30, 31, 31, 29};
if (sizeof(time_t) == 4) {
if (total_seconds < 0x80000000)
return time_utils::OutOfRange();
if (total_seconds > 0x7FFFFFFF)
return time_utils::OutOfRange();
} else {
if (total_seconds <
INT_MIN * static_cast<int64_t>(
TimeConstants::NumberOfSecondsInLeapYear) ||
total_seconds > INT_MAX * static_cast<int64_t>(
TimeConstants::NumberOfSecondsInLeapYear))
return time_utils::OutOfRange();
}
int64_t seconds = total_seconds - TimeConstants::SecondsUntil2000MarchFirst;
int64_t days = seconds / TimeConstants::SecondsPerDay;
int64_t remainingSeconds = seconds % TimeConstants::SecondsPerDay;
if (remainingSeconds < 0) {
remainingSeconds += TimeConstants::SecondsPerDay;
days--;
}
int64_t wday = (TimeConstants::WeekDayOf2000MarchFirst + days) %
TimeConstants::DaysPerWeek;
if (wday < 0)
wday += TimeConstants::DaysPerWeek;
// Compute the number of 400 year cycles.
int64_t numOfFourHundredYearCycles = days / TimeConstants::DaysPer400Years;
int64_t remainingDays = days % TimeConstants::DaysPer400Years;
if (remainingDays < 0) {
remainingDays += TimeConstants::DaysPer400Years;
numOfFourHundredYearCycles--;
}
// The reminder number of years after computing number of
// "four hundred year cycles" will be 4 hundred year cycles or less in 400
// years.
int64_t numOfHundredYearCycles =
computeRemainingYears(TimeConstants::DaysPer100Years, 4, &remainingDays);
// The reminder number of years after computing number of
// "hundred year cycles" will be 25 four year cycles or less in 100 years.
int64_t numOfFourYearCycles =
computeRemainingYears(TimeConstants::DaysPer4Years, 25, &remainingDays);
// The reminder number of years after computing number of "four year cycles"
// will be 4 one year cycles or less in 4 years.
int64_t remainingYears = computeRemainingYears(
TimeConstants::DaysPerNonLeapYear, 4, &remainingDays);
// Calculate number of years from year 2000.
int64_t years = remainingYears + 4 * numOfFourYearCycles +
100 * numOfHundredYearCycles +
400LL * numOfFourHundredYearCycles;
int leapDay =
!remainingYears && (numOfFourYearCycles || !numOfHundredYearCycles);
int64_t yday = remainingDays + 31 + 28 + leapDay;
if (yday >= TimeConstants::DaysPerNonLeapYear + leapDay)
yday -= TimeConstants::DaysPerNonLeapYear + leapDay;
int64_t months = 0;
while (daysInMonth[months] <= remainingDays) {
remainingDays -= daysInMonth[months];
months++;
}
if (months >= TimeConstants::MonthsPerYear - 2) {
months -= TimeConstants::MonthsPerYear;
years++;
}
if (years > INT_MAX || years < INT_MIN)
return time_utils::OutOfRange();
// All the data (years, month and remaining days) was calculated from
// March, 2000. Thus adjust the data to be from January, 1900.
tm->tm_year = years + 2000 - TimeConstants::TimeYearBase;
tm->tm_mon = months + 2;
tm->tm_mday = remainingDays + 1;
tm->tm_wday = wday;
tm->tm_yday = yday;
tm->tm_hour = remainingSeconds / TimeConstants::SecondsPerHour;
tm->tm_min = remainingSeconds / TimeConstants::SecondsPerMin %
TimeConstants::SecondsPerMin;
tm->tm_sec = remainingSeconds % TimeConstants::SecondsPerMin;
return 0;
}
LLVM_LIBC_FUNCTION(time_t, mktime, (struct tm * tm_out)) {
// Unlike most C Library functions, mktime doesn't just die on bad input.
// TODO(rtenneti); Handle leap seconds.
int64_t tmYearFromBase = tm_out->tm_year + TimeConstants::TimeYearBase;
// 32-bit end-of-the-world is 03:14:07 UTC on 19 January 2038.
if (sizeof(time_t) == 4 &&
tmYearFromBase >= TimeConstants::EndOf32BitEpochYear) {
if (tmYearFromBase > TimeConstants::EndOf32BitEpochYear)
return time_utils::OutOfRange();
if (tm_out->tm_mon > 0)
return time_utils::OutOfRange();
if (tm_out->tm_mday > 19)
return time_utils::OutOfRange();
if (tm_out->tm_hour > 3)
return time_utils::OutOfRange();
if (tm_out->tm_min > 14)
return time_utils::OutOfRange();
if (tm_out->tm_sec > 7)
return time_utils::OutOfRange();
}
// Years are ints. A 32-bit year will fit into a 64-bit time_t.
// A 64-bit year will not.
static_assert(sizeof(int) == 4,
"ILP64 is unimplemented. This implementation requires "
"32-bit integers.");
// Calculate number of months and years from tm_mon.
int64_t month = tm_out->tm_mon;
if (month < 0 || month >= TimeConstants::MonthsPerYear - 1) {
int64_t years = month / 12;
month %= 12;
if (month < 0) {
years--;
month += 12;
}
tmYearFromBase += years;
}
bool tmYearIsLeap = isLeapYear(tmYearFromBase);
// Calculate total number of days based on the month and the day (tm_mday).
int64_t totalDays = tm_out->tm_mday - 1;
for (int64_t i = 0; i < month; ++i)
totalDays += NonLeapYearDaysInMonth[i];
// Add one day if it is a leap year and the month is after February.
if (tmYearIsLeap && month > 1)
totalDays++;
// Calculate total numbers of days based on the year.
totalDays += (tmYearFromBase - TimeConstants::EpochYear) *
TimeConstants::DaysPerNonLeapYear;
if (tmYearFromBase >= TimeConstants::EpochYear) {
totalDays += getNumOfLeapYearsBefore(tmYearFromBase - 1) -
getNumOfLeapYearsBefore(TimeConstants::EpochYear);
} else if (tmYearFromBase >= 1) {
totalDays -= getNumOfLeapYearsBefore(TimeConstants::EpochYear) -
getNumOfLeapYearsBefore(tmYearFromBase - 1);
} else {
// Calculate number of leap years until 0th year.
totalDays -= getNumOfLeapYearsBefore(TimeConstants::EpochYear) -
getNumOfLeapYearsBefore(0);
if (tmYearFromBase <= 0) {
totalDays -= 1; // Subtract 1 for 0th year.
// Calculate number of leap years until -1 year
if (tmYearFromBase < 0) {
totalDays -= getNumOfLeapYearsBefore(-tmYearFromBase) -
getNumOfLeapYearsBefore(1);
}
}
}
// TODO(rtenneti): Need to handle timezone and update of tm_isdst.
int64_t seconds = tm_out->tm_sec +
tm_out->tm_min * TimeConstants::SecondsPerMin +
tm_out->tm_hour * TimeConstants::SecondsPerHour +
totalDays * TimeConstants::SecondsPerDay;
// Update the tm structure's year, month, day, etc. from seconds.
if (updateFromSeconds(seconds, tm_out) < 0)
return time_utils::OutOfRange();
return static_cast<time_t>(seconds);
}
} // namespace __llvm_libc
| 38.495935
| 80
| 0.665048
|
kubamracek
|
a353f580de9d5c28c18aee20f46b20fe469fc4fc
| 8,306
|
cpp
|
C++
|
quill3d/openpmd_output.cpp
|
blendersamsonov/Quill
|
5567b3dd70becf50084014c5cc53a95dda53ce4c
|
[
"MIT"
] | null | null | null |
quill3d/openpmd_output.cpp
|
blendersamsonov/Quill
|
5567b3dd70becf50084014c5cc53a95dda53ce4c
|
[
"MIT"
] | null | null | null |
quill3d/openpmd_output.cpp
|
blendersamsonov/Quill
|
5567b3dd70becf50084014c5cc53a95dda53ce4c
|
[
"MIT"
] | null | null | null |
#include "openpmd_output.h"
#include <iostream>
#include <vector>
#include <cstring>
const std::string MESHES_GROUP = "meshes";
std::string get_parent(const std::string & path) {
auto last_separator = path.find_last_of('/');
if (last_separator == std::string::npos) {
return "/";
} else {
return path.substr(0, last_separator);
}
}
std::string get_name(const std::string & path) {
auto last_separator = path.find_last_of('/');
if (last_separator == std::string::npos) {
return path;
} else {
return path.substr(last_separator + 1);
}
}
H5::Group open_group(const H5::Group & base_group, const std::string & group_name) {
auto first_separator = group_name.find_first_of('/');
if (first_separator == std::string::npos) {
if (base_group.nameExists(group_name)) {
return base_group.openGroup(group_name);
} else {
return base_group.createGroup(group_name);
}
} else {
auto first_group_name = group_name.substr(0, first_separator);
auto subgroup_name = group_name.substr(first_separator+1);
auto first_group = open_group(base_group, first_group_name);
return open_group(first_group, subgroup_name);
}
}
H5::DataSet create_dataset(const H5::Group & base_group, const std::string & name, const H5::DataSpace & dataspace) {
auto last_separator = name.find_last_of('/');
if (last_separator == std::string::npos) {
return base_group.createDataSet(name, H5::PredType::NATIVE_DOUBLE, dataspace);
} else {
auto new_base_group = open_group(base_group, name.substr(0, last_separator));
auto new_name = name.substr(last_separator+1);
return create_dataset(new_base_group, new_name, dataspace);
}
}
H5::DataSet openpmd::open_dataset(const H5::Group & base_group, const std::string & name) {
auto last_separator = name.find_last_of('/');
if (last_separator == std::string::npos) {
return base_group.openDataSet(name);
} else {
auto new_base_group = open_group(base_group, name.substr(0, last_separator));
auto new_name = name.substr(last_separator+1);
return open_dataset(new_base_group, new_name);
}
}
void create_attribute(H5::H5Object & object, const std::string & name, const std::string & value) {
H5::DataSpace scalar_dataspace{};
auto type = H5::StrType(0, value.length());
auto attribute = object.createAttribute(name, type, scalar_dataspace);
attribute.write(type, (&value[0]));
}
void create_attribute(H5::H5Object & object, const std::string & name, int value) {
H5::DataSpace scalar_dataspace{};
auto attribute = object.createAttribute(name, H5::PredType::NATIVE_UINT32, scalar_dataspace);
attribute.write(H5::PredType::NATIVE_UINT32, &value);
}
void create_attribute(H5::H5Object & object, const std::string & name, double value) {
H5::DataSpace scalar_dataspace{};
auto attribute = object.createAttribute(name, H5::PredType::NATIVE_DOUBLE, scalar_dataspace);
attribute.write(H5::PredType::NATIVE_DOUBLE, &value);
}
void create_attribute(H5::H5Object & object, const std::string & name, const std::vector<double> & values) {
auto size = values.size();
const hsize_t dims[1] { size };
H5::DataSpace dataspace(1, dims);
auto attribute = object.createAttribute(name, H5::PredType::NATIVE_DOUBLE, dataspace);
attribute.write(H5::PredType::NATIVE_DOUBLE, &(values[0]));
}
// An alternative (nicer) implementation using variable-length string arrays.
// Currently not supported by openpmd-validator (see https://github.com/openPMD/openPMD-validator/issues/61)
/*
void create_attribute(H5::H5Object & object, const std::string & name, const std::vector<std::string> & values) {
auto size = values.size();
std::vector<const char *> values_cstr(size);
for (size_t i = 0; i < size; i++) {
values_cstr[i] = values[i].c_str();
}
const hsize_t dims[1] { size };
H5::DataSpace dataspace(1, dims);
auto datatype = H5::StrType(H5::PredType::C_S1, H5T_VARIABLE);
auto attribute = object.createAttribute(name, datatype, dataspace);
attribute.write(datatype, values_cstr.data());
}
*/
void create_attribute(H5::H5Object & object, const std::string & name, const std::vector<std::string> & values) {
auto size = values.size();
size_t max_element_size = 0;
for (size_t i = 0; i < size; i++) {
if (values[i].length() > max_element_size) {
max_element_size = values[i].length() + 1;
}
}
std::vector<char> write_array(size * max_element_size);
for (size_t i = 0; i < size; i++) {
strcpy(&(write_array[i * max_element_size]), values[i].c_str());
}
const hsize_t dims[1] { size };
H5::DataSpace dataspace(1, dims);
auto datatype = H5::StrType(H5::PredType::C_S1, max_element_size);
auto attribute = object.createAttribute(name, datatype, dataspace);
for (size_t i = 0; i < size; i++) {
attribute.write(datatype, write_array.data());
}
}
std::string iteration_group_string(int iteration) {
return std::string("data/") + std::to_string(iteration);
}
std::string openpmd::iteration_meshes_group_string(int iteration) {
return iteration_group_string(iteration) + "/" + MESHES_GROUP;
}
void openpmd::initialize_file(const std::string & filepath) {
auto file = H5::H5File(filepath, H5F_ACC_TRUNC);
create_attribute(file, "openPMD", "1.1.0");
create_attribute(file, "openPMDextension", 0);
create_attribute(file, "basePath", "/data/%T/");
create_attribute(file, "software", "Quill");
create_attribute(file, "iterationEncoding", "groupBased");
create_attribute(file, "iterationFormat", "/data/%T/");
create_attribute(file, "meshesPath", MESHES_GROUP + "/");
}
std::vector<std::string> get_axes_labels(openpmd::Space space) {
if (space == openpmd::Space::XY) {
return {"x", "y"};
} else if (space == openpmd::Space::YZ) {
return {"y", "z"};
} else if (space == openpmd::Space::XZ) {
return {"x", "z"};
} else {
return {};
}
}
void initialize_mesh_attrs(H5::H5Object & obj, openpmd::Space space, const std::vector<double> & grid_spacing) {
create_attribute(obj, "geometry", "cartesian");
create_attribute(obj, "dataOrder", "C");
create_attribute(obj, "gridUnitSI", 1.0);
create_attribute(obj, "gridSpacing", grid_spacing);
create_attribute(obj, "gridGlobalOffset", std::vector<double>{0.0, 0.0});
create_attribute(obj, "unitDimension", std::vector<double>(7, 0.0));
create_attribute(obj, "timeOffset", 0.0);
create_attribute(obj, "axisLabels", get_axes_labels(space));
}
void openpmd::initialize_2d_dataset(const std::string & filepath, const std::string & name, hsize_t n1, hsize_t n2, Space space, std::array<double, 2> grid_spacing) {
auto file = H5::H5File(filepath, H5F_ACC_RDWR);
const hsize_t dims[2] {n1, n2};
H5::DataSpace dataspace(2, dims);
auto group_name = get_parent(name);
auto group = open_group(file, group_name);
auto dataset_name = get_name(name);
H5::DataSet dataset = create_dataset(group, dataset_name, dataspace);
std::vector<double> grid_spacing_v{grid_spacing.begin(), grid_spacing.end()};
if (dataset_name == "x" || dataset_name == "y" || dataset_name == "z") {
if (!group.attrExists("geometry")) {
initialize_mesh_attrs(group, space, grid_spacing_v);
}
} else {
initialize_mesh_attrs(dataset, space, grid_spacing_v);
}
// TODO proper SI units
create_attribute(dataset, "unitSI", 1.0);
// TODO proper position of the grid
create_attribute(dataset, "position", std::vector<double>{0.0, 0.0});
}
void openpmd::create_iteration_group(const std::string & filepath, int iteration, double dt, double time, double time_units_SI) {
auto file = H5::H5File(filepath, H5F_ACC_RDWR);
auto iteration_group_name = iteration_group_string(iteration);
auto iteration_group = open_group(file, iteration_group_name);
create_attribute(iteration_group, "time", time);
create_attribute(iteration_group, "dt", dt);
create_attribute(iteration_group, "timeUnitSI", time_units_SI);
}
| 36.113043
| 166
| 0.672646
|
blendersamsonov
|
a355ed6fb46ae61eca5acc7b26fc8100dcf130bc
| 5,368
|
cpp
|
C++
|
src/osvr/Connection/GenerateVrpnDynamicServer.cpp
|
ccccjason/OSVR_device_plugin
|
6c9171265900530341cfa79357151daa39618737
|
[
"Apache-2.0"
] | 1
|
2022-03-28T05:09:11.000Z
|
2022-03-28T05:09:11.000Z
|
src/osvr/Connection/GenerateVrpnDynamicServer.cpp
|
ccccjason/my_osvr
|
fdb2a64cbf88211c34f8c8bd42f0f83a6b98769e
|
[
"Apache-2.0"
] | null | null | null |
src/osvr/Connection/GenerateVrpnDynamicServer.cpp
|
ccccjason/my_osvr
|
fdb2a64cbf88211c34f8c8bd42f0f83a6b98769e
|
[
"Apache-2.0"
] | null | null | null |
/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "GenerateVrpnDynamicServer.h"
#include "VrpnBaseFlexServer.h"
#include "VrpnAnalogServer.h"
#include "VrpnButtonServer.h"
#include "VrpnTrackerServer.h"
#include "GenerateCompoundServer.h"
// Library/third-party includes
#include <boost/mpl/vector.hpp>
#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/next.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/utility.hpp>
// Standard includes
// - none
namespace osvr {
namespace connection {
namespace server_generation {
typedef boost::mpl::vector<vrpn_BaseFlexServer, VrpnAnalogServer,
VrpnButtonServer,
VrpnTrackerServer> ServerTypes;
template <typename T> struct ShouldInclude {
static bool predicate(DeviceConstructionData &);
};
template <>
bool ShouldInclude<vrpn_BaseFlexServer>::predicate(
DeviceConstructionData &) {
return true;
}
template <>
bool ShouldInclude<VrpnAnalogServer>::predicate(
DeviceConstructionData &init) {
return init.obj.getAnalogs().is_initialized();
}
template <>
bool ShouldInclude<VrpnButtonServer>::predicate(
DeviceConstructionData &init) {
return init.obj.getButtons().is_initialized();
}
template <>
bool ShouldInclude<VrpnTrackerServer>::predicate(
DeviceConstructionData &init) {
return init.obj.getTracker();
}
typedef boost::mpl::begin<ServerTypes>::type Begin;
typedef boost::mpl::end<ServerTypes>::type End;
/// @brief Template to invoke construction once sequence filtering is
/// complete.
template <typename Result, typename Enable = void>
struct MakeServerFromSequence;
/// @brief Don't attempt to construct with an empty sequence.
template <typename Result>
struct MakeServerFromSequence<
Result, typename boost::enable_if<
typename boost::mpl::empty<Result>::type>::type> {
static vrpn_MainloopObject *make(DeviceConstructionData &) {
return nullptr;
}
};
/// @brief Normal construction case.
template <typename Result>
struct MakeServerFromSequence<
Result, typename boost::disable_if<
typename boost::mpl::empty<Result>::type>::type> {
static vrpn_MainloopObject *make(DeviceConstructionData &init) {
return vrpn_MainloopObject::wrap(
GenerateServer<Result>::make(init));
}
};
/// Template to perform the list filtering.
template <typename Iter = Begin,
typename Result = boost::mpl::vector0<>,
typename Enable = void>
struct FilterAndGenerate;
/// Recursive case: Iter is not past the end.
template <typename Iter, typename Result>
struct FilterAndGenerate<
Iter, Result,
typename boost::disable_if<boost::is_same<Iter, End> >::type> {
static vrpn_MainloopObject *run(DeviceConstructionData &init) {
typedef typename boost::mpl::deref<Iter>::type CurrentType;
typedef typename boost::mpl::next<Iter>::type NextIter;
typedef
typename boost::mpl::push_back<Result, CurrentType>::type
ExtendedResult;
typedef FilterAndGenerate<NextIter, ExtendedResult> NextWith;
typedef FilterAndGenerate<NextIter, Result> NextWithout;
if (ShouldInclude<CurrentType>::predicate(init)) {
return NextWith::run(init);
} else {
return NextWithout::run(init);
}
}
};
/// Base case: iter is past the end.
template <typename Iter, typename Result>
struct FilterAndGenerate<
Iter, Result,
typename boost::enable_if<boost::is_same<Iter, End> >::type> {
static vrpn_MainloopObject *run(DeviceConstructionData &init) {
return MakeServerFromSequence<Result>::make(init);
}
};
} // namespace server_generation
vrpn_MainloopObject *
generateVrpnDynamicServer(server_generation::ConstructorArgument &init) {
return server_generation::FilterAndGenerate<>::run(init);
}
} // namespace connection
} // namespace osvr
| 35.084967
| 77
| 0.618666
|
ccccjason
|
a356f8b24e620fa4f66951cd003fba010cc2e2f3
| 165
|
cpp
|
C++
|
template/base_template.cpp
|
ganmodokix/ysn
|
74cad18941102539493dda821e17e767bbecde89
|
[
"MIT"
] | null | null | null |
template/base_template.cpp
|
ganmodokix/ysn
|
74cad18941102539493dda821e17e767bbecde89
|
[
"MIT"
] | null | null | null |
template/base_template.cpp
|
ganmodokix/ysn
|
74cad18941102539493dda821e17e767bbecde89
|
[
"MIT"
] | null | null | null |
// #REQ: base_template/575 base_template/ll base_template/debug_mode base_template/gcc base_template/macro base_template/dump base_template/qin
// base template set
| 55
| 143
| 0.842424
|
ganmodokix
|
a35a58d45072ac782099a90d3585896c2b41a6c8
| 32,284
|
cpp
|
C++
|
cpp/lib/src/outstation/OutstationContext.cpp
|
ekra-ltd/opendnp3
|
f3e49c08af770da74c53d17d840bf1a4113b50df
|
[
"Apache-2.0"
] | null | null | null |
cpp/lib/src/outstation/OutstationContext.cpp
|
ekra-ltd/opendnp3
|
f3e49c08af770da74c53d17d840bf1a4113b50df
|
[
"Apache-2.0"
] | null | null | null |
cpp/lib/src/outstation/OutstationContext.cpp
|
ekra-ltd/opendnp3
|
f3e49c08af770da74c53d17d840bf1a4113b50df
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2013-2020 Automatak, LLC
*
* Licensed to Green Energy Corp (www.greenenergycorp.com) and Automatak
* LLC (www.automatak.com) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. Green Energy Corp and Automatak LLC license
* this file to you under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may obtain
* a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OutstationContext.h"
#include "app/APDUBuilders.h"
#include "app/APDULogging.h"
#include "app/Functions.h"
#include "app/parsing/APDUHeaderParser.h"
#include "app/parsing/APDUParser.h"
#include "link/LinkHeader.h"
#include "logging/LogMacros.h"
#include "outstation/AssignClassHandler.h"
#include "outstation/ClassBasedRequestHandler.h"
#include "outstation/CommandActionAdapter.h"
#include "outstation/CommandResponseHandler.h"
#include "outstation/ConstantCommandAction.h"
#include "outstation/FreezeRequestHandler.h"
#include "outstation/IINHelpers.h"
#include "outstation/ReadHandler.h"
#include "outstation/WriteHandler.h"
#include "opendnp3/logging/LogLevels.h"
#include "transport/TransportHeader.h"
#include <utility>
namespace opendnp3
{
OContext::OContext(const Addresses& addresses,
const OutstationConfig& config,
const DatabaseConfig& db_config,
const Logger& logger,
const std::shared_ptr<exe4cpp::IExecutor>& executor,
std::shared_ptr<ILowerLayer> lower,
std::shared_ptr<ICommandHandler> commandHandler,
std::shared_ptr<IOutstationApplication> application)
:
addresses(addresses),
logger(logger),
executor(executor),
lower(std::move(lower)),
commandHandler(std::move(commandHandler)),
application(std::move(application)),
eventBuffer(config.eventBufferConfig),
database(db_config, eventBuffer, *this->application, config.params.typesAllowedInClass0),
rspContext(database, eventBuffer),
params(config.params),
isOnline(false),
isTransmitting(false),
staticIIN(IINBit::DEVICE_RESTART),
deferred(config.params.maxRxFragSize),
sol(config.params.maxTxFragSize),
unsol(config.params.maxTxFragSize),
unsolRetries(config.params.numUnsolRetries),
shouldCheckForUnsolicited(false),
_fileTransferWorker(config.params.enableFileTransfer, config.params.maxOpenedFiles, config.params.shouldOverrideFiles,
config.params.permitDeleteFiles, this->logger)
{
// because mxRx/Tx frag size not taking into account the size of headers for file transfer
// and just the max size of packet and not file data size
// the amount we reading/writting from/to the file should be reduced by the all headers size or it may cause malformed packets
const uint32_t fileTransferMaxTxBlockSize = config.params.maxRxFragSize
- LinkHeader::HEADER_SIZE
- TransportHeader::HEADER_SIZE
- APDUHeader::RESPONSE_SIZE
- 3;
const uint32_t fileTransferMaxRxBlockSize = config.params.maxTxFragSize
- LinkHeader::HEADER_SIZE
- TransportHeader::HEADER_SIZE
- APDUHeader::REQUEST_SIZE
- 3;
_fileTransferWorker.SetPrefferedBlockSize(fileTransferMaxTxBlockSize, fileTransferMaxRxBlockSize);
}
bool OContext::OnLowerLayerUp()
{
if (isOnline)
{
SIMPLE_LOG_BLOCK(logger, flags::ERR, "already online");
return false;
}
isOnline = true;
this->shouldCheckForUnsolicited = true;
this->CheckForTaskStart();
return true;
}
bool OContext::OnLowerLayerDown()
{
if (!isOnline)
{
SIMPLE_LOG_BLOCK(logger, flags::ERR, "already offline");
return false;
}
this->state = &StateIdle::Inst();
isOnline = false;
isTransmitting = false;
sol.Reset();
unsol.Reset();
history.Reset();
deferred.Reset();
eventBuffer.Unselect();
rspContext.Reset();
confirmTimer.cancel();
_fileTransferWorker.Reset();
return true;
}
bool OContext::OnTxReady()
{
if (!isOnline || !isTransmitting)
{
return false;
}
this->isTransmitting = false;
this->CheckForTaskStart();
return true;
}
bool OContext::OnReceive(const Message& message)
{
if (!this->isOnline)
{
SIMPLE_LOG_BLOCK(this->logger, flags::ERR, "ignoring received data while offline");
return false;
}
this->ProcessMessage(message);
this->CheckForTaskStart();
return true;
}
OutstationState& OContext::OnReceiveSolRequest(const ParsedRequest& request)
{
// analyze this request to see how it compares to the last request
if (this->history.HasLastRequest())
{
if (this->sol.seq.num.Equals(request.header.control.SEQ))
{
if (this->history.FullyEqualsLastRequest(request.header, request.objects))
{
if (request.header.function == FunctionCode::READ)
{
return this->state->OnRepeatReadRequest(*this, request);
}
return this->state->OnRepeatNonReadRequest(*this, request);
}
else // new operation with same SEQ
{
return this->ProcessNewRequest(request);
}
}
else // completely new sequence #
{
return this->ProcessNewRequest(request);
}
}
else
{
return this->ProcessNewRequest(request);
}
}
OutstationState& OContext::ProcessNewRequest(const ParsedRequest& request)
{
this->sol.seq.num = request.header.control.SEQ;
if (request.header.function == FunctionCode::READ)
{
return this->state->OnNewReadRequest(*this, request);
}
return this->state->OnNewNonReadRequest(*this, request);
}
bool OContext::ProcessObjects(const ParsedRequest& request)
{
if (request.addresses.IsBroadcast())
{
this->state = &this->state->OnBroadcastMessage(*this, request);
return true;
}
if (Functions::IsNoAckFuncCode(request.header.function))
{
// this is the only request we process while we are transmitting
// because it doesn't require a response of any kind
return this->ProcessRequestNoAck(request);
}
if (this->isTransmitting)
{
this->deferred.Set(request);
return true;
}
if (request.header.function == FunctionCode::CONFIRM)
{
return this->ProcessConfirm(request);
}
return this->ProcessRequest(request);
}
bool OContext::ProcessRequest(const ParsedRequest& request)
{
if (request.header.control.UNS)
{
FORMAT_LOG_BLOCK(this->logger, flags::WARN, "Ignoring unsol with invalid function code: %s",
FunctionCodeSpec::to_human_string(request.header.function));
return false;
}
this->state = &this->OnReceiveSolRequest(request);
return true;
}
bool OContext::ProcessConfirm(const ParsedRequest& request)
{
this->state = &this->state->OnConfirm(*this, request);
return true;
}
OutstationState& OContext::BeginResponseTx(uint16_t destination, APDUResponse& response)
{
CheckForBroadcastConfirmation(response);
const auto data = response.ToRSeq();
this->sol.tx.Record(response.GetControl(), data);
this->sol.seq.confirmNum = response.GetControl().SEQ;
this->BeginTx(destination, data);
if (response.GetControl().CON)
{
this->RestartSolConfirmTimer();
return StateSolicitedConfirmWait::Inst();
}
return StateIdle::Inst();
}
void OContext::BeginRetransmitLastResponse(uint16_t destination)
{
this->BeginTx(destination, this->sol.tx.GetLastResponse());
}
void OContext::BeginRetransmitLastUnsolicitedResponse()
{
this->BeginTx(this->addresses.destination, this->unsol.tx.GetLastResponse());
}
void OContext::BeginUnsolTx(APDUResponse& response)
{
CheckForBroadcastConfirmation(response);
const auto data = response.ToRSeq();
this->unsol.tx.Record(response.GetControl(), data);
this->unsol.seq.confirmNum = this->unsol.seq.num;
this->unsol.seq.num.Increment();
this->BeginTx(this->addresses.destination, data);
}
void OContext::BeginTx(uint16_t destination, const ser4cpp::rseq_t& message)
{
logging::ParseAndLogResponseTx(this->logger, message);
this->isTransmitting = true;
this->lower->BeginTransmit(Message(Addresses(this->addresses.source, destination), message));
}
void OContext::CheckForTaskStart()
{
// do these checks in order of priority
this->CheckForDeferredRequest();
this->CheckForUnsolicitedNull();
if (this->shouldCheckForUnsolicited)
{
this->CheckForUnsolicited();
}
}
void OContext::CheckForDeferredRequest()
{
if (this->CanTransmit() && this->deferred.IsSet())
{
auto handler = [this](const ParsedRequest& request) { return this->ProcessDeferredRequest(request); };
this->deferred.Process(handler);
}
}
void OContext::CheckForUnsolicitedNull()
{
if (this->CanTransmit() && this->state->IsIdle() && this->params.allowUnsolicited)
{
if (!this->unsol.completedNull)
{
// send a NULL unsolcited message
auto response = this->unsol.tx.Start();
build::NullUnsolicited(response, this->unsol.seq.num, this->GetResponseIIN());
this->RestartUnsolConfirmTimer();
this->state = this->params.noDefferedReadDuringUnsolicitedNullResponse
? &StateNullUnsolicitedConfirmWait::Inst()
: &StateUnsolicitedConfirmWait::Inst();
this->BeginUnsolTx(response);
}
}
}
void OContext::CheckForUnsolicited()
{
if (this->shouldCheckForUnsolicited && this->CanTransmit() && this->state->IsIdle()
&& this->params.allowUnsolicited)
{
this->shouldCheckForUnsolicited = false;
if (this->unsol.completedNull)
{
// are there events to be reported?
if (this->params.unsolClassMask.Intersects(this->eventBuffer.UnwrittenClassField()))
{
auto response = this->unsol.tx.Start();
auto writer = response.GetWriter();
this->unsolRetries.Reset();
this->eventBuffer.Unselect();
this->eventBuffer.SelectAllByClass(this->params.unsolClassMask);
this->eventBuffer.Load(writer);
build::NullUnsolicited(response, this->unsol.seq.num, this->GetResponseIIN());
this->RestartUnsolConfirmTimer();
this->state = &StateUnsolicitedConfirmWait::Inst();
this->BeginUnsolTx(response);
}
}
}
}
bool OContext::ProcessDeferredRequest(const ParsedRequest& request)
{
if (request.header.function == FunctionCode::CONFIRM)
{
this->ProcessConfirm(request);
return true;
}
if (request.header.function == FunctionCode::READ)
{
if (this->state->IsIdle())
{
this->ProcessRequest(request);
return true;
}
return false;
}
else
{
this->ProcessRequest(request);
return true;
}
}
void OContext::RestartSolConfirmTimer()
{
auto timeout = [&]() {
this->state = &this->state->OnConfirmTimeout(*this);
this->CheckForTaskStart();
};
this->confirmTimer.cancel();
this->confirmTimer = this->executor->start(this->params.solConfirmTimeout.value, timeout);
}
void OContext::RestartUnsolConfirmTimer()
{
auto timeout = [&]() {
this->state = &this->state->OnConfirmTimeout(*this);
this->CheckForTaskStart();
};
this->confirmTimer.cancel();
this->confirmTimer = this->executor->start(this->params.unsolConfirmTimeout.value, timeout);
}
OutstationState& OContext::RespondToNonReadRequest(const ParsedRequest& request)
{
this->history.RecordLastProcessedRequest(request.header, request.objects);
auto response = this->sol.tx.Start();
auto writer = response.GetWriter();
response.SetFunction(FunctionCode::RESPONSE);
response.SetControl(AppControlField(true, true, false, false, request.header.control.SEQ));
const auto iin = this->HandleNonReadResponse(request.header, request.objects, writer);
response.SetIIN(iin | this->GetResponseIIN());
return this->BeginResponseTx(request.addresses.source, response);
}
OutstationState& OContext::RespondToReadRequest(const ParsedRequest& request)
{
this->history.RecordLastProcessedRequest(request.header, request.objects);
auto response = this->sol.tx.Start();
auto writer = response.GetWriter();
response.SetFunction(FunctionCode::RESPONSE);
auto result = this->HandleRead(request.objects, writer);
result.second.SEQ = request.header.control.SEQ;
response.SetControl(result.second);
response.SetIIN(result.first | this->GetResponseIIN());
return this->BeginResponseTx(request.addresses.source, response);
}
OutstationState& OContext::ContinueMultiFragResponse(const Addresses& addresses, const AppSeqNum& seq)
{
auto response = this->sol.tx.Start();
auto writer = response.GetWriter();
response.SetFunction(FunctionCode::RESPONSE);
auto control = this->rspContext.LoadResponse(writer);
control.SEQ = seq;
response.SetControl(control);
response.SetIIN(this->GetResponseIIN());
return this->BeginResponseTx(addresses.source, response);
}
bool OContext::CanTransmit() const
{
return isOnline && !isTransmitting;
}
IINField OContext::GetResponseIIN()
{
return this->staticIIN | this->GetDynamicIIN() | this->application->GetApplicationIIN().ToIIN();
}
IINField OContext::GetDynamicIIN()
{
const auto classField = this->eventBuffer.UnwrittenClassField();
IINField ret;
ret.SetBitToValue(IINBit::CLASS1_EVENTS, classField.HasClass1());
ret.SetBitToValue(IINBit::CLASS2_EVENTS, classField.HasClass2());
ret.SetBitToValue(IINBit::CLASS3_EVENTS, classField.HasClass3());
ret.SetBitToValue(IINBit::EVENT_BUFFER_OVERFLOW, this->eventBuffer.IsOverflown());
return ret;
}
void OContext::UpdateLastBroadcastMessageReceived(uint16_t destination)
{
switch (destination)
{
case LinkBroadcastAddress::DontConfirm:
lastBroadcastMessageReceived.set(LinkBroadcastAddress::DontConfirm);
break;
case LinkBroadcastAddress::ShallConfirm:
lastBroadcastMessageReceived.set(LinkBroadcastAddress::ShallConfirm);
break;
case LinkBroadcastAddress::OptionalConfirm:
lastBroadcastMessageReceived.set(LinkBroadcastAddress::OptionalConfirm);
break;
default:
lastBroadcastMessageReceived.clear();
}
}
void OContext::CheckForBroadcastConfirmation(APDUResponse& response)
{
if (lastBroadcastMessageReceived.is_set())
{
response.SetIIN(response.GetIIN() | IINField(IINBit::BROADCAST));
if (lastBroadcastMessageReceived.get() != LinkBroadcastAddress::ShallConfirm)
{
lastBroadcastMessageReceived.clear();
}
else
{
// The broadcast address requested a confirmation
auto control = response.GetControl();
control.CON = true;
response.SetControl(control);
}
}
}
bool OContext::ProcessMessage(const Message& message)
{
// is the message addressed to this outstation
if (message.addresses.destination != this->addresses.source && !message.addresses.IsBroadcast())
{
return false;
}
// is the message coming from the expected master?
if (!this->params.respondToAnyMaster && (message.addresses.source != this->addresses.destination))
{
return false;
}
FORMAT_HEX_BLOCK(this->logger, flags::APP_HEX_RX, message.payload, 18, 18);
if (message.addresses.IsBroadcast())
{
UpdateLastBroadcastMessageReceived(message.addresses.destination);
}
const auto result = APDUHeaderParser::ParseRequest(message.payload, &this->logger);
if (!result.success)
{
return false;
}
logging::LogHeader(this->logger, flags::APP_HEADER_RX, result.header);
if (!result.header.control.IsFirAndFin())
{
SIMPLE_LOG_BLOCK(this->logger, flags::WARN, "Ignoring fragment. Requests must have FIR/FIN == 1");
return false;
}
if (result.header.control.CON)
{
SIMPLE_LOG_BLOCK(this->logger, flags::WARN, "Ignoring fragment. Requests cannot request confirmation");
return false;
}
return this->ProcessObjects(ParsedRequest(message.addresses, result.header, result.objects));
}
void OContext::HandleNewEvents()
{
this->shouldCheckForUnsolicited = true;
this->CheckForTaskStart();
}
void OContext::SetRestartIIN()
{
this->staticIIN.SetBit(IINBit::DEVICE_RESTART);
}
IUpdateHandler& OContext::GetUpdateHandler()
{
return this->database;
}
//// ----------------------------- function handlers -----------------------------
bool OContext::ProcessBroadcastRequest(const ParsedRequest& request)
{
switch (request.header.function)
{
case (FunctionCode::WRITE):
this->HandleWrite(request.objects, nullptr);
return true;
case (FunctionCode::DIRECT_OPERATE_NR):
this->HandleDirectOperate(request.objects, OperateType::DirectOperateNoAck, nullptr);
return true;
case (FunctionCode::IMMED_FREEZE_NR):
this->HandleFreeze(request.objects);
return true;
case (FunctionCode::FREEZE_CLEAR_NR):
this->HandleFreezeAndClear(request.objects);
return true;
case (FunctionCode::ASSIGN_CLASS):
{
if (this->application->SupportsAssignClass())
{
this->HandleAssignClass(request.objects);
return true;
}
else
{
return false;
}
}
case (FunctionCode::RECORD_CURRENT_TIME):
{
if (request.objects.is_not_empty())
{
this->HandleRecordCurrentTime();
return true;
}
else
{
return false;
}
}
case (FunctionCode::DISABLE_UNSOLICITED):
{
if (this->params.allowUnsolicited)
{
this->HandleDisableUnsolicited(request.objects, nullptr);
return true;
}
else
{
return false;
}
}
case (FunctionCode::ENABLE_UNSOLICITED):
{
if (this->params.allowUnsolicited)
{
this->HandleEnableUnsolicited(request.objects, nullptr);
return true;
}
else
{
return false;
}
}
default:
FORMAT_LOG_BLOCK(this->logger, flags::WARN, "Ignoring broadcast on function code: %s",
FunctionCodeSpec::to_string(request.header.function));
return false;
}
}
bool OContext::ProcessRequestNoAck(const ParsedRequest& request)
{
switch (request.header.function)
{
case (FunctionCode::DIRECT_OPERATE_NR):
this->HandleDirectOperate(request.objects, OperateType::DirectOperateNoAck,
nullptr); // no object writer, this is a no ack code
return true;
case (FunctionCode::IMMED_FREEZE_NR):
this->HandleFreeze(request.objects);
return true;
case (FunctionCode::FREEZE_CLEAR_NR):
this->HandleFreezeAndClear(request.objects);
return true;
default:
FORMAT_LOG_BLOCK(this->logger, flags::WARN, "Ignoring NR function code: %s",
FunctionCodeSpec::to_human_string(request.header.function));
return false;
}
}
IINField OContext::HandleNonReadResponse(const APDUHeader& header, const ser4cpp::rseq_t& objects, HeaderWriter& writer)
{
switch (header.function)
{
case (FunctionCode::WRITE):
return this->HandleWrite(objects, &writer);
case (FunctionCode::SELECT):
return this->HandleSelect(objects, writer);
case (FunctionCode::OPERATE):
return this->HandleOperate(objects, writer);
case (FunctionCode::DIRECT_OPERATE):
return this->HandleDirectOperate(objects, OperateType::DirectOperate, &writer);
case (FunctionCode::COLD_RESTART):
return this->HandleRestart(objects, false, &writer);
case (FunctionCode::WARM_RESTART):
return this->HandleRestart(objects, true, &writer);
case (FunctionCode::ASSIGN_CLASS):
return this->HandleAssignClass(objects);
case (FunctionCode::DELAY_MEASURE):
return this->HandleDelayMeasure(objects, writer);
case (FunctionCode::RECORD_CURRENT_TIME):
return objects.is_empty() ? this->HandleRecordCurrentTime() : IINField(IINBit::PARAM_ERROR);
case (FunctionCode::DISABLE_UNSOLICITED):
return this->params.allowUnsolicited ? this->HandleDisableUnsolicited(objects, &writer)
: IINField(IINBit::FUNC_NOT_SUPPORTED);
case (FunctionCode::ENABLE_UNSOLICITED):
return this->params.allowUnsolicited ? this->HandleEnableUnsolicited(objects, &writer)
: IINField(IINBit::FUNC_NOT_SUPPORTED);
case (FunctionCode::IMMED_FREEZE):
return this->HandleFreeze(objects);
case (FunctionCode::FREEZE_CLEAR):
return this->HandleFreezeAndClear(objects);
case FunctionCode::OPEN_FILE:
case FunctionCode::CLOSE_FILE:
case FunctionCode::DELETE_FILE:
case FunctionCode::GET_FILE_INFO:
case FunctionCode::AUTHENTICATE_FILE:
case FunctionCode::ABORT_FILE:
return this->HandleFileTransfer(objects, &writer, header.function);
default:
return { IINBit::FUNC_NOT_SUPPORTED };
}
}
ser4cpp::Pair<IINField, AppControlField> OContext::HandleRead(const ser4cpp::rseq_t& objects, HeaderWriter& writer)
{
this->rspContext.Reset();
this->eventBuffer.Unselect(); // always un-select any previously selected points when we start a new read request
this->database.Unselect();
ReadHandler handler(this->database, this->eventBuffer);
const auto result = APDUParser::Parse(objects, handler, &this->logger,
ParserSettings::NoContents()); // don't expect range/count context on a READ
if (handler.IsFileRead())
{
return _fileTransferWorker.HandleReadFile(objects, &writer);
}
if (result == ParseResult::OK)
{
const auto controlField = this->rspContext.LoadResponse(writer);
return ser4cpp::Pair<IINField, AppControlField>(handler.Errors(), controlField);
}
this->rspContext.Reset();
return ser4cpp::Pair<IINField, AppControlField>(IINFromParseResult(result),
AppControlField(true, true, false, false));
}
IINField OContext::HandleWrite(const ser4cpp::rseq_t& objects, HeaderWriter* writer)
{
WriteHandler handler(*this->application, this->time, this->sol.seq.num, Timestamp(this->executor->get_time()),
&this->staticIIN);
const auto result = APDUParser::Parse(objects, handler, &this->logger);
if (handler.IsFileWrite() && writer != nullptr)
{
return _fileTransferWorker.HandleWriteFile(objects, writer);
}
return (result == ParseResult::OK) ? handler.Errors() : IINFromParseResult(result);
}
IINField OContext::HandleDirectOperate(const ser4cpp::rseq_t& objects, OperateType opType, HeaderWriter* pWriter)
{
// since we're echoing, make sure there's enough size before beginning
if (pWriter && (objects.length() > pWriter->Remaining()))
{
FORMAT_LOG_BLOCK(this->logger, flags::WARN, "Igonring command request due to oversized payload size of %zu",
objects.length());
return {IINBit::PARAM_ERROR};
}
CommandActionAdapter adapter(*this->commandHandler, false, this->database, opType);
CommandResponseHandler handler(this->params.maxControlsPerRequest, &adapter, pWriter);
const auto result = APDUParser::Parse(objects, handler, &this->logger);
this->shouldCheckForUnsolicited = true;
return (result == ParseResult::OK) ? handler.Errors() : IINFromParseResult(result);
}
IINField OContext::HandleSelect(const ser4cpp::rseq_t& objects, HeaderWriter& writer)
{
// since we're echoing, make sure there's enough size before beginning
if (objects.length() > writer.Remaining())
{
FORMAT_LOG_BLOCK(this->logger, flags::WARN, "Igonring command request due to oversized payload size of %zu",
objects.length());
return {IINBit::PARAM_ERROR};
}
// the 'OperateType' is just ignored since it's a select
CommandActionAdapter adapter(*this->commandHandler, true, this->database, OperateType::DirectOperate);
CommandResponseHandler handler(this->params.maxControlsPerRequest, &adapter, &writer);
const auto result = APDUParser::Parse(objects, handler, &this->logger);
if (result == ParseResult::OK)
{
if (handler.AllCommandsSuccessful())
{
this->control.Select(this->sol.seq.num, Timestamp(this->executor->get_time()), objects);
}
return handler.Errors();
}
return IINFromParseResult(result);
}
IINField OContext::HandleOperate(const ser4cpp::rseq_t& objects, HeaderWriter& writer)
{
// since we're echoing, make sure there's enough size before beginning
if (objects.length() > writer.Remaining())
{
FORMAT_LOG_BLOCK(this->logger, flags::WARN, "Igonring command request due to oversized payload size of %zu",
objects.length());
return {IINBit::PARAM_ERROR};
}
const auto now = Timestamp(this->executor->get_time());
const auto result = this->control.ValidateSelection(this->sol.seq.num, now, this->params.selectTimeout, objects);
if (result == CommandStatus::SUCCESS)
{
CommandActionAdapter adapter(*this->commandHandler, false, this->database, OperateType::SelectBeforeOperate);
CommandResponseHandler handler(this->params.maxControlsPerRequest, &adapter, &writer);
const auto innerResult = APDUParser::Parse(objects, handler, &this->logger);
this->shouldCheckForUnsolicited = true;
return (innerResult == ParseResult::OK) ? handler.Errors() : IINFromParseResult(innerResult);
}
else
{
this->control.Unselect();
}
return this->HandleCommandWithConstant(objects, writer, result);
}
IINField OContext::HandleDelayMeasure(const ser4cpp::rseq_t& objects, HeaderWriter& writer)
{
if (objects.is_empty())
{
Group52Var2 value;
value.time = 0; // respond with 0 time delay
writer.WriteSingleValue<ser4cpp::UInt8, Group52Var2>(QualifierCode::UINT8_CNT, value);
return IINField::Empty();
}
// there shouldn't be any trailing headers in delay measure request, no need to even parse
return {IINBit::PARAM_ERROR};
}
IINField OContext::HandleRecordCurrentTime()
{
this->time.RecordCurrentTime(this->sol.seq.num, Timestamp(this->executor->get_time()));
return IINField::Empty();
}
IINField OContext::HandleRestart(const ser4cpp::rseq_t& objects, bool isWarmRestart, HeaderWriter* pWriter)
{
if (objects.is_not_empty())
return {IINBit::PARAM_ERROR};
const auto mode = isWarmRestart ? this->application->WarmRestartSupport() : this->application->ColdRestartSupport();
switch (mode)
{
case (RestartMode::UNSUPPORTED):
return IINField(IINBit::FUNC_NOT_SUPPORTED);
case (RestartMode::SUPPORTED_DELAY_COARSE):
{
const auto delay = isWarmRestart ? this->application->WarmRestart() : this->application->ColdRestart();
if (pWriter)
{
Group52Var1 coarse;
coarse.time = delay;
pWriter->WriteSingleValue<ser4cpp::UInt8>(QualifierCode::UINT8_CNT, coarse);
}
return IINField::Empty();
}
default:
{
const auto delay = isWarmRestart ? this->application->WarmRestart() : this->application->ColdRestart();
if (pWriter)
{
Group52Var2 fine;
fine.time = delay;
pWriter->WriteSingleValue<ser4cpp::UInt8>(QualifierCode::UINT8_CNT, fine);
}
return IINField::Empty();
}
}
}
IINField OContext::HandleAssignClass(const ser4cpp::rseq_t& objects)
{
if (this->application->SupportsAssignClass())
{
AssignClassHandler handler(*this->application, this->database);
const auto result = APDUParser::Parse(objects, handler, &this->logger, ParserSettings::NoContents());
return (result == ParseResult::OK) ? handler.Errors() : IINFromParseResult(result);
}
return {IINBit::FUNC_NOT_SUPPORTED};
}
IINField OContext::HandleDisableUnsolicited(const ser4cpp::rseq_t& objects, HeaderWriter* /*writer*/)
{
ClassBasedRequestHandler handler;
const auto result = APDUParser::Parse(objects, handler, &this->logger);
if (result == ParseResult::OK)
{
this->params.unsolClassMask.Clear(handler.GetClassField());
return handler.Errors();
}
return IINFromParseResult(result);
}
IINField OContext::HandleEnableUnsolicited(const ser4cpp::rseq_t& objects, HeaderWriter* /*writer*/)
{
ClassBasedRequestHandler handler;
const auto result = APDUParser::Parse(objects, handler, &this->logger);
if (result == ParseResult::OK)
{
this->params.unsolClassMask.Set(handler.GetClassField());
this->shouldCheckForUnsolicited = true;
return handler.Errors();
}
return IINFromParseResult(result);
}
IINField OContext::HandleCommandWithConstant(const ser4cpp::rseq_t& objects, HeaderWriter& writer, CommandStatus status)
{
ConstantCommandAction constant(status);
CommandResponseHandler handler(this->params.maxControlsPerRequest, &constant, &writer);
const auto result = APDUParser::Parse(objects, handler, &this->logger);
return IINFromParseResult(result);
}
IINField OContext::HandleFreeze(const ser4cpp::rseq_t& objects)
{
FreezeRequestHandler handler(false, database);
const auto result = APDUParser::Parse(objects, handler, &this->logger, ParserSettings::NoContents());
return IINFromParseResult(result);
}
IINField OContext::HandleFreezeAndClear(const ser4cpp::rseq_t& objects)
{
FreezeRequestHandler handler(true, database);
const auto result = APDUParser::Parse(objects, handler, &this->logger, ParserSettings::NoContents());
return IINFromParseResult(result);
}
IINField OContext::HandleFileTransfer(const ser4cpp::rseq_t& objects, HeaderWriter* writer, FunctionCode fc)
{
switch (fc) {
case FunctionCode::OPEN_FILE:
return _fileTransferWorker.HandleOpenFile(objects, writer);
case FunctionCode::CLOSE_FILE:
return _fileTransferWorker.HandleCloseFile(objects, writer);
case FunctionCode::DELETE_FILE:
return _fileTransferWorker.HandleDeleteFile(objects, writer);
case FunctionCode::GET_FILE_INFO:
return _fileTransferWorker.HandleGetFileInfo(objects, writer);
case FunctionCode::AUTHENTICATE_FILE:
return _fileTransferWorker.HandleAuthFile(objects, writer);
case FunctionCode::ABORT_FILE:
return _fileTransferWorker.HandleAbortFile(objects, writer);
default:
return IINField::Empty();
}
}
} // namespace opendnp3
| 33.629167
| 130
| 0.665686
|
ekra-ltd
|
a35ae202dd6cd89c20defd71dfe73d2a9d27188b
| 1,258
|
cpp
|
C++
|
src/main/cpp/wee/engine/line_renderer.cpp
|
emdavoca/wee
|
60344dd646a2e27d1cfdb1131dd679558d9cfa2b
|
[
"MIT"
] | 1
|
2019-02-11T12:18:39.000Z
|
2019-02-11T12:18:39.000Z
|
src/main/cpp/wee/engine/line_renderer.cpp
|
emdavoca/wee
|
60344dd646a2e27d1cfdb1131dd679558d9cfa2b
|
[
"MIT"
] | 1
|
2021-11-11T07:27:58.000Z
|
2021-11-11T07:27:58.000Z
|
src/main/cpp/wee/engine/line_renderer.cpp
|
emdavoca/wee
|
60344dd646a2e27d1cfdb1131dd679558d9cfa2b
|
[
"MIT"
] | 1
|
2021-11-11T07:22:12.000Z
|
2021-11-11T07:22:12.000Z
|
#include <engine/line_renderer.hpp>
#include <gfx/graphics_device.hpp>
#include <ostream>
using namespace wee;
line_renderer::line_renderer(size_t n) {
_vertices.resize(n);
_buf = new vertex_buffer(n * sizeof(line_vertex));
_valid = true;
_size = 0;
}
void line_renderer::draw(graphics_device* dev) {
if(!_valid) {
std::ostream os(_buf);
os.write(
reinterpret_cast<char*>(&_vertices[0]),
sizeof(line_vertex) * _size
);
_valid = true;
}
install_vertex_attributes<line_vertex, vertex_attribute_installer>();
dev->draw_primitives<primitive_type::line_list>(0, _size, 1);
}
void line_renderer::resize(size_t) {
throw not_implemented();
}
void line_renderer::position(size_t ix, float x, float y, float z) {
_vertices[ix]._position.x = x;
_vertices[ix]._position.y = y;
_vertices[ix]._position.z = z;
_size = ix > _size ? ix : _size;
_valid = false;
}
void line_renderer::color(size_t ix, const SDL_Color& c) {
_vertices[ix]._color = static_cast<int>(c.r) << 24 | static_cast<int>(c.g) << 16 | static_cast<int>(c.b) << 8 | static_cast<int>(c.a); // could be other way around....
_size = ix > _size ? ix : _size;
_valid = false;
}
| 28.590909
| 171
| 0.644674
|
emdavoca
|
a35b3e5408955e4e8fcbf7778b50fabfb2303690
| 16,000
|
hxx
|
C++
|
source/code/modules/vulkan_renderer/private/vk_utility.hxx
|
iceshard-engine/engine
|
4f2092af8d2d389ea72addc729d0c2c8d944c95c
|
[
"BSD-3-Clause-Clear"
] | 39
|
2019-08-17T09:08:51.000Z
|
2022-02-13T10:14:19.000Z
|
source/code/modules/vulkan_renderer/private/vk_utility.hxx
|
iceshard-engine/engine
|
4f2092af8d2d389ea72addc729d0c2c8d944c95c
|
[
"BSD-3-Clause-Clear"
] | 63
|
2020-05-22T16:09:30.000Z
|
2022-01-21T14:24:05.000Z
|
source/code/modules/vulkan_renderer/private/vk_utility.hxx
|
iceshard-engine/engine
|
4f2092af8d2d389ea72addc729d0c2c8d944c95c
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
#pragma once
#include <ice/pod/array.hxx>
#include <ice/log_tag.hxx>
#include <ice/log.hxx>
#include <ice/render/render_pass.hxx>
#include <ice/render/render_image.hxx>
#include <ice/render/render_resource.hxx>
#include <ice/render/render_pipeline.hxx>
#include <ice/render/render_buffer.hxx>
#include "vk_include.hxx"
namespace ice::render
{
enum class ImageFormat : ice::u32;
enum class ImageLayout : ice::u32;
enum class AttachmentType : ice::u32;
enum class AttachmentOperation : ice::u32;
enum class PipelineStage : ice::u32;
enum class AccessFlags : ice::u32;
} // namespace ice::render
namespace ice::render::vk
{
constexpr ice::LogTagDefinition log_tag = ice::create_log_tag(ice::LogTag::Module, "Vulkan");
template<typename T, typename Fn, typename... Args>
bool enumerate_objects(ice::pod::Array<T>& objects_out, Fn&& fn, Args&&... args) noexcept;
inline auto native_enum_value(ImageType type) noexcept -> VkImageType;
inline auto native_enum_value(ImageFormat image_format) noexcept -> VkFormat;
inline auto native_enum_value(ImageLayout attachment_type) noexcept -> VkImageLayout;
inline void native_enum_value(AttachmentOperation attachment_op, VkAttachmentStoreOp& store_op) noexcept;
inline void native_enum_value(AttachmentOperation attachment_op, VkAttachmentLoadOp& load_op) noexcept;
inline auto native_enum_value(PipelineStage stage) noexcept -> VkPipelineStageFlags;
inline auto native_enum_value(AccessFlags flags) noexcept -> VkAccessFlags;
inline auto native_enum_value(ResourceType type) noexcept -> VkDescriptorType;
inline auto native_enum_value(BufferType type) noexcept -> VkBufferUsageFlags;
inline auto native_enum_value(ShaderStageFlags flags) noexcept -> VkShaderStageFlagBits;
inline auto native_enum_value(ShaderAttribType type) noexcept -> VkFormat;
inline auto native_enum_value(SamplerFilter filter) noexcept -> VkFilter;
inline auto native_enum_value(PrimitiveTopology topology) noexcept -> VkPrimitiveTopology;
inline auto native_enum_value(SamplerAddressMode address_mode) noexcept -> VkSamplerAddressMode;
inline auto native_enum_value(SamplerMipMapMode mipmap_mode) noexcept -> VkSamplerMipmapMode;
inline auto native_enum_flags(ImageUsageFlags flags) noexcept -> VkImageUsageFlags;
inline auto native_enum_flags(ShaderStageFlags flags) noexcept -> VkShaderStageFlags;
template<typename T, typename Fn, typename... Args>
bool enumerate_objects(ice::pod::Array<T>& objects_out, Fn&& fn, Args&&... args) noexcept
{
using result_type = decltype(fn(args..., nullptr, nullptr));
if constexpr (std::is_same_v<result_type, void>)
{
ice::u32 obj_count = 0;
fn(args..., &obj_count, nullptr);
if (obj_count > 0)
{
ice::pod::array::resize(objects_out, obj_count);
fn(args..., &obj_count, ice::pod::array::begin(objects_out));
}
return true;
}
else
{
ice::u32 obj_count = 0;
VkResult result = fn(args..., &obj_count, nullptr);
if (result == VkResult::VK_SUCCESS && obj_count > 0)
{
ice::pod::array::resize(objects_out, obj_count);
result = fn(args..., &obj_count, ice::pod::array::begin(objects_out));
}
return result == VK_SUCCESS;
}
}
inline auto native_enum_value(ImageType type) noexcept -> VkImageType
{
switch (type)
{
case ImageType::Image2D:
return VK_IMAGE_TYPE_2D;
}
}
inline auto native_enum_value(ImageFormat image_format) noexcept -> VkFormat
{
switch (image_format)
{
case ImageFormat::I32_RGBA:
return VK_FORMAT_R8G8B8A8_SINT;
case ImageFormat::UNORM_RGBA:
return VK_FORMAT_R8G8B8A8_UNORM;
case ImageFormat::UNORM_BGRA:
return VK_FORMAT_B8G8R8A8_UNORM;
case ImageFormat::SRGB_RGBA:
return VK_FORMAT_R8G8B8A8_SRGB;
case ImageFormat::SRGB_BGRA:
return VK_FORMAT_B8G8R8A8_SRGB;
case ImageFormat::UNORM_D24_UINT_S8:
return VK_FORMAT_D24_UNORM_S8_UINT;
case ImageFormat::SFLOAT_D32_UINT_S8:
return VK_FORMAT_D32_SFLOAT_S8_UINT;
case ImageFormat::SFLOAT_D32:
return VK_FORMAT_D32_SFLOAT;
default:
return VK_FORMAT_UNDEFINED;
}
}
inline auto api_enum_value(VkFormat image_format) noexcept -> ImageFormat
{
switch (image_format)
{
case VK_FORMAT_R8G8B8A8_SINT:
return ImageFormat::I32_RGBA;
case VK_FORMAT_R8G8B8A8_UNORM:
return ImageFormat::UNORM_RGBA;
case VK_FORMAT_B8G8R8A8_UNORM:
return ImageFormat::UNORM_BGRA;
case VK_FORMAT_R8G8B8A8_SRGB:
return ImageFormat::SRGB_RGBA;
case VK_FORMAT_B8G8R8A8_SRGB:
return ImageFormat::SRGB_BGRA;
case VK_FORMAT_D24_UNORM_S8_UINT:
return ImageFormat::UNORM_D24_UINT_S8;
default:
return ImageFormat::Invalid;
}
}
inline auto native_enum_value(ImageLayout attachment_layout) noexcept -> VkImageLayout
{
switch (attachment_layout)
{
case ImageLayout::Color:
return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
case ImageLayout::Present:
return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
case ImageLayout::ShaderReadOnly:
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
case ImageLayout::DepthStencil:
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
case ImageLayout::TransferDstOptimal:
return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
case ImageLayout::Undefined:
default:
return VK_IMAGE_LAYOUT_UNDEFINED;
}
}
inline void native_enum_value(AttachmentOperation attachment_op, VkAttachmentStoreOp& store_op) noexcept
{
switch (attachment_op)
{
case AttachmentOperation::Store_Store:
store_op = VK_ATTACHMENT_STORE_OP_STORE;
break;
case AttachmentOperation::Store_DontCare:
store_op = VK_ATTACHMENT_STORE_OP_DONT_CARE;
break;
}
}
inline void native_enum_value(AttachmentOperation attachment_op, VkAttachmentLoadOp& load_op) noexcept
{
switch (attachment_op)
{
case AttachmentOperation::Load_Clear:
load_op = VK_ATTACHMENT_LOAD_OP_CLEAR;
break;
case AttachmentOperation::Load_DontCare:
load_op = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
break;
}
}
inline auto native_enum_value(PipelineStage stage) noexcept -> VkPipelineStageFlags
{
switch (stage)
{
case PipelineStage::TopOfPipe:
return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
case PipelineStage::Transfer:
return VK_PIPELINE_STAGE_TRANSFER_BIT;
case PipelineStage::ColorAttachmentOutput:
return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
case PipelineStage::FramentShader:
return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
default:
return VK_PIPELINE_STAGE_FLAG_BITS_MAX_ENUM;
}
}
inline auto native_enum_value(AccessFlags flags) noexcept -> VkAccessFlags
{
switch (flags)
{
case AccessFlags::None:
return VK_ACCESS_NONE_KHR;
case AccessFlags::ShaderRead:
return VK_ACCESS_SHADER_READ_BIT;
case AccessFlags::InputAttachmentRead:
return VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
case AccessFlags::TransferWrite:
return VK_ACCESS_TRANSFER_WRITE_BIT;
case AccessFlags::ColorAttachmentWrite:
return VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
default:
return VK_ACCESS_FLAG_BITS_MAX_ENUM;
}
}
auto native_enum_value(ResourceType type) noexcept -> VkDescriptorType
{
switch (type)
{
case ResourceType::Sampler:
case ResourceType::SamplerImmutable:
return VK_DESCRIPTOR_TYPE_SAMPLER;
case ResourceType::SampledImage:
return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
case ResourceType::CombinedImageSampler:
return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
case ResourceType::UniformBuffer:
return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
case ResourceType::InputAttachment:
return VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
default:
return VK_DESCRIPTOR_TYPE_MAX_ENUM;
}
}
auto native_enum_value(ice::render::BufferType type) noexcept -> VkBufferUsageFlags
{
switch (type)
{
case BufferType::Index:
return VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
case BufferType::Vertex:
return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
case BufferType::Uniform:
return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
case BufferType::Transfer:
return VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
default:
return VK_BUFFER_USAGE_FLAG_BITS_MAX_ENUM;
}
}
auto native_enum_value(ShaderStageFlags value) noexcept -> VkShaderStageFlagBits
{
switch (value)
{
case ShaderStageFlags::VertexStage:
return VK_SHADER_STAGE_VERTEX_BIT;
case ShaderStageFlags::FragmentStage:
return VK_SHADER_STAGE_FRAGMENT_BIT;
case ShaderStageFlags::GeometryStage:
return VK_SHADER_STAGE_GEOMETRY_BIT;
case ShaderStageFlags::TesselationControlStage:
return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
case ShaderStageFlags::TesselationEvaluationStage:
return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
default:
return VK_SHADER_STAGE_FLAG_BITS_MAX_ENUM;
}
}
auto native_enum_value(ShaderAttribType type) noexcept -> VkFormat
{
switch (type)
{
case ShaderAttribType::Vec1f:
return VK_FORMAT_R32_SFLOAT;
case ShaderAttribType::Vec2f:
return VK_FORMAT_R32G32_SFLOAT;
case ShaderAttribType::Vec3f:
return VK_FORMAT_R32G32B32_SFLOAT;
case ShaderAttribType::Vec4f:
return VK_FORMAT_R32G32B32A32_SFLOAT;
case ShaderAttribType::Vec4f_Unorm8:
return VK_FORMAT_R8G8B8A8_UNORM;
case ShaderAttribType::Vec1u:
return VK_FORMAT_R32_UINT;
case ShaderAttribType::Vec1i:
return VK_FORMAT_R32_SINT;
default:
return VK_FORMAT_MAX_ENUM;
}
}
auto native_enum_value(SamplerFilter filter) noexcept -> VkFilter
{
switch (filter)
{
case SamplerFilter::Nearest:
return VkFilter::VK_FILTER_NEAREST;
case SamplerFilter::Linear:
return VkFilter::VK_FILTER_LINEAR;
case SamplerFilter::CubicImg:
return VkFilter::VK_FILTER_CUBIC_IMG;
case SamplerFilter::CubicExt:
return VkFilter::VK_FILTER_CUBIC_EXT;
default:
return VkFilter::VK_FILTER_MAX_ENUM;
}
}
auto native_enum_value(PrimitiveTopology topology) noexcept -> VkPrimitiveTopology
{
switch (topology)
{
case PrimitiveTopology::LineStrip:
return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
case PrimitiveTopology::LineStripWithAdjency:
return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY;
case PrimitiveTopology::TriangleList:
return VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
case PrimitiveTopology::TriangleStrip:
return VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
case PrimitiveTopology::TriangleFan:
return VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN;
case PrimitiveTopology::PatchList:
return VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_PATCH_LIST;
default:
return VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_MAX_ENUM;
}
}
auto native_enum_value(SamplerAddressMode address_mode) noexcept -> VkSamplerAddressMode
{
switch (address_mode)
{
case SamplerAddressMode::Repeat:
return VkSamplerAddressMode::VK_SAMPLER_ADDRESS_MODE_REPEAT;
case SamplerAddressMode::RepeatMirrored:
return VkSamplerAddressMode::VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
case SamplerAddressMode::ClampToBorder:
return VkSamplerAddressMode::VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
case SamplerAddressMode::ClampToEdge:
return VkSamplerAddressMode::VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
case SamplerAddressMode::ClampToEdgeMirrored:
return VkSamplerAddressMode::VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE;
default:
return VkSamplerAddressMode::VK_SAMPLER_ADDRESS_MODE_MAX_ENUM;
}
}
auto native_enum_value(SamplerMipMapMode mipmap_mode) noexcept -> VkSamplerMipmapMode
{
switch (mipmap_mode)
{
case SamplerMipMapMode::Nearest:
return VkSamplerMipmapMode::VK_SAMPLER_MIPMAP_MODE_NEAREST;
case SamplerMipMapMode::Linear:
return VkSamplerMipmapMode::VK_SAMPLER_MIPMAP_MODE_LINEAR;
default:
return VkSamplerMipmapMode::VK_SAMPLER_MIPMAP_MODE_MAX_ENUM;
}
}
template<typename T>
bool has_flag(T flags, T flag) noexcept
{
using ValueType = std::underlying_type_t<T>;
ValueType const flags_value = static_cast<ValueType>(flags);
ValueType const flag_value = static_cast<ValueType>(flag);
return (flags_value & flag_value) == flag_value;
}
auto native_enum_flags(ImageUsageFlags flags) noexcept -> VkImageUsageFlags
{
VkImageUsageFlags usage_flags = 0;
if (has_flag(flags, ImageUsageFlags::Sampled))
{
usage_flags |= VK_IMAGE_USAGE_SAMPLED_BIT;
}
if (has_flag(flags, ImageUsageFlags::TransferDst))
{
usage_flags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
}
if (has_flag(flags, ImageUsageFlags::ColorAttachment))
{
usage_flags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
}
if (has_flag(flags, ImageUsageFlags::InputAttachment))
{
usage_flags |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
}
if (has_flag(flags, ImageUsageFlags::DepthStencilAttachment))
{
usage_flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
}
return usage_flags;
}
auto native_enum_flags(ShaderStageFlags flags) noexcept -> VkShaderStageFlags
{
VkShaderStageFlags usage_flags = 0;
if (has_flag(flags, ShaderStageFlags::VertexStage))
{
usage_flags |= VK_SHADER_STAGE_VERTEX_BIT;
}
if (has_flag(flags, ShaderStageFlags::FragmentStage))
{
usage_flags |= VK_SHADER_STAGE_FRAGMENT_BIT;
}
if (has_flag(flags, ShaderStageFlags::GeometryStage))
{
usage_flags |= VK_SHADER_STAGE_GEOMETRY_BIT;
}
if (has_flag(flags, ShaderStageFlags::TesselationControlStage))
{
usage_flags |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
}
if (has_flag(flags, ShaderStageFlags::TesselationEvaluationStage))
{
usage_flags |= VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
}
return usage_flags;
}
} // namespace ice::render::vk
#define VK_LOG(severity, message, ...) \
ICE_LOG(severity, ice::render::vk::log_tag, message, __VA_ARGS__)
| 35.087719
| 109
| 0.66975
|
iceshard-engine
|
a35e46d2d6858945d6329147a326157d8f1cbf03
| 14,894
|
hpp
|
C++
|
include/rovio/featureTracker.hpp
|
marco-tranzatto/rovio
|
3ec48b14e24f04295020fdacea90f8ac2f2399b0
|
[
"BSD-3-Clause"
] | 1
|
2021-02-08T02:32:25.000Z
|
2021-02-08T02:32:25.000Z
|
include/rovio/featureTracker.hpp
|
marco-tranzatto/rovio
|
3ec48b14e24f04295020fdacea90f8ac2f2399b0
|
[
"BSD-3-Clause"
] | null | null | null |
include/rovio/featureTracker.hpp
|
marco-tranzatto/rovio
|
3ec48b14e24f04295020fdacea90f8ac2f2399b0
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2014, Autonomous Systems Lab
* 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 Autonomous Systems Lab, ETH Zurich 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 FEATURE_TRACKER_HPP_
#define FEATURE_TRACKER_HPP_
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/Imu.h>
#include "rovio/MultiCamera.hpp"
#include "rovio/FeatureManager.hpp"
#include "rovio/MultilevelPatchAlignment.hpp"
namespace rovio{
/** \brief Ros Node, executing a MultilevelPatchFeature tracking on an incoming image stream.
*/
class FeatureTrackerNode{
public:
ros::NodeHandle nh_;
ros::Subscriber subImu_; /**<IMU subscriber.*/
ros::Subscriber subImg_; /**<Image subscriber.*/
static constexpr int nMax_ = 100; /**<Maximum number of MultilevelPatchFeature%s in a MultilevelPatchSet.*/
static constexpr int patchSize_ = 8; /**<Edge length of the patches in pixels. Value must be a multiple of 2!*/
static constexpr int nLevels_ = 4; /**<Total number of image pyramid levels.*/
static constexpr int nCam_ = 1; /**<Total number of image pyramid levels. Only 1 camera supported so far.*/
cv::Mat draw_image_, img_, draw_patches_;
unsigned int min_feature_count_; /**<New MultilevelPatchFeature%s are added to the existing MultilevelPatchSet,
if the number of valid MultilevelPatchFeature%s in the set is smaller
than min_feature_count_.*/
unsigned int max_feature_count_; /**<Maximal number of features, which are added at a time (not total). See rovio::addBestCandidates().*/
ImagePyramid<nLevels_> pyr_;
FeatureSetManager<nLevels_,patchSize_,nCam_,nMax_> fsm_;
MultilevelPatchAlignment<nLevels_,patchSize_> alignment_;
static constexpr int nDetectionBuckets_ = 100; /**<See rovio::addBestCandidates().*/
static constexpr double scoreDetectionExponent_ = 0.25; /**<See rovio::addBestCandidates().*/
static constexpr double penaltyDistance_ = 20; /**<See rovio::addBestCandidates().*/
static constexpr double zeroDistancePenalty_ = nDetectionBuckets_*100.0; /**<See rovio::addBestCandidates(). [nDetectionBuckets_*100] is a strong penalty, thus features with a distance of less penaltyDistance_ will not be added.*/
static constexpr int l1 = 1; /**<Minimal pyramid level, which should be used e.g. for corner detection and patch alignment. (l1<l2)*/
static constexpr int l2 = 3; /**<Maximal pyramid level, which should be used e.g. for corner detection and patch alignment. (l1<l2)*/
static constexpr int detectionThreshold = 10; /**<See rovio::detectFastCorners().*/
static constexpr bool drawNotFound_ = false; /**<Draw MultilevelPatchFeature%s which were not found again.*/
rovio::MultiCamera<nCam_> multiCamera_;
/** \brief Constructor
*/
FeatureTrackerNode(ros::NodeHandle& nh): nh_(nh), fsm_(&multiCamera_){
static_assert(l2>=l1, "l2 must be larger than l1");
subImu_ = nh_.subscribe("imuMeas", 1000, &FeatureTrackerNode::imuCallback,this);
subImg_ = nh_.subscribe("/cam0/image_raw", 1000, &FeatureTrackerNode::imgCallback,this);
min_feature_count_ = 50;
max_feature_count_ = 20; // Maximal number of feature which is added at a time (not total)
cv::namedWindow("Tracker");
multiCamera_.cameras_[0].load("/home/michael/calibrations/p22035_equidist.yaml");
fsm_.allocateMissing();
};
/** \brief Destructor.
*/
virtual ~FeatureTrackerNode(){}
/** \brief Empty, yet.
*/
void imuCallback(const sensor_msgs::Imu::ConstPtr& imu_msg){
}
/** \brief Image callback, handling the tracking of MultilevelPatchFeature%s.
*
* The sequence of the callback can be summarized as follows:
* 1. Extract image from message. Compute the image pyramid from the extracted image.
* 2. Predict the position of the valid MultilevelPatchFeature%s in the current image,
* using the previous 2 image locations of these MultilevelPatchFeature%s.
* 3. Execute 2D patch alignment at the predicted MultilevelPatchFeature locations.
* If successful the matching status of the MultilevelPatchFeature is set to FOUND and its image location is updated.
* 4. Prune: Check the MultilevelPatchFeature%s in the MultilevelPatchSet for their quality (MultilevelPatchFeature::isGoodFeature()).
* If a bad quality of a MultilevelPatchFeature is recognized, it is set to invalid.
* 5. Get new features and add them to the MultilevelPatchSet, if there are too little valid MultilevelPatchFeature%s
* in the MultilevelPatchSet. MultilevelPatchFeature%s which are stated invalid are replaced by new features.
*
* @param img_msg - Image message (ros)
*/
void imgCallback(const sensor_msgs::ImageConstPtr & img_msg){
// Get image from msg
cv_bridge::CvImagePtr cv_ptr;
try {
cv_ptr = cv_bridge::toCvCopy(img_msg, sensor_msgs::image_encodings::TYPE_8UC1);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
cv_ptr->image.copyTo(img_);
// Timing
static double last_time = 0.0;
double current_time = img_msg->header.stamp.toSec();
// Pyramid
pyr_.computeFromImage(img_,true);
// Drawing
cvtColor(img_, draw_image_, CV_GRAY2RGB);
const int numPatchesPlot = 10;
draw_patches_ = cv::Mat::zeros(numPatchesPlot*(patchSize_*pow(2,nLevels_-1)+4),3*(patchSize_*pow(2,nLevels_-1)+4),CV_8UC1);
// Prediction
cv::Point2f dc;
for(unsigned int i=0;i<nMax_;i++){
if(fsm_.isValid_[i]){
dc = 0.75*(fsm_.features_[i].mpCoordinates_->get_c() - fsm_.features_[i].log_previous_.get_c());
fsm_.features_[i].log_previous_ = *(fsm_.features_[i].mpCoordinates_);
fsm_.features_[i].mpCoordinates_->set_c(fsm_.features_[i].mpCoordinates_->get_c() + dc);
if(!fsm_.features_[i].mpMultilevelPatch_->isMultilevelPatchInFrame(pyr_,*(fsm_.features_[i].mpCoordinates_),nLevels_-1,false)){
fsm_.features_[i].mpCoordinates_->set_c(fsm_.features_[i].log_previous_.get_c());
}
fsm_.features_[i].mpStatistics_->increaseStatistics(current_time);
for(int j=0;j<nCam_;j++){
fsm_.features_[i].mpStatistics_->status_[j] = UNKNOWN;
}
}
}
// Track valid features
FeatureCoordinates alignedCoordinates;
const double t1 = (double) cv::getTickCount();
for(unsigned int i=0;i<nMax_;i++){
if(fsm_.isValid_[i]){
fsm_.features_[i].log_prediction_ = *(fsm_.features_[i].mpCoordinates_);
if(alignment_.align2DComposed(alignedCoordinates,pyr_,*fsm_.features_[i].mpMultilevelPatch_,*fsm_.features_[i].mpCoordinates_,l2,l1,l1)){
fsm_.features_[i].mpStatistics_->status_[0] = TRACKED;
fsm_.features_[i].mpCoordinates_->set_c(alignedCoordinates.get_c());
fsm_.features_[i].log_previous_ = *(fsm_.features_[i].mpCoordinates_);
fsm_.features_[i].mpCoordinates_->drawPoint(draw_image_,cv::Scalar(0,255,255));
fsm_.features_[i].mpCoordinates_->drawLine(draw_image_,fsm_.features_[i].log_prediction_,cv::Scalar(0,255,255));
fsm_.features_[i].mpCoordinates_->drawText(draw_image_,std::to_string(i),cv::Scalar(0,255,255));
if(i==18){
for(int j=0;j<nLevels_;j++){
// std::cout << fsm_.features_[i].mpMultilevelPatch_->isValidPatch_[j] << std::endl;
// std::cout << fsm_.features_[i].mpMultilevelPatch_->patches_[j].dx_[0] << std::endl;
}
// std::cout << alignment_.A_.transpose() << std::endl;
// std::cout << alignment_.b_.transpose() << std::endl;
}
} else {
fsm_.features_[i].mpStatistics_->status_[0] = FAILED_ALIGNEMENT;
fsm_.features_[i].mpCoordinates_->drawPoint(draw_image_,cv::Scalar(0,0,255));
fsm_.features_[i].mpCoordinates_->drawText(draw_image_,std::to_string(fsm_.features_[i].idx_),cv::Scalar(0,0,255));
}
}
}
const double t2 = (double) cv::getTickCount();
ROS_INFO_STREAM(" Matching " << fsm_.getValidCount() << " patches (" << (t2-t1)/cv::getTickFrequency()*1000 << " ms)");
MultilevelPatch<nLevels_,patchSize_> mp;
for(unsigned int i=0;i<numPatchesPlot;i++){
if(fsm_.isValid_[i+10]){
fsm_.features_[i+10].mpMultilevelPatch_->drawMultilevelPatch(draw_patches_,cv::Point2i(2,2+i*(patchSize_*pow(2,nLevels_-1)+4)),1,false);
if(mp.isMultilevelPatchInFrame(pyr_,fsm_.features_[i+10].log_prediction_,nLevels_-1,false)){
mp.extractMultilevelPatchFromImage(pyr_,fsm_.features_[i+10].log_prediction_,nLevels_-1,false);
mp.drawMultilevelPatch(draw_patches_,cv::Point2i(patchSize_*pow(2,nLevels_-1)+6,2+i*(patchSize_*pow(2,nLevels_-1)+4)),1,false);
}
if(fsm_.features_[i+10].mpStatistics_->status_[0] == TRACKED
&& mp.isMultilevelPatchInFrame(pyr_,*fsm_.features_[i+10].mpCoordinates_,nLevels_-1,false)){
mp.extractMultilevelPatchFromImage(pyr_,*fsm_.features_[i+10].mpCoordinates_,nLevels_-1,false);
mp.drawMultilevelPatch(draw_patches_,cv::Point2i(2*patchSize_*pow(2,nLevels_-1)+10,2+i*(patchSize_*pow(2,nLevels_-1)+4)),1,false);
cv::rectangle(draw_patches_,cv::Point2i(0,i*(patchSize_*pow(2,nLevels_-1)+4)),cv::Point2i(patchSize_*pow(2,nLevels_-1)+3,(i+1)*(patchSize_*pow(2,nLevels_-1)+4)-1),cv::Scalar(255),2,8,0);
cv::rectangle(draw_patches_,cv::Point2i(patchSize_*pow(2,nLevels_-1)+4,i*(patchSize_*pow(2,nLevels_-1)+4)),cv::Point2i(2*patchSize_*pow(2,nLevels_-1)+7,(i+1)*(patchSize_*pow(2,nLevels_-1)+4)-1),cv::Scalar(255),2,8,0);
} else {
cv::rectangle(draw_patches_,cv::Point2i(0,i*(patchSize_*pow(2,nLevels_-1)+4)),cv::Point2i(patchSize_*pow(2,nLevels_-1)+3,(i+1)*(patchSize_*pow(2,nLevels_-1)+4)-1),cv::Scalar(0),2,8,0);
cv::rectangle(draw_patches_,cv::Point2i(patchSize_*pow(2,nLevels_-1)+4,i*(patchSize_*pow(2,nLevels_-1)+4)),cv::Point2i(2*patchSize_*pow(2,nLevels_-1)+7,(i+1)*(patchSize_*pow(2,nLevels_-1)+4)-1),cv::Scalar(0),2,8,0);
}
cv::putText(draw_patches_,std::to_string(fsm_.features_[i+10].idx_),cv::Point2i(2,2+i*(patchSize_*pow(2,nLevels_-1)+4)+10),cv::FONT_HERSHEY_SIMPLEX, 0.4, cv::Scalar(255));
}
}
// Prune
// Check the MultilevelPatchFeature%s in the MultilevelPatchSet for their quality (isGoodFeature(...)).
// If a bad quality of a MultilevelPatchFeature is recognized, it is set to invalid. New MultilevelPatchFeature%s
// replace the array places of invalid MultilevelPatchFeature%s in the MultilevelPatchSet.
int prune_count = 0;
for(unsigned int i=0;i<nMax_;i++){
if(fsm_.isValid_[i]){
if(fsm_.features_[i].mpStatistics_->status_[0] == FAILED_ALIGNEMENT){
fsm_.isValid_[i] = false;
prune_count++;
}
}
}
ROS_INFO_STREAM(" Pruned " << prune_count << " features");
// Extract feature patches
// Extract new MultilevelPatchFeature%s at the current tracked feature positions.
// Extracted multilevel patches are aligned with the image axes.
for(unsigned int i=0;i<nMax_;i++){
if(fsm_.isValid_[i]){
if(fsm_.features_[i].mpStatistics_->status_[0] == TRACKED
&& fsm_.features_[i].mpMultilevelPatch_->isMultilevelPatchInFrame(pyr_,*fsm_.features_[i].mpCoordinates_,nLevels_-1,true)){
fsm_.features_[i].mpMultilevelPatch_->extractMultilevelPatchFromImage(pyr_,*fsm_.features_[i].mpCoordinates_,nLevels_-1,true);
}
}
}
// Get new features, if there are too little valid MultilevelPatchFeature%s in the MultilevelPatchSet.
if(fsm_.getValidCount() < min_feature_count_){
std::vector<FeatureCoordinates> candidates;
ROS_INFO_STREAM(" Adding keypoints");
const double t1 = (double) cv::getTickCount();
for(int l=l1;l<=l2;l++){
pyr_.detectFastCorners(candidates,l,detectionThreshold);
}
const double t2 = (double) cv::getTickCount();
ROS_INFO_STREAM(" == Detected " << candidates.size() << " on levels " << l1 << "-" << l2 << " (" << (t2-t1)/cv::getTickFrequency()*1000 << " ms)");
// pruneCandidates(fsm_,candidates,0);
const double t3 = (double) cv::getTickCount();
// ROS_INFO_STREAM(" == Selected " << candidates.size() << " candidates (" << (t3-t2)/cv::getTickFrequency()*1000 << " ms)");
std::unordered_set<unsigned int> newSet = fsm_.addBestCandidates( candidates,pyr_,0,current_time,
l1,l2,max_feature_count_,nDetectionBuckets_, scoreDetectionExponent_,
penaltyDistance_, zeroDistancePenalty_,true,0.0);
const double t4 = (double) cv::getTickCount();
ROS_INFO_STREAM(" == Got " << fsm_.getValidCount() << " after adding " << newSet.size() << " features (" << (t4-t3)/cv::getTickFrequency()*1000 << " ms)");
for(auto it = newSet.begin();it != newSet.end();++it){
fsm_.features_[*it].log_previous_ = *(fsm_.features_[*it].mpCoordinates_);
for(int j=0;j<nCam_;j++){
fsm_.features_[*it].mpStatistics_->status_[j] = TRACKED;
}
}
}
cv::imshow("Tracker", draw_image_);
cv::imshow("Patches", draw_patches_);
cv::waitKey(30);
last_time = current_time;
}
};
}
#endif /* FEATURE_TRACKER_HPP_ */
| 56.203774
| 233
| 0.690748
|
marco-tranzatto
|
a35fe2158aa15578d61681e208859bae4aa6bd14
| 3,202
|
cpp
|
C++
|
tools/pb2tarscpp/CppPlugin.cpp
|
cSingleboy/TarsCpp
|
17b228b660d540baa1a93215fc007c5131a2fc68
|
[
"BSD-3-Clause"
] | 386
|
2018-09-11T06:17:10.000Z
|
2022-03-31T05:59:41.000Z
|
tools/pb2tarscpp/CppPlugin.cpp
|
cSingleboy/TarsCpp
|
17b228b660d540baa1a93215fc007c5131a2fc68
|
[
"BSD-3-Clause"
] | 128
|
2018-09-12T03:43:33.000Z
|
2022-03-24T10:03:54.000Z
|
tools/pb2tarscpp/CppPlugin.cpp
|
cSingleboy/TarsCpp
|
17b228b660d540baa1a93215fc007c5131a2fc68
|
[
"BSD-3-Clause"
] | 259
|
2018-09-19T08:50:37.000Z
|
2022-03-11T07:17:56.000Z
|
// Generates C++ tars service interface out of Protobuf IDL.
//
// This is a Proto2 compiler plugin. See net/proto2/compiler/proto/plugin.proto
// and net/proto2/compiler/public/plugin.h for more information on plugins.
#include <iostream>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/descriptor.h>
#include "CppPlugin.h"
#include "CppGenCallback.h"
#include "CppGenProxy.h"
#include "CppGenServant.h"
bool CppTarsGenerator::Generate(const google::protobuf::FileDescriptor *file,
const std::string ¶meter,
google::protobuf::compiler::GeneratorContext *context,
std::string *error) const {
if (!_CheckFile(file, error)) {
return false;
}
std::string content = _GenHeader(ProtoFileBaseName(file->name()));
// namespace
content += _GenNamespaceBegin(file->package());
const int indent = 1;
content += LineFeed(indent);
for (int i = 0; i < file->service_count(); ++i) {
content += GenPrxCallback(file->service(i), indent);
content += GenPrx(file->service(i), indent);
content += GenServant(file->service(i), indent);
}
content += _GenNamespaceEnd(file->package());
// gen response to parent
const std::string& outputFile = ProtoFileBaseName(file->name()) + ".tars.h";
std::string output = _GenResponse(outputFile, content);
std::cout << output;
return true;
}
std::string
CppTarsGenerator::_GenResponse(const std::string& filename,
const std::string& content) {
google::protobuf::compiler::CodeGeneratorResponse response;
auto f = response.add_file();
f->set_name(filename);
f->set_content(content);
// output to parent
std::string outbytes;
response.SerializeToString(&outbytes);
return outbytes;
}
bool CppTarsGenerator::_CheckFile(const google::protobuf::FileDescriptor* file,
std::string* error) const {
if (file->package().empty()) {
error->append("package name is missed.");
return false;
}
return true;
}
std::string CppTarsGenerator::_GenHeader(const std::string& name) {
std::string content;
content.reserve(8 * 1024);
content += kDeclaration;
content += "#pragma once\n\n";
content += "#include <map>\n";
content += "#include <string>\n";
content += "#include <vector>\n";
content += "#include \"servant/ServantProxy.h\"\n";
content += "#include \"servant/Servant.h\"\n";
// include pb file
content += "#include \"" + name + ".pb.h\"\n";
return content;
}
std::string CppTarsGenerator::_GenNamespaceBegin(const std::string& ns) {
std::string content;
content += "\n\nnamespace ";
content += ns + "\n{";
return content;
}
std::string CppTarsGenerator::_GenNamespaceEnd(const std::string& ns) {
return std::string("\n} // end namespace " + ns + "\n\n");
}
int main(int argc, char *argv[]) {
CppTarsGenerator generator;
return google::protobuf::compiler::PluginMain(argc, argv, &generator);
}
| 29.376147
| 86
| 0.630231
|
cSingleboy
|
a360822d4f32cd2146a959f0d9614f8587e7dea0
| 6,214
|
cpp
|
C++
|
3rdparty/poco/Data/SQLite/src/Extractor.cpp
|
wohaaitinciu/zpublic
|
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
|
[
"Unlicense"
] | 50
|
2015-01-07T01:54:54.000Z
|
2021-01-15T00:41:48.000Z
|
3rdparty/poco/Data/SQLite/src/Extractor.cpp
|
lib1256/zpublic
|
64c2be9ef1abab878288680bb58122dcc25df81d
|
[
"Unlicense"
] | 1
|
2015-05-26T07:40:19.000Z
|
2015-05-26T07:40:19.000Z
|
3rdparty/poco/Data/SQLite/src/Extractor.cpp
|
lib1256/zpublic
|
64c2be9ef1abab878288680bb58122dcc25df81d
|
[
"Unlicense"
] | 39
|
2015-01-07T02:03:15.000Z
|
2021-01-15T00:41:50.000Z
|
//
// Extractor.cpp
//
// $Id: //poco/1.4/Data/SQLite/src/Extractor.cpp#1 $
//
// Library: Data/SQLite
// Package: SQLite
// Module: Extractor
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Data/SQLite/Extractor.h"
#include "Poco/Data/SQLite/Utility.h"
#include "Poco/Data/BLOB.h"
#include "Poco/Data/DataException.h"
#include "Poco/Exception.h"
#if defined(POCO_UNBUNDLED)
#include <sqlite3.h>
#else
#include "sqlite3.h"
#endif
#include <cstdlib>
namespace Poco {
namespace Data {
namespace SQLite {
Extractor::Extractor(sqlite3_stmt* pStmt):
_pStmt(pStmt)
{
}
Extractor::~Extractor()
{
}
bool Extractor::extract(std::size_t pos, Poco::Int32& val)
{
if (isNull(pos))
return false;
val = sqlite3_column_int(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, Poco::Int64& val)
{
if (isNull(pos))
return false;
val = sqlite3_column_int64(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, double& val)
{
if (isNull(pos))
return false;
val = sqlite3_column_double(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, std::string& val)
{
if (isNull(pos))
return false;
const char *pBuf = reinterpret_cast<const char*>(sqlite3_column_text(_pStmt, (int) pos));
if (!pBuf)
val.clear();
else
val = std::string(pBuf);
return true;
}
bool Extractor::extract(std::size_t pos, Poco::Data::BLOB& val)
{
if (isNull(pos))
return false;
int size = sqlite3_column_bytes(_pStmt, (int) pos);
const char* pTmp = reinterpret_cast<const char*>(sqlite3_column_blob(_pStmt, (int) pos));
val = Poco::Data::BLOB(pTmp, size);
return true;
}
bool Extractor::extract(std::size_t pos, Poco::Int8& val)
{
if (isNull(pos))
return false;
val = sqlite3_column_int(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, Poco::UInt8& val)
{
if (isNull(pos))
return false;
val = sqlite3_column_int(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, Poco::Int16& val)
{
if (isNull(pos))
return false;
val = sqlite3_column_int(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, Poco::UInt16& val)
{
if (isNull(pos))
return false;
val = sqlite3_column_int(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, Poco::UInt32& val)
{
if (isNull(pos))
return false;
val = sqlite3_column_int(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, Poco::UInt64& val)
{
if (isNull(pos))
return false;
val = sqlite3_column_int64(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, bool& val)
{
if (isNull(pos))
return false;
val = (0 != sqlite3_column_int(_pStmt, (int) pos));
return true;
}
bool Extractor::extract(std::size_t pos, float& val)
{
if (isNull(pos))
return false;
val = static_cast<float>(sqlite3_column_double(_pStmt, (int) pos));
return true;
}
bool Extractor::extract(std::size_t pos, char& val)
{
if (isNull(pos)) return false;
val = sqlite3_column_int(_pStmt, (int) pos);
return true;
}
bool Extractor::extract(std::size_t pos, Poco::Any& val)
{
if (isNull(pos)) return false;
bool ret = false;
switch (Utility::getColumnType(_pStmt, pos))
{
case MetaColumn::FDT_BOOL:
{
bool i = false;
ret = extract(pos, i);
val = i;
break;
}
case MetaColumn::FDT_INT8:
{
Poco::Int8 i = 0;
ret = extract(pos, i);
val = i;
break;
}
case MetaColumn::FDT_UINT8:
{
Poco::UInt8 i = 0;
ret = extract(pos, i);
val = i;
break;
}
case MetaColumn::FDT_INT16:
{
Poco::Int16 i = 0;
ret = extract(pos, i);
val = i;
break;
}
case MetaColumn::FDT_UINT16:
{
Poco::UInt16 i = 0;
ret = extract(pos, i);
val = i;
break;
}
case MetaColumn::FDT_INT32:
{
Poco::Int32 i = 0;
ret = extract(pos, i);
val = i;
break;
}
case MetaColumn::FDT_UINT32:
{
Poco::UInt32 i = 0;
ret = extract(pos, i);
val = i;
break;
}
case MetaColumn::FDT_INT64:
{
Poco::Int64 i = 0;
ret = extract(pos, i);
val = i;
break;
}
case MetaColumn::FDT_UINT64:
{
Poco::UInt64 i = 0;
ret = extract(pos, i);
val = i;
break;
}
case MetaColumn::FDT_STRING:
{
std::string s;
ret = extract(pos, s);
val = s;
break;
}
case MetaColumn::FDT_DOUBLE:
{
double d(0.0);
ret = extract(pos, d);
val = d;
break;
}
case MetaColumn::FDT_FLOAT:
{
float f(0.0);
ret = extract(pos, f);
val = f;
break;
}
case MetaColumn::FDT_BLOB:
{
BLOB b;
ret = extract(pos, b);
val = b;
break;
}
default:
throw Poco::Data::UnknownTypeException("Unknown type during extraction");
}
return ret;
}
bool Extractor::isNull(std::size_t pos)
{
return sqlite3_column_type(_pStmt, (int) pos) == SQLITE_NULL;
}
} } } // namespace Poco::Data::SQLite
| 19.980707
| 90
| 0.68233
|
wohaaitinciu
|
a3637d25bc9ac46b8d41d5d327ac8e9c2c200d4a
| 22,243
|
cpp
|
C++
|
SSCode/SSImportHIP.cpp
|
ultrapre/SSCore
|
c7d6ff221750bab051df32c7efc5798e93924100
|
[
"IJG",
"FSFAP"
] | 2
|
2020-11-23T09:08:23.000Z
|
2021-01-09T13:15:52.000Z
|
SSCode/SSImportHIP.cpp
|
ultrapre/SSCore
|
c7d6ff221750bab051df32c7efc5798e93924100
|
[
"IJG",
"FSFAP"
] | null | null | null |
SSCode/SSImportHIP.cpp
|
ultrapre/SSCore
|
c7d6ff221750bab051df32c7efc5798e93924100
|
[
"IJG",
"FSFAP"
] | null | null | null |
// SSHipparcos.cpp
// SSCore
//
// Created by Tim DeBenedictis on 3/23/20.
// Copyright © 2020 Southern Stars. All rights reserved.
#include <algorithm>
#include <iostream>
#include <fstream>
#include "SSCoordinates.hpp"
#include "SSImportHIP.hpp"
// Cleans up some oddball conventions in the Hipparcos star name identification tables
// for Bayer, Flamsteed, and variable star names so SSIdentifier understands them.
// Returns cleaned-up name string, does not modify input string.
string cleanHIPNameString ( string str )
{
// Change abbreviation for "alpha" from "alf" to "alp"
if ( str.find ( "alf" ) == 0 )
str.replace ( 0, 3, "alp" );
// Change abbreviation for "xi" from "ksi"
if ( str.find ( "ksi" ) == 0 )
str.replace ( 0, 3, "xi." );
// Remove "." after "mu", "nu", "xi"
size_t idx = str.find ( "." );
if ( idx != string::npos )
str.erase ( idx, 1 );
// Remove multiple star designations "_A", "_B", "_C" etc. after constellation
size_t len = str.length();
if ( str[ len - 2 ] == '_' )
str.erase ( len - 2, 2 );
// Convert remaining underscores to whitespace.
idx = str.find ( "_" );
if ( idx != string::npos )
str.replace ( idx, 1, " " );
return str;
}
// Imports Hipparcos star name identification table (IDENT6.DOC)
// into map of HIP identifiers to name strings (nameMap).
// Returns number of names imported (should be 96 if successful).
int SSImportHIPNames ( const char *filename, SSIdentifierNameMap &nameMap )
{
// Open file; return on failure.
ifstream file ( filename );
if ( ! file )
return 0;
// Read file line-by-line until we reach end-of-file
string line = "";
int nameCount = 0;
while ( getline ( file, line ) )
{
string strHIP = trim ( line.substr ( 17, 6 ) );
string strName = trim ( line.substr ( 0, 16 ) );
int hip = strtoint ( strHIP );
if ( ! hip )
continue;
// cout << hip << "," << strName << endl;
nameMap.insert ( { SSIdentifier ( kCatHIP, hip ), strName } );
nameCount++;
}
// Return imported name count; file is closed automatically.
return nameCount;
}
// Updates star coordinates and motion for space velocity from the input julian year (jyear) to 2000.0
// and for precession from an input equinox to J2000, using a rotation matrix (pMatrix) as returned by
// SSCoordinates::getPrecessionMatrxx() - but use transpose of matrix returned by that function!
// Pass null pointer for pMatrix if coords and motion alread refer to equinox J2000.
// This function uses a rigorous transformation which is accurate in all parts of the sky.
void SSUpdateStarCoordsAndMotion ( double jyear, SSMatrix *pMatrix, SSSpherical &coords, SSSpherical &motion )
{
double rad = coords.rad;
double radvel = motion.rad;
coords.rad = 1.0;
motion.rad = 0.0;
SSVector position = coords.toVectorPosition();
SSVector velocity = coords.toVectorVelocity ( motion );
if ( jyear != 2000.0 )
{
position += velocity * ( 2000.0 - jyear );
position = position.normalize();
}
if ( pMatrix != nullptr )
{
position = *pMatrix * position;
velocity = *pMatrix * velocity;
}
coords = position.toSpherical();
motion = position.toSphericalVelocity ( velocity );
coords.rad = rad;
motion.rad = radvel;
}
// Imports the Hipparcos Input Catalog, version 2.
// Still useful for SAO and variable star identifiers
// and radial velocities, all omitted from the final Hipparcos catalog.
// Stores results in vector of SSObjects (stars).
// Returns number of objects imported (118209 if successful).
int SSImportHIC ( const char *filename, SSObjectVec &stars )
{
// Open file; return on failure.
ifstream file ( filename );
if ( ! file )
return 0;
// Read file line-by-line until we reach end-of-file
string line = "";
int numStars = 0;
while ( getline ( file, line ) )
{
string strHIP = trim ( line.substr ( 0, 6 ) );
string strRA = trim ( line.substr ( 13, 12 ) );
string strDec = trim ( line.substr ( 26, 12 ) );
string strPMRA = trim ( line.substr ( 155, 6 ) );
string strPMDec = trim ( line.substr ( 162, 6 ) );
string strMag = trim ( line.substr ( 190, 6 ) );
string strBmV = trim ( line.substr ( 202, 6 ) );
string strSpec = trim ( line.substr ( 216, 11 ) );
string strPlx = trim ( line.substr ( 230, 6 ) );
string strRV = trim ( line.substr ( 241, 6 ) );
string strVar = trim ( line.substr ( 251, 9 ) );
string strVarType = trim ( line.substr ( 261, 3 ) );
string strVarPer = trim ( line.substr ( 265, 6 ) );
string strVarMax = trim ( line.substr ( 272, 4 ) );
string strVarMin = trim ( line.substr ( 277, 4 ) );
string strHD = trim ( line.substr ( 359, 6 ) );
string strBD = trim ( line.substr ( 320, 10 ) );
string strCD = trim ( line.substr ( 334, 10 ) );
string strCP = trim ( line.substr ( 348, 10 ) );
string strSAO = trim ( line.substr ( 385, 6 ) );
// Get J2000 Right Ascension and Declination
SSSpherical position ( INFINITY, INFINITY, INFINITY );
SSSpherical velocity ( INFINITY, INFINITY, INFINITY );
position.lon = SSHourMinSec ( strRA );
position.lat = SSDegMinSec ( strDec );
// If we have a parallax, use it to compute distance in light years
float plx = strPlx.empty() ? 0.0 : strtofloat ( strPlx );
if ( plx > 0.0 )
position.rad = 1000.0 * SSCoordinates::kLYPerParsec / plx;
// Convert proper motion to radians per year
if ( ! strPMRA.empty() )
velocity.lon = SSAngle::fromArcsec ( strtofloat ( strPMRA ) ) / cos ( position.lat );
if ( ! strPMDec.empty() )
velocity.lat = SSAngle::fromArcsec ( strtofloat ( strPMDec ) );
// Convert radial velocity from km/sec to fraction of light speed
if ( ! strRV.empty() )
velocity.rad = strtofloat ( strRV ) / SSCoordinates::kLightKmPerSec;
// Get Johnson V magnitude; get B magnitude from B-V color index.
float vmag = strMag.empty() ? INFINITY : strtofloat ( strMag );
float bmag = strBmV.empty() ? INFINITY : strtofloat ( strBmV ) + vmag;
vector<SSIdentifier> idents ( 0 );
vector<string> names ( 0 );
if ( ! strHD.empty() )
SSAddIdentifier ( SSIdentifier ( kCatHD, strtoint ( strHD ) ), idents );
if ( ! strSAO.empty() )
SSAddIdentifier ( SSIdentifier ( kCatSAO, strtoint ( strSAO ) ), idents );
if ( ! strHIP.empty() )
SSAddIdentifier ( SSIdentifier ( kCatHIP, strtoint ( strHIP ) ), idents );
// Sert identifier vector. Get name string(s) corresponding to identifier(s).
// Construct star and insert into star vector.
sort ( idents.begin(), idents.end(), compareSSIdentifiers );
SSObjectType type = kTypeStar;
SSObjectPtr pObj = SSNewObject ( type );
SSStarPtr pStar = SSGetStarPtr ( pObj );
if ( pStar != nullptr )
{
pStar->setNames ( names );
pStar->setIdentifiers ( idents );
pStar->setFundamentalMotion ( position, velocity );
pStar->setVMagnitude ( vmag );
pStar->setBMagnitude ( bmag );
pStar->setSpectralType ( strSpec );
// cout << pStar->toCSV() << endl;
stars.push_back ( pObj );
numStars++;
}
}
// Return imported star count; file is closed automatically.
return numStars;
}
// Imports Hipparcos New Reduction 2007 star catalog (HIP2).
// Stores results in vector of SSObjects (stars).
// Returns number of objects imported (117955 if successful).
int SSImportHIP2 ( const char *filename, SSObjectVec &stars )
{
// Open file; return on failure.
ifstream file ( filename );
if ( ! file )
return 0;
// Read file line-by-line until we reach end-of-file
string line = "";
int numStars = 0;
while ( getline ( file, line ) )
{
string strHIP = trim ( line.substr ( 0, 6 ) );
string strRA = trim ( line.substr ( 15, 13 ) );
string strDec = trim ( line.substr ( 29, 13 ) );
string strPMRA = trim ( line.substr ( 51, 8 ) );
string strPMDec = trim ( line.substr ( 60, 8 ) );
string strMag = trim ( line.substr ( 129, 7 ) );
string strBmV = trim ( line.substr ( 152, 6 ) );
string strPlx = trim ( line.substr ( 43, 7 ) );
if ( strRA.empty() || strDec.empty() )
continue;
SSSpherical position ( INFINITY, INFINITY, INFINITY );
SSSpherical velocity ( INFINITY, INFINITY, INFINITY );
// Get right ascension and declination in radians
position.lon = strtofloat ( strRA );
position.lat = strtofloat ( strDec );
// Get proper motion in RA and Dec and convert to radians per year
if ( ! strPMRA.empty() )
velocity.lon = SSAngle::fromArcsec ( strtofloat ( strPMRA ) / 1000.0 ) / cos ( position.lat );
if ( ! strPMDec.empty() )
velocity.lat = SSAngle::fromArcsec ( strtofloat ( strPMDec ) / 1000.0 );
// If proper motion is valid, use it to bring position from J1991.25 to J2000
if ( ! isinf ( velocity.lon ) && ! isinf ( velocity.lat ) )
SSUpdateStarCoordsAndMotion ( 1991.25, nullptr, position, velocity );
// Get Hipparcos magnitude
float vmag = INFINITY;
if ( ! strMag.empty() )
vmag = strtofloat ( strMag );
// Get B-V color index and use it to convert Hipparcos magnitude to Johnson B and V
float bmv = INFINITY, bmag = INFINITY;
if ( ! strBmV.empty() )
{
bmv = strtofloat ( strBmV );
vmag += -0.2964 * bmv + 0.1110 * bmv * bmv;
bmag = vmag + bmv;
}
// If we have a parallax greater than 1 milliarcec, use it to compute distance in light years
if ( ! strPlx.empty() )
{
float plx = strtofloat ( strPlx );
if ( plx > 1.0 )
position.rad = 1000.0 * SSCoordinates::kLYPerParsec / plx;
}
// Add single Hipparcos identifier and empty name string.
vector<SSIdentifier> idents ( 0 );
vector<string> names ( 0 );
int hip = strtoint ( strHIP );
SSAddIdentifier ( SSIdentifier ( kCatHIP, hip ), idents );
// Sert identifier vector. Get name string(s) corresponding to identifier(s).
// Construct star and insert into star vector.
sort ( idents.begin(), idents.end(), compareSSIdentifiers );
SSObjectType type = kTypeStar;
SSObjectPtr pObj = SSNewObject ( type );
SSStarPtr pStar = SSGetStarPtr ( pObj );
if ( pStar != nullptr )
{
pStar->setNames ( names );
pStar->setIdentifiers ( idents );
pStar->setFundamentalMotion ( position, velocity );
pStar->setVMagnitude ( vmag );
pStar->setBMagnitude ( bmag );
// cout << pStar->toCSV() << endl;
stars.push_back ( pObj );
numStars++;
}
}
// Return imported star count; file is closed automatically.
return numStars;
}
// Imports the main Hipparcos star catalog.
// Adds HR, Bayer/Flamsteed, and GCVS identifiers from auxiliary identification tables (mapHIPtoHR, mapHIPtoBF, mapHIPtoVar).
// Adds SAO identifiers and radial velocity from Hipparcos Input Catalog (hicStars).
// Uses position and proper motion with values from Hippacos New Reduction (hip2Stars) if possible.
// Adds star name strings from a mapping of identifiers to names (nameMap).
// Stores results in vector of SSObjects (stars).
// Returns number of objects imported (118218 if successful).
int SSImportHIP ( const char *filename, SSIdentifierMap &hrMap, SSIdentifierMap &bayMap, SSIdentifierMap &gcvsMap, SSIdentifierNameMap &nameMap, SSObjectVec &hicStars, SSObjectVec &hip2Stars, SSObjectVec &stars )
{
// Open file; return on failure.
ifstream file ( filename );
if ( ! file )
return 0;
// Make mappings of HIP identifiers to object indices
// in HIC and HIP2 star vectors.
SSObjectMap hicMap = SSMakeObjectMap ( hicStars, kCatHIP );
SSObjectMap hip2Map = SSMakeObjectMap ( hip2Stars, kCatHIP );
// Read file line-by-line until we reach end-of-file
string line = "";
int numStars = 0;
while ( getline ( file, line ) )
{
string strHIP = trim ( line.substr ( 8, 6 ) );
string strRA = trim ( line.substr ( 51, 12 ) );
string strDec = trim ( line.substr ( 64, 12 ) );
string strPMRA = trim ( line.substr ( 87, 8 ) );
string strPMDec = trim ( line.substr ( 96, 8 ) );
string strMag = trim ( line.substr ( 41, 5 ) );
string strBmV = trim ( line.substr ( 245, 6 ) );
string strPlx = trim ( line.substr ( 79, 7 ) );
string strSpec = trim ( line.substr ( 435, 12 ) );
string strHD = trim ( line.substr ( 390, 6 ) );
string strBD = trim ( line.substr ( 398, 9 ) );
string strCD = trim ( line.substr ( 409, 9 ) );
string strCP = trim ( line.substr ( 420, 9 ) );
SSSpherical position ( INFINITY, INFINITY, INFINITY );
SSSpherical velocity ( INFINITY, INFINITY, INFINITY );
// Get right ascension and convert to radians
if ( ! strRA.empty() )
position.lon = SSAngle::fromDegrees ( strtofloat ( strRA ) );
else
position.lon = SSHourMinSec ( trim ( line.substr ( 17, 11 ) ) );
// Get declination and convert to radians
if ( ! strDec.empty() )
position.lat = SSAngle::fromDegrees ( strtofloat ( strDec ) );
else
position.lat = SSDegMinSec ( trim ( line.substr ( 29, 11 ) ) );
// Get proper motion in RA and convert to radians per year
if ( ! strPMRA.empty() )
velocity.lon = SSAngle::fromArcsec ( strtofloat ( strPMRA ) / 1000.0 ) / cos ( position.lat );
// Get proper motion in Dec and convert to radians per year
if ( ! strPMDec.empty() )
velocity.lat = SSAngle::fromArcsec ( strtofloat ( strPMDec ) / 1000.0 );
// If proper motion is valid, use it to update position and proper motion from J1991.25 to J2000.
if ( ! isinf ( velocity.lon ) && ! isinf ( velocity.lat ) )
SSUpdateStarCoordsAndMotion ( 1991.25, nullptr, position, velocity );
// Get Johnson V magnitude, and (if present) get B-V color index then compute Johnson B magnitude.
float vmag = strMag.empty() ? INFINITY : strtofloat ( strMag );
float bmag = strBmV.empty() ? INFINITY : strtofloat ( strBmV ) + vmag;
// If we have a parallax > 1 milliarcsec, use it to compute distance in light years.
float plx = strPlx.empty() ? 0.0 : strtofloat ( strPlx );
if ( plx > 0.0 )
position.rad = 1000.0 * SSCoordinates::kLYPerParsec / plx;
// Set up name and identifier vectors.
vector<SSIdentifier> idents ( 0 );
vector<string> names ( 0 );
// Parse HIP catalog number and add Hipparcos identifier.
int hip = strtoint ( strHIP );
SSIdentifier hipID = SSIdentifier ( kCatHIP, hip );
SSAddIdentifier ( hipID, idents );
// Add Henry Draper and Durchmusterung identifiers.
if ( ! strHD.empty() )
SSAddIdentifier ( SSIdentifier ( kCatHD, strtoint ( strHD ) ), idents );
if ( ! strBD.empty() )
SSAddIdentifier ( SSIdentifier::fromString ( "BD " + strBD ), idents );
if ( ! strCD.empty() )
SSAddIdentifier ( SSIdentifier::fromString ( "CD " + strCD ), idents );
if ( ! strCP.empty() )
SSAddIdentifier ( SSIdentifier::fromString ( "CP " + strCP ), idents );
// Add HR identification (if present) from Bright Star identification table.
// Add Bayer and Flamsteed identifier(s) (if present) from Bayer identification table.
// Add GCVS identifier(s) from the variable star ident table.
SSAddIdentifiers ( hipID, hrMap, idents );
SSAddIdentifiers ( hipID, bayMap, idents );
SSAddIdentifiers ( hipID, gcvsMap, idents );
// Add names(s) from identifier-to-name map.
names = SSIdentifiersToNames ( idents, nameMap );
// If we found a matching Hipparcos New Reduction star,
// replace position and velocity with newer values.
SSStarPtr pStar = SSGetStarPtr ( SSIdentifierToObject ( hipID, hip2Map, hip2Stars ) );
if ( pStar != nullptr )
{
position = pStar->getFundamentalCoords();
velocity = pStar->getFundamentalMotion();
}
// If we found a matching Hipparcos Input Catalog star,
// splice in SAO identifier and radial velocity.
pStar = SSGetStarPtr ( SSIdentifierToObject ( hipID, hicMap, hicStars ) );
if ( pStar != nullptr )
{
SSIdentifier saoID = pStar->getIdentifier ( kCatSAO );
if ( saoID )
SSAddIdentifier ( saoID, idents );
velocity.rad = pStar->getRadVel();
}
// Sert identifier vector. Get name string(s) corresponding to identifier(s).
// Construct star and insert into star vector.
sort ( idents.begin(), idents.end(), compareSSIdentifiers );
SSObjectType type = kTypeStar;
SSObjectPtr pObj = SSNewObject ( type );
pStar = SSGetStarPtr ( pObj );
if ( pStar != nullptr )
{
pStar->setNames ( names );
pStar->setIdentifiers ( idents );
pStar->setFundamentalMotion ( position, velocity );
pStar->setVMagnitude ( vmag );
pStar->setBMagnitude ( bmag );
pStar->setSpectralType ( strSpec );
// cout << pStar->toCSV() << endl;
stars.push_back ( pObj );
numStars++;
}
}
// Return imported star count; file is closed automatically.
return numStars;
}
// Imports Hipparcos HR (Bright Star) identifier table (IDENT3.DOC).
// Returns map of HR identifiers indexed by HIP number,
// which should contain 9077 entries if successful.
int SSImportHIPHRIdentifiers ( const char *filename, SSIdentifierMap &map )
{
// Open file; return on failure.
ifstream file ( filename );
if ( ! file )
return 0;
// Read file line-by-line until we reach end-of-file
string line ( "" );
int count = 0;
while ( getline ( file, line ) )
{
string strHR = trim ( line.substr ( 0, 6 ) );
string strHIP = trim ( line.substr ( 7, 6 ) );
int hip = strtoint ( strHIP );
int hr = strtoint ( strHR );
if ( hip == 0 || hr == 0 )
continue;
// cout << hip << "," << hr << "," << endl;
map.insert ( { SSIdentifier ( kCatHIP, hip ), SSIdentifier ( kCatHR, hr ) } );
count++;
}
// Return count of identifiers added. File closed automatically.
return count;
}
// Imports Hipparcos Bayer/Flamsteed identifier table (IDENT4.DOC).
// Returns map of Bayer/Flamsteed identifiers indexed by HIP number,
// which should contain 4440 entries if successful.
int SSImportHIPBayerIdentifiers ( const char *filename, SSIdentifierMap &map )
{
// Open file; return on failure.
ifstream file ( filename );
if ( ! file )
return 0;
// Read file line-by-line until we reach end-of-file
string line = "";
int count = 0;
while ( getline ( file, line ) )
{
string strBF = trim ( line.substr ( 0, 11 ) );
string strHIP = trim ( line.substr ( 12, 6 ) );
SSIdentifier id = SSIdentifier::fromString ( cleanHIPNameString ( strBF ) );
int hip = strtoint ( strHIP );
if ( hip == 0 || id == 0 )
continue;
// cout << hip << "," << id.toString() << endl;
map.insert ( { SSIdentifier ( kCatHIP, hip ), id } );
count++;
}
// Return count of identifiers added. File closed automatically.
return count;
}
// Imports Hipparcos variable star identifier table (IDENT5.DOC).
// Returns map of GCVS identifiers indexed by HIP number,
// which should contain 6390 entries if successful.
int SSImportHIPGCVSIdentifiers ( const char *filename, SSIdentifierMap &map )
{
// Open file; return on failure.
ifstream file ( filename );
if ( ! file )
return 0;
// Read file line-by-line until we reach end-of-file
string line = "";
int count = 0;
while ( getline ( file, line ) )
{
string strVar = trim ( line.substr ( 0, 11 ) );
string strHIP = trim ( line.substr ( 12, 6 ) );
int hip = strtoint ( strHIP );
SSIdentifier id = SSIdentifier::fromString ( cleanHIPNameString ( strVar ) );
// cout << hip << "," << id.toString() << endl;
if ( id == 0 || hip == 0 )
{
cout << "Warning: con't convert " << strVar << " for HIP " << hip << endl;
continue;
}
// cout << hip << "," << id.toString() << endl;
map.insert ( { SSIdentifier ( kCatHIP, hip ), id } );
count++;
}
// Return count of identifiers added. File closed automatically.
return count;
}
| 34.592535
| 212
| 0.577575
|
ultrapre
|
a3665bd09ffc7ad389af7bffee52732af30c43ca
| 293
|
cpp
|
C++
|
C语言程序设计基础/56. 【大学】求表示方法.cpp
|
xiabee/BIT-CS
|
5d8d8331e6b9588773991a872c259e430ef1eae1
|
[
"Apache-2.0"
] | 63
|
2021-01-10T02:32:17.000Z
|
2022-03-30T04:08:38.000Z
|
C语言程序设计基础/56. 【大学】求表示方法.cpp
|
xiabee/BIT-CS
|
5d8d8331e6b9588773991a872c259e430ef1eae1
|
[
"Apache-2.0"
] | 2
|
2021-06-09T05:38:58.000Z
|
2021-12-14T13:53:54.000Z
|
C语言程序设计基础/56. 【大学】求表示方法.cpp
|
xiabee/BIT-CS
|
5d8d8331e6b9588773991a872c259e430ef1eae1
|
[
"Apache-2.0"
] | 20
|
2021-01-12T11:49:36.000Z
|
2022-03-26T11:04:58.000Z
|
#include <stdio.h>
int dic(int n, int m)
{
if (m > n) return dic(n, n);
else if (m == 1 || n == 1) return 1;
else if (m == n) return dic(n, m-1) + 1;
else return dic(n, m-1) + dic(n-m, m);
}
int main()
{
int n, m;
scanf ("%d %d", &n, &m);
int tot = dic(n, m);
printf ("%d\n", tot);
}
| 19.533333
| 42
| 0.494881
|
xiabee
|
a36749ba0d32cb34785213f5d46493652855775c
| 2,333
|
cpp
|
C++
|
Google/KickStart/2020/Round A/Plates.cpp
|
Code-With-Aagam/competitive-programming
|
610520cc396fb13a03c606b5fb6739cfd68cc444
|
[
"MIT"
] | 2
|
2022-02-08T12:37:41.000Z
|
2022-03-09T03:48:56.000Z
|
KickStart/2020/Round A/Plates.cpp
|
ShubhamJagtap2000/competitive-programming-1
|
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
|
[
"MIT"
] | null | null | null |
KickStart/2020/Round A/Plates.cpp
|
ShubhamJagtap2000/competitive-programming-1
|
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
|
[
"MIT"
] | null | null | null |
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("fast-math")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define deb(x) cout << #x << " is " << x << "\n"
#define int long long
#define MOD 1000000007LL
#define PI acos(-1)
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
template <typename T>
using max_heap = priority_queue<T>;
template <class T>
using ordered_set = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename... T>
void read(T &...args) {
((cin >> args), ...);
}
template <typename... T>
void write(T &&...args) {
((cout << args), ...);
}
template <typename T>
void readContainer(T &t) {
for (auto &e : t) {
read(e);
}
}
template <typename T>
void writeContainer(T &t) {
for (const auto &e : t) {
write(e, " ");
}
write("\n");
}
auto speedup = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// taken: plates taken from 0 to index - 1 plates
int solve(vector<vector<int>> &plates, vector<vector<int>> &dp, int n, int k, int p, int index, int taken) {
if (taken == p) {
return 0;
}
if (index > n || taken > p) {
return -1e9;
}
int ans = -1e9;
if (dp[index][taken] != ans) {
return dp[index][taken];
}
for (int i = 0; i <= k; i++) {
ans = max(ans, plates[index][i] + solve(plates, dp, n, k, p, index + 1, taken + i));
}
return dp[index][taken] = ans;
}
void solve(int tc) {
int N, K, P;
read(N, K, P);
vector<vector<int>> plates(N + 1, vector<int>(K + 1, 0));
vector<vector<int>> dp(N + 1, vector<int>((K * N) + 1, -1e9));
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= K; j++) {
read(plates[i][j]);
plates[i][j] += plates[i][j - 1];
}
}
int ans = solve(plates, dp, N, K, P, 1, 0);
write("Case #", tc, ": ", ans, "\n");
}
signed main() {
int tc = 1;
read(tc);
for (int curr = 1; curr <= tc; curr++) {
solve(curr);
}
return 0;
}
| 23.09901
| 108
| 0.557222
|
Code-With-Aagam
|
a3698023d6ad85298f41646dbc762cd9dcb3ecca
| 3,406
|
hpp
|
C++
|
test/framework/integration_framework/fake_peer/proposal_storage.hpp
|
IvanTyulyandin/iroha
|
442a08325c7b808236569600653370e28ec5eff6
|
[
"Apache-2.0"
] | 24
|
2016-09-26T17:11:46.000Z
|
2020-03-03T13:42:58.000Z
|
test/framework/integration_framework/fake_peer/proposal_storage.hpp
|
ecsantana76/iroha
|
9cc430bb2c8eb885393e2a636fa92d1e605443ae
|
[
"Apache-2.0"
] | 11
|
2016-10-13T10:09:55.000Z
|
2019-06-13T08:49:11.000Z
|
test/framework/integration_framework/fake_peer/proposal_storage.hpp
|
ecsantana76/iroha
|
9cc430bb2c8eb885393e2a636fa92d1e605443ae
|
[
"Apache-2.0"
] | 4
|
2016-09-27T13:18:28.000Z
|
2019-08-05T20:47:15.000Z
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef INTEGRATION_FRAMEWORK_FAKE_PEER_PROPOSAL_STORAGE_HPP_
#define INTEGRATION_FRAMEWORK_FAKE_PEER_PROPOSAL_STORAGE_HPP_
#include <map>
#include <mutex>
#include <shared_mutex>
#include <unordered_set>
#include "backend/protobuf/proposal.hpp"
#include "consensus/round.hpp"
#include "framework/integration_framework/fake_peer/types.hpp"
#include "interfaces/iroha_internal/unsafe_proposal_factory.hpp"
#include "multi_sig_transactions/hash.hpp" // for PointerBatchHasher
#include "multi_sig_transactions/state/mst_state.hpp" // for BatchHashEquality
namespace integration_framework {
namespace fake_peer {
namespace detail {
using TxPointerType =
std::shared_ptr<shared_model::interface::Transaction>;
class PointerTxHasher {
public:
size_t operator()(const TxPointerType &tx_pointer) const;
};
class PointerTxHashEquality {
public:
bool operator()(const TxPointerType &left_tx,
const TxPointerType &right_tx) const;
};
} // namespace detail
class ProposalStorage final {
public:
using Round = iroha::consensus::Round;
using Proposal = shared_model::proto::Proposal;
using DefaultProvider = std::function<OrderingProposalRequestResult(
const OrderingProposalRequest &)>;
ProposalStorage();
OrderingProposalRequestResult getProposal(
const OrderingProposalRequest &round);
ProposalStorage &storeProposal(const Round &round,
std::shared_ptr<Proposal> proposal);
/// Adds transactions to internal storage. When a proposal is asked for a
/// round, and there was no storeProposal call for this round, a proposal
/// with the transactions from internal storage will be returned
void addTransactions(
std::vector<std::shared_ptr<shared_model::interface::Transaction>>
transactions);
/// Adds batches to internal storage. When a proposal is asked for a
/// round, and there was no storeProposal call for this round, a proposal
/// with the transactions from internal storage will be returned
void addBatches(const BatchesCollection &batches);
ProposalStorage &setDefaultProvider(DefaultProvider provider);
private:
/// Create a proposal from pending transactions, if any.
boost::optional<std::unique_ptr<Proposal>> makeProposalFromPendingTxs(
shared_model::interface::types::HeightType height);
OrderingProposalRequestResult getDefaultProposal(
const Round &round) const;
std::unique_ptr<shared_model::interface::UnsafeProposalFactory>
proposal_factory_;
std::shared_ptr<DefaultProvider> default_provider_;
std::map<Round, std::shared_ptr<const Proposal>> proposals_map_;
mutable std::shared_timed_mutex proposals_map_mutex_;
std::unordered_set<std::shared_ptr<shared_model::interface::Transaction>,
detail::PointerTxHasher,
detail::PointerTxHashEquality> pending_txs_;
mutable std::mutex pending_txs_mutex_;
};
} // namespace fake_peer
} // namespace integration_framework
#endif /* INTEGRATION_FRAMEWORK_FAKE_PEER_PROPOSAL_STORAGE_HPP_ */
| 35.479167
| 80
| 0.70552
|
IvanTyulyandin
|
a36adcf045573fbf2aeebd4bf9e3ba2a9b37455b
| 2,718
|
hpp
|
C++
|
sciplot/specs/fontspecs.hpp
|
CaeruleusAqua/sciplot
|
4470cbd43a08b4caa897631159a47d35d72f5a18
|
[
"MIT"
] | 1
|
2021-01-28T07:46:26.000Z
|
2021-01-28T07:46:26.000Z
|
sciplot/specs/fontspecs.hpp
|
CaeruleusAqua/sciplot
|
4470cbd43a08b4caa897631159a47d35d72f5a18
|
[
"MIT"
] | null | null | null |
sciplot/specs/fontspecs.hpp
|
CaeruleusAqua/sciplot
|
4470cbd43a08b4caa897631159a47d35d72f5a18
|
[
"MIT"
] | null | null | null |
// sciplot - a modern C++ scientific plotting library powered by gnuplot
// https://github.com/sciplot/sciplot
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
//
// Copyright (c) 2018 Allan Leal
//
// 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.
#pragma once
// sciplot includes
#include <sciplot/default.hpp>
#include <sciplot/specs/specs.hpp>
#include <sciplot/util.hpp>
namespace sciplot
{
/// The class used to specify options for font.
template <typename derivedspecs>
class fontspecs : virtual public internal::specs<derivedspecs>
{
public:
/// Construct a default fontspecs instance.
fontspecs();
/// Convert this fontspecs object into a gnuplot formatted string.
auto repr() const -> std::string;
/// Set the name of the font (e.g., Helvetica, Georgia, Times).
auto fontname(std::string name) -> derivedspecs&
{
m_fontname = name;
return static_cast<derivedspecs&>(*this);
}
/// Set the point size of the font (e.g., 10, 12, 16).
auto fontsize(std::size_t size) -> derivedspecs&
{
m_fontsize = size;
return static_cast<derivedspecs&>(*this);
}
private:
/// The name of the font.
std::string m_fontname;
/// The point size of the font.
std::size_t m_fontsize;
};
template <typename derivedspecs>
fontspecs<derivedspecs>::fontspecs()
{
fontname(internal::DEFAULT_FONTNAME);
fontsize(internal::DEFAULT_FONTSIZE);
}
template <typename derivedspecs>
auto fontspecs<derivedspecs>::repr() const -> std::string
{
std::stringstream ss;
ss << "font '" << m_fontname << "," << m_fontsize << "'";
return ss.str();
}
} // namespace sciplot
| 31.976471
| 81
| 0.708609
|
CaeruleusAqua
|
a36bdd00a1c0f8574bcf456b6d803374aa4c0c04
| 1,301
|
hpp
|
C++
|
inference-engine/src/vpu/common/include/vpu/ngraph/operations/out_shape_of_reshape.hpp
|
calvinfeng/openvino
|
11f591c16852637506b1b40d083b450e56d0c8ac
|
[
"Apache-2.0"
] | null | null | null |
inference-engine/src/vpu/common/include/vpu/ngraph/operations/out_shape_of_reshape.hpp
|
calvinfeng/openvino
|
11f591c16852637506b1b40d083b450e56d0c8ac
|
[
"Apache-2.0"
] | 16
|
2021-07-20T13:00:28.000Z
|
2022-02-21T13:10:23.000Z
|
inference-engine/src/vpu/common/include/vpu/ngraph/operations/out_shape_of_reshape.hpp
|
calvinfeng/openvino
|
11f591c16852637506b1b40d083b450e56d0c8ac
|
[
"Apache-2.0"
] | 1
|
2021-07-28T17:30:46.000Z
|
2021-07-28T17:30:46.000Z
|
// Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <ngraph/node.hpp>
#include <ngraph/op/op.hpp>
#include "ngraph/runtime/host_tensor.hpp"
namespace ngraph { namespace vpu { namespace op {
class OutShapeOfReshape : public ngraph::op::Op {
public:
static constexpr NodeTypeInfo type_info{"OutShapeOfReshape", 1};
const NodeTypeInfo& get_type_info() const override { return type_info; }
OutShapeOfReshape(
const Output<Node>& inDataShape,
const Output<Node>& outShapeDescriptor,
bool specialZero);
void validate_and_infer_types() override;
std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;
bool visit_attributes(ngraph::AttributeVisitor& visitor) override;
bool getSpecialZero() const { return m_specialZero; }
void setSpecialZero(bool special_zero) { m_specialZero = special_zero; }
bool evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const override;
void set_output_type(const ngraph::element::Type& output_type);
using Node::set_output_type;
private:
bool m_specialZero;
element::Type m_output_type = element::i64;
};
} // namespace op
} // namespace vpu
} // namespace ngraph
| 29.568182
| 98
| 0.730208
|
calvinfeng
|
a36da3c285054b6a4e05951f39349f0e17ad5030
| 1,580
|
hpp
|
C++
|
libmeasure/gpu_nvidia_tesla_kepler/CMeasureNVMLThread.hpp
|
akiml/ampehre
|
383a863442574ea2e6a6ac853a9b99e153daeccf
|
[
"BSD-2-Clause"
] | 3
|
2016-01-20T13:41:52.000Z
|
2018-04-10T17:50:49.000Z
|
libmeasure/gpu_nvidia_tesla_kepler/CMeasureNVMLThread.hpp
|
akiml/ampehre
|
383a863442574ea2e6a6ac853a9b99e153daeccf
|
[
"BSD-2-Clause"
] | null | null | null |
libmeasure/gpu_nvidia_tesla_kepler/CMeasureNVMLThread.hpp
|
akiml/ampehre
|
383a863442574ea2e6a6ac853a9b99e153daeccf
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* CMeasureNVMLThread.hpp
*
* Copyright (C) 2015, Achim Lösch <achim.loesch@upb.de>, Christoph Knorr <cknorr@mail.uni-paderborn.de>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*
* encoding: UTF-8
* tab size: 4
*
* author: Achim Lösch (achim.loesch@upb.de)
* created: 3/04/14
* version: 0.1.0 - initial implementation
* 0.1.4 - add signals for measuring system start and stop
* 0.2.2 - add semaphore to synchronize the start of the measurements
* 0.5.1 - modularized libmeasure
* 0.5.2 - delete different ThreadTimer classes in libmeasure
* 0.5.3 - add abstract measure and abstract measure thread
* 0.6.0 - add ioctl for the ipmi timeout, new parameters to skip certain measurements
* and to select between the full or light library.
* 0.7.0 - modularized measurement struct
*/
#ifndef __CMEASURENVMLTHREAD_HPP__
#define __CMEASURENVMLTHREAD_HPP__
#include <iostream>
#include <ctime>
#include <nvml.h>
#include "../common/CMeasureAbstractThread.hpp"
#include "CMeasureNVML.hpp"
namespace NLibMeasure {
template <int TVariant>
class CMeasureNVMLThread : public CMeasureAbstractThread {
public:
CMeasureNVMLThread(CLogger& rLogger, CSemaphore& rStartSem, void* pMsMeasurement, CMeasureAbstractResource& rMeasureRes);
~CMeasureNVMLThread();
private:
void run(void);
};
}
#include "CMeasureNVMLThread.cpp"
#endif /* __CMEASURENVMLTHREAD_HPP__ */
| 30.980392
| 124
| 0.703797
|
akiml
|
a373700a84b443190f647ec9bdc990a95263fc21
| 5,211
|
cpp
|
C++
|
test/test11.cpp
|
tjachmann/utest.h
|
aeb78834480993866fc200f496558cc2c2436fe3
|
[
"Unlicense"
] | 482
|
2015-12-11T16:20:40.000Z
|
2022-03-31T05:26:22.000Z
|
test/test11.cpp
|
tjachmann/utest.h
|
aeb78834480993866fc200f496558cc2c2436fe3
|
[
"Unlicense"
] | 43
|
2019-08-09T22:23:52.000Z
|
2022-03-01T20:22:16.000Z
|
test/test11.cpp
|
tjachmann/utest.h
|
aeb78834480993866fc200f496558cc2c2436fe3
|
[
"Unlicense"
] | 51
|
2016-01-13T11:55:51.000Z
|
2022-02-17T14:29:07.000Z
|
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// 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 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.
//
// For more information, please refer to <http://unlicense.org/>
#include "utest.h"
#ifdef _MSC_VER
// disable 'conditional expression is constant' - our examples below use this!
#pragma warning(disable : 4127)
#endif
UTEST(cpp11, ASSERT_TRUE) { ASSERT_TRUE(1); }
UTEST(cpp11, ASSERT_FALSE) { ASSERT_FALSE(0); }
UTEST(cpp11, ASSERT_EQ) { ASSERT_EQ(1, 1); }
UTEST(cpp11, ASSERT_NE) { ASSERT_NE(1, 2); }
UTEST(cpp11, ASSERT_LT) { ASSERT_LT(1, 2); }
UTEST(cpp11, ASSERT_LE) {
ASSERT_LE(1, 1);
ASSERT_LE(1, 2);
}
UTEST(cpp11, ASSERT_GT) { ASSERT_GT(2, 1); }
UTEST(cpp11, ASSERT_GE) {
ASSERT_GE(1, 1);
ASSERT_GE(2, 1);
}
UTEST(cpp11, ASSERT_STREQ) { ASSERT_STREQ("foo", "foo"); }
UTEST(cpp11, ASSERT_STRNE) { ASSERT_STRNE("foo", "bar"); }
UTEST(cpp11, ASSERT_STRNEQ) { ASSERT_STRNEQ("foo", "foobar", strlen("foo")); }
UTEST(cpp11, ASSERT_STRNNE) { ASSERT_STRNNE("foo", "barfoo", strlen("foo")); }
UTEST(cpp11, EXPECT_TRUE) { EXPECT_TRUE(1); }
UTEST(cpp11, EXPECT_FALSE) { EXPECT_FALSE(0); }
UTEST(cpp11, EXPECT_EQ) { EXPECT_EQ(1, 1); }
UTEST(cpp11, EXPECT_NE) { EXPECT_NE(1, 2); }
UTEST(cpp11, EXPECT_LT) { EXPECT_LT(1, 2); }
UTEST(cpp11, EXPECT_LE) {
EXPECT_LE(1, 1);
EXPECT_LE(1, 2);
}
UTEST(cpp11, EXPECT_GT) { EXPECT_GT(2, 1); }
UTEST(cpp11, EXPECT_GE) {
EXPECT_GE(1, 1);
EXPECT_GE(2, 1);
}
UTEST(cpp11, EXPECT_STREQ) { EXPECT_STREQ("foo", "foo"); }
UTEST(cpp11, EXPECT_STRNE) { EXPECT_STRNE("foo", "bar"); }
UTEST(cpp11, EXPECT_STRNEQ) { EXPECT_STRNEQ("foo", "foobar", strlen("foo")); }
UTEST(cpp11, EXPECT_STRNNE) { EXPECT_STRNNE("foo", "barfoo", strlen("foo")); }
UTEST(cpp11, no_double_eval) {
int i = 0;
ASSERT_EQ(i++, 0);
ASSERT_EQ(i, 1);
}
struct MyTestF {
int foo;
};
UTEST_F_SETUP(MyTestF) {
ASSERT_EQ(0, utest_fixture->foo);
utest_fixture->foo = 42;
}
UTEST_F_TEARDOWN(MyTestF) { ASSERT_EQ(13, utest_fixture->foo); }
UTEST_F(MyTestF, cpp11_1) {
ASSERT_EQ(42, utest_fixture->foo);
utest_fixture->foo = 13;
}
UTEST_F(MyTestF, cpp11_2) {
ASSERT_EQ(42, utest_fixture->foo);
utest_fixture->foo = 13;
}
struct MyTestI {
size_t foo;
size_t bar;
};
UTEST_I_SETUP(MyTestI) {
ASSERT_EQ(0u, utest_fixture->foo);
ASSERT_EQ(0u, utest_fixture->bar);
utest_fixture->foo = 42;
utest_fixture->bar = utest_index;
}
UTEST_I_TEARDOWN(MyTestI) {
ASSERT_EQ(13u, utest_fixture->foo);
ASSERT_EQ(utest_index, utest_fixture->bar);
}
UTEST_I(MyTestI, cpp11_1, 2) {
ASSERT_GT(2u, utest_fixture->bar);
utest_fixture->foo = 13;
}
UTEST_I(MyTestI, cpp11_2, 128) {
ASSERT_GT(128u, utest_fixture->bar);
utest_fixture->foo = 13;
}
UTEST(cpp11, Float) {
float a = 1;
float b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, Double) {
double a = 1;
double b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, LongDouble) {
long double a = 1;
long double b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, Char) {
signed char a = 1;
signed char b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, UChar) {
unsigned char a = 1;
unsigned char b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, Short) {
short a = 1;
short b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, UShort) {
unsigned short a = 1;
unsigned short b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, Int) {
int a = 1;
int b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, UInt) {
unsigned int a = 1;
unsigned int b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, Long) {
long a = 1;
long b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, ULong) {
unsigned long a = 1;
unsigned long b = 2;
EXPECT_NE(a, b);
ASSERT_NE(a, b);
}
UTEST(cpp11, Ptr) {
char foo = 42;
EXPECT_NE(&foo, &foo + 1);
}
UTEST(cpp11, VoidPtr) {
void *foo = reinterpret_cast<void *>(0);
EXPECT_NE(foo, static_cast<char *>(foo) + 1);
}
static const int data[4] = {42, 13, 6, -53};
UTEST(cpp11, Array) { EXPECT_NE(data, data + 1); }
| 21.987342
| 78
| 0.672232
|
tjachmann
|
a374d5bbbe78d1af6519804fdbb74558d0d14d55
| 5,184
|
cpp
|
C++
|
omron_b5l_a/src/publisher_member_function.cpp
|
deepinbubblegum/b5l_TOFsensor_for_ROS2
|
92c28f3ddedb821b4036127678a199072aefe825
|
[
"Apache-2.0"
] | 1
|
2021-11-22T14:54:39.000Z
|
2021-11-22T14:54:39.000Z
|
omron_b5l_a/src/publisher_member_function.cpp
|
deepinbubblegum/b5l_TOFsensor_for_ROS2
|
92c28f3ddedb821b4036127678a199072aefe825
|
[
"Apache-2.0"
] | 1
|
2021-08-13T00:57:49.000Z
|
2021-08-13T00:57:49.000Z
|
omron_b5l_a/src/publisher_member_function.cpp
|
deepinbubblegum/b5l_TOFsensor_for_ROS2
|
92c28f3ddedb821b4036127678a199072aefe825
|
[
"Apache-2.0"
] | 2
|
2021-03-05T14:29:10.000Z
|
2022-01-20T06:40:53.000Z
|
/*---------------------------------------------------------------------------*/
/* Copyright(C) 2019-2020 OMRON Corporation */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/*---------------------------------------------------------------------------*/
/*******************************************************************************
* File Name : publisher_member_function.cpp
* revision : 0.1
* Description : main publisher module source file.
******************************************************************************/
/******************************************************************************
* History : DD.MM.YYYY Version Description
* : 15.07.2020 0.1 Initial Version
*****************************************************************************/
#include "publisher_member_function.hpp"
#include <unistd.h>
using PointT = pcl::PointXYZI;
using PointCloudT = pcl::PointCloud<PointT>;
int ShutDownFlag;
/* Topc string */
std::string Topic = "";
/* Output formate */
INT32 Tof_output_format = 0;
/*****************************************************************************
* Function Name : terminate
*****************************************************************************/
/**
* @brief This function is for stop communication and shutdown application
*
* @param[in/out] None
*
* @return None
*/
void MinimalPublisher::terminate_application()
{
CTOFSample::Stop();
rclcpp::shutdown();
}
/*****************************************************************************
* Class Constructor : MinimalPublisher
*****************************************************************************/
/**
* @brief Init variables of class
*/
MinimalPublisher::MinimalPublisher() : Node("minimal_publisher")
{
frame_id_ = "map";
ShutDownFlag = 0;
/*Create pulisher with topic as per config file 'OUTPUT_FORMAT' parameter*/
/* Here 10 represents max number of messages in publisher queue*/
publisher_ = create_publisher<sensor_msgs::msg::PointCloud2>(Topic, PUB_MSG_QUEUE_DEPTH);
pc2_msg_ = std::make_shared<sensor_msgs::msg::PointCloud2>();
/* Create timer for 80ms to achive approx 10/12 Fps */
timer_ = this->create_wall_timer(50ms, std::bind(&MinimalPublisher::timer_callback, this));
}
/*****************************************************************************
* Function Name : timer_callback
*****************************************************************************/
/**
* @brief This function is Timer callback function which publish ROS2 msg on particuler time interval
*
* @param[in/out] None
*
* @return None
*/
void MinimalPublisher::timer_callback()
{
pcl::PointCloud<pcl::PointXYZI> cloud_;
int Ret = CTOFSample::Run(&cloud_);
if (Ret == 0)
{
/* Convert cloud data to ROS2 msg type */
pcl::toROSMsg(cloud_, *pc2_msg_);
pc2_msg_->header.frame_id = frame_id_;
pc2_msg_->header.stamp = now();
/* Publish ROS2 message */
publisher_->publish(*pc2_msg_);
}
else
{
ShutDownFlag = 1;
terminate_application();
}
}
/*****************************************************************************
* Function Name : main
*****************************************************************************/
/**
* @brief main function for init and start application
*
* @param[in/out] None
*
* @return 0 on successful shutdown
*/
int main(int argc, char *argv[])
{
std::string config_file = SOURCE_DIR_PREFIX;
ShutDownFlag = 0;
/* Load USB serial module */
system("sudo modprobe usbserial vendor=0x0590 product=0x00ca");
rclcpp::init(argc, argv);
config_file.append(CONFIG_FILE_PATH);
std::cout<< "omron_b5l_a application version 0.1 started"<< std::endl;
int Ret = CTOFSample::Init(config_file, Tof_output_format); // Init camera and UART
/* Here we are supporting output format 257 || 258 || 1 || 2 */
/* Format validation done in Init function and if fails then it returns non zero value */
if (Ret == 0)
{
if (Tof_output_format == 257 || Tof_output_format == 258)
{
Topic = PUB_TOPIC_FRMT_257_258;
}
else
{
Topic = PUB_TOPIC_FRMT_001_002;
}
rclcpp::spin(std::make_shared<MinimalPublisher>());
if (ShutDownFlag == 0)
{
MinimalPublisher::terminate_application();
}
}
return 0;
}
| 34.105263
| 101
| 0.495756
|
deepinbubblegum
|
a3767cb0a2d3add3a8ef2fc52db1dcddb39f33d7
| 27,211
|
cpp
|
C++
|
arangod/RestHandler/RestVocbaseBaseHandler.cpp
|
snykiotcubedev/arangodb-3.7.6
|
fce8f85f1c2f070c8e6a8e76d17210a2117d3833
|
[
"Apache-2.0"
] | null | null | null |
arangod/RestHandler/RestVocbaseBaseHandler.cpp
|
snykiotcubedev/arangodb-3.7.6
|
fce8f85f1c2f070c8e6a8e76d17210a2117d3833
|
[
"Apache-2.0"
] | 109
|
2022-01-06T07:05:24.000Z
|
2022-03-21T01:39:35.000Z
|
arangod/RestHandler/RestVocbaseBaseHandler.cpp
|
snykiotcubedev/arangodb-3.7.6
|
fce8f85f1c2f070c8e6a8e76d17210a2117d3833
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "RestVocbaseBaseHandler.h"
#include "ApplicationFeatures/ApplicationServer.h"
#include "Basics/StaticStrings.h"
#include "Basics/StringBuffer.h"
#include "Basics/StringUtils.h"
#include "Basics/VPackStringBufferAdapter.h"
#include "Basics/VelocyPackHelper.h"
#include "Basics/conversions.h"
#include "Basics/tri-strings.h"
#include "Cluster/ClusterFeature.h"
#include "Cluster/ServerState.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerStream.h"
#include "Meta/conversion.h"
#include "Rest/CommonDefines.h"
#include "StorageEngine/TransactionState.h"
#include "Transaction/Helpers.h"
#include "Transaction/Manager.h"
#include "Transaction/ManagerFeature.h"
#include "Transaction/Methods.h"
#include "Transaction/SmartContext.h"
#include "Transaction/StandaloneContext.h"
#include "Utils/SingleCollectionTransaction.h"
#include <velocypack/Builder.h>
#include <velocypack/Dumper.h>
#include <velocypack/Exception.h>
#include <velocypack/Parser.h>
#include <velocypack/Slice.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;
////////////////////////////////////////////////////////////////////////////////
/// @brief agency public path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::AGENCY_PATH = "/_api/agency";
////////////////////////////////////////////////////////////////////////////////
/// @brief agency private path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::AGENCY_PRIV_PATH =
"/_api/agency_priv";
////////////////////////////////////////////////////////////////////////////////
/// @brief analyzer path
////////////////////////////////////////////////////////////////////////////////
/*static*/ std::string const RestVocbaseBaseHandler::ANALYZER_PATH =
"/_api/analyzer";
////////////////////////////////////////////////////////////////////////////////
/// @brief batch path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::BATCH_PATH = "/_api/batch";
////////////////////////////////////////////////////////////////////////////////
/// @brief collection path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::COLLECTION_PATH = "/_api/collection";
////////////////////////////////////////////////////////////////////////////////
/// @brief control pregel path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::CONTROL_PREGEL_PATH =
"/_api/control_pregel";
////////////////////////////////////////////////////////////////////////////////
/// @brief cursor path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::CURSOR_PATH = "/_api/cursor";
////////////////////////////////////////////////////////////////////////////////
/// @brief database path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::DATABASE_PATH = "/_api/database";
////////////////////////////////////////////////////////////////////////////////
/// @brief document path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::DOCUMENT_PATH = "/_api/document";
////////////////////////////////////////////////////////////////////////////////
/// @brief edges path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::EDGES_PATH = "/_api/edges";
////////////////////////////////////////////////////////////////////////////////
/// @brief gharial graph api path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::GHARIAL_PATH = "/_api/gharial";
////////////////////////////////////////////////////////////////////////////////
/// @brief endpoint path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::ENDPOINT_PATH = "/_api/endpoint";
////////////////////////////////////////////////////////////////////////////////
/// @brief documents import path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::IMPORT_PATH = "/_api/import";
////////////////////////////////////////////////////////////////////////////////
/// @brief index path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::INDEX_PATH = "/_api/index";
////////////////////////////////////////////////////////////////////////////////
/// @brief replication path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::REPLICATION_PATH =
"/_api/replication";
////////////////////////////////////////////////////////////////////////////////
/// @brief simple query all path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::SIMPLE_QUERY_ALL_PATH =
"/_api/simple/all";
////////////////////////////////////////////////////////////////////////////////
/// @brief simple query all-keys path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::SIMPLE_QUERY_ALL_KEYS_PATH =
"/_api/simple/all-keys";
//////////////////////////////////////////////////////////////////////////////
/// @brief simple query by example path
//////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::SIMPLE_QUERY_BY_EXAMPLE =
"/_api/simple/by-example";
//////////////////////////////////////////////////////////////////////////////
/// @brief simple query first example path
//////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::SIMPLE_FIRST_EXAMPLE =
"/_api/simple/first-example";
//////////////////////////////////////////////////////////////////////////////
/// @brief simple query remove by example path
//////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::SIMPLE_REMOVE_BY_EXAMPLE =
"/_api/simple/remove-by-example";
//////////////////////////////////////////////////////////////////////////////
/// @brief simple query replace by example path
//////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::SIMPLE_REPLACE_BY_EXAMPLE =
"/_api/simple/replace-by-example";
//////////////////////////////////////////////////////////////////////////////
/// @brief simple query replace by example path
//////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::SIMPLE_UPDATE_BY_EXAMPLE =
"/_api/simple/update-by-example";
////////////////////////////////////////////////////////////////////////////////
/// @brief document batch lookup path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::SIMPLE_LOOKUP_PATH =
"/_api/simple/lookup-by-keys";
////////////////////////////////////////////////////////////////////////////////
/// @brief document batch remove path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::SIMPLE_REMOVE_PATH =
"/_api/simple/remove-by-keys";
////////////////////////////////////////////////////////////////////////////////
/// @brief tasks path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::TASKS_PATH = "/_api/tasks";
////////////////////////////////////////////////////////////////////////////////
/// @brief upload path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::UPLOAD_PATH = "/_api/upload";
////////////////////////////////////////////////////////////////////////////////
/// @brief users path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::USERS_PATH = "/_api/user";
////////////////////////////////////////////////////////////////////////////////
/// @brief view path
////////////////////////////////////////////////////////////////////////////////
std::string const RestVocbaseBaseHandler::VIEW_PATH = "/_api/view";
/// @brief Internal Traverser path
std::string const RestVocbaseBaseHandler::INTERNAL_TRAVERSER_PATH =
"/_internal/traverser";
RestVocbaseBaseHandler::RestVocbaseBaseHandler(application_features::ApplicationServer& server,
GeneralRequest* request,
GeneralResponse* response)
: RestBaseHandler(server, request, response),
_context(*static_cast<VocbaseContext*>(request->requestContext())),
_vocbase(_context.vocbase()) {
TRI_ASSERT(request->requestContext());
}
RestVocbaseBaseHandler::~RestVocbaseBaseHandler() = default;
/// @brief returns the short id of the server which should handle this request
ResultT<std::pair<std::string, bool>> RestVocbaseBaseHandler::forwardingTarget() {
bool found = false;
std::string const& value = _request->header(StaticStrings::TransactionId, found);
if (found) {
TRI_voc_tid_t tid = 0;
std::size_t pos = 0;
try {
tid = std::stoull(value, &pos, 10);
} catch (...) {
}
if (tid != 0) {
uint32_t sourceServer = TRI_ExtractServerIdFromTick(tid);
if (sourceServer != ServerState::instance()->getShortId()) {
auto& ci = server().getFeature<ClusterFeature>().clusterInfo();
return {std::make_pair(ci.getCoordinatorByShortID(sourceServer), false)};
}
}
}
return {std::make_pair(StaticStrings::Empty, false)};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief assemble a document id from a string and a string
/// optionally url-encodes
////////////////////////////////////////////////////////////////////////////////
std::string RestVocbaseBaseHandler::assembleDocumentId(std::string const& collectionName,
std::string const& key,
bool urlEncode) {
if (urlEncode) {
return collectionName + TRI_DOCUMENT_HANDLE_SEPARATOR_STR + StringUtils::urlEncode(key);
}
return collectionName + TRI_DOCUMENT_HANDLE_SEPARATOR_STR + key;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Generate a result for successful save
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::generateSaved(arangodb::OperationResult const& result,
std::string const& collectionName,
TRI_col_type_e type,
VPackOptions const* options, bool isMultiple) {
generate20x(result, collectionName, type, options, isMultiple, rest::ResponseCode::CREATED);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Generate a result for successful delete
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::generateDeleted(arangodb::OperationResult const& result,
std::string const& collectionName,
TRI_col_type_e type,
VPackOptions const* options, bool isMultiple) {
generate20x(result, collectionName, type, options, isMultiple, rest::ResponseCode::OK);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief generates a HTTP 20x response
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::generate20x(arangodb::OperationResult const& result,
std::string const& collectionName, TRI_col_type_e type,
VPackOptions const* options, bool isMultiple,
rest::ResponseCode waitForSyncResponseCode) {
if (result._options.waitForSync) {
resetResponse(waitForSyncResponseCode);
} else {
resetResponse(rest::ResponseCode::ACCEPTED);
}
if (isMultiple && !result.countErrorCodes.empty()) {
VPackBuilder errorBuilder;
errorBuilder.openObject();
for (auto const& it : result.countErrorCodes) {
errorBuilder.add(basics::StringUtils::itoa(it.first), VPackValue(it.second));
}
errorBuilder.close();
_response->setHeaderNC(StaticStrings::ErrorCodes, errorBuilder.toJson());
}
VPackSlice slice = result.slice();
if (slice.isNone()) {
// will happen if silent == true
slice = arangodb::velocypack::Slice::emptyObjectSlice();
} else {
TRI_ASSERT(slice.isObject() || slice.isArray());
if (slice.isObject()) {
_response->setHeaderNC(StaticStrings::Etag,
"\"" + slice.get(StaticStrings::RevString).copyString() +
"\"");
// pre 1.4 location headers withdrawn for >= 3.0
std::string escapedHandle(
assembleDocumentId(collectionName,
slice.get(StaticStrings::KeyString).copyString(), true));
_response->setHeaderNC(StaticStrings::Location,
std::string("/_db/" + _request->databaseName() +
DOCUMENT_PATH + "/" + escapedHandle));
}
}
writeResult(slice, *options);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief generates not implemented
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::generateNotImplemented(std::string const& path) {
generateError(rest::ResponseCode::NOT_IMPLEMENTED, TRI_ERROR_NOT_IMPLEMENTED,
"'" + path + "' not implemented");
}
////////////////////////////////////////////////////////////////////////////////
/// @brief generates forbidden
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::generateForbidden() {
generateError(rest::ResponseCode::FORBIDDEN, TRI_ERROR_FORBIDDEN,
"operation forbidden");
}
////////////////////////////////////////////////////////////////////////////////
/// @brief generates precondition failed
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::generatePreconditionFailed(OperationResult const& opres) {
TRI_ASSERT(opres.errorNumber() == TRI_ERROR_ARANGO_CONFLICT);
resetResponse(rest::ResponseCode::PRECONDITION_FAILED);
VPackSlice slice = opres.slice();
if (slice.isObject()) { // single document case
std::string const rev =
VelocyPackHelper::getStringValue(slice, StaticStrings::RevString, "");
_response->setHeaderNC(StaticStrings::Etag, "\"" + rev + "\"");
}
VPackBuilder builder;
{
VPackObjectBuilder guard(&builder);
builder.add(StaticStrings::Error, VPackValue(true));
builder.add(StaticStrings::Code,
VPackValue(static_cast<int32_t>(rest::ResponseCode::PRECONDITION_FAILED)));
builder.add(StaticStrings::ErrorNum, VPackValue(TRI_ERROR_ARANGO_CONFLICT));
builder.add(StaticStrings::ErrorMessage, VPackValue(opres.errorMessage()));
if (slice.isObject()) {
builder.add(StaticStrings::IdString, slice.get(StaticStrings::IdString));
builder.add(StaticStrings::KeyString, slice.get(StaticStrings::KeyString));
builder.add(StaticStrings::RevString, slice.get(StaticStrings::RevString));
} else {
builder.add("result", slice);
}
}
auto ctx = transaction::StandaloneContext::Create(_vocbase);
writeResult(builder.slice(), *(ctx->getVPackOptionsForDump()));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief generates not modified
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::generateNotModified(TRI_voc_rid_t rid) {
resetResponse(rest::ResponseCode::NOT_MODIFIED);
_response->setHeaderNC(StaticStrings::Etag,
"\"" + TRI_RidToString(rid) + "\"");
}
////////////////////////////////////////////////////////////////////////////////
/// @brief generates next entry from a result set
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::generateDocument(VPackSlice const& input, bool generateBody,
VPackOptions const* options) {
VPackSlice document = input.resolveExternal();
std::string rev;
if (document.isObject()) {
rev =
VelocyPackHelper::getStringValue(document, StaticStrings::RevString, "");
}
// and generate a response
resetResponse(rest::ResponseCode::OK);
// set ETAG header
if (!rev.empty()) {
_response->setHeaderNC(StaticStrings::Etag, "\"" + rev + "\"");
}
try {
_response->setContentType(_request->contentTypeResponse());
_response->setGenerateBody(generateBody);
_response->setPayload(document, *options);
} catch (...) {
generateError(rest::ResponseCode::SERVER_ERROR, TRI_ERROR_INTERNAL,
"cannot generate output");
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief generate an error message for a transaction error, this method is
/// used by the others.
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::generateTransactionError(std::string const& collectionName,
OperationResult const& result,
std::string const& key,
TRI_voc_rid_t rev) {
int code = result.errorNumber();
switch (code) {
case TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND:
if (collectionName.empty()) {
// no collection name specified
generateError(rest::ResponseCode::BAD, code,
"no collection name specified");
} else {
// collection name specified but collection not found
generateError(rest::ResponseCode::NOT_FOUND, code,
"collection '" + collectionName + "' not found");
}
return;
case TRI_ERROR_ARANGO_READ_ONLY:
generateError(rest::ResponseCode::FORBIDDEN, code,
"collection is read-only");
return;
case TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND:
generateDocumentNotFound(collectionName, key);
return;
case TRI_ERROR_ARANGO_CONFLICT:
if (result.buffer != nullptr && !result.slice().isNone()) {
// This case happens if we come via the generateTransactionError that
// has a proper OperationResult with a slice:
generatePreconditionFailed(result);
} else {
// This case happens if we call this method directly with a dummy
// OperationResult:
OperationResult tmp(result.result);
tmp.buffer = std::make_shared<VPackBufferUInt8>();
VPackBuilder builder(tmp.buffer);
builder.openObject();
builder.add(StaticStrings::IdString,
VPackValue(assembleDocumentId(collectionName, key, false)));
builder.add(StaticStrings::KeyString, VPackValue(key));
builder.add(StaticStrings::RevString, VPackValue(TRI_RidToString(rev)));
builder.close();
generatePreconditionFailed(tmp);
}
return;
default:
generateError(GeneralResponse::responseCode(code), code, result.errorMessage());
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief extracts the revision
////////////////////////////////////////////////////////////////////////////////
TRI_voc_rid_t RestVocbaseBaseHandler::extractRevision(char const* header, bool& isValid) const {
isValid = true;
bool found;
std::string const& etag = _request->header(header, found);
if (found) {
char const* s = etag.c_str();
char const* e = s + etag.size();
while (s < e && (s[0] == ' ' || s[0] == '\t')) {
++s;
}
if (s < e && (s[0] == '"' || s[0] == '\'')) {
++s;
}
while (s < e && (e[-1] == ' ' || e[-1] == '\t')) {
--e;
}
if (s < e && (e[-1] == '"' || e[-1] == '\'')) {
--e;
}
TRI_voc_rid_t rid = 0;
bool isOld;
rid = TRI_StringToRid(s, e - s, isOld, false);
isValid = (rid != 0 && rid != UINT64_MAX);
return rid;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief extracts a string parameter value
////////////////////////////////////////////////////////////////////////////////
void RestVocbaseBaseHandler::extractStringParameter(std::string const& name,
std::string& ret) const {
bool found;
std::string const& value = _request->value(name, found);
if (found) {
ret = value;
}
}
std::unique_ptr<transaction::Methods> RestVocbaseBaseHandler::createTransaction(
std::string const& collectionName, AccessMode::Type type, OperationOptions const& opOptions) const {
bool found = false;
std::string const& value = _request->header(StaticStrings::TransactionId, found);
if (!found) {
auto tmp = std::make_unique<SingleCollectionTransaction>(transaction::StandaloneContext::Create(_vocbase),
collectionName, type);
if (!opOptions.isSynchronousReplicationFrom.empty() && ServerState::instance()->isDBServer()) {
tmp->addHint(transaction::Hints::Hint::IS_FOLLOWER_TRX);
}
return tmp;
}
TRI_voc_tid_t tid = 0;
std::size_t pos = 0;
try {
tid = std::stoull(value, &pos, 10);
} catch (...) {}
if (tid == 0 || (transaction::isLegacyTransactionId(tid) &&
ServerState::instance()->isRunningInCluster())) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, "invalid transaction ID");
}
transaction::Manager* mgr = transaction::ManagerFeature::manager();
TRI_ASSERT(mgr != nullptr);
if (pos > 0 && pos < value.size() &&
value.compare(pos, std::string::npos, " begin") == 0) {
if (!ServerState::instance()->isDBServer()) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_TRANSACTION_DISALLOWED_OPERATION,
"cannot start a managed transaction here");
}
std::string const& trxDef = _request->header(StaticStrings::TransactionBody, found);
if (found) {
auto trxOpts = VPackParser::fromJson(trxDef);
Result res =
mgr->ensureManagedTrx(_vocbase, tid, trxOpts->slice(),
!opOptions.isSynchronousReplicationFrom.empty());
if (res.fail()) {
THROW_ARANGO_EXCEPTION(res);
}
}
}
auto ctx = mgr->leaseManagedTrx(tid, type);
if (!ctx) {
LOG_TOPIC("e94ea", DEBUG, Logger::TRANSACTIONS) << "Transaction with id '" << tid << "' not found";
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_TRANSACTION_NOT_FOUND, std::string("transaction '") + std::to_string(tid) + "' not found");
}
return std::make_unique<transaction::Methods>(std::move(ctx));
}
/// @brief create proper transaction context, inclusing the proper IDs
std::shared_ptr<transaction::Context> RestVocbaseBaseHandler::createTransactionContext(AccessMode::Type mode) const {
bool found = false;
std::string const& value = _request->header(StaticStrings::TransactionId, found);
if (!found) {
return std::make_shared<transaction::StandaloneContext>(_vocbase);
}
TRI_voc_tid_t tid = 0;
std::size_t pos = 0;
try {
tid = std::stoull(value, &pos, 10);
} catch (...) {}
if (tid == 0 || (transaction::isLegacyTransactionId(tid) &&
ServerState::instance()->isRunningInCluster())) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, "invalid transaction ID");
}
transaction::Manager* mgr = transaction::ManagerFeature::manager();
TRI_ASSERT(mgr != nullptr);
if (pos > 0 && pos < value.size()) {
if (!transaction::isLeaderTransactionId(tid) || !ServerState::instance()->isDBServer()) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_TRANSACTION_DISALLOWED_OPERATION,
"illegal to start a managed transaction here");
}
if (value.compare(pos, std::string::npos, " aql") == 0) {
return std::make_shared<transaction::AQLStandaloneContext>(_vocbase, tid);
} else if (value.compare(pos, std::string::npos, " begin") == 0) {
// this means we lazily start a transaction
std::string const& trxDef = _request->header(StaticStrings::TransactionBody, found);
if (found) {
auto trxOpts = VPackParser::fromJson(trxDef);
Result res = mgr->ensureManagedTrx(_vocbase, tid, trxOpts->slice(), false);
if (res.fail()) {
THROW_ARANGO_EXCEPTION(res);
}
}
}
}
auto ctx = mgr->leaseManagedTrx(tid, mode);
if (!ctx) {
LOG_TOPIC("2cfed", DEBUG, Logger::TRANSACTIONS) << "Transaction with id '" << tid << "' not found";
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_TRANSACTION_NOT_FOUND, std::string("transaction '") + std::to_string(tid) + "' not found");
}
return ctx;
}
| 40.252959
| 136
| 0.501893
|
snykiotcubedev
|
a379d0c0fd85c3a32fdff6a56a0b1c7cb20bb5ef
| 3,907
|
cpp
|
C++
|
test/imu.cpp
|
uos/hatsdf_slam
|
f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682
|
[
"BSD-3-Clause"
] | 5
|
2021-05-21T07:52:50.000Z
|
2022-02-09T04:26:31.000Z
|
test/imu.cpp
|
uos/hatsdf_slam
|
f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682
|
[
"BSD-3-Clause"
] | null | null | null |
test/imu.cpp
|
uos/hatsdf_slam
|
f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682
|
[
"BSD-3-Clause"
] | 1
|
2022-02-09T04:26:33.000Z
|
2022-02-09T04:26:33.000Z
|
#include "catch2_config.h"
#include <msg/imu.h>
#include <util/filter.h>
using namespace fastsense;
using namespace fastsense::util;
#define REQUIRE_IMU(msg, val) \
REQUIRE(msg.acc(0) == Approx(val)); \
REQUIRE(msg.acc(1) == Approx(val)); \
REQUIRE(msg.acc(2) == Approx(val)); \
REQUIRE(msg.ang(0) == Approx(val)); \
REQUIRE(msg.ang(1) == Approx(val)); \
REQUIRE(msg.ang(2) == Approx(val)); \
REQUIRE(msg.mag(0) == Approx(val)); \
REQUIRE(msg.mag(1) == Approx(val)); \
REQUIRE(msg.mag(2) == Approx(val)); \
#define IMU_WITH_VAL(val) msg::Imu(msg::LinearAcceleration(val, val, val), msg::AngularVelocity(val, val, val), msg::MagneticField(val, val, val))
TEST_CASE("Moving Average Filter Built In Type (window=0)", "[MovAvgFilter]")
{
size_t window_size = 0;
double mean = 0;
SlidingWindowFilter<double> filter(window_size);
mean = filter.update(1.);
REQUIRE(mean == 1.);
mean = filter.update(2.);
REQUIRE(mean == 2.);
mean = filter.update(3.);
REQUIRE(mean == 3.);
}
TEST_CASE("Moving Average Filter Built In Type", "[MovAvgFilter]")
{
double window_size = 3;
double mean = 0;
SlidingWindowFilter<double> filter(window_size);
mean = filter.update(1.);
REQUIRE(mean == 1.);
mean = filter.update(2.);
REQUIRE(mean == 2.);
mean = filter.update(2.);
REQUIRE(mean == 2.);
// Buffer is filled for first time
REQUIRE(filter.get_buffer().size() == window_size);
// Mean from first three steps is (internally)
// (((0 + 1/3) + 2/3) + 2/3) ~ 1.66667
REQUIRE(filter.get_mean() == (((0. + 1./3.) + 2./3.) + 2./3.));
// Now actual sliding window averaging begins: more than window_size measurements
// front(): 1.
REQUIRE(filter.get_buffer().front() == 1.);
// Update with 3: mean += back (now 3) - front (1) / window_size => 2.33333
auto old_mean = filter.get_mean();
mean = filter.update(3.);
REQUIRE(mean == old_mean + (3. - 1.)/window_size);
// back(): 3, as just declared
REQUIRE(filter.get_buffer().back() == 3.);
// front(): 2.
REQUIRE(filter.get_buffer().front() == 2.);
// Update with 2: mean (2.33333) += (back (now 2) - front(now 2)/3)
old_mean = filter.get_mean();
mean = filter.update(2.);
REQUIRE(mean == old_mean);
// back(): 2.
REQUIRE(filter.get_buffer().back() == 2.);
}
TEST_CASE("Moving Average Filter Imu", "[MovAvgFilter]")
{
// Same logic as test above, but on all Imu Data
double window_size = 3;
msg::Imu mean{};
SlidingWindowFilter<msg::Imu> filter(window_size);
mean = filter.update(IMU_WITH_VAL(1.));
REQUIRE_IMU(mean, 1.);
mean = filter.update(IMU_WITH_VAL(2.));
REQUIRE_IMU(mean, 2.);
mean = filter.update(IMU_WITH_VAL(2.));
REQUIRE_IMU(mean, 2.);
// Buffer is filled for first time
REQUIRE(filter.get_buffer().size() == window_size);
// Mean from first three steps is (internally)
// (((0 + 1/3) + 2/3) + 2/3) ~ 1.66667
REQUIRE_IMU(filter.get_mean(), (((0. + 1./3.) + 2./3.) + 2./3.));
// Now actual sliding window averaging begins: more than window_size measurements
// front(): 1.
REQUIRE_IMU(filter.get_buffer().front(), 1.);
// Update with 3: mean += back (now 3) - front (1) / window_size => 2.33333
auto old_mean = static_cast<double>(filter.get_mean().acc(0));
mean = filter.update(IMU_WITH_VAL(3.));
REQUIRE_IMU(mean, old_mean + (3. - 1.)/window_size);
// back(): 3, as just declared
REQUIRE_IMU(filter.get_buffer().back(), 3.);
// front(): 2.
REQUIRE_IMU(filter.get_buffer().front(), 2.);
// Update with 2: mean (2.33333) += (back (now 2) - front(now 2)/3)
auto old_imu_mean = filter.get_mean();
mean = filter.update(IMU_WITH_VAL(2.));
REQUIRE(mean == old_imu_mean);
// back(): 2.
REQUIRE_IMU(filter.get_buffer().back(), 2.);
}
| 31.007937
| 146
| 0.609931
|
uos
|
a37b1edcef6f3db71b01218a180dc14bf92cc17d
| 3,907
|
hpp
|
C++
|
include/range/v3/algorithm/minmax_element.hpp
|
mydeveloperday/range-v3
|
66c9f5fb528f55b75c5737199bd7bd82a39b8613
|
[
"MIT"
] | 1
|
2019-07-21T02:51:05.000Z
|
2019-07-21T02:51:05.000Z
|
include/range/v3/algorithm/minmax_element.hpp
|
mydeveloperday/range-v3
|
66c9f5fb528f55b75c5737199bd7bd82a39b8613
|
[
"MIT"
] | null | null | null |
include/range/v3/algorithm/minmax_element.hpp
|
mydeveloperday/range-v3
|
66c9f5fb528f55b75c5737199bd7bd82a39b8613
|
[
"MIT"
] | null | null | null |
/// \file
// Range v3 library
//
// Copyright Eric Niebler 2014-present
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
// Implementation based on the code in libc++
// http://http://libcxx.llvm.org/
#ifndef RANGES_V3_ALGORITHM_MINMAX_ELEMENT_HPP
#define RANGES_V3_ALGORITHM_MINMAX_ELEMENT_HPP
#include <range/v3/range_fwd.hpp>
#include <range/v3/algorithm/result_types.hpp>
#include <range/v3/functional/comparisons.hpp>
#include <range/v3/functional/identity.hpp>
#include <range/v3/functional/invoke.hpp>
#include <range/v3/iterator/concepts.hpp>
#include <range/v3/iterator/traits.hpp>
#include <range/v3/range/access.hpp>
#include <range/v3/range/concepts.hpp>
#include <range/v3/range/dangling.hpp>
#include <range/v3/range/traits.hpp>
#include <range/v3/utility/static_const.hpp>
namespace ranges
{
/// \addtogroup group-algorithms
/// @{
template<typename I>
using minmax_element_result = detail::min_max_result<I, I>;
struct minmax_element_fn
{
template<typename I, typename S, typename C = less, typename P = identity>
auto operator()(I begin, S end, C pred = C{}, P proj = P{}) const
-> CPP_ret(minmax_element_result<I>)( //
requires ForwardIterator<I> && Sentinel<S, I> &&
IndirectStrictWeakOrder<C, projected<I, P>>)
{
minmax_element_result<I> result{begin, begin};
if(begin == end || ++begin == end)
return result;
if(invoke(pred, invoke(proj, *begin), invoke(proj, *result.min)))
result.min = begin;
else
result.max = begin;
while(++begin != end)
{
I tmp = begin;
if(++begin == end)
{
if(invoke(pred, invoke(proj, *tmp), invoke(proj, *result.min)))
result.min = tmp;
else if(!invoke(pred, invoke(proj, *tmp), invoke(proj, *result.max)))
result.max = tmp;
break;
}
else
{
if(invoke(pred, invoke(proj, *begin), invoke(proj, *tmp)))
{
if(invoke(pred, invoke(proj, *begin), invoke(proj, *result.min)))
result.min = begin;
if(!invoke(pred, invoke(proj, *tmp), invoke(proj, *result.max)))
result.max = tmp;
}
else
{
if(invoke(pred, invoke(proj, *tmp), invoke(proj, *result.min)))
result.min = tmp;
if(!invoke(pred, invoke(proj, *begin), invoke(proj, *result.max)))
result.max = begin;
}
}
}
return result;
}
template<typename Rng, typename C = less, typename P = identity>
auto operator()(Rng && rng, C pred = C{}, P proj = P{}) const
-> CPP_ret(minmax_element_result<safe_iterator_t<Rng>>)( //
requires ForwardRange<Rng> &&
IndirectStrictWeakOrder<C, projected<iterator_t<Rng>, P>>)
{
return (*this)(begin(rng), end(rng), std::move(pred), std::move(proj));
}
};
/// \sa `minmax_element_fn`
/// \ingroup group-algorithms
RANGES_INLINE_VARIABLE(minmax_element_fn, minmax_element)
namespace cpp20
{
using ranges::minmax_element;
using ranges::minmax_element_result;
} // namespace cpp20
/// @}
} // namespace ranges
#endif // include guard
| 35.518182
| 90
| 0.545943
|
mydeveloperday
|
a37b95ceddd85e6528c2d8abcc637d1579eae73f
| 2,315
|
hpp
|
C++
|
abcd/wallet/Wallet.hpp
|
Airbitz/airbitz-core-private
|
dc6742a5622f6d8bae750e60fcee3bb473bc67ce
|
[
"BSD-2-Clause-FreeBSD"
] | 1
|
2021-05-28T02:52:00.000Z
|
2021-05-28T02:52:00.000Z
|
abcd/wallet/Wallet.hpp
|
Airbitz/airbitz-core-private
|
dc6742a5622f6d8bae750e60fcee3bb473bc67ce
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
abcd/wallet/Wallet.hpp
|
Airbitz/airbitz-core-private
|
dc6742a5622f6d8bae750e60fcee3bb473bc67ce
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
/*
* Copyright (c) 2015, Airbitz, Inc.
* All rights reserved.
*
* See the LICENSE file for more information.
*/
#ifndef ABCD_WALLET_WALLET_HPP
#define ABCD_WALLET_WALLET_HPP
#include "../WalletPaths.hpp"
#include "../util/Data.hpp"
#include "../util/Status.hpp"
#include "AddressDb.hpp"
#include "TxDb.hpp"
#include <atomic>
#include <memory>
#include <mutex>
namespace abcd {
class Account;
class Cache;
/**
* Manages the information stored in the top-level wallet sync directory.
*/
class Wallet:
public std::enable_shared_from_this<Wallet>
{
public:
~Wallet();
Account &account;
WalletPaths paths;
static Status
create(std::shared_ptr<Wallet> &result, Account &account,
const std::string &id);
static Status
createNew(std::shared_ptr<Wallet> &result, Account &account,
const std::string &name, int currency);
const std::string &id() const { return id_; }
const DataChunk &bitcoinKey() const;
const DataChunk &dataKey() const { return dataKey_; }
int currency() const;
std::string name() const;
Status nameSet(const std::string &name);
// Balance cache:
Status balance(int64_t &result);
void balanceDirty();
/**
* Return the XPub of this wallet
*/
std::string
bitcoinXPub(void);
/**
* Syncs the account with the file server.
* This is a blocking network operation.
*/
Status
sync(bool &dirty);
private:
mutable std::mutex mutex_;
const std::shared_ptr<Account> parent_;
const std::string id_;
// Account data:
DataChunk bitcoinKey_;
DataChunk bitcoinKeyBackup_;
std::string bitcoinXPub_;
std::string bitcoinXPubBackup_;
DataChunk dataKey_;
std::string syncKey_;
// Sync dir data:
int currency_;
std::string name_;
Status currencySet(int currency);
// Balance cache:
int64_t balance_;
std::atomic<bool> balanceDirty_;
Wallet(Account &account, const std::string &id);
Status
createNew(const std::string &name, int currency);
Status
loadKeys();
/**
* Loads the synced data, performing an initial sync if necessary.
*/
Status
loadSync();
public:
AddressDb addresses;
TxDb txs;
Cache &cache;
};
} // namespace abcd
#endif
| 19.956897
| 73
| 0.6527
|
Airbitz
|
a37db42f3bb6cddee63291b6110b491cc592d6d7
| 1,526
|
cpp
|
C++
|
src/tools/tools/src/assets/importers/codegen_importer.cpp
|
lye/halley
|
16b6c9783e4b21377f902a9d02366c1f19450a21
|
[
"Apache-2.0"
] | 1
|
2019-11-27T20:23:45.000Z
|
2019-11-27T20:23:45.000Z
|
src/tools/tools/src/assets/importers/codegen_importer.cpp
|
lye/halley
|
16b6c9783e4b21377f902a9d02366c1f19450a21
|
[
"Apache-2.0"
] | null | null | null |
src/tools/tools/src/assets/importers/codegen_importer.cpp
|
lye/halley
|
16b6c9783e4b21377f902a9d02366c1f19450a21
|
[
"Apache-2.0"
] | null | null | null |
#include "codegen_importer.h"
#include "halley/tools/codegen/codegen.h"
#include "halley/tools/assets/import_assets_database.h"
using namespace Halley;
String CodegenImporter::getAssetId(const Path& file, const Maybe<Metadata>& metadata) const
{
return ":codegen";
}
void CodegenImporter::import(const ImportingAsset& asset, IAssetCollector& collector)
{
Codegen codegen;
std::vector<std::pair<String, gsl::span<const gsl::byte>>> srcs;
int n = 0;
for (auto& f : asset.inputFiles) {
if (!collector.reportProgress(lerp(0.0f, 0.25f, float(n) / asset.inputFiles.size()), "Loading sources")) {
return;
}
srcs.push_back(std::make_pair(f.name.string(), gsl::as_bytes(gsl::span<const Byte>(f.data))));
++n;
}
codegen.loadSources(srcs, [&](float progress, String label) -> bool {
return collector.reportProgress(lerp(0.0f, 0.25f, progress), "Loading " + label);
});
if (!collector.reportProgress(0.25f, "Validating")) {
return;
}
codegen.validate([&](float progress, String label) -> bool {
return collector.reportProgress(lerp(0.25f, 0.5f, progress), "Validating " + label);
});
if (!collector.reportProgress(0.50f, "Processing")) {
return;
}
codegen.process();
if (!collector.reportProgress(0.75f, "Generating code")) {
return;
}
codegen.generateCode(collector.getDestinationDirectory(), [&](float progress, String label) -> bool {
return collector.reportProgress(lerp(0.75f, 1.0f, progress), "Generating " + label);
});
if (!collector.reportProgress(0.999f, "")) {
return;
}
}
| 29.346154
| 108
| 0.700524
|
lye
|
a37f7c3cc14918f2e9da1d69fb355ce6cb374cb3
| 8,966
|
hpp
|
C++
|
tsig/signal.hpp
|
tprk77/tsig
|
33e9365b6d2b15c3a363e2f1ccde400e889a5f69
|
[
"MIT"
] | null | null | null |
tsig/signal.hpp
|
tprk77/tsig
|
33e9365b6d2b15c3a363e2f1ccde400e889a5f69
|
[
"MIT"
] | null | null | null |
tsig/signal.hpp
|
tprk77/tsig
|
33e9365b6d2b15c3a363e2f1ccde400e889a5f69
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2019 Tim Perkins
// 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.
#ifndef TSIG_SIGNAL_HPP
#define TSIG_SIGNAL_HPP
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <vector>
#if defined(__GNUC__) && (__GNUC__ >= 4)
#define TSIG_CHECK_RESULT __attribute__((warn_unused_result))
#elif defined(_MSC_VER) && (_MSC_VER >= 1700)
#define TSIG_CHECK_RESULT _Check_return_
#else
#define TSIG_CHECK_RESULT
#endif
namespace tsig {
// template <typename Dispatcher>
// class SignalFactory;
class Sigcon;
template <typename Func>
class Signal;
template <typename Func>
class SignalConnector;
namespace detail {
static constexpr std::size_t INVALID_HANDLER_ID = std::numeric_limits<std::size_t>::max();
class SigdatBase;
template <typename Func>
class Sigdat;
} // namespace detail
class Sigcon {
template <typename Func>
friend class Signal;
template <typename Func>
friend class SignalConnector;
public:
Sigcon();
Sigcon(const Sigcon&) = delete;
Sigcon(Sigcon&& sigcon);
~Sigcon();
Sigcon& operator=(const Sigcon&) = delete;
Sigcon& operator=(Sigcon&& sigcon);
void Reset();
private:
Sigcon(const std::weak_ptr<detail::SigdatBase>& sigdat_wptr, std::size_t handler_id);
std::weak_ptr<detail::SigdatBase> sigdat_wptr_;
std::size_t handler_id_;
};
template <typename... Param>
class Signal<void(Param...)> {
friend class SignalConnector<void(Param...)>;
public:
using Handler = std::function<void(Param...)>;
Signal();
Signal(const Signal&) = delete;
Signal(Signal&& signal) = default;
Signal& operator=(const Signal&) = delete;
Signal& operator=(Signal&& signal) = default;
TSIG_CHECK_RESULT Sigcon Connect(const Handler& handler);
TSIG_CHECK_RESULT Sigcon Connect(Handler&& handler);
void Emit(Param&&... param) const;
private:
std::shared_ptr<detail::Sigdat<void(Param...)>> sigdat_ptr_;
};
// template <typename Ret, typename ...Param>
// class Signal<Ret(Param...)> : private SignalBase {
// };
template <typename Func>
class SignalConnector {
public:
using Handler = typename Signal<Func>::Handler;
explicit SignalConnector(Signal<Func>& signal);
SignalConnector(const SignalConnector&) = default;
SignalConnector(SignalConnector&&) = default;
SignalConnector& operator=(const SignalConnector&) = default;
SignalConnector& operator=(SignalConnector&&) = default;
TSIG_CHECK_RESULT Sigcon Connect(const Handler& handler);
TSIG_CHECK_RESULT Sigcon Connect(Handler&& handler);
TSIG_CHECK_RESULT Sigcon operator()(const Handler& handler);
TSIG_CHECK_RESULT Sigcon operator()(Handler&& handler);
private:
std::weak_ptr<detail::Sigdat<Func>> sigdat_wptr_;
};
template <typename Func>
SignalConnector<Func> MakeSignalConnector(Signal<Func>& signal);
namespace detail {
class SigdatBase {
public:
virtual ~SigdatBase() = default;
virtual void RemoveHandler(std::size_t handler_id) = 0;
};
template <typename... Param>
class Sigdat<void(Param...)> final : public SigdatBase {
public:
using Handler = std::function<void(Param...)>;
std::size_t AddHandler(const Handler& handler);
std::size_t AddHandler(Handler&& handler);
void CallHandlers(Param&&... param) const;
void RemoveHandler(std::size_t handler_id) final;
private:
std::size_t incremental_handler_id_ = 0u;
std::map<std::size_t, std::shared_ptr<Handler>> handler_ptrs_;
};
} // namespace detail
Sigcon::Sigcon() : handler_id_(detail::INVALID_HANDLER_ID)
{
// Do nothing
}
Sigcon::Sigcon(const std::weak_ptr<detail::SigdatBase>& sigdat_wptr, std::size_t handler_id)
: sigdat_wptr_(sigdat_wptr), handler_id_(handler_id)
{
// Do nothing
}
Sigcon::Sigcon(Sigcon&& sigcon) : sigdat_wptr_(sigcon.sigdat_wptr_), handler_id_(sigcon.handler_id_)
{
sigcon.sigdat_wptr_.reset();
sigcon.handler_id_ = detail::INVALID_HANDLER_ID;
}
Sigcon::~Sigcon()
{
const std::shared_ptr<detail::SigdatBase> sigdat_ptr = sigdat_wptr_.lock();
if (sigdat_ptr) {
sigdat_ptr->RemoveHandler(handler_id_);
}
}
Sigcon& Sigcon::operator=(Sigcon&& sigcon)
{
// Remove the handler if there was one
const std::shared_ptr<detail::SigdatBase> sigdat_ptr = sigdat_wptr_.lock();
if (sigdat_ptr) {
sigdat_ptr->RemoveHandler(handler_id_);
}
// Transfer over the handler info
sigdat_wptr_ = sigcon.sigdat_wptr_;
handler_id_ = sigcon.handler_id_;
// Clean up the old handler info
sigcon.sigdat_wptr_.reset();
sigcon.handler_id_ = detail::INVALID_HANDLER_ID;
return *this;
}
void Sigcon::Reset()
{
// Remove the handler if there was one
const std::shared_ptr<detail::SigdatBase> sigdat_ptr = sigdat_wptr_.lock();
if (sigdat_ptr) {
sigdat_ptr->RemoveHandler(handler_id_);
}
// Clean up the handler info
sigdat_wptr_.reset();
handler_id_ = detail::INVALID_HANDLER_ID;
}
template <typename... Param>
Signal<void(Param...)>::Signal() : sigdat_ptr_(std::make_shared<detail::Sigdat<void(Param...)>>())
{
// Do nothing
}
template <typename... Param>
Sigcon Signal<void(Param...)>::Connect(const Signal::Handler& handler)
{
const std::size_t handler_id = sigdat_ptr_->AddHandler(handler);
return Sigcon(sigdat_ptr_, handler_id);
}
template <typename... Param>
Sigcon Signal<void(Param...)>::Connect(Signal::Handler&& handler)
{
const std::size_t handler_id = sigdat_ptr_->AddHandler(std::move(handler));
return Sigcon(sigdat_ptr_, handler_id);
}
template <typename... Param>
void Signal<void(Param...)>::Emit(Param&&... param) const
{
sigdat_ptr_->CallHandlers(std::forward<Param>(param)...);
}
template <typename Func>
SignalConnector<Func>::SignalConnector(Signal<Func>& signal) : sigdat_wptr_(signal.sigdat_ptr_)
{
// Do nothing
}
template <typename Func>
Sigcon SignalConnector<Func>::Connect(const Handler& handler)
{
const std::shared_ptr<detail::Sigdat<Func>> sigdat_ptr = sigdat_wptr_.lock();
if (!sigdat_ptr) {
return {};
}
const std::size_t handler_id = sigdat_ptr->AddHandler(handler);
return Sigcon(sigdat_ptr, handler_id);
}
template <typename Func>
Sigcon SignalConnector<Func>::Connect(Handler&& handler)
{
const std::shared_ptr<detail::Sigdat<Func>> sigdat_ptr = sigdat_wptr_.lock();
if (!sigdat_ptr) {
return {};
}
const std::size_t handler_id = sigdat_ptr->AddHandler(std::move(handler));
return Sigcon(sigdat_ptr, handler_id);
}
template <typename Func>
Sigcon SignalConnector<Func>::operator()(const Handler& handler)
{
return Connect(handler);
}
template <typename Func>
Sigcon SignalConnector<Func>::operator()(Handler&& handler)
{
return Connect(std::move(handler));
}
template <typename Func>
SignalConnector<Func> MakeSignalConnector(Signal<Func>& signal)
{
return SignalConnector<Func>(signal);
}
namespace detail {
template <typename... Param>
std::size_t Sigdat<void(Param...)>::AddHandler(const Handler& handler)
{
handler_ptrs_.emplace(incremental_handler_id_, std::make_shared<Handler>(handler));
return incremental_handler_id_++;
}
template <typename... Param>
std::size_t Sigdat<void(Param...)>::AddHandler(Handler&& handler)
{
handler_ptrs_.emplace(incremental_handler_id_, std::make_shared<Handler>(std::move(handler)));
return incremental_handler_id_++;
}
template <typename... Param>
void Sigdat<void(Param...)>::CallHandlers(Param&&... param) const
{
// Copy handlers to prevent in-flight modifications
const auto handler_ptrs = handler_ptrs_;
// TODO It would be more efficient to only copy if a modification takes place
for (const auto& handler_pair : handler_ptrs) {
const std::shared_ptr<Handler> handler_ptr = std::get<1>(handler_pair);
// TODO Better exception handling
(*handler_ptr)(std::forward<Param>(param)...);
}
}
template <typename... Param>
void Sigdat<void(Param...)>::RemoveHandler(std::size_t handler_id)
{
handler_ptrs_.erase(handler_id);
}
} // namespace detail
} // namespace tsig
#undef TSIG_CHECK_RESULT
#endif // TSIG_SIGNAL_HPP
| 27.087613
| 100
| 0.73511
|
tprk77
|
a384ba3619b105548dc3cc788e75488429287091
| 1,347
|
hpp
|
C++
|
include/CL/sycl/allocator.hpp
|
infinitesnow/InceptionCL
|
e3d3a6218e551d42dfcead4f121cec294d50d85c
|
[
"Unlicense"
] | 2
|
2017-10-05T13:13:41.000Z
|
2019-05-15T19:20:49.000Z
|
include/CL/sycl/allocator.hpp
|
infinitesnow/InceptionCL
|
e3d3a6218e551d42dfcead4f121cec294d50d85c
|
[
"Unlicense"
] | null | null | null |
include/CL/sycl/allocator.hpp
|
infinitesnow/InceptionCL
|
e3d3a6218e551d42dfcead4f121cec294d50d85c
|
[
"Unlicense"
] | null | null | null |
#ifndef TRISYCL_SYCL_ALLOCATOR_HPP
#define TRISYCL_SYCL_ALLOCATOR_HPP
/** \file The OpenCL SYCL allocator
Ronan at Keryell point FR
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
*/
#include <memory>
namespace cl {
namespace sycl {
/** \addtogroup data Data access and storage in SYCL
@{
*/
/** The allocator objects give the programmer some control on how the
memory is allocated inside SYCL
*/
/** The allocator used for the \c buffer inside SYCL
Just use the default allocator for now.
*/
template <typename T>
using buffer_allocator = std::allocator<T>;
/** The allocator used for the \c image inside SYCL
Just use the default allocator for now.
*/
template <typename T>
using image_allocator = std::allocator<T>;
/** The allocator used to map the memory at the same place
Just use the default allocator for now.
\todo : implement and clarify the specification. It looks like it
is not really an allocator according the current spec
*/
template <typename T>
using map_allocator = std::allocator<T>;
/// @} End the data Doxygen group
}
}
/*
# Some Emacs stuff:
### Local Variables:
### ispell-local-dictionary: "american"
### eval: (flyspell-prog-mode)
### End:
*/
#endif // TRISYCL_SYCL_ALLOCATOR_HPP
| 20.409091
| 73
| 0.708983
|
infinitesnow
|
a388af8cb175fc2b3c509e22bbc2b5dd2c68b26a
| 1,871
|
cpp
|
C++
|
arkana-lib/crc32/crc32.cpp
|
ttsuki/arkana
|
3681f32b1ebe7f14aee03d7abc88467672aec573
|
[
"MIT"
] | null | null | null |
arkana-lib/crc32/crc32.cpp
|
ttsuki/arkana
|
3681f32b1ebe7f14aee03d7abc88467672aec573
|
[
"MIT"
] | null | null | null |
arkana-lib/crc32/crc32.cpp
|
ttsuki/arkana
|
3681f32b1ebe7f14aee03d7abc88467672aec573
|
[
"MIT"
] | null | null | null |
/// @file
/// @brief arkana::crc32
/// - An implementation of CRC32
/// @author Copyright(c) 2020 ttsuki
///
/// This software is released under the MIT License.
/// https://opensource.org/licenses/MIT
#include "../crc32.h"
#include <arkana/bits/cpuid.h>
namespace arkana::crc32
{
crc32_value_t calculate_crc32(const void* data, size_t length, crc32_value_t current)
{
if (cpuid::cpu_supports::AVX2 && cpuid::cpu_supports::PCLMULQDQ)
return calculate_crc32_avx2clmul(data, length, current);
if (cpuid::cpu_supports::AVX2)
return calculate_crc32_avx2(data, length, current);
return calculate_crc32_ia32(data, length, current);
}
std::unique_ptr<crc32_context_t> create_crc32_context(crc32_value_t initial)
{
if (cpuid::cpu_supports::AVX2 && cpuid::cpu_supports::PCLMULQDQ)
return create_crc32_context_avx2clmul(initial);
if (cpuid::cpu_supports::AVX2)
return create_crc32_context_avx2(initial);
return create_crc32_context_ia32(initial);
}
}
#include <arkana/crc32/crc32.h>
namespace arkana::crc32
{
crc32_value_t calculate_crc32_ref(const void* data, size_t length, crc32_value_t current)
{
return ref::calculate_crc32<0xEDB88320>(data, length, current);
}
std::unique_ptr<crc32_context_t> create_crc32_context_ref(crc32_value_t initial)
{
struct crc32_context_impl_t final : public virtual crc32_context_t
{
crc32_value_t value{};
crc32_context_impl_t(crc32_value_t initial) : value(initial) { }
crc32_value_t current() const override { return value; }
void update(const void* data, size_t length) override { value = calculate_crc32_ref(data, length, value); }
};
return std::make_unique<crc32_context_impl_t>(initial);
}
}
| 31.711864
| 119
| 0.683057
|
ttsuki
|
a38eccb952d70edc3b07f4e3c78016ceb414ba67
| 21,648
|
cc
|
C++
|
examples/comps/egl_gl_fbo.cc
|
halleyzhao/alios-mm
|
bef2a6de0c207a5ae9bf4f63de2e562df864aa3e
|
[
"Apache-2.0"
] | null | null | null |
examples/comps/egl_gl_fbo.cc
|
halleyzhao/alios-mm
|
bef2a6de0c207a5ae9bf4f63de2e562df864aa3e
|
[
"Apache-2.0"
] | null | null | null |
examples/comps/egl_gl_fbo.cc
|
halleyzhao/alios-mm
|
bef2a6de0c207a5ae9bf4f63de2e562df864aa3e
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <pthread.h>
#include "egl_gl_fbo.h"
#include "multimedia/mm_debug.h"
#include "WaylandConnection.h"
#include <Surface.h>
MM_LOG_DEFINE_MODULE_NAME("EGL-FBO")
#if 0
#undef DEBUG
#undef INFO
#undef WARNING
#undef ERROR
#define DEBUG(format, ...) printf("[D] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__)
#define INFO(format, ...) printf("[I] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__)
#define WARNING(format, ...) printf("[W] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__)
#define ERROR(format, ...) printf("[E] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__)
#endif
#define FUNC_TRACK() FuncTracker tracker(MM_LOG_TAG, __FUNCTION__, __LINE__)
// #define FUNC_TRACK()
#define CHECK_GL_ERROR() do { \
int error = glGetError(); \
if (error != GL_NO_ERROR) \
ERROR("glGetError() = %d", error); \
} while (0)
// shader source
#define SHADER(Src) #Src
// draw yuv texture
const char* vs0 =SHADER(
attribute vec2 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_texcoord = texcoord;
}
);
const char* fs0 = "#extension GL_OES_EGL_image_external : require \n" SHADER(
precision mediump float;
varying vec2 v_texcoord;
uniform samplerExternalOES sampler;
void main() {
gl_FragColor = texture2D(sampler, v_texcoord);
}
);
// render to YUV FBO
const char* vs1 = "#version 300 es \n" \
SHADER(
in vec2 position;
in vec2 texcoord;
out vec2 v_texcoord;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_texcoord = texcoord;
}
);
const char* fs1 = "#version 300 es \n" \
"#extension GL_EXT_YUV_target : require \n" \
SHADER(
precision mediump float;
layout (yuv) out vec4 fragColor ;
in vec2 v_texcoord;
uniform sampler2D sampler;
void main() {
fragColor = texture(sampler, v_texcoord);
}
);
// gl_FragColor = texture2D(sampler, v_texcoord);
// layout (yuv) out vec4 color;
// yuvCscStandardEXT conv = itu_601;
#undef SHADER
// FIXME, FBO doesn't require native display/surface, but not reality yet (fail to eglCreateWindowSurface())
class WorkAroundEglInit {
public:
static void Init() {
mConnection = new yunos::wpc::WaylandConnection(NULL);
mWlSurface = mConnection->compositor_create_surface();
struct wl_egl_window_copy* tmp = (struct wl_egl_window_copy*)malloc(sizeof(struct wl_egl_window_copy));
memset(tmp, 0, sizeof(struct wl_egl_window_copy));
tmp->surface = mWlSurface;
tmp->attached_width = 0;
tmp->attached_height = 0;
tmp->nativewindow = 0;
mEglWindow = (struct wl_egl_window*)tmp;
ASSERT(mConnection && mWlSurface && mEglWindow);
mInited = true;
}
static void Deinit() {
usleep(50000);
mConnection->destroy_surface(mWlSurface);
mConnection->dec_ref();
delete mConnection;
free(mEglWindow);
mConnection = NULL;
mWlSurface = NULL;
}
static struct wl_display* getNativeDisplay() {
if (!mInited)
Init();
return mConnection->get_wayland_display();
}
static struct wl_egl_window* getNativeSurface() { return mEglWindow; }
private:
// hack, copied from wayland, with additional padding
struct wl_egl_window_copy {
struct wl_surface *surface;
int width;
int height;
int dx;
int dy;
int attached_width;
int attached_height;
void *nativewindow;
void (*resize_callback)(struct wl_egl_window *, void *);
void (*free_callback)(struct wl_egl_window *, void *);
uint8_t padding[20];
};
public: // C++ should support 'private-static' variable declare/define at the same time. however fails
static yunos::wpc::WaylandConnection* mConnection;
static struct wl_surface* mWlSurface; // a wl_surface to work around eglCreateWindowSurface issue
static struct wl_egl_window* mEglWindow;
static bool mInited;
};
yunos::wpc::WaylandConnection* WorkAroundEglInit::mConnection = NULL;
struct wl_surface* WorkAroundEglInit::mWlSurface = NULL;
struct wl_egl_window* WorkAroundEglInit::mEglWindow = NULL;
bool WorkAroundEglInit::mInited = false;
// ##################################################
static void printGLString() {
typedef struct {
const char* str;
GLenum e;
}GLString;
GLString glStrings[] = {
{"Version", GL_VERSION},
{"Vendor", GL_VENDOR},
{ "Renderer", GL_RENDERER},
{ "Extensions", GL_EXTENSIONS}
};
uint32_t i =0;
for (i=0; i<sizeof(glStrings)/sizeof (GLString); i++) {
const char *v = (const char *) glGetString(glStrings[i].e);
INFO("GL %s = %s", glStrings[i].str, v);
}
}
// parameter to init EGL
static const EGLint context_attribs[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
static EGLint config_attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_ALPHA_SIZE, 1,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, // use gles v3
EGL_NONE
};
// singleton/global context
static EGLDisplay eglDisplay = NULL;
static EGLConfig eglConfig = NULL; // choosed EGLConfig
static EGLConfig* configs; // all possible EGLConfigs
#ifndef GL_GLEXT_PROTOTYPES
static PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR;
static PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR;
static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES;
static PFNGLDRAWBUFFERSEXTPROC glDrawBuffersEXT;
#endif
// shader program for gles2
unsigned LoadShader(unsigned type, const std::string& source) {
FUNC_TRACK();
unsigned shader = glCreateShader(type);
const char* src = source.data();
if (shader) {
glShaderSource(shader, 1, &src, NULL);
glCompileShader(shader);
int compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
char logInfo[4096];
glGetShaderInfoLog(shader, sizeof(logInfo), NULL, logInfo);
ERROR("compile shader logInfo = %s\n", logInfo);
DEBUG("shader source:\n %s\n", src);
ASSERT(0 && "compile fragment shader failed");
glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
unsigned LoadProgram(const std::string& vertex_source, const std::string& fragment_source) {
FUNC_TRACK();
unsigned vertex_shader = LoadShader(GL_VERTEX_SHADER, vertex_source);
unsigned fragment_shader = LoadShader(GL_FRAGMENT_SHADER, fragment_source);
unsigned program = glCreateProgram();
if (vertex_shader && fragment_shader && program) {
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
int linked = 0;
glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (!linked) {
ASSERT(0 && "link shader program failed");
glDeleteProgram(program);
program = 0;
}
}
if (vertex_shader)
glDeleteShader(vertex_shader);
if (fragment_shader)
glDeleteShader(fragment_shader);
return program;
}
// destroy egl global context
static void destroyEglGlobal() __attribute__((destructor(203)));
static void destroyEglGlobal() {
if (!eglDisplay)
return;
printf("%s, about to call elgTerminate\n", __func__);
eglTerminate(eglDisplay);
free(configs);
configs = NULL;
eglDisplay= NULL;
eglConfig = NULL;
printf("%s, done\n", __func__);
WorkAroundEglInit::Deinit();
}
// init the global env for all eglContext
static bool ensureEglGlobal()
{
FUNC_TRACK();
EGLint major, minor;
EGLBoolean ret = EGL_FALSE;
EGLint count = -1, n = 0, i = 0, size = 0;
WorkAroundEglInit::Init();
if (eglDisplay && eglConfig)
return true;
ASSERT(!eglDisplay && !eglConfig);
#ifndef GL_GLEXT_PROTOTYPES
eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC) eglGetProcAddress("eglCreateImageKHR");
ASSERT(eglCreateImageKHR != NULL);
eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC) eglGetProcAddress("eglDestroyImageKHR");
ASSERT(eglDestroyImageKHR != NULL);
glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress("glEGLImageTargetTexture2DOES");
ASSERT(glEGLImageTargetTexture2DOES != NULL);
glDrawBuffersEXT = (PFNGLDRAWBUFFERSEXTPROC)eglGetProcAddress("glDrawBuffersEXT");
ASSERT(glDrawBuffersEXT != NULL);
#endif
#ifdef YUNOS_ENABLE_UNIFIED_SURFACE
eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
#elif PLUGIN_HAL // FIXME, use EGL_DEFAULT_DISPLAY
eglDisplay = eglGetDisplay(WorkAroundEglInit::getNativeDisplay());
#else
eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
#endif
ASSERT(eglDisplay != NULL);
ret = eglInitialize(eglDisplay, &major, &minor);
ASSERT(ret == EGL_TRUE);
ret = eglBindAPI(EGL_OPENGL_ES_API);
ASSERT(ret == EGL_TRUE);
if (!eglGetConfigs(eglDisplay, NULL, 0, &count) || count < 1)
ASSERT(0);
configs = (EGLConfig*)malloc(sizeof(EGLConfig) * count);
ASSERT(configs);
memset(configs, 0, sizeof(EGLConfig) * count);
ret = eglChooseConfig(eglDisplay, config_attribs, configs, count, &n);
ASSERT(ret && n >= 1);
for (i = 0; i < n; i++) {
eglGetConfigAttrib(eglDisplay, configs[i], EGL_BUFFER_SIZE, &size);
if (32 == size) {
eglConfig = configs[i];
break;
}
}
DEBUG("ensureEglGlobal done");
return true;
}
namespace YUNOS_MM {
// ################################################################
// EGL context per window
EglWindowContext::EglWindowContext()
: mWidth(0), mHeight(0)
, mEglSurface(EGL_NO_SURFACE), mEglContext(EGL_NO_CONTEXT)
, mCurrTexId(0), mUseSingleTexture(true)
{
FUNC_TRACK();
int i=0;
for (i=0; i<MAX_BUFFER_NUM; i++) {
mBufferInfo[i].anb = NULL;
mBufferInfo[i].texId = 0;
mBufferInfo[i].img = EGL_NO_IMAGE_KHR;
}
for (i=0; i<2; i++) {
mProgramId[i] = 0;
mVertexPointerHandle[i] = -1;
mVertexTextureHandle[i] = -1;
mSamplerHandle[i] = -1;
}
mRgbxTexId[0] = 0;
mRgbxTexId[1] = 0;
mUseSingleTexture = YUNOS_MM::mm_check_env_str("mm.test.use.single.texture", "MM_TEST_USE_SINGLE_TEXTURE", "1", true);
}
/* usually, FBO doesn't require native-display to init EGL, doesn't require native-window to create EGLSurface.
* however, it isn't the fact on our platform yet.
*/
bool EglWindowContext::init(/*void* nativeDisplay, void* nativeWindow*/)
{
FUNC_TRACK();
EGLBoolean ret;
if (!ensureEglGlobal())
return false;
// shader source code
static const char* vs[2] = {vs0, vs1};
const char* fs[2] = {fs0, fs1};
// init EGL/GLES context
mEglContext = eglCreateContext(eglDisplay, eglConfig, NULL, context_attribs);
void *w = NULL;
// a NULL native surface to create EGLSurface should be ok (especially for FBO), however it fails. let's work around it
w = WorkAroundEglInit::getNativeSurface();
mEglSurface = eglCreateWindowSurface(eglDisplay, eglConfig,
(EGLNativeWindowType)w, NULL);
ASSERT(mEglContext != EGL_NO_CONTEXT && mEglSurface != EGL_NO_SURFACE);
ret = eglMakeCurrent(eglDisplay, mEglSurface, mEglSurface, mEglContext);
ASSERT(ret == EGL_TRUE);
printGLString();
// compile and link shader program
uint32_t i, j;
for (i=0; i<2; i++) {
ASSERT(mProgramId[i] == 0 && mVertexPointerHandle[i] == -1 && mVertexTextureHandle[i] == -1 && mSamplerHandle[i] == -1);
mProgramId[i] = LoadProgram(vs[i], fs[i]);
ASSERT(mProgramId);
glUseProgram(mProgramId[i]);
mVertexPointerHandle[i] = glGetAttribLocation(mProgramId[i], "position");
mVertexTextureHandle[i] = glGetAttribLocation(mProgramId[i], "texcoord");
mSamplerHandle[i] = glGetUniformLocation(mProgramId[i], "sampler");
// ASSERT(GLenum(GL_NO_ERROR) == glGetError());
ASSERT(mVertexPointerHandle[i] != -1);
// ASSERT(mVertexPointerHandle[i] != -1 && mVertexTextureHandle[i] != -1 && mSamplerHandle[i] != -1);
DEBUG("index: %d, mVertexPointerHandle: %d, mVertexTextureHandle: %d, mSamplerHandle: %d",
i, mVertexPointerHandle[i], mVertexTextureHandle[i], mSamplerHandle[i]);
}
// create temp RGBX texture test. [0] uses as src to draw rect, [1] uses as fbo;
// use same resolution as WindowSurface, so we needn't change glViewport() for FBO
uint32_t texW = 256, texH = 256; // I tried to use video size to create these texture. but it seems late to init EGL when the first video frame comes (mediacodec stucks)
char* texData = (char*) malloc (texW * texH * 4);
glGenTextures(2, mRgbxTexId);
for (i=0; i<2; i++) {
glBindTexture(GL_TEXTURE_2D, mRgbxTexId[i]);
// memset(texData, i*0xf0, texW * texH * 4);
uint32_t *pixel = (uint32_t*)texData;
uint32_t pixelValue = 0;
if (i == 0)
pixelValue = 0x00f000ff;
else
pixelValue = 0x0000f0ff;
for (j=0; j<texW; j++ ){
*pixel++ = pixelValue;
}
for (j=1; j<texH; j++) {
memcpy(texData+j*texW*4, texData, texW*4);
}
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, texW, texH, 0,GL_RGBA, GL_UNSIGNED_BYTE, texData);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
CHECK_GL_ERROR();
}
DEBUG("mRgbxTexId[0]: %d, mRgbxTexId[1]: %d", mRgbxTexId[0], mRgbxTexId[1]);
free(texData);
DEBUG("texW: %d, texH: %d", texW, texH);
glViewport(0, 0, mWidth, mHeight);
if (mUseSingleTexture)
glGenTextures(1, &mCurrTexId);
DEBUG("mCurrTexId: %d", mCurrTexId);
return true;
}
bool EglWindowContext::deinit() {
FUNC_TRACK();
if (mUseSingleTexture && mCurrTexId)
glDeleteTextures(1, &mCurrTexId);
glDeleteTextures(2, mRgbxTexId);
int i = 0;
for (i = 0; i < MAX_BUFFER_NUM; i++) {
if (mBufferInfo[i].anb == NULL)
break;
if (mBufferInfo[i].texId)
glDeleteTextures(1, &mBufferInfo[i].texId);
eglDestroyImageKHR(eglDisplay, mBufferInfo[i].img);
mBufferInfo[i].anb = NULL;
mBufferInfo[i].texId = 0;
mBufferInfo[i].img = EGL_NO_IMAGE_KHR;
}
// Free GL resource.
for (i=0; i<2; i++) {
if (mProgramId[i]) {
glDeleteProgram(mProgramId[i]);
mProgramId[i] = 0;
mVertexPointerHandle[i] = -1;
mVertexTextureHandle[i] = -1;
mSamplerHandle[i] = -1;
}
}
ASSERT(eglDisplay != EGL_NO_DISPLAY && mEglContext != EGL_NO_CONTEXT && mEglSurface != EGL_NO_SURFACE);
eglDestroyContext(eglDisplay, mEglContext);
eglDestroySurface(eglDisplay, mEglSurface);
eglMakeCurrent(eglDisplay, NULL, NULL, NULL);
mEglContext = EGL_NO_CONTEXT;
mEglSurface = EGL_NO_SURFACE;
// workAroundEglDeinit();
return true;
}
bool EglWindowContext::bindTexture(YNativeSurfaceBuffer* anb)
{
FUNC_TRACK();
int i;
bool needBindTexture = false;
if (!anb)
return false;
for (i = 0; i < MAX_BUFFER_NUM; i++) {
if (mBufferInfo[i].anb == anb)
break;
if (mBufferInfo[i].anb == NULL) {
EGLClientBuffer clientBuffer = (EGLClientBuffer)anb;
#ifdef PLUGIN_HAL
EGLenum target = 0x3140;
#else
EGLenum target = EGL_NATIVE_BUFFER_YUNOS;
#endif
mBufferInfo[i].img = eglCreateImageKHR(eglDisplay, EGL_NO_CONTEXT, target, clientBuffer, 0);
ASSERT(mBufferInfo[i].img != EGL_NO_IMAGE_KHR);
// Note: increase ref count; since eglDestroyImageKHR will decrease one refcount for mali driver
VERBOSE("(%s, %d): eglCreateImageKHR\n", __func__, __LINE__);
if (!mUseSingleTexture)
glGenTextures(1, &mBufferInfo[i].texId);
mBufferInfo[i].anb = anb;
needBindTexture = true;
break;
}
}
if (i >= MAX_BUFFER_NUM) {
ERROR("run out of buffer, mBufferInfo is full\n");
return false;
}
if (!mUseSingleTexture)
mCurrTexId = mBufferInfo[i].texId;
glBindTexture(GL_TEXTURE_EXTERNAL_OES, mCurrTexId);
#ifdef __PHONE_BOARD_MTK__
needBindTexture = true;
#endif
if (needBindTexture || mUseSingleTexture)
glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, mBufferInfo[i].img);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES,GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES,GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES,GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES,GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// INFO("bind texture[%d]: %d for anb %p", i, mCurrTexId, anb);
glViewport(0, 0, mWidth, mHeight);
return true;
}
bool EglWindowContext::drawTestRect(GLuint tex, GLenum texTarget, int mode /* 0: center diamond, 1: left-half, 2: right-half , 3: full-window */)
{
FUNC_TRACK();
static const GLfloat vtx[] = {
// center diamond
0.0f, -0.75f,
-0.75f, 0.0f,
0.0f, 0.75f,
0.75f, 0.0f,
// half-left
-1.0f, 1.0f,
-1.0f, -1.0f,
0.0f, -1.0f,
0.0f, 1.0f,
// right-half
-0.0f, 1.0f,
-0.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
// full window
-1.0f, 1.0f,
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0, };
static const GLfloat texcoords[4][2] = {
{ 0.0f, 0.0f },
{ 0.0f, 1.0f },
{ 1.0f, 1.0f },
{ 1.0f, 0.0f },
};
int programIdx = 1;
if (texTarget == GL_TEXTURE_EXTERNAL_OES)
programIdx = 0;
glBindTexture(texTarget, tex);
glUseProgram(mProgramId[programIdx]);
glEnableVertexAttribArray(mVertexPointerHandle[programIdx]);
glVertexAttribPointer(mVertexPointerHandle[programIdx], 2, GL_FLOAT, GL_FALSE, 0, vtx+mode*8);
CHECK_GL_ERROR();
if (mVertexTextureHandle[programIdx] != -1) {
glEnableVertexAttribArray(mVertexTextureHandle[programIdx]);
glVertexAttribPointer(mVertexTextureHandle[programIdx], 2, GL_FLOAT, GL_FALSE, 0, texcoords);
}
if (mSamplerHandle[programIdx] != -1)
glUniform1i(mSamplerHandle[programIdx], 0);
CHECK_GL_ERROR();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
CHECK_GL_ERROR();
return true;
}
bool EglWindowContext::updateFbo(GLenum target, GLuint FboTex, int mode)
{
FUNC_TRACK();
GLuint mFramebuffer = 0;
DEBUG("FboTex: %d", FboTex);
glBindTexture(target, FboTex);
CHECK_GL_ERROR();
glGenFramebuffers(1, &(mFramebuffer));
glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, target, FboTex, 0);
CHECK_GL_ERROR();
GLenum pDrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffersEXT(1, pDrawBuffers);
GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
CHECK_GL_ERROR();
if( status != GL_FRAMEBUFFER_COMPLETE ) {
ERROR("error creating FBO: %d", status );
}
// draw something to FBO
drawTestRect(mRgbxTexId[0], GL_TEXTURE_2D, mode);
CHECK_GL_ERROR();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return true;
}
bool EglWindowContext::processBuffer(YNativeSurfaceBuffer* anb, uint32_t width, uint32_t height)
{
FUNC_TRACK();
mWidth = width;
mHeight = height;
if (! bindTexture(anb))
return false;
static uint32_t drawCount = 0;
drawCount++;
// 0: does nothing
// 1: use texture as FBO and does glClear().
// 2: use texture as FBO and draw a rectangle on it. it is ok on RGBX FBO but fails on YUV FBO
int drawMode = drawCount/60 % 4;
INFO("rendering mode ##################### %d anb: %p######################", drawMode, anb);
// updateFbo(GL_TEXTURE_2D, mRgbxTexId[1], true);
updateFbo(GL_TEXTURE_EXTERNAL_OES, mCurrTexId, drawMode);
return true;
}
} // end of namespace YUNOS_MM
| 33
| 173
| 0.633315
|
halleyzhao
|
a38ef7ac4e696c5480e312c8ac725e5cbbd7ab5d
| 1,567
|
hpp
|
C++
|
src/engine/graphics/camera/FPSCamera.hpp
|
raresica1234/Helltooth
|
6d30c4567c2c4a491bc72fa89a268a476ffb3e4c
|
[
"MIT"
] | 10
|
2016-04-27T20:18:26.000Z
|
2018-01-21T09:54:37.000Z
|
src/engine/graphics/camera/FPSCamera.hpp
|
Helltooth-Engine/Helltooth
|
6d30c4567c2c4a491bc72fa89a268a476ffb3e4c
|
[
"MIT"
] | 1
|
2020-02-27T07:28:19.000Z
|
2020-02-27T07:28:19.000Z
|
src/engine/graphics/camera/FPSCamera.hpp
|
Helltooth-Engine/Helltooth
|
6d30c4567c2c4a491bc72fa89a268a476ffb3e4c
|
[
"MIT"
] | 1
|
2018-09-04T19:21:00.000Z
|
2018-09-04T19:21:00.000Z
|
/*
* Copyright (c) 2020 Rareș-Nicolaie Ciorbă
*
* 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.
*
*/
#pragma once
#include "Camera.hpp"
namespace ht { namespace graphics {
class FPSCamera : public Camera {
private:
f32 m_SpeedFactor = 10; // 10 units / second
f32 m_YawSensitivity = 0.2f; // degrees / second
f32 m_PitchSensitivty = 0.2f; // degres / second
maths::Vector2 m_MouseLast;
public:
FPSCamera(const maths::Vector3& position);
FPSCamera(f32 x, f32 y, f32 z);
void Update(f32 delta) override;
};
} }
| 34.065217
| 81
| 0.738354
|
raresica1234
|
a39329124a06e3c17dc9c85989643e5aaba626b5
| 468
|
hpp
|
C++
|
Application/include/ToonMaterial.hpp
|
inhibitor1217/cs380-lighting
|
7949a743d78a4151db807c17ef89c7999a2c5334
|
[
"MIT"
] | null | null | null |
Application/include/ToonMaterial.hpp
|
inhibitor1217/cs380-lighting
|
7949a743d78a4151db807c17ef89c7999a2c5334
|
[
"MIT"
] | null | null | null |
Application/include/ToonMaterial.hpp
|
inhibitor1217/cs380-lighting
|
7949a743d78a4151db807c17ef89c7999a2c5334
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Light.hpp>
#include <Material.hpp>
class ToonMaterial : public Engine::Material
{
public:
void CreateMaterial(float terrain);
void UpdateAmbientReflectance(glm::vec3 color);
void UpdateDiffuseReflectance(glm::vec3 color);
void UpdateSpecularReflectance(glm::vec3 color);
void UpdateLight(std::vector<Light> &lights);
void UpdateFogColor(glm::vec3 color);
void UpdateTime(float time);
void UpdateCameraPos(glm::vec3 cameraPosition);
};
| 26
| 49
| 0.779915
|
inhibitor1217
|
a395cfcf332f8338cfbd2b0acb7a4202c452eaf9
| 10,625
|
cpp
|
C++
|
source/DosPopupMenu.cpp
|
ArphonePei/DOSLib
|
3aafa6b56b7910084cca96fc815aca580e1c1e3f
|
[
"MIT"
] | 37
|
2018-12-10T13:37:45.000Z
|
2022-01-29T15:45:48.000Z
|
source/DosPopupMenu.cpp
|
ArphonePei/DOSLib
|
3aafa6b56b7910084cca96fc815aca580e1c1e3f
|
[
"MIT"
] | 17
|
2020-01-31T21:12:51.000Z
|
2022-01-28T14:30:00.000Z
|
source/DosPopupMenu.cpp
|
ArphonePei/DOSLib
|
3aafa6b56b7910084cca96fc815aca580e1c1e3f
|
[
"MIT"
] | 18
|
2018-12-10T13:37:48.000Z
|
2021-06-28T09:04:46.000Z
|
/////////////////////////////////////////////////////////////////////////////
// DosPopupMenu.cpp
//
// Copyright (c) 1992-2020, Robert McNeel & Associates. All rights reserved.
// DOSLib is a trademark of Robert McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
#include "StdAfx.h"
#include "DosPopupMenu.h"
#define DOS_POPUP_SEP L"$$seperator$$"
enum constants
{
start_at = 100,
};
CDosPopupMenu::CDosPopupMenu(UINT nResourceID, HINSTANCE hInst)
: m_hMenu(0)
{
Init();
CheckDefaults(MAKEINTRESOURCE(nResourceID), hInst);
}
CDosPopupMenu::CDosPopupMenu(LPCTSTR lpsResourceID, HINSTANCE hInst)
: m_hMenu(0)
{
Init();
CheckDefaults(lpsResourceID, hInst);
}
void CDosPopupMenu::Init()
{
m_menu_select = -1;
m_menu_char = false;
m_point.x = m_point.y = 0;
m_bLeft = m_bRight = false;
}
bool CDosPopupMenu::CheckDefaults(LPCTSTR nResourceID, HINSTANCE hInst)
{
if (nResourceID)
ASSERT(hInst);
else
ASSERT(!nResourceID && !hInst);
// Nothing to do so return okay
if (!nResourceID)
return true;
m_hMenu = ::LoadMenu(hInst, nResourceID);
ASSERT(m_hMenu);
if (!m_hMenu)
return false;
return true;
}
CDosPopupMenu::~CDosPopupMenu()
{
}
int CDosPopupMenu::AddItem(LPCTSTR lpszItem)
{
m_item_array.Add(CString(lpszItem));
m_nEnabledList.Add(1);
return (int)m_nEnabledList.GetUpperBound();
}
void CDosPopupMenu::EnableItem(int nItem, BOOL bEnable)
{
if (nItem < 0 || nItem > m_nEnabledList.GetUpperBound())
return;
m_nEnabledList[nItem] = bEnable ? 1 : 0;
}
void CDosPopupMenu::AddSeperator()
{
m_item_array.Add(CString(DOS_POPUP_SEP));
}
class CDosMenuFont
{
public:
CDosMenuFont()
{
ZeroMemory((PVOID)&m_lf, sizeof(LOGFONT));
NONCLIENTMETRICS nm;
nm.cbSize = sizeof(NONCLIENTMETRICS);
//Get the system metrics for the Captionfromhere
VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, &nm, 0));
m_lf = nm.lfMenuFont;
m_iMenuHeight = nm.iMenuHeight;
m_fontMenu.CreateFontIndirect(&m_lf);
}
LOGFONT m_lf;
CFont m_fontMenu;
UINT m_iMenuHeight;
};
static LRESULT CALLBACK PopupWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
CDosPopupMenu* this_popup = (CDosPopupMenu*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (NULL == this_popup)
return DefWindowProc(hWnd, message, wParam, lParam);
return this_popup->WindowProc(hWnd, message, wParam, lParam);
}
static int g_nTransparencty = 0;
static CMenu* g_pMenu = 0;
static bool SetMenuTransparency(HWND hWnd, int nPercent)
{
if (!::IsWindow(hWnd))
return false;
CWnd* pWnd = CWnd::FromHandle(hWnd);
if (NULL == pWnd)
return false;
#define LWA_ALPHA 0x00000002
#define WS_EX_LAYERED 0x00080000
if (WS_EX_LAYERED & pWnd->GetExStyle())
return false; // Already done....
typedef BOOL(WINAPI *fpSetLayeredWindowAttributesFunc)(
HWND hwnd,
COLORREF crKey,
BYTE bAlpha,
DWORD dwFlags);
static fpSetLayeredWindowAttributesFunc fpSetLayeredWindowAttributes = NULL;
if (NULL == fpSetLayeredWindowAttributes)
{
HINSTANCE hModule = ::GetModuleHandle(L"User32.dll");
if (NULL == hModule)
return false;
fpSetLayeredWindowAttributes = (fpSetLayeredWindowAttributesFunc)::GetProcAddress(hModule, "SetLayeredWindowAttributes");
}
if (NULL == fpSetLayeredWindowAttributes)
return false;
if (pWnd->ModifyStyleEx(0, WS_EX_LAYERED) && fpSetLayeredWindowAttributes(hWnd, RGB(0, 0, 0), (255 * nPercent) / 100, LWA_ALPHA))
return true;
return false;
}
static bool IsMenuItemHighlighted(CMenu* pMenu, UINT nID, bool byPosition)
{
MENUITEMINFO mii;
memset(&mii, 0, sizeof(mii));
mii.cbSize = sizeof(mii);
mii.fMask = MIIM_STATE;
if (pMenu->GetMenuItemInfo(nID, &mii, byPosition))
return(MFS_HILITE & mii.fState ? true : false);
return false;
}
LRESULT CALLBACK CDosPopupMenu::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static bool could_not_get_menu_hwnd = false;
static bool delete_last_menu_item = false;
switch (message)
{
case WM_MEASUREITEM:
{
LPMEASUREITEMSTRUCT lpMIS = (LPMEASUREITEMSTRUCT)lParam;
CString s;
g_pMenu->GetMenuString(lpMIS->CtlID, s, MF_BYCOMMAND);
if (s.IsEmpty())
s = L"empty_string";
// Obtain the width of the text:
CDosMenuFont mf;
CWnd* pWnd = AfxGetMainWnd(); // Get main window
CDC*pDC = pWnd->GetDC(); // Get device context
CFont* pFont = pDC->SelectObject(&mf.m_fontMenu); // Select menu font in...
SIZE t;
GetTextExtentPoint32(pDC->GetSafeHdc(), s, s.GetLength(), &t); // Width of caption
pDC->SelectObject(pFont); // Select old font in
AfxGetApp()->m_pMainWnd->ReleaseDC(pDC); // Release the DC
lpMIS->itemWidth = t.cx;
lpMIS->itemHeight = t.cy;
}
return true;
case WM_DRAWITEM:
{
LPDRAWITEMSTRUCT lpDIS = (LPDRAWITEMSTRUCT)lParam;
HWND hWndMenu = ::WindowFromDC(lpDIS->hDC);
if (!::IsWindow(hWndMenu))
{
could_not_get_menu_hwnd = true;
}
else if (::SetMenuTransparency(hWndMenu, g_nTransparencty))
{
CMenu cmenu;
CString s;
//
// Remove owner draw flag, our work here is done!
//
cmenu.Attach((HMENU)lpDIS->hwndItem);
cmenu.GetMenuString(lpDIS->itemID, s, MF_BYCOMMAND);
if (!s.IsEmpty())
{
UINT nFlags = MF_BYCOMMAND | MF_STRING;
if (::IsMenuItemHighlighted(&cmenu, lpDIS->itemID, false))
nFlags |= MF_HILITE;
cmenu.ModifyMenu(lpDIS->itemID, nFlags, lpDIS->itemID, s);
}
if (delete_last_menu_item)
{
cmenu.DeleteMenu(cmenu.GetMenuItemCount() - 1, MF_BYPOSITION);
delete_last_menu_item = false;
}
cmenu.Detach();
}
}
return true;
case WM_ENTERIDLE:
if (could_not_get_menu_hwnd)
{
// Force menu to redraw
g_pMenu->AppendMenu(MF_STRING, start_at + g_pMenu->GetMenuItemCount(), L".");
could_not_get_menu_hwnd = false;
delete_last_menu_item = true;
}
break;
case WM_INITMENU:
could_not_get_menu_hwnd = false;
delete_last_menu_item = false;
m_menu_select = -1;
PopupWndProcOnInitMenu(hWnd, (HMENU)wParam);
break;
case WM_MENUCHAR:
m_menu_char = true;
return MAKELONG(m_menu_select, MNC_CLOSE); // make spacebar (and other keys) work just like right click
case WM_MENUSELECT:
{
int id = LOWORD(wParam);
if (m_menu_char || lParam == 0)
break;
m_menu_select = id;
id = id > 0 ? id - start_at : -1;
OnMenuSelect(hWnd, (HMENU)lParam, id);
}
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void CDosPopupMenu::PopupWndProcOnInitMenu(HWND hWnd, HMENU hMenu)
{
CString sSeperator(DOS_POPUP_SEP);
for (int i = 0, j = 0, cnt = (int)m_item_array.GetCount(); i < cnt; i++)
{
if (sSeperator.CompareNoCase(m_item_array[i]) == 0)
{
j++;
continue;
}
if ((i - j) > m_nEnabledList.GetUpperBound())
break;
if (m_nEnabledList[i - j] > 0)
continue;
::EnableMenuItem(hMenu, i, MF_BYPOSITION | MF_DISABLED | MF_GRAYED);
}
OnInitMenu(hWnd, hMenu);
}
void CDosPopupMenu::OnInitMenu(HWND hWnd, HMENU hMenu)
{
}
bool CDosPopupMenu::LeftButtonPicked()
{
return m_bLeft;
}
bool CDosPopupMenu::RightButtonPicked()
{
return m_bRight;
}
LPPOINT CDosPopupMenu::PointPicked()
{
if (LeftButtonPicked() || RightButtonPicked())
return &m_point;
return NULL;
}
int CDosPopupMenu::PopUp(CWnd* parent, CPoint bottom, CPoint top)
{
return PopUpEx(parent, bottom, top, 0);
}
int CDosPopupMenu::PopUpEx(CWnd* parent, CPoint bottom, CPoint top, int nTransparent)
{
g_nTransparencty = nTransparent;
g_pMenu = NULL;
ASSERT(parent && ::IsWindow(parent->m_hWnd));
Init();
CMenu menu, *pmenu = &menu;
bool bCreateMenu = m_hMenu ? false : true;
if (!bCreateMenu && !menu.Attach(m_hMenu))
return -1;
if (!bCreateMenu)
pmenu = menu.GetSubMenu(0);
if (bCreateMenu && !menu.CreatePopupMenu())
return -1;
const int cnt = (int)m_item_array.GetCount();
if (bCreateMenu && cnt < 1)
return -1;
HWND hwnd = 0;
g_pMenu = pmenu; // Make sure that menu is available to message loop
if (bCreateMenu)
hwnd = ::CreateWindow(L"STATIC", 0, WS_POPUP, 0, 0, 10, 10, NULL, 0, ::AfxGetInstanceHandle(), 0);
else
hwnd = parent->m_hWnd;
if (!hwnd)
return -1;
if (bCreateMenu)
{
#ifdef _WIN64
::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)PopupWndProc);
::SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)this);
#else
::SetWindowLongPtr(hwnd, GWLP_WNDPROC, PtrToLong(PopupWndProc));
::SetWindowLongPtr(hwnd, GWLP_USERDATA, PtrToLong(this));
#endif
}
CString sSeparator(DOS_POPUP_SEP);
for (int j = 0, i = 0; i < cnt; i++)
{
CString s(m_item_array[i]);
if (s.Compare(sSeparator))
pmenu->AppendMenu(MF_STRING, start_at + j++, s);
else
pmenu->AppendMenu(MF_SEPARATOR, 0, L"");
}
if (nTransparent > 0)
{
g_nTransparencty = min(nTransparent, 100);
for (int i = 0, cnt = pmenu->GetMenuItemCount(); i < cnt; i++)
{
CString s;
pmenu->GetMenuString(i, s, MF_BYPOSITION);
if (s.IsEmpty())
continue;
UINT nFlags = MF_BYPOSITION | MF_STRING | MF_OWNERDRAW;
if (::IsMenuItemHighlighted(pmenu, i, true))
nFlags |= MF_HILITE;
pmenu->ModifyMenu(i, nFlags, pmenu->GetMenuItemID(i), s);
break;
}
}
::ClientToScreen(parent->m_hWnd, &bottom);
UINT nFlags = TPM_LEFTALIGN | TPM_RIGHTBUTTON;
if (bCreateMenu)
nFlags |= TPM_RETURNCMD;
int result = ::TrackPopupMenu(pmenu->m_hMenu, nFlags, bottom.x, bottom.y, 0, hwnd, 0);
if (result == 0 && m_menu_char)
result = m_menu_select;
// check what's left in the queue
// it gives an indication how the menu got closed
MSG msg;
::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
if (msg.message == WM_RBUTTONDOWN)
{
m_bRight = true;
m_point.x = LOWORD(msg.lParam);
m_point.y = HIWORD(msg.lParam);
}
else if (msg.message == WM_LBUTTONDOWN)
{
m_bLeft = true;
m_point.x = LOWORD(msg.lParam);
m_point.y = HIWORD(msg.lParam);
}
else if (msg.message == WM_KEYDOWN && msg.wParam == VK_RETURN)
{
result = m_menu_select;
}
if (bCreateMenu)
::DestroyWindow(hwnd);
else if (m_hMenu)
::DestroyMenu(m_hMenu);
if (result < 1)
return -1;
return(bCreateMenu ? result - start_at : result);
}
| 23.611111
| 131
| 0.665694
|
ArphonePei
|
a39770b2ca145b0134019e175d1fdcd930edad79
| 5,098
|
cpp
|
C++
|
tests/benchdnn/utils/perf_report.cpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
tests/benchdnn/utils/perf_report.cpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
tests/benchdnn/utils/perf_report.cpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************************************************
* Copyright 2021-2022 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "dnn_types.hpp"
#include "dnnl_common.hpp"
#include "utils/perf_report.hpp"
void base_perf_report_t::report(res_t *res, const char *prb_str) const {
dump_perf_footer();
std::stringstream ss;
const char *pt = pt_;
char c;
while ((c = *pt++) != '\0') {
if (c != '%') {
ss << c;
continue;
}
handle_option(ss, pt, res, prb_str);
}
std::string str = ss.str();
BENCHDNN_PRINT(0, "%s\n", str.c_str());
};
void base_perf_report_t::dump_engine(std::ostream &s) const {
s << engine_tgt_kind;
}
void base_perf_report_t::handle_option(std::ostream &s, const char *&option,
res_t *res, const char *prb_str) const {
const auto &prim_create_timer = res->timer_map.prim_create_timer();
const auto &par_compl_timer = res->timer_map.par_compl_timer();
timer::timer_t::mode_t mode = timer::timer_t::min;
(void)mode;
double unit = 1e0;
char c = *option;
if (c == '-' || c == '0' || c == '+') {
mode = modifier2mode(c);
c = *(++option);
}
if (c == 'K' || c == 'M' || c == 'G') {
unit = modifier2unit(c);
c = *(++option);
}
auto get_flops = [&](const timer::timer_t &t) -> double {
if (!t.sec(mode)) return 0;
return ops() / t.sec(mode) / unit;
};
auto get_bw = [&](const timer::timer_t &t) -> double {
if (!t.sec(mode)) return 0;
return (res->ibytes + res->obytes) / t.sec(mode) / unit;
};
auto get_freq = [&](const timer::timer_t &t) -> double {
if (!t.sec(mode)) return 0;
return t.ticks(mode) / t.sec(mode) / unit;
};
auto ctime_ratio = par_compl_timer.ms(mode) != 0.0
? prim_create_timer.ms(mode) / par_compl_timer.ms(mode)
: 0.0;
// Please update doc/knobs_perf_report.md in case of any new options!
#define HANDLE(opt, ...) \
if (!strncmp(opt "%", option, strlen(opt) + 1)) { \
__VA_ARGS__; \
option += strlen(opt) + 1; \
return; \
}
// Options operating on driver specific types, e.g. alg_t.
HANDLE("alg", dump_alg(s));
HANDLE("cfg", dump_cfg(s));
HANDLE("desc", dump_desc(s));
HANDLE("DESC", dump_desc_csv(s));
HANDLE("engine", dump_engine(s));
HANDLE("flags", dump_flags(s));
HANDLE("activation", dump_rnn_activation(s));
HANDLE("direction", dump_rnn_direction(s));
// Options operating on common types, e.g. attr_t.
HANDLE("attr", if (attr() && !attr()->is_def()) s << *attr());
HANDLE("axis", if (axis()) s << *axis());
HANDLE("dir", if (dir()) s << *dir());
HANDLE("dt", if (dt()) s << *dt());
HANDLE("group", if (group()) s << *group());
HANDLE("sdt", if (sdt()) s << *sdt());
HANDLE("stag", if (stag()) s << *stag());
HANDLE("mb", if (user_mb()) s << *user_mb());
HANDLE("name", if (name()) s << *name());
HANDLE("ddt", if (ddt()) s << *ddt());
HANDLE("dtag", if (dtag()) s << *dtag());
HANDLE("prop", if (prop()) s << prop2str(*prop()));
HANDLE("tag", if (tag()) s << *tag());
HANDLE("stat_tag", if (stat_tag()) s << *stat_tag());
HANDLE("wtag", if (wtag()) s << *wtag());
// Options operating on driver independent objects, e.g. timer values.
HANDLE("bw", s << get_bw(res->timer_map.perf_timer()));
HANDLE("driver", s << driver_name);
HANDLE("flops", s << get_flops(res->timer_map.perf_timer()));
HANDLE("clocks", s << res->timer_map.perf_timer().ticks(mode) / unit);
HANDLE("prb", s << prb_str);
HANDLE("freq", s << get_freq(res->timer_map.perf_timer()));
HANDLE("ops", s << ops() / unit);
HANDLE("time", s << res->timer_map.perf_timer().ms(mode) / unit);
HANDLE("ctime_ratio", s << ctime_ratio / unit);
HANDLE("prim_ctime", s << prim_create_timer.ms(mode) / unit);
HANDLE("par_ctime", s << par_compl_timer.ms(mode) / unit);
HANDLE("impl", s << res->impl_name);
HANDLE("ibytes", s << res->ibytes / unit);
HANDLE("obytes", s << res->obytes / unit);
HANDLE("iobytes", s << (res->ibytes + res->obytes) / unit);
HANDLE("idx", s << benchdnn_stat.tests);
#undef HANDLE
auto opt_name = std::string(option);
opt_name.pop_back();
BENCHDNN_PRINT(0, "Error: perf report option \"%s\" is not supported\n",
opt_name.c_str());
SAFE_V(FAIL);
}
| 35.402778
| 80
| 0.566889
|
wuxun-zhang
|
a398e6442b1b4ef514df68d825c2e32812066888
| 5,809
|
cpp
|
C++
|
lib/src/Rendering/StandardShapes.cpp
|
F4r3n/FarenMediaLibrary
|
3f71054df7178ca79781b101ca2d58cd95a20a43
|
[
"Apache-2.0"
] | 7
|
2016-09-09T16:43:15.000Z
|
2021-06-16T22:32:33.000Z
|
lib/src/Rendering/StandardShapes.cpp
|
F4r3n/FarenMediaLibrary
|
3f71054df7178ca79781b101ca2d58cd95a20a43
|
[
"Apache-2.0"
] | null | null | null |
lib/src/Rendering/StandardShapes.cpp
|
F4r3n/FarenMediaLibrary
|
3f71054df7178ca79781b101ca2d58cd95a20a43
|
[
"Apache-2.0"
] | 1
|
2020-01-05T19:22:32.000Z
|
2020-01-05T19:22:32.000Z
|
#include <Rendering/StandardShapes.h>
#include <Core/Math/Functions.h>
#include <Rendering/Mesh.hpp>
namespace fm {
using namespace rendering;
void StandardShapes::AddVertex(MeshContainer* mesh,
const fm::math::Vector3f& position,
const fm::math::Vector2f& uv,
const fm::math::Vector3f& normals
) {
mesh->vertices.push_back({position, uv, normals});
}
MeshContainer* StandardShapes::CreateQuad()
{
MeshContainer* meshContainer = new MeshContainer();
AddVertex(meshContainer, {-0.5, 0.5, 0}, {0.0, 1.0}, {0.0,0.0,-1.0});
AddVertex(meshContainer, {-0.5f, -0.5f, 0}, {0.0, 0.0},{0.0,0.0,-1.0});
AddVertex(meshContainer, {0.5, -0.5, 0}, {1.0, 0.0},{0.0,0.0,-1.0});
AddVertex(meshContainer, {0.5, 0.5, 0}, {1.0, 1.0},{0.0,0.0,-1.0});
meshContainer->listIndices = {0, 1, 2, 0, 2, 3};
return meshContainer;
}
MeshContainer* StandardShapes::CreateCube()
{
MeshContainer* meshContainer = new MeshContainer();
//Back
AddVertex(meshContainer, {-0.5f, -0.5f, 0.5f},{0.0,0.0},{ 0.0f, 0.0f, 1.0f});
AddVertex(meshContainer, { 0.5f, -0.5f, 0.5f},{0.0,0.0},{ 0.0f, 0.0f, 1.0f});
AddVertex(meshContainer, { 0.5f, 0.5f, 0.5f},{0.0,0.0},{ 0.0f, 0.0f, 1.0f});
AddVertex(meshContainer, { 0.5f, 0.5f, 0.5f},{0.0,0.0},{ 0.0f, 0.0f, 1.0f});
AddVertex(meshContainer, {-0.5f, 0.5f, 0.5f},{0.0,0.0},{ 0.0f, 0.0f, 1.0f});
AddVertex(meshContainer, {-0.5f, -0.5f, 0.5f},{0.0,0.0},{ 0.0f, 0.0f, 1.0f});
//Front
AddVertex(meshContainer, { -0.5f, -0.5f, -0.5f }, { 0.0,0.0 }, { 0.0f, 0.0f, -1.0f });
AddVertex(meshContainer, { 0.5f, -0.5f, -0.5f }, { 0.0,0.0 }, { 0.0f, 0.0f, -1.0f });
AddVertex(meshContainer, { 0.5f, 0.5f, -0.5f }, { 0.0,0.0 }, { 0.0f, 0.0f, -1.0f });
AddVertex(meshContainer, { 0.5f, 0.5f, -0.5f }, { 0.0,0.0 }, { 0.0f, 0.0f, -1.0f });
AddVertex(meshContainer, { -0.5f, 0.5f, -0.5f }, { 0.0,0.0 }, { 0.0f, 0.0f, -1.0f });
AddVertex(meshContainer, { -0.5f, -0.5f, -0.5f }, { 0.0,0.0 }, { 0.0f, 0.0f, -1.0f });
//Left
AddVertex(meshContainer, {-0.5f, 0.5f, 0.5f},{0.0,0.0},{-1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, {-0.5f, 0.5f, -0.5f},{0.0,0.0},{-1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, {-0.5f, -0.5f, -0.5f},{0.0,0.0},{-1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, {-0.5f, -0.5f, -0.5f},{0.0,0.0},{-1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, {-0.5f, -0.5f, 0.5f},{0.0,0.0},{-1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, {-0.5f, 0.5f, 0.5f},{0.0,0.0},{-1.0f, 0.0f, 0.0f});
//Right
AddVertex(meshContainer, { 0.5f, 0.5f, 0.5f},{0.0,0.0},{ 1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, 0.5f, -0.5f},{0.0,0.0},{ 1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, -0.5f, -0.5f},{0.0,0.0},{ 1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, -0.5f, -0.5f},{0.0,0.0},{ 1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, -0.5f, 0.5f},{0.0,0.0},{ 1.0f, 0.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, 0.5f, 0.5f},{0.0,0.0},{ 1.0f, 0.0f, 0.0f});
//Bottom
AddVertex(meshContainer, {-0.5f, -0.5f, -0.5f},{0.0,0.0},{ 0.0f, -1.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, -0.5f, -0.5f},{0.0,0.0},{ 0.0f, -1.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, -0.5f, 0.5f},{0.0,0.0},{ 0.0f, -1.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, -0.5f, 0.5f},{0.0,0.0},{ 0.0f, -1.0f, 0.0f});
AddVertex(meshContainer, {-0.5f, -0.5f, 0.5f},{0.0,0.0},{ 0.0f, -1.0f, 0.0f});
AddVertex(meshContainer, {-0.5f, -0.5f, -0.5f},{0.0,0.0},{ 0.0f, -1.0f, 0.0f});
//Top
AddVertex(meshContainer, {-0.5f, 0.5f, -0.5f},{0.0,0.0},{ 0.0f, 1.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, 0.5f, -0.5f},{0.0,0.0},{ 0.0f, 1.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, 0.5f, 0.5f},{0.0,0.0},{ 0.0f, 1.0f, 0.0f});
AddVertex(meshContainer, { 0.5f, 0.5f, 0.5f},{0.0,0.0},{ 0.0f, 1.0f, 0.0f});
AddVertex(meshContainer, {-0.5f, 0.5f, 0.5f},{0.0,0.0},{ 0.0f, 1.0f, 0.0f});
AddVertex(meshContainer, {-0.5f, 0.5f, -0.5f},{0.0,0.0},{ 0.0f, 1.0f, 0.0f});
meshContainer->listIndices = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35};
return meshContainer;
}
MeshContainer* StandardShapes::CreateQuadFullScreen()
{
MeshContainer* meshContainer = new MeshContainer();
AddVertex(meshContainer, {-1, 1, 0}, {0.0, 0.0}, {0.0, 0.0, 0.0});
AddVertex(meshContainer, {-1, -1, 0}, {0.0, 1.0}, {0.0, 0.0, 0.0});
AddVertex(meshContainer, {1, -1, 0}, {1.0, 1.0}, {0.0, 0.0, 0.0});
AddVertex(meshContainer, {1, 1, 0}, {1.0, 0.0}, {0.0, 0.0, 0.0});
meshContainer->listIndices = {0, 1, 2, 0, 2, 3};
return meshContainer;
}
MeshContainer* StandardShapes::CreateCircle()
{
MeshContainer* meshContainer = new MeshContainer();
unsigned int numberVertices = 100;
float intervall = 2 * fm::math::pi() / numberVertices;
AddVertex(meshContainer, {0.5, 0.5, 0}, {0.5, 0.5}, {0.0,0.0,0.0});
for(float teta = 0; teta < 2 * fm::math::pi(); teta += intervall) {
fm::math::Vector2f uv((float)(0.5 + cos(teta) / 2),
(float)(0.5 + sin(teta) / 2.0f));
AddVertex(meshContainer, uv, uv, {0.0, 0.0,-1.0});
}
int j = 0;
for(unsigned int i = 1; i < numberVertices; ++i) {
j = i;
meshContainer->listIndices.push_back(j++);
meshContainer->listIndices.push_back(j);
meshContainer->listIndices.push_back(0);
}
meshContainer->listIndices.push_back(j);
meshContainer->listIndices.push_back(1);
meshContainer->listIndices.push_back(0);
return meshContainer;
}
}
| 45.382813
| 133
| 0.548115
|
F4r3n
|
a39969ce321905a84cc87408a19c9e0b58baa661
| 6,586
|
cpp
|
C++
|
networkit/cpp/linkprediction/EvaluationMetric.cpp
|
angriman/network
|
3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894
|
[
"MIT"
] | 366
|
2019-06-27T18:48:18.000Z
|
2022-03-29T08:36:49.000Z
|
networkit/cpp/linkprediction/EvaluationMetric.cpp
|
angriman/network
|
3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894
|
[
"MIT"
] | 387
|
2019-06-24T11:30:39.000Z
|
2022-03-31T10:37:28.000Z
|
networkit/cpp/linkprediction/EvaluationMetric.cpp
|
angriman/network
|
3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894
|
[
"MIT"
] | 131
|
2019-07-04T15:40:13.000Z
|
2022-03-29T12:34:23.000Z
|
// no-networkit-format
/*
* EvaluationMetric.cpp
*
* Created on: 17.03.2015
* Author: Kolja Esders
*/
#include <algorithm>
#include <numeric>
#include <set>
#include <networkit/auxiliary/Parallel.hpp>
#include <networkit/linkprediction/EvaluationMetric.hpp>
#include <networkit/linkprediction/PredictionsSorter.hpp>
namespace NetworKit {
EvaluationMetric::EvaluationMetric() : testGraph(nullptr) {}
EvaluationMetric::EvaluationMetric(const Graph& testGraph) : testGraph(&testGraph) {}
void EvaluationMetric::setTestGraph(const Graph& newTestGraph) {
testGraph = &newTestGraph;
}
std::pair<std::vector<double>, std::vector<double>> EvaluationMetric::getCurve(std::vector<LinkPredictor::prediction> predictions, count numThresholds) {
if (testGraph == nullptr) {
throw std::logic_error("Set testGraph first.");
} else if (predictions.empty()) {
throw std::logic_error("predictions.size() == 0");
} else if (numThresholds < 2) {
throw std::invalid_argument("numThresholds < 2: At least 2 thresholds needed for curve.");
}
// Don't overshoot with the number of thresholds being greater than the number of predictions + 1.
if (predictions.size() + 1 < numThresholds || numThresholds == 0) {
numThresholds = predictions.size() + 1;
}
std::set<index> thresholdSet;
count numPredictions = predictions.size();
for (index i = 0; i < numThresholds; ++i) {
// Percentile calculation through nearest rank method.
// This calculation is numerically instable. This is why we use a set to make sure that
// we obtain pairwise different thresholds.
thresholdSet.insert(std::ceil(numPredictions * (1.0 * i / static_cast<double>(numThresholds - 1))));
}
thresholds.assign(thresholdSet.begin(), thresholdSet.end());
// The extraction of statistical measures requires sorted predictions
PredictionsSorter::sortByScore(predictions);
this->predictions = predictions;
calculateStatisticalMeasures();
generatedPoints = generatePoints();
return generatedPoints;
}
double EvaluationMetric::getAreaUnderCurve(std::pair<std::vector<double>, std::vector<double>> curve) const {
if (curve.first.size() < 2) {
throw std::invalid_argument("At least 2 points needed for AUC.");
} else if (curve.first.size() != curve.second.size()) {
throw std::invalid_argument("X- and Y-vector differ in size().");
}
// Sort points so that x-values start at zero.
sortPointsOfCurve(curve);
double AUC = 0;
for (index i = 0; i < curve.first.size() - 1; ++i) {
// Trapezoid rule
AUC += 0.5 * (curve.first[i + 1] - curve.first[i]) * (curve.second[i] + curve.second[i + 1]);
}
return AUC;
}
double EvaluationMetric::getAreaUnderCurve() const {
if (generatedPoints.first.empty()) {
throw std::logic_error("Call getCurve first or use getAreaUnderCurve(curve).");
}
return getAreaUnderCurve(generatedPoints);
}
void EvaluationMetric::calculateStatisticalMeasures() {
#pragma omp parallel sections
{
#pragma omp section
setTrueAndFalsePositives();
#pragma omp section
setTrueAndFalseNegatives();
#pragma omp section
setPositivesAndNegatives();
}
}
void EvaluationMetric::setTrueAndFalsePositives() {
count tmpTruePositives = 0;
count tmpFalsePositives = 0;
truePositives.clear();
falsePositives.clear();
std::vector<index>::iterator thresholdIt = thresholds.begin();
for (index i = 0; i < predictions.size(); ++i) {
// Check in the beginning to catch threshold = 0 as well.
if (thresholdIt != thresholds.end() && i == *thresholdIt) {
truePositives.push_back(tmpTruePositives);
falsePositives.push_back(tmpFalsePositives);
++thresholdIt;
}
bool hasEdge = testGraph->hasEdge(predictions[i].first.first, predictions[i].first.second);
if (hasEdge) {
tmpTruePositives++;
} else {
tmpFalsePositives++;
}
}
// If there is a threshold at predictions.size() add it as well
if (thresholdIt != thresholds.end()) {
truePositives.push_back(tmpTruePositives);
falsePositives.push_back(tmpFalsePositives);
}
}
void EvaluationMetric::setTrueAndFalseNegatives() {
count tmpTrueNegatives = 0;
count tmpFalseNegatives = 0;
trueNegatives.clear();
falseNegatives.clear();
std::vector<index>::reverse_iterator thresholdIt = thresholds.rbegin();
for (index i = predictions.size(); i > 0; --i) {
// Check in the beginning to catch threshold = predictions.size().
if (thresholdIt != thresholds.rend() && i == *thresholdIt) {
trueNegatives.push_back(tmpTrueNegatives);
falseNegatives.push_back(tmpFalseNegatives);
if (*thresholdIt != 0)
++thresholdIt;
}
bool hasEdge = testGraph->hasEdge(predictions[i - 1].first.first, predictions[i - 1].first.second);
if (hasEdge) {
tmpFalseNegatives++;
} else {
tmpTrueNegatives++;
}
}
// If there is a threshold at 0 add it as well
if (thresholdIt != thresholds.rend()) {
trueNegatives.push_back(tmpTrueNegatives);
falseNegatives.push_back(tmpFalseNegatives);
}
// We need to reverse so that TN/FN and TP/FP have the same index for a given threshold.
// As we have started at the bottom of the predictions we need to reverse our results since
// the TP/FP calculation started at the top.
std::reverse(trueNegatives.begin(), trueNegatives.end());
std::reverse(falseNegatives.begin(), falseNegatives.end());
}
void EvaluationMetric::setPositivesAndNegatives() {
numPositives = 0;
#pragma omp parallel for
for (omp_index i = 0; i < static_cast<omp_index>(predictions.size()); ++i) {
if (testGraph->hasEdge(predictions[i].first.first, predictions[i].first.second)) {
#pragma omp atomic
numPositives++;
}
}
numNegatives = predictions.size() - numPositives;
}
void EvaluationMetric::sortPointsOfCurve(std::pair<std::vector<double>, std::vector<double>>& curve) const {
// Create a permutation that you would use in sorting the x-values ascendingly
std::vector<int> permutation(curve.first.size());
std::iota(permutation.begin(), permutation.end(), 0);
Aux::Parallel::sort(permutation.begin(), permutation.end(), [&](int i, int j){ return curve.first[i] < curve.first[j]; });
// Actually sort x-vector
Aux::Parallel::sort(curve.first.begin(), curve.first.end());
// Apply the permutation to the y-vector
std::vector<double> sortedY(permutation.size());
std::transform(permutation.begin(), permutation.end(), sortedY.begin(), [&](int i){ return curve.second[i]; });
curve.second = sortedY;
}
} // namespace NetworKit
| 37.20904
| 153
| 0.700273
|
angriman
|
a39c440138f7252e26d01608b6834e4b674d89bd
| 2,762
|
cpp
|
C++
|
Tests/VisualTests/VTests/src/ParticleTest.cpp
|
Stazer/ogre-next
|
4d3aa2aedf4575ac8a9e32a4e2af859562752d51
|
[
"MIT"
] | 4
|
2018-11-12T02:18:44.000Z
|
2020-09-03T12:16:14.000Z
|
Tests/VisualTests/VTests/src/ParticleTest.cpp
|
Stazer/ogre-next
|
4d3aa2aedf4575ac8a9e32a4e2af859562752d51
|
[
"MIT"
] | 2
|
2020-12-01T18:20:39.000Z
|
2021-02-09T21:04:25.000Z
|
Tests/VisualTests/VTests/src/ParticleTest.cpp
|
Stazer/ogre-next
|
4d3aa2aedf4575ac8a9e32a4e2af859562752d51
|
[
"MIT"
] | 3
|
2020-10-15T15:11:41.000Z
|
2021-04-04T03:38:54.000Z
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "ParticleTest.h"
#include "OgreParticleSystem.h"
ParticleTest::ParticleTest()
{
mInfo["Title"] = "VTests_Particles";
mInfo["Description"] = "Tests basic particle system functionality.";
// take screenshot early, when emitters are just beginning
addScreenshotFrame(35);
// and another after particles have died, extra emitters emitted, etc
addScreenshotFrame(500);
}
//---------------------------------------------------------------------------
void ParticleTest::setupContent()
{
// create a bunch of random particle systems
Ogre::ParticleSystem* ps = mSceneMgr->createParticleSystem("Examples/Fireworks");
mSceneMgr->getRootSceneNode()->attachObject(ps);
// Multiple systems didn't seem to stay deterministic... (in gcc at least...)
//ps = mSceneMgr->createParticleSystem("Fountain", "Examples/PurpleFountain");
//mSceneMgr->getRootSceneNode()->attachObject(ps);
//ps = mSceneMgr->createParticleSystem("Nimbus", "Examples/GreenyNimbus");
//mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(150, 0, 0))->attachObject(ps);
//ps = mSceneMgr->createParticleSystem("Nimbus2", "Examples/GreenyNimbus");
//mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-150, 0, 0))->attachObject(ps);
mCamera->setPosition(0,150,500);
}
//-----------------------------------------------------------------------
| 45.278689
| 97
| 0.673063
|
Stazer
|
a39c4bd825d9de2ce4386d370b17fe4a2cdf9c10
| 983
|
cpp
|
C++
|
battlegui.cpp
|
alphagocc/FiveChess-
|
d73d7b71f5d1d0834c08d89525964021d7ba69f5
|
[
"MIT"
] | 2
|
2018-01-21T14:09:39.000Z
|
2020-07-25T00:43:51.000Z
|
battlegui.cpp
|
alphagocc/FiveChess-
|
d73d7b71f5d1d0834c08d89525964021d7ba69f5
|
[
"MIT"
] | null | null | null |
battlegui.cpp
|
alphagocc/FiveChess-
|
d73d7b71f5d1d0834c08d89525964021d7ba69f5
|
[
"MIT"
] | null | null | null |
#include "battlegui.h"
#include "ui_battlegui.h"
#include <QDebug>
battleGui::battleGui(QWidget* parent)
: QWidget(parent), ui(new Ui::battleGui), timer(new QTimer)
{
qDebug() << "OK2" << endl;
ui->setupUi(this);
ui->labelTime->setText(tr("Time:%1 Second").arg(0));
timer->start(1000);
connect(ui->pushButtonSave, &QPushButton::clicked, this,
[] { chessBoard.saveBoard(); });
connect(timer, &QTimer::timeout, this, [&] {
chessBoard.addUsedTime();
ui->labelTime->setText(tr("Time:%1 Second").arg(chessBoard.getUsedTime()));
});
connect(&chessBoard, &ChessBoardCore::dataChanged, this,
[&](int x, int y, ChessBoardCore::DataType d) {
ui->labelColor->setText(tr("Waiting:%1").arg(d == ChessBoardCore::DataType::black ? tr("White") : tr("Black")));
});
}
battleGui::~battleGui() { delete ui; }
bool battleGui::close()
{
QWidget* p = parentWidget();
p->show();
return true;
}
| 29.787879
| 120
| 0.608342
|
alphagocc
|
a39d79eb3c7df804f1558a2ee46ee0d6e555c033
| 5,642
|
cpp
|
C++
|
src/Enzo/enzo_EnzoInitialSoup.cpp
|
TrevorMcCrary/enzo-e
|
abeb5d73d6ff210fc6cd675c25430cfb93c374ac
|
[
"BSD-3-Clause"
] | null | null | null |
src/Enzo/enzo_EnzoInitialSoup.cpp
|
TrevorMcCrary/enzo-e
|
abeb5d73d6ff210fc6cd675c25430cfb93c374ac
|
[
"BSD-3-Clause"
] | null | null | null |
src/Enzo/enzo_EnzoInitialSoup.cpp
|
TrevorMcCrary/enzo-e
|
abeb5d73d6ff210fc6cd675c25430cfb93c374ac
|
[
"BSD-3-Clause"
] | null | null | null |
// See LICENSE_CELLO file for license and copyright information
/// @file enzo_Soup.cpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2016-09-10
/// @brief Definition of the Soup class for "alphabet soup" test problem
#include "enzo.hpp"
#include <random>
const int EnzoInitialSoup::position_[] =
{
0,1,2,4,5,6,7,9,10,12,13,14,15,16,17,19,20,21,22,24,25,27,28,29,30,31
};
//======================================================================
EnzoInitialSoup::EnzoInitialSoup
(int cycle,
double time,
std::string filename,
int rank,
bool rotate,
int nax, int nay, int naz,
double dpx, double dpy, double dpz,
double dsx, double dsy, double dsz,
double density,
double pressure_in, double pressure_out) throw ()
: Initial(cycle,time),
file_name_(filename),
rank_(rank),
rotate_(rotate),
png_(NULL),
density_(density),
pressure_in_(pressure_in),
pressure_out_(pressure_out)
{
array_[0] = nax;
array_[1] = nay;
array_[2] = naz;
d_pos_[0] = dpx;
d_pos_[1] = dpy;
d_pos_[2] = dpz;
d_size_[0] = dsx;
d_size_[1] = dsy;
d_size_[2] = dsz;
png_ = new pngwriter;
png_->readfromfile(file_name_.c_str());
int nx = png_->getwidth();
int ny = png_->getheight();
ASSERT3 ("EnzoInitialSoup::EnzoInitialSoup()",
"Error reading input PNG file %s: size must be %d x %d",
file_name_.c_str(),SOUP_IMAGE_NX,SOUP_IMAGE_NY,
(nx == SOUP_IMAGE_NX) &&
(ny == SOUP_IMAGE_NY));
std::random_device rd;
std::uniform_int_distribution<int> dist(0, 25);
letter_ = new char [nax*nay*naz];
for (int kz=0; kz<naz; kz++) {
for (int ky=0; ky<nay; ky++) {
for (int kx=0; kx<nax; kx++) {
int k = kx + nax*(ky + nay*kz);
letter_[k] = 'A' + dist(rd);
}
}
}
}
//----------------------------------------------------------------------
EnzoInitialSoup::~EnzoInitialSoup() throw ()
{
delete png_;
png_ = NULL;
delete [] letter_;
letter_ = NULL;
}
//----------------------------------------------------------------------
void EnzoInitialSoup::enforce_block
( Block * block, const Hierarchy * hierarchy ) throw()
{
Field field = block->data()->field();
enzo_float * d = (enzo_float *) field.values("density");
enzo_float * te = (enzo_float *) field.values ("total_energy");
int nx,ny,nz;
field.size(&nx,&ny,&nz);
double xmb,ymb,zmb;
double xpb,ypb,zpb;
block->data()->lower(&xmb,&ymb,&zmb);
block->data()->upper(&xpb,&ypb,&zpb);
double hx,hy,hz;
field.cell_width(xmb,xpb,&hx,
ymb,ypb,&hy,
zmb,zpb,&hz);
int gx,gy,gz;
field.ghost_depth(0,&gx,&gy,&gz);
int mx = nx + 2*gx;
int my = ny + 2*gy;
int mz = nz + 2*gz;
// array of explosions
double xmd,ymd,zmd;
hierarchy->lower(&xmd,&ymd,&zmd);
double xpd,ypd,zpd;
hierarchy->upper(&xpd,&ypd,&zpd);
double hxa = (xpd-xmd) / array_[0];
double hya = (ypd-ymd) / array_[1];
double hza = (zpd-zmd) / array_[2];
const enzo_float gamma = EnzoBlock::Gamma[cello::index_static()];
const double te_in = pressure_in_ / ((gamma - 1.0) * density_);
const double te_out= pressure_out_ / ((gamma - 1.0) * density_);
// background
for (int iz=0; iz<mz; iz++) {
for (int iy=0; iy<my; iy++) {
for (int ix=0; ix<mx; ix++) {
int i = INDEX(ix,iy,iz,mx,my);
d[i] = density_;
te[i] = te_out;
}
}
}
// bounds of possible explosions intersecting this Block
int kxm = MAX((int)floor(xmb/(xpd-xmd)*array_[0])-1,0);
int kym = MAX((int)floor(ymb/(ypd-ymd)*array_[1])-1,0);
int kzm = MAX((int)floor(zmb/(zpd-zmd)*array_[2])-1,0);
int kxp = MIN((int) ceil(xpb/(xpd-xmd)*array_[0])+1,array_[0]);
int kyp = MIN((int) ceil(ypb/(ypd-ymd)*array_[1])+1,array_[1]);
int kzp = MIN((int) ceil(zpb/(zpd-zmd)*array_[2])+1,array_[2]);
const double rx = d_size_[0]/array_[0];
const double ry = d_size_[1]/array_[1];
const double rz = d_size_[2]/array_[2];
const bool one_letter = (array_[0]*array_[1]*array_[2] == 1);
for (int kz=kzm; kz<kzp; kz++) {
double cz = hza*(0.5+kz);
for (int ky=kym; ky<kyp; ky++) {
double cy = hya*(0.5+ky);
for (int kx=kxm; kx<kxp; kx++) {
const double cx = hxa*(0.5+kx);
// (cx,cy,cz) center of letter in domain
// (kx,ky,kz) index of letter in array
const int k = kx + array_[0]*(ky + array_[1]*kz);
char letter = one_letter ? 'C' : letter_[k];
// (jx,jy) position of letter in font image
int jx=position_[letter-'A'] % 8;
int jy=position_[letter-'A'] / 8;
// (lxm:lxp,lym:lyp) bounds of letter in font image
int lxm = SOUP_CHAR_X0 + SOUP_CHAR_DX*jx;
int lyp = SOUP_IMAGE_NY - (SOUP_CHAR_Y0 + SOUP_CHAR_DY*jy);
int lxp = lxm + SOUP_CHAR_NX;
int lym = lyp - SOUP_CHAR_NY;
// (explosion center cx,cy,cz)
for (int iz=0; iz<mz; iz++) {
double z = zmb + (iz - gz + 0.5)*hz;
bool in_range_z = (rank_ < 3) || (cz-rz <= z && z <= cz+rz);
for (int iy=0; iy<my; iy++) {
double y = ymb + (iy - gy + 0.5)*hy;
int ly = lym + 1.0*(lyp-lym)/(2.0*ry)*(y - cy + ry);
bool in_range_y = (lym <= ly && ly <= lyp);
for (int ix=0; ix<mx; ix++) {
int i=ix + mx*(iy + my*iz);
double x = xmb + (ix - gx + 0.5)*hx;
// (x,y,z) position of current cell center
// compute image font array index
int lx = lxm + 1.0*(lxp-lxm)/(2.0*rx)*(x - cx + rx);
bool in_range_x = (lxm <= lx && lx <= lxp);
if ( in_range_x && in_range_y && in_range_z) {
if (png_->read(lx+1,ly+1,1) +
png_->read(lx+1,ly+1,2) +
png_->read(lx+1,ly+1,3) > 0.0) {
te[i] = te_in;
}
}
}
}
}
}
}
}
block->initial_done();
}
| 26.739336
| 75
| 0.569302
|
TrevorMcCrary
|
a3a45f5caa66ab94dede00d074b4aaf5ef0b61e4
| 776
|
cpp
|
C++
|
gwen/src/Controls/ScrollBarButton.cpp
|
Oipo/GWork
|
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
|
[
"MIT"
] | null | null | null |
gwen/src/Controls/ScrollBarButton.cpp
|
Oipo/GWork
|
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
|
[
"MIT"
] | null | null | null |
gwen/src/Controls/ScrollBarButton.cpp
|
Oipo/GWork
|
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
|
[
"MIT"
] | null | null | null |
/*
* GWEN
* Copyright (c) 2010 Facepunch Studios
* See license in Gwen.h
*/
#include "Gwen/Controls/ScrollBar.h"
#include "Gwen/Controls/ScrollBarButton.h"
using namespace Gwen;
using namespace Gwen::Controls;
using namespace Gwen::ControlsInternal;
GWEN_CONTROL_CONSTRUCTOR(ScrollBarButton)
{
SetDirectionUp();
}
void ScrollBarButton::SetDirectionUp()
{
m_iDirection = Pos::Top;
}
void ScrollBarButton::SetDirectionDown()
{
m_iDirection = Pos::Bottom;
}
void ScrollBarButton::SetDirectionLeft()
{
m_iDirection = Pos::Left;
}
void ScrollBarButton::SetDirectionRight()
{
m_iDirection = Pos::Right;
}
void ScrollBarButton::Render(Skin::Base* skin)
{
skin->DrawScrollButton(this, m_iDirection, m_bDepressed, IsHovered(), IsDisabled());
}
| 17.244444
| 88
| 0.73067
|
Oipo
|
a3a4a844d1b5ad860436cf21522518c3d9d1738f
| 12,981
|
cpp
|
C++
|
src/smtrat-modules/MaxSMTModule/MaxSMTModule.cpp
|
modass/smtrat
|
2e6909bb764cf30d6afc231a2d447dfc13f3fa40
|
[
"MIT"
] | null | null | null |
src/smtrat-modules/MaxSMTModule/MaxSMTModule.cpp
|
modass/smtrat
|
2e6909bb764cf30d6afc231a2d447dfc13f3fa40
|
[
"MIT"
] | null | null | null |
src/smtrat-modules/MaxSMTModule/MaxSMTModule.cpp
|
modass/smtrat
|
2e6909bb764cf30d6afc231a2d447dfc13f3fa40
|
[
"MIT"
] | null | null | null |
/**
* @file MaxSMT.cpp
* @author YOUR NAME <YOUR EMAIL ADDRESS>
*
* @version 2019-01-25
* Created on 2019-01-25.
*/
#include "MaxSMTModule.h"
#include <smtrat-solver/Manager.h>
#include <smtrat-unsat-cores/smtrat-unsat-cores.h>
namespace smtrat
{
template<class Settings>
MaxSMTModule<Settings>::MaxSMTModule(const ModuleInput* _formula, Conditionals& _conditionals, Manager* _manager):
Module( _formula, _conditionals, _manager )
#ifdef SMTRAT_DEVOPTION_Statistics
, mStatistics(Settings::moduleName)
#endif
{}
template<class Settings>
MaxSMTModule<Settings>::~MaxSMTModule()
{}
template<class Settings>
bool MaxSMTModule<Settings>::informCore( const FormulaT& _constraint )
{
return true;
}
template<class Settings>
void MaxSMTModule<Settings>::init()
{}
template<class Settings>
bool MaxSMTModule<Settings>::addCore( ModuleInput::const_iterator _subformula )
{
// To this point we only expect receiving hard clauses. Soft clauses are saved in the manager.
// All hard clauses need to be passed on to the backend since they always have to be satisfied.
mBackend.add(_subformula->formula());
return true;
}
template<class Settings>
bool MaxSMTModule<Settings>::isSoft( const FormulaT& formula )
{
bool isSoft = false;
isSoft = isSoft || mpManager->weightedFormulas().find(formula) != mpManager->weightedFormulas().end(); // formula is initially soft
isSoft = isSoft || std::find(softclauses.begin(), softclauses.end(), formula) != softclauses.end(); // formula is softly created by algorithm
SMTRAT_LOG_DEBUG("smtrat.maxsmt", "Formula " << formula << " is soft: " << isSoft);
return isSoft;
}
template<class Settings>
void MaxSMTModule<Settings>::addSoftFormula( const FormulaT& formula )
{
softclauses.push_back(formula);
}
template<class Settings>
void MaxSMTModule<Settings>::removeCore( ModuleInput::const_iterator _subformula )
{
assert(false && "Removing from MAXSMT module could cause unexpected and inconsistent behavior.");
}
template<class Settings>
Answer MaxSMTModule<Settings>::checkCore()
{
SMTRAT_LOG_INFO("smtrat.maxsmt", "Running MAXSMT.");
// check sat for hard constraints. If UNSAT for hard-clauses, we are UNSAT, for unknown we are lost as well.
Answer ans = mBackend.check();
SMTRAT_LOG_DEBUG("smtrat.maxsmt", "Checking satisfiability of hard clauses... Got " << ans);
if (ans != Answer::SAT) return ans;
// populate all known soft clauses
for (auto softFormula : mpManager->weightedFormulas()) {
addSoftFormula(softFormula.first);
}
SMTRAT_LOG_INFO("smtrat.maxsmt", "Trying to maximize weight for following soft formulas " << softclauses);
std::vector<FormulaT> satiesfiedSoftClauses;
if (Settings::ALGORITHM == MAXSATAlgorithm::FU_MALIK_INCREMENTAL) {
SMTRAT_LOG_INFO("smtrat.maxsmt", "Running FUMALIK Algorithm.");
satiesfiedSoftClauses = runFuMalik();
} else if (Settings::ALGORITHM == MAXSATAlgorithm::LINEAR_SEARCH) {
SMTRAT_LOG_INFO("smtrat.maxsmt", "Running Linear Search Algorithm.");
satiesfiedSoftClauses = runLinearSearch();
} else if (Settings::ALGORITHM == MAXSATAlgorithm::MSU3) {
SMTRAT_LOG_INFO("smtrat.maxsmt", "Running MSU3 Algorithm.");
satiesfiedSoftClauses = runMSU3();
} else {
SMTRAT_LOG_ERROR("smtrat.maxsmt", "The selected MAXSATAlgorithm is not implemented.");
assert(false);
}
SMTRAT_LOG_DEBUG("smtrat.maxsmt", "Found maximal set of satisfied soft clauses: " << satiesfiedSoftClauses);
// at this point we can be sure to be SAT. Worst case is that all soft-constraints are false.
return Answer::SAT;
}
template<class Settings>
std::vector<FormulaT> MaxSMTModule<Settings>::runFuMalik()
{
getInfeasibleSubsets();
assert(mInfeasibleSubsets.size() == 0 && "hard clauses must be SAT and we haven't experienced any UNSAT yet.");
// a set of assignments we need to keep track of the enabled clauses
std::map<carl::Variable, FormulaT> assignments;
std::map<FormulaT, FormulaT> extendedClauses;
std::vector<FormulaT> newSoftClauses;
// now add all soft clauses with a blocking variable which we assert to false in order to enable all soft clauses
// NB! if we added the soft clauses directly to the backend we would need to remove them later on which is not what we want
// in an incremental approach
for (const FormulaT& clause : softclauses) {
carl::Variable blockingVar = carl::freshBooleanVariable();
// remember the blockingVar associated to clause
blockingVars[clause] = blockingVar;
// add the clause v blockingVar to backend
FormulaT clauseWithBlockingVar(carl::FormulaType::OR, FormulaT(blockingVar), clause);
extendedClauses[clauseWithBlockingVar] = clause;
mBackend.add(clauseWithBlockingVar);
// we may not add or remove from softclauses, hence we save a intermediate result which new soft clauses to add
newSoftClauses.push_back(clauseWithBlockingVar);
// enable the clause related to blocking var
assignments[blockingVar] = !FormulaT(blockingVar);
formulaPositionMap[assignments[blockingVar]] = addToLocalBackend(assignments[blockingVar]);
}
for (FormulaT& f : newSoftClauses) {
addSoftFormula(f); // need to add internally otherwise we assume that this would be a hard clause
SMTRAT_LOG_DEBUG("smtrat.maxsmt.fumalik", "Added new clause to backend " << f);
}
// TODO implement weighted case according to https://www.seas.upenn.edu/~xsi/data/cp16.pdf
for (;;) {
std::vector<carl::Variable> relaxationVars;
// try to solve
//Answer ans = runBackends();
Answer ans = mBackend.check();
SMTRAT_LOG_DEBUG("smtrat.maxsmt.fumalik", "Checked satisfiability of current soft/hardclause mixture got... " << ans);
if (ans == Answer::SAT) return gatherSatisfiedSoftClauses();
for (auto it : getUnsatCore()) {
if (!isSoft(it)) continue; // hard clauses are ignored here since we can not "relax".
relaxationVars.push_back(carl::freshBooleanVariable()); // r
carl::Variable blockingRelaxationVar = carl::freshBooleanVariable(); // b_r
// build new clause to add to formula
assert(extendedClauses.find(it) != extendedClauses.end());
FormulaT replacementClause = FormulaT(carl::FormulaType::OR, extendedClauses[it], FormulaT(relaxationVars.back()), FormulaT(blockingRelaxationVar));
addSoftFormula(replacementClause);
extendedClauses[replacementClause] = it;
blockingVars[replacementClause] = blockingRelaxationVar;
assignments[blockingRelaxationVar] = !FormulaT(blockingRelaxationVar);
SMTRAT_LOG_DEBUG("smtrat.maxsat.fumalik", "adding clause to backend: " << replacementClause);
mBackend.add(replacementClause);
formulaPositionMap[assignments[blockingRelaxationVar]] = addToLocalBackend(assignments[blockingRelaxationVar]);
// disable original clause
carl::Variable prevBlockingVar = blockingVars[extendedClauses[it]];
const auto& prevAssignment = assignments.find(prevBlockingVar);
assert(prevAssignment != assignments.end() && "Could not find an assignment which we must have made before.");
mBackend.remove(formulaPositionMap[prevAssignment->second]);
assignments.erase(prevAssignment);
SMTRAT_LOG_DEBUG("smtrat.maxsat.fumalik", "adding clause to backend: " << FormulaT(prevBlockingVar));
mBackend.add(FormulaT(prevBlockingVar));
}
Poly relaxationPoly;
for (carl::Variable& var : relaxationVars) {
relaxationPoly = relaxationPoly + var;
}
// \sum r \ in relaxationVars : r <= 1
FormulaT pbEncoding = FormulaT(ConstraintT(relaxationPoly - Rational(1),carl::Relation::LEQ));
mBackend.add(pbEncoding);
// addSubformulaToPassedFormula(pbEncoding); // translate/solve this in backend!
SMTRAT_LOG_DEBUG("smtrat.maxsmt.fumalik", "Adding cardinality constraint to solver: " << pbEncoding);
}
return gatherSatisfiedSoftClauses();
}
template<class Settings>
std::vector<FormulaT> MaxSMTModule<Settings>::runOLL()
{
return std::vector<FormulaT>();
}
template<class Settings>
std::vector<FormulaT> MaxSMTModule<Settings>::runLinearSearch()
{
// add all soft clauses with relaxation var
// for i = 0; i < soft.size; i++:
// check sat for \sum relaxation var <= i to determine if we have to disable some constraint
// if sat return;
std::vector<carl::Variable> relaxationVars;
for (const auto& clause : softclauses) {
carl::Variable relaxationVar = carl::freshBooleanVariable();
mBackend.add(FormulaT(carl::FormulaType::OR, clause, FormulaT(relaxationVar)));
relaxationVars.push_back(relaxationVar);
}
Poly relaxationPoly;
for (carl::Variable& var : relaxationVars) {
relaxationPoly = relaxationPoly + var;
}
// initially all constraints must be enabled
ConstraintT initialRelaxationConstraint(relaxationPoly - Rational(0),carl::Relation::LEQ);
ModuleInput::iterator previousRelaxationConstraint = addToLocalBackend(FormulaT(initialRelaxationConstraint));
for (unsigned i = 1; i < softclauses.size(); i++) {
// check sat for max i disables clauses
SMTRAT_LOG_DEBUG("smtrat.maxsmt.linear", "Trying to check SAT for " << i - 1 << " disabled soft constraints...");
Answer ans = mBackend.check();
if (ans == Answer::SAT) return gatherSatisfiedSoftClauses();
mBackend.remove(previousRelaxationConstraint);
ConstraintT relaxationConstraint(relaxationPoly - Rational(i),carl::Relation::LEQ);
previousRelaxationConstraint = addToLocalBackend(FormulaT(relaxationConstraint));
}
// from here, none of the soft clauses can be satisfied
return gatherSatisfiedSoftClauses();
}
template<class Settings>
std::vector<FormulaT> MaxSMTModule<Settings>::runMSU3()
{
// initialise data structures
for (const auto& clause : softclauses) {
// add clause backend and remember where we put it so we can easily remove it later
ModuleInput::iterator it = addToLocalBackend(clause);
formulaPositionMap[clause] = it;
}
std::vector<carl::Variable> relaxationVars;
std::vector<FormulaT> relaxedConstraints;
for (unsigned i = 0; i < softclauses.size(); i++) {
// rebuild polynomial since we add relaxation vars incrementally
Poly relaxationPoly;
for (carl::Variable& var : relaxationVars) {
relaxationPoly = relaxationPoly + var;
}
ConstraintT relaxationConstraint(relaxationPoly - Rational(i),carl::Relation::LEQ);
SMTRAT_LOG_DEBUG("smtrat.maxsmt.msu3", FormulaT(relaxationConstraint));
ModuleInput::iterator relaxationFormula = addToLocalBackend(FormulaT(relaxationConstraint));
SMTRAT_LOG_DEBUG("smtrat.maxsmt.msu3", "Checking SAT for up to " << i << " disabled constraints.");
Answer ans = mBackend.check();
if (ans == Answer::SAT) return gatherSatisfiedSoftClauses();
// We extract directly from the backend because newly added formulas get deleted from the infeasible subset!
FormulasT unsatisfiableCore = getUnsatCore();
SMTRAT_LOG_DEBUG("smtrat.maxsmt.msu3", "Got unsat core " << unsatisfiableCore);
for (const auto& f : unsatisfiableCore) { // for all soft constraints in unsat core...
if (!isSoft(f)) continue;
// check whether we already relaxed f
bool alreadyRelaxed = std::find(relaxedConstraints.begin(), relaxedConstraints.end(), f) != relaxedConstraints.end();
if (alreadyRelaxed) continue;
carl::Variable relaxationVar = carl::freshBooleanVariable();
mBackend.remove(formulaPositionMap[f]); // first erase non-relaxed clause
addToLocalBackend(FormulaT(carl::FormulaType::OR, f, FormulaT(relaxationVar))); // ...then add relaxed clause
relaxedConstraints.push_back(f);
relaxationVars.push_back(relaxationVar);
}
mBackend.remove(relaxationFormula); // remove cardinality constraint again
}
// from here, none of the soft clauses can be satisfied
return gatherSatisfiedSoftClauses();
}
template<class Settings>
std::vector<FormulaT> MaxSMTModule<Settings>::gatherSatisfiedSoftClauses()
{
std::vector<FormulaT> result;
for (const auto& clause : mpManager->weightedFormulas()) {
auto res = carl::model::substitute(FormulaT(clause.first), mBackend.model());
if (res.isTrue()) {
result.push_back(clause.first);
}
}
return result;
}
template<class Settings>
void MaxSMTModule<Settings>::updateModel() const
{
mModel.clear();
if( solverState() == Answer::SAT )
{
mModel = mBackend.model();
}
}
template<class Settings>
ModuleInput::iterator MaxSMTModule<Settings>::addToLocalBackend(const FormulaT& formula)
{
mBackend.add(formula);
for (auto it = mBackend.formulaEnd(); it != mBackend.formulaBegin(); --it) {
if (it->formula() == formula) {
return it;
}
}
assert(false && "Formula was not added correctly to backend. Expected to find formula.");
return mBackend.formulaEnd();
}
template<class Settings>
FormulasT MaxSMTModule<Settings>::getUnsatCore()
{
return computeUnsatCore(mBackend, UnsatCoreStrategy::ModelExclusion);
}
}
#include "Instantiation.h"
| 35.859116
| 152
| 0.732147
|
modass
|
a3aac52a4613339546a87ae6731c9fa4aa98d19e
| 3,100
|
cpp
|
C++
|
thrift/lib/cpp2/transport/rsocket/server/test/RequestResponseTest.cpp
|
ahhygx/fbthrift
|
48a91f91036a5201914b1ad9f98826709812ad10
|
[
"Apache-2.0"
] | null | null | null |
thrift/lib/cpp2/transport/rsocket/server/test/RequestResponseTest.cpp
|
ahhygx/fbthrift
|
48a91f91036a5201914b1ad9f98826709812ad10
|
[
"Apache-2.0"
] | null | null | null |
thrift/lib/cpp2/transport/rsocket/server/test/RequestResponseTest.cpp
|
ahhygx/fbthrift
|
48a91f91036a5201914b1ad9f98826709812ad10
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp2/transport/rsocket/server/test/RSResponderTestFixture.h>
#include <folly/io/async/EventBase.h>
#include <gtest/gtest.h>
#include <thrift/lib/cpp2/async/RSocketClientChannel.h>
#include <thrift/lib/cpp2/transport/core/testutil/CoreTestFixture.h>
#include <thrift/lib/cpp2/transport/rsocket/server/RSResponder.h>
#include <thrift/lib/cpp2/transport/rsocket/server/RequestResponse.h>
#include <yarpl/flowable/Flowable.h>
namespace apache {
namespace thrift {
using namespace testing;
using namespace testutil::testservice;
TEST_F(RSResponderTestFixture, RequestResponse_Simple) {
EXPECT_CALL(service_, sumTwoNumbers_(5, 10));
eventBase_.runInEventBaseThread([this]() {
folly::IOBufQueue request;
auto metadata = std::make_unique<RequestRpcMetadata>();
CoreTestFixture::serializeSumTwoNumbers(
5, 10, false, &request, metadata.get());
auto metaBuf = RSocketClientChannel::serializeMetadata(*metadata);
responder_->handleRequestResponse(
rsocket::Payload(request.move(), std::move(metaBuf)),
0,
yarpl::single::SingleObserver<rsocket::Payload>::create(
[](auto payload) {
auto result =
CoreTestFixture::deserializeSumTwoNumbers(payload.data.get());
EXPECT_EQ(result, 15);
},
[](folly::exception_wrapper) {
FAIL() << "No error is expected";
}));
});
eventBase_.loop();
threadManager_->join();
}
TEST_F(RSResponderTestFixture, RequestResponse_MissingRPCMethod) {
eventBase_.runInEventBaseThread([this]() {
folly::IOBufQueue request;
auto metadata = std::make_unique<RequestRpcMetadata>();
CoreTestFixture::serializeSumTwoNumbers(
5, 10, true, &request, metadata.get());
auto metaBuf = RSocketClientChannel::serializeMetadata(*metadata);
responder_->handleRequestResponse(
rsocket::Payload(request.move(), std::move(metaBuf)),
0,
yarpl::single::SingleObserver<rsocket::Payload>::create(
[](auto payload) {
EXPECT_THAT(
payload.data->cloneCoalescedAsValue()
.moveToFbString()
.toStdString(),
HasSubstr("not found"));
},
[](folly::exception_wrapper) {
FAIL() << "No error is expected";
}));
});
eventBase_.loop();
threadManager_->join();
}
} // namespace thrift
} // namespace apache
| 34.065934
| 81
| 0.66871
|
ahhygx
|
a3ac177bba8c2692598381b934a0de51a5a70568
| 1,817
|
cpp
|
C++
|
src/anl/source/pyfunc_anl.cpp
|
goroyabu/anlpy
|
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
|
[
"MIT"
] | null | null | null |
src/anl/source/pyfunc_anl.cpp
|
goroyabu/anlpy
|
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
|
[
"MIT"
] | null | null | null |
src/anl/source/pyfunc_anl.cpp
|
goroyabu/anlpy
|
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
|
[
"MIT"
] | null | null | null |
/**
@date 2020/03/27
**/
#include "VANL_Module.hpp"
#include "ANLmanager.hpp"
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
PYBIND11_MODULE(anlpy, m) {
m.attr("__name__") = "anlpy";
m.doc() = R"pbdoc(
ANLpy Documentation
-----------------------
.. currentmodule:: anlpy
.. autosummary::
:toctree: _generate
)pbdoc";
pybind11::class_<anl::VANL_Module>(m, "VANL_Module")
.def(pybind11::init<>())
.def(pybind11::init<const std::string, const std::string>())
.def(pybind11::init<const anl::VANL_Module&>())
.def("SetParameter", &anl::VANL_Module::set_parameter<int>)
.def("SetParameter", &anl::VANL_Module::set_parameter<double>)
.def("SetParameter", &anl::VANL_Module::set_parameter<bool>)
.def("SetParameter", &anl::VANL_Module::set_parameter<std::string>)
.def("DefineParameter", &anl::VANL_Module::define_parameter<int>)
.def("DefineParameter", &anl::VANL_Module::define_parameter<double>)
.def("DefineParameter", &anl::VANL_Module::define_parameter<bool>)
.def("DefineParameter", &anl::VANL_Module::define_parameter<std::string>)
.def("ShowParameter", &anl::VANL_Module::show_parameters);
pybind11::class_<anl::ANLmanager, anl::VANL_Module>(m, "ANLmanager")
.def(pybind11::init<>())
.def(pybind11::init<const anl::ANLmanager&>())
.def("AddModule", &anl::ANLmanager::add_module)
.def(
"ReadData", &anl::ANLmanager::read_data,
pybind11::arg("nevent")=-1, pybind11::arg("print_freq")=10
)
.def("ShowAnalysis", &anl::ANLmanager::show_analysis)
.def("ShowStatus", &anl::ANLmanager::show_status)
.def("Quit", &anl::ANLmanager::quit)
.def("ResetStatus", &anl::ANLmanager::reset_status);
#ifdef VERSION_INFO
m.attr("__version__") = VERSION_INFO;
#else
m.attr("__version__") = "dev";
#endif
}
| 31.327586
| 74
| 0.669785
|
goroyabu
|
a3ae6eb4269f4e4e1f7f0ada847254caa7e424ec
| 29,897
|
cpp
|
C++
|
vstgui/lib/cbitmapfilter.cpp
|
whydoubt/vstgui
|
24c6e5e82f55fd1eff0fb5ab3b451adc912d29d5
|
[
"BSD-3-Clause"
] | null | null | null |
vstgui/lib/cbitmapfilter.cpp
|
whydoubt/vstgui
|
24c6e5e82f55fd1eff0fb5ab3b451adc912d29d5
|
[
"BSD-3-Clause"
] | null | null | null |
vstgui/lib/cbitmapfilter.cpp
|
whydoubt/vstgui
|
24c6e5e82f55fd1eff0fb5ab3b451adc912d29d5
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#include "cbitmapfilter.h"
#include "cbitmap.h"
#include "platform/iplatformbitmap.h"
#include "ccolor.h"
#include "cgraphicspath.h"
#include "cgraphicstransform.h"
#include <cassert>
#include <algorithm>
#include <memory>
namespace VSTGUI {
namespace BitmapFilter {
//----------------------------------------------------------------------------------------------------
template<typename T> void Property::assign (T toAssign)
{
value = std::malloc (sizeof (toAssign));
memcpy (value, &toAssign, sizeof (toAssign));
}
//----------------------------------------------------------------------------------------------------
Property::Property (Type type)
: type (type)
, value (nullptr)
{
}
//----------------------------------------------------------------------------------------------------
Property::Property (int32_t intValue)
: type (kInteger)
{
assign (intValue);
}
//----------------------------------------------------------------------------------------------------
Property::Property (double floatValue)
: type (kFloat)
{
assign (floatValue);
}
//----------------------------------------------------------------------------------------------------
Property::Property (IReference* objectValue)
: type (kObject)
{
value = static_cast<void*> (objectValue);
objectValue->remember ();
}
//----------------------------------------------------------------------------------------------------
Property::Property (const CRect& rectValue)
: type (kRect)
{
assign (rectValue);
}
//----------------------------------------------------------------------------------------------------
Property::Property (const CPoint& pointValue)
: type (kPoint)
{
assign (pointValue);
}
//----------------------------------------------------------------------------------------------------
Property::Property (const CColor& colorValue)
: type (kColor)
{
assign (colorValue);
}
//----------------------------------------------------------------------------------------------------
Property::Property (const CGraphicsTransform& transformValue)
: type (kTransformMatrix)
{
assign (transformValue);
}
//----------------------------------------------------------------------------------------------------
Property::Property (const Property& p)
: type (p.type)
, value (nullptr)
{
*this = p;
}
//----------------------------------------------------------------------------------------------------
Property::~Property () noexcept
{
if (value)
{
if (type == kObject)
getObject ()->forget ();
else
std::free (value);
}
}
//----------------------------------------------------------------------------------------------------
Property::Property (Property&& p) noexcept
: value (nullptr)
{
*this = std::move (p);
}
//----------------------------------------------------------------------------------------------------
Property& Property::operator=(Property&& p) noexcept
{
if (value)
{
if (type == kObject)
getObject ()->forget ();
else
std::free (value);
}
type = p.type;
value = p.value;
p.value = nullptr;
p.type = kUnknown;
return *this;
}
//----------------------------------------------------------------------------------------------------
Property& Property::operator=(const Property& p)
{
if (value)
{
if (type == kObject)
getObject ()->forget ();
else
std::free (value);
value = nullptr;
}
type = p.type;
if (p.value)
{
uint32_t valueSize = 0u;
switch (type)
{
case kInteger: valueSize = sizeof (int32_t); break;
case kFloat: valueSize = sizeof (double); break;
case kObject: value = p.value; p.getObject ()->remember (); break;
case kRect: valueSize = sizeof (CRect); break;
case kPoint: valueSize = sizeof (CPoint); break;
case kColor: valueSize = sizeof (CColor); break;
case kTransformMatrix: valueSize = sizeof (CGraphicsTransform); break;
case kUnknown: valueSize = 0u; break;
}
if (valueSize)
{
value = std::malloc (valueSize);
memcpy (value, p.value, valueSize);
}
}
return *this;
}
//----------------------------------------------------------------------------------------------------
int32_t Property::getInteger () const
{
vstgui_assert (type == kInteger);
return *static_cast<int32_t*> (value);
}
//----------------------------------------------------------------------------------------------------
double Property::getFloat () const
{
vstgui_assert (type == kFloat);
return *static_cast<double*> (value);
}
//----------------------------------------------------------------------------------------------------
IReference* Property::getObject () const
{
vstgui_assert (type == kObject);
return static_cast<IReference*> (value);
}
//----------------------------------------------------------------------------------------------------
const CRect& Property::getRect () const
{
vstgui_assert (type == kRect);
return *static_cast<CRect*> (value);
}
//----------------------------------------------------------------------------------------------------
const CPoint& Property::getPoint () const
{
vstgui_assert (type == kPoint);
return *static_cast<CPoint*> (value);
}
//----------------------------------------------------------------------------------------------------
const CColor& Property::getColor () const
{
vstgui_assert (type == kColor);
return *static_cast<CColor*> (value);
}
//----------------------------------------------------------------------------------------------------
const CGraphicsTransform& Property::getTransform () const
{
vstgui_assert (type == kTransformMatrix);
return *static_cast<CGraphicsTransform*> (value);
}
namespace Standard {
static void registerStandardFilters (Factory& factory);
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
Factory& Factory::getInstance ()
{
static Factory gInstance;
static bool initialized = false;
if (initialized == false)
{
Standard::registerStandardFilters (gInstance);
initialized = true;
}
return gInstance;
}
//----------------------------------------------------------------------------------------------------
uint32_t Factory::getNumFilters () const
{
return (uint32_t)filters.size ();
}
//----------------------------------------------------------------------------------------------------
IdStringPtr Factory::getFilterName (uint32_t index) const
{
for (const auto& filter : filters)
{
if (index == 0)
return filter.first.c_str ();
--index;
}
return nullptr;
}
//----------------------------------------------------------------------------------------------------
IFilter* Factory::createFilter (IdStringPtr name) const
{
FilterMap::const_iterator it = filters.find (name);
if (it != filters.end ())
return (*it).second (name);
return nullptr;
}
//----------------------------------------------------------------------------------------------------
bool Factory::registerFilter (IdStringPtr name, IFilter::CreateFunction createFunction)
{
FilterMap::iterator it = filters.find (name);
if (it != filters.end ())
it->second = createFunction;
else
filters.emplace (name, createFunction);
return true;
}
//----------------------------------------------------------------------------------------------------
bool Factory::unregisterFilter (IdStringPtr name, IFilter::CreateFunction createFunction)
{
FilterMap::iterator it = filters.find (name);
if (it == filters.end ())
return false;
filters.erase (it);
return true;
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
FilterBase::FilterBase (UTF8StringPtr description)
: description (description ? description : "")
{
}
//----------------------------------------------------------------------------------------------------
UTF8StringPtr FilterBase::getDescription () const
{
return description.c_str ();
}
//----------------------------------------------------------------------------------------------------
bool FilterBase::setProperty (IdStringPtr name, const Property& property)
{
auto it = properties.find (name);
if (it != properties.end () && it->second.getType () == property.getType ())
{
properties[name] = property;
return true;
}
return false;
}
//----------------------------------------------------------------------------------------------------
bool FilterBase::setProperty (IdStringPtr name, Property&& property)
{
auto it = properties.find (name);
if (it != properties.end () && it->second.getType () == property.getType ())
{
properties[name] = std::move (property);
return true;
}
return false;
}
//----------------------------------------------------------------------------------------------------
const Property& FilterBase::getProperty (IdStringPtr name) const
{
auto it = properties.find (name);
if (it != properties.end ())
return it->second;
static Property notFound (Property::kUnknown);
return notFound;
}
//----------------------------------------------------------------------------------------------------
uint32_t FilterBase::getNumProperties () const
{
return static_cast<uint32_t> (properties.size ());
}
//----------------------------------------------------------------------------------------------------
IdStringPtr FilterBase::getPropertyName (uint32_t index) const
{
for (const auto & it : properties)
{
if (index == 0)
return it.first.c_str ();
index--;
}
return nullptr;
}
//----------------------------------------------------------------------------------------------------
Property::Type FilterBase::getPropertyType (uint32_t index) const
{
for (const auto & it : properties)
{
if (index == 0)
return it.second.getType ();
index--;
}
return Property::kUnknown;
}
//----------------------------------------------------------------------------------------------------
Property::Type FilterBase::getPropertyType (IdStringPtr name) const
{
auto it = properties.find (name);
if (it != properties.end ())
{
return (*it).second.getType ();
}
return Property::kUnknown;
}
//----------------------------------------------------------------------------------------------------
bool FilterBase::registerProperty (IdStringPtr name, const Property& defaultProperty)
{
return properties.emplace (name, defaultProperty).second;
}
//----------------------------------------------------------------------------------------------------
CBitmap* FilterBase::getInputBitmap () const
{
auto it = properties.find (Standard::Property::kInputBitmap);
if (it != properties.end ())
{
auto obj = (*it).second.getObject ();
return obj ? dynamic_cast<CBitmap*>(obj) : nullptr;
}
return nullptr;
}
///@cond ignore
namespace Standard {
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
class BoxBlur : public FilterBase
{
public:
static IFilter* CreateFunction (IdStringPtr _name)
{
return new BoxBlur ();
}
private:
BoxBlur ()
: FilterBase ("A Box Blur Filter")
{
registerProperty (Property::kInputBitmap, BitmapFilter::Property (BitmapFilter::Property::kObject));
registerProperty (Property::kRadius, BitmapFilter::Property ((int32_t)2));
}
bool run (bool replace) override
{
CBitmap* inputBitmap = getInputBitmap ();
uint32_t radius = static_cast<uint32_t>(static_cast<double>(getProperty (Property::kRadius).getInteger ()) * inputBitmap->getPlatformBitmap ()->getScaleFactor ());
if (inputBitmap == nullptr || radius == UINT_MAX)
return false;
if (radius < 2)
{
if (replace)
return true;
return false; // TODO: We should just copy the input bitmap to the output bitmap
}
if (replace)
{
SharedPointer<CBitmapPixelAccess> inputAccessor = owned (CBitmapPixelAccess::create (inputBitmap));
if (inputAccessor == nullptr)
return false;
run (*inputAccessor, *inputAccessor, radius);
return registerProperty (Property::kOutputBitmap, BitmapFilter::Property (inputBitmap));
}
SharedPointer<CBitmap> outputBitmap = owned (new CBitmap (inputBitmap->getWidth (), inputBitmap->getHeight ()));
if (outputBitmap)
{
SharedPointer<CBitmapPixelAccess> inputAccessor = owned (CBitmapPixelAccess::create (inputBitmap));
SharedPointer<CBitmapPixelAccess> outputAccessor = owned (CBitmapPixelAccess::create (outputBitmap));
if (inputAccessor == nullptr || outputAccessor == nullptr)
return false;
run (*inputAccessor, *outputAccessor, radius);
return registerProperty (Property::kOutputBitmap, BitmapFilter::Property (outputBitmap));
}
return false;
}
void run (CBitmapPixelAccess& inputAccessor, CBitmapPixelAccess& outputAccessor, uint32_t radius)
{
auto inputPbpa = inputAccessor.getPlatformBitmapPixelAccess ();
auto outputPbpa = outputAccessor.getPlatformBitmapPixelAccess ();
auto inputAddressPtr = inputPbpa->getAddress ();
auto outputAddressPtr = outputPbpa->getAddress ();
auto width = inputPbpa->getBytesPerRow () / 4;
auto height = inputAccessor.getBitmapHeight ();
switch (inputPbpa->getPixelFormat ())
{
case IPlatformBitmapPixelAccess::kARGB:
case IPlatformBitmapPixelAccess::kABGR:
{
algo<0, 1, 2, 3> (inputAddressPtr, outputAddressPtr, width, height,
static_cast<int32_t> (radius / 2));
break;
}
case IPlatformBitmapPixelAccess::kRGBA:
case IPlatformBitmapPixelAccess::kBGRA:
{
algo<1, 2, 3, 0> (inputAddressPtr, outputAddressPtr, width, height,
static_cast<int32_t> (radius / 2));
break;
}
}
}
template <int32_t redPos, int32_t greenPos, int32_t bluePos, int32_t alphaPos>
void algo (uint8_t* inputPixel, uint8_t* outputPixel, int32_t width, int32_t height,
int32_t radius)
{
vstgui_assert (radius > 0);
constexpr int32_t numComponents = 4;
int32_t wm = width - 1;
int32_t hm = height - 1;
int32_t areaSize = width * height;
int32_t div = radius + radius + 1;
auto red = std::unique_ptr<uint8_t[]> (new uint8_t[areaSize]);
auto green = std::unique_ptr<uint8_t[]> (new uint8_t[areaSize]);
auto blue = std::unique_ptr<uint8_t[]> (new uint8_t[areaSize]);
auto vMin = std::unique_ptr<int32_t[]> (new int32_t[std::max (width, height)]);
auto vMax = std::unique_ptr<int32_t[]> (new int32_t[std::max (width, height)]);
auto dv = std::unique_ptr<uint8_t[]> (new uint8_t[256 * div]);
for (auto i = 0; i < 256 * div; ++i)
dv[i] = (i / div);
int32_t rsum, gsum, bsum;
for (auto y = 0, yw = 0, yi = 0; y < height; ++y, yw += width)
{
rsum = gsum = bsum = 0;
for (auto i = -radius; i <= radius; i++)
{
auto p = (yi + std::min (wm, std::max (i, 0))) * numComponents;
rsum += inputPixel[p + redPos];
gsum += inputPixel[p + greenPos];
bsum += inputPixel[p + bluePos];
}
if (y == 0)
{
for (auto x = 0; x < width; ++x, ++yi)
{
red[yi] = dv[rsum];
green[yi] = dv[gsum];
blue[yi] = dv[bsum];
vMin[x] = std::min (x + radius + 1, wm);
vMax[x] = std::max (x - radius, 0);
auto p1 = (yw + vMin[x]) * numComponents;
auto p2 = (yw + vMax[x]) * numComponents;
rsum += inputPixel[p1 + redPos] - inputPixel[p2 + redPos];
gsum += inputPixel[p1 + greenPos] - inputPixel[p2 + greenPos];
bsum += inputPixel[p1 + bluePos] - inputPixel[p2 + bluePos];
}
}
else
{
for (auto x = 0; x < width; ++x, ++yi)
{
red[yi] = dv[rsum];
green[yi] = dv[gsum];
blue[yi] = dv[bsum];
auto p1 = (yw + vMin[x]) * numComponents;
auto p2 = (yw + vMax[x]) * numComponents;
rsum += inputPixel[p1 + redPos] - inputPixel[p2 + redPos];
gsum += inputPixel[p1 + greenPos] - inputPixel[p2 + greenPos];
bsum += inputPixel[p1 + bluePos] - inputPixel[p2 + bluePos];
}
}
}
rsum = gsum = bsum = 0;
for (auto i = -radius, yp = -radius * width; i <= radius; ++i, yp += width)
{
auto yi = std::max (0, yp);
rsum += red[yi];
gsum += green[yi];
bsum += blue[yi];
}
for (auto y = 0, yi = 0; y < height; ++y, yi += width)
{
auto pos = yi * numComponents;
outputPixel[pos + redPos] = dv[rsum];
outputPixel[pos + greenPos] = dv[gsum];
outputPixel[pos + bluePos] = dv[bsum];
outputPixel[pos + alphaPos] = inputPixel[pos + alphaPos];
vMin[y] = std::min (y + radius + 1, hm) * width;
vMax[y] = std::max (y - radius, 0) * width;
auto p1 = vMin[y];
auto p2 = vMax[y];
rsum += red[p1] - red[p2];
gsum += green[p1] - green[p2];
bsum += blue[p1] - blue[p2];
}
for (auto x = 1; x < width; ++x)
{
rsum = gsum = bsum = 0;
for (auto i = -radius, yp = -radius * width; i <= radius; ++i, yp += width)
{
auto yi = std::max (0, yp) + x;
rsum += red[yi];
gsum += green[yi];
bsum += blue[yi];
}
for (auto y = 0, yi = x; y < height; ++y, yi += width)
{
auto pos = yi * numComponents;
outputPixel[pos + redPos] = dv[rsum];
outputPixel[pos + greenPos] = dv[gsum];
outputPixel[pos + bluePos] = dv[bsum];
outputPixel[pos + alphaPos] = inputPixel[pos + alphaPos];
auto p1 = x + vMin[y];
auto p2 = x + vMax[y];
rsum += red[p1] - red[p2];
gsum += green[p1] - green[p2];
bsum += blue[p1] - blue[p2];
}
}
}
};
//----------------------------------------------------------------------------------------------------
class ScaleBase : public FilterBase
{
protected:
ScaleBase (UTF8StringPtr description = "")
: FilterBase (description)
{
registerProperty (Property::kInputBitmap, BitmapFilter::Property (BitmapFilter::Property::kObject));
registerProperty (Property::kOutputRect, CRect (0, 0, 10, 10));
}
bool run (bool replace) override
{
if (replace)
return false;
CRect outSize = getProperty (Property::kOutputRect).getRect ();
outSize.makeIntegral ();
if (outSize.getWidth () <= 0 || outSize.getHeight () <= 0)
return false;
CBitmap* inputBitmap = getInputBitmap ();
if (inputBitmap == nullptr)
return false;
SharedPointer<CBitmap> outputBitmap = owned (new CBitmap (outSize.getWidth (), outSize.getHeight ()));
if (outputBitmap == nullptr)
return false;
SharedPointer<CBitmapPixelAccess> inputAccessor = owned (CBitmapPixelAccess::create (inputBitmap));
SharedPointer<CBitmapPixelAccess> outputAccessor = owned (CBitmapPixelAccess::create (outputBitmap));
if (inputAccessor == nullptr || outputAccessor == nullptr)
return false;
process (*inputAccessor, *outputAccessor);
return registerProperty (Property::kOutputBitmap, BitmapFilter::Property (outputBitmap));
}
virtual void process (CBitmapPixelAccess& originalBitmap, CBitmapPixelAccess& copyBitmap) = 0;
};
//----------------------------------------------------------------------------------------------------
class ScaleLinear : public ScaleBase
{
public:
static IFilter* CreateFunction (IdStringPtr _name)
{
return new ScaleLinear ();
}
private:
ScaleLinear () : ScaleBase ("A Linear Scale Filter") {}
void process (CBitmapPixelAccess& originalBitmap, CBitmapPixelAccess& copyBitmap) override
{
originalBitmap.setPosition (0, 0);
copyBitmap.setPosition (0, 0);
uint32_t origWidth = (uint32_t)originalBitmap.getBitmapWidth ();
uint32_t origHeight = (uint32_t)originalBitmap.getBitmapHeight ();
uint32_t newWidth = (uint32_t)copyBitmap.getBitmapWidth ();
uint32_t newHeight = (uint32_t)copyBitmap.getBitmapHeight ();
float xRatio = (float)origWidth / (float)newWidth;
float yRatio = (float)origHeight / (float)newHeight;
uint8_t* origAddress = originalBitmap.getPlatformBitmapPixelAccess ()->getAddress ();
uint8_t* copyAddress = copyBitmap.getPlatformBitmapPixelAccess ()->getAddress ();
uint32_t origBytesPerRow = originalBitmap.getPlatformBitmapPixelAccess ()->getBytesPerRow ();
uint32_t copyBytesPerRow = copyBitmap.getPlatformBitmapPixelAccess ()->getBytesPerRow ();
int32_t ix;
int32_t iy = -1;
int32_t* origPixel = nullptr;
float origY = 0;
float origX = 0;
for (uint32_t y = 0; y < newHeight; y++, origY += yRatio)
{
int32_t* copyPixel = (int32_t*)(copyAddress + y * copyBytesPerRow);
if (iy != (int32_t)origY)
iy = (int32_t)origY;
ix = -1;
origX = 0;
for (uint32_t x = 0; x < newWidth; x++, origX += xRatio, copyPixel++)
{
if (ix != (int32_t)origX || origPixel == nullptr)
{
ix = (int32_t)origX;
vstgui_assert (iy >= 0);
origPixel = (int32_t*)(origAddress + static_cast<uint32_t> (iy) * origBytesPerRow + ix * 4);
}
*copyPixel = *origPixel;
}
}
}
};
//----------------------------------------------------------------------------------------------------
class ScaleBiliniear : public ScaleBase
{
public:
static IFilter* CreateFunction (IdStringPtr _name)
{
return new ScaleBiliniear ();
}
private:
ScaleBiliniear () : ScaleBase ("A Biliniear Scale Filter") {}
void process (CBitmapPixelAccess& originalBitmap, CBitmapPixelAccess& copyBitmap) override
{
originalBitmap.setPosition (0, 0);
copyBitmap.setPosition (0, 0);
uint32_t origWidth = (uint32_t)originalBitmap.getBitmapWidth ();
uint32_t origHeight = (uint32_t)originalBitmap.getBitmapHeight ();
uint32_t newWidth = (uint32_t)copyBitmap.getBitmapWidth ();
uint32_t newHeight = (uint32_t)copyBitmap.getBitmapHeight ();
float xRatio = ((float)(origWidth-1)) / (float)newWidth;
float yRatio = ((float)(origHeight-1)) / (float)newHeight;
float xDiff, yDiff, r, g, b, a;
uint32_t x, y;
CColor color[4];
CColor result;
for (uint32_t i = 0; i < newHeight; i++)
{
y = static_cast<uint32_t> (yRatio * i);
yDiff = (yRatio * i) - y;
for (uint32_t j = 0; j < newWidth; j++, ++copyBitmap)
{
x = static_cast<uint32_t> (xRatio * j);
xDiff = (xRatio * j) - x;
originalBitmap.setPosition (x, y);
originalBitmap.getColor (color[0]);
originalBitmap.setPosition (x+1, y);
originalBitmap.getColor (color[1]);
originalBitmap.setPosition (x, y+1);
originalBitmap.getColor (color[2]);
originalBitmap.setPosition (x+1, y+1);
originalBitmap.getColor (color[3]);
r = color[0].red * (1.f - xDiff) * (1.f - yDiff) + color[1].red * xDiff * (1.f - yDiff)
+ color[2].red * yDiff * (1.f - xDiff) + color[3].red * xDiff * yDiff;
g = color[0].green * (1.f - xDiff) * (1.f - yDiff) + color[1].green * xDiff * (1.f - yDiff)
+ color[2].green * yDiff * (1.f - xDiff) + color[3].green * xDiff * yDiff;
b = color[0].blue * (1.f - xDiff) * (1.f - yDiff) + color[1].blue * xDiff * (1.f - yDiff)
+ color[2].blue * yDiff * (1.f - xDiff) + color[3].blue * xDiff * yDiff;
a = color[0].alpha * (1.f - xDiff) * (1.f - yDiff) + color[1].alpha * xDiff * (1.f - yDiff)
+ color[2].alpha * yDiff * (1.f - xDiff) + color[3].alpha * xDiff * yDiff;
result = CColor ((uint8_t)r, (uint8_t)g, (uint8_t)b, (uint8_t)a);
copyBitmap.setColor (result);
}
}
}
};
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
using SimpleFilterProcessFunction = void (*) (CColor& color, FilterBase* self);
template<typename SimpleFilterProcessFunction>
class SimpleFilter : public FilterBase
{
protected:
SimpleFilter (UTF8StringPtr description, SimpleFilterProcessFunction function)
: FilterBase (description)
, processFunction (function)
{
registerProperty (Property::kInputBitmap, BitmapFilter::Property (BitmapFilter::Property::kObject));
}
bool run (bool replace) override
{
SharedPointer<CBitmap> inputBitmap = getInputBitmap ();
if (inputBitmap == nullptr)
return false;
SharedPointer<CBitmapPixelAccess> inputAccessor = owned (CBitmapPixelAccess::create (inputBitmap));
if (inputAccessor == nullptr)
return false;
SharedPointer<CBitmap> outputBitmap;
SharedPointer<CBitmapPixelAccess> outputAccessor;
if (replace == false)
{
outputBitmap = owned (new CBitmap (inputBitmap->getWidth (), inputBitmap->getHeight ()));
if (outputBitmap == nullptr)
return false;
outputAccessor = owned (CBitmapPixelAccess::create (outputBitmap));
if (outputAccessor == nullptr)
return false;
}
else
{
outputBitmap = inputBitmap;
outputAccessor = inputAccessor;
}
run (*inputAccessor, *outputAccessor);
return registerProperty (Property::kOutputBitmap, BitmapFilter::Property (outputBitmap));
}
void run (CBitmapPixelAccess& inputAccessor, CBitmapPixelAccess& outputAccessor)
{
inputAccessor.setPosition (0, 0);
outputAccessor.setPosition (0, 0);
CColor color;
if (&inputAccessor == &outputAccessor)
{
do
{
inputAccessor.getColor (color);
processFunction (color, this);
outputAccessor.setColor (color);
}
while (++inputAccessor);
}
else
{
do
{
inputAccessor.getColor (color);
processFunction (color, this);
outputAccessor.setColor (color);
++outputAccessor;
}
while (++inputAccessor);
}
}
SimpleFilterProcessFunction processFunction;
};
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
class SetColor : public SimpleFilter<SimpleFilterProcessFunction>
{
public:
static IFilter* CreateFunction (IdStringPtr _name)
{
return new SetColor ();
}
private:
SetColor ()
: SimpleFilter<SimpleFilterProcessFunction> ("A Set Color Filter", processSetColor)
{
registerProperty (Property::kIgnoreAlphaColorValue, BitmapFilter::Property ((int32_t)1));
registerProperty (Property::kInputColor, BitmapFilter::Property (kWhiteCColor));
}
static void processSetColor (CColor& color, FilterBase* obj)
{
SetColor* filter = static_cast<SetColor*> (obj);
if (filter->ignoreAlpha)
filter->inputColor.alpha = color.alpha;
color = filter->inputColor;
}
bool ignoreAlpha;
CColor inputColor;
bool run (bool replace) override
{
inputColor = getProperty (Property::kInputColor).getColor ();
ignoreAlpha = getProperty (Property::kIgnoreAlphaColorValue).getInteger () > 0;
return SimpleFilter<SimpleFilterProcessFunction>::run (replace);
}
};
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
class Grayscale : public SimpleFilter<SimpleFilterProcessFunction>
{
public:
static IFilter* CreateFunction (IdStringPtr name)
{
return new Grayscale ();
}
private:
Grayscale ()
: SimpleFilter<SimpleFilterProcessFunction> ("A Grayscale Filter", processGrayscale)
{
}
static void processGrayscale (CColor& color, FilterBase* obj)
{
color.red = color.green = color.blue = color.getLuma ();
}
};
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
class ReplaceColor : public SimpleFilter<SimpleFilterProcessFunction>
{
public:
static IFilter* CreateFunction (IdStringPtr name)
{
return new ReplaceColor ();
}
private:
ReplaceColor ()
: SimpleFilter<SimpleFilterProcessFunction> ("A Replace Color Filter", processReplace)
{
registerProperty (Property::kInputColor, BitmapFilter::Property (kWhiteCColor));
registerProperty (Property::kOutputColor, BitmapFilter::Property (kTransparentCColor));
}
static void processReplace (CColor& color, FilterBase* obj)
{
ReplaceColor* filter = static_cast<ReplaceColor*> (obj);
if (color == filter->inputColor)
color = filter->outputColor;
}
CColor inputColor;
CColor outputColor;
bool run (bool replace) override
{
inputColor = getProperty (Property::kInputColor).getColor ();
outputColor = getProperty (Property::kOutputColor).getColor ();
return SimpleFilter<SimpleFilterProcessFunction>::run (replace);
}
};
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
void registerStandardFilters (Factory& factory)
{
factory.registerFilter (kBoxBlur, BoxBlur::CreateFunction);
factory.registerFilter (kSetColor, SetColor::CreateFunction);
factory.registerFilter (kGrayscale, Grayscale::CreateFunction);
factory.registerFilter (kReplaceColor, ReplaceColor::CreateFunction);
factory.registerFilter (kScaleBilinear, ScaleBiliniear::CreateFunction);
factory.registerFilter (kScaleLinear, ScaleLinear::CreateFunction);
}
} // namespace Standard
///@end cond
}} // namespaces
| 32.112782
| 165
| 0.53487
|
whydoubt
|
a3af498e127b3e474fda3530c67d0ed9e7e52e48
| 7,312
|
cpp
|
C++
|
src/http/server/http-thread.cpp
|
corehacker/ch-cpp-utils
|
4b03045fbecc867f7c6b088eabd8aa4cc30f1170
|
[
"MIT"
] | 5
|
2017-11-05T11:41:42.000Z
|
2020-09-03T07:49:12.000Z
|
src/http/server/http-thread.cpp
|
corehacker/ch-cpp-utils
|
4b03045fbecc867f7c6b088eabd8aa4cc30f1170
|
[
"MIT"
] | 1
|
2017-11-14T02:50:16.000Z
|
2017-11-14T02:50:16.000Z
|
src/http/server/http-thread.cpp
|
corehacker/ch-cpp-utils
|
4b03045fbecc867f7c6b088eabd8aa4cc30f1170
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* BSD 2-Clause License
*
* Copyright (c) 2017, Sandeep Prakash
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/*******************************************************************************
* Copyright (c) 2017, Sandeep Prakash <123sandy@gmail.com>
*
* \file http-thread.cpp
*
* \author Sandeep Prakash
*
* \date Oct 26, 2017
*
* \brief
*
******************************************************************************/
#include <glog/logging.h>
#include "ch-cpp-utils/http/server/http.hpp"
namespace ChCppUtils {
namespace Http {
namespace Server {
struct evhttp_bound_socket *HttpThread::evListenSocket = nullptr;
RequestMetadata::RequestMetadata() {
}
RequestMetadata::~RequestMetadata() {
}
Request::Request(HttpThread *threadCtxt, evhttp_request *request) {
this->mThreadCtxt = threadCtxt;
this->request = request;
}
evhttp_request *Request::getRequest() {
return request;
}
HttpThread *Request::getThreadCtxt() {
return mThreadCtxt;
}
void Request::accessLog() {
LOG(INFO) << "Request onComplete";
}
string RequestEvent::getNextQuery(string path, size_t from) {
if (from >= path.size()) return "";
size_t pos = path.find("&", from);
return path.substr(from, (pos - from));
}
void RequestEvent::buildHeaderMap(evhttp_request *req) {
struct evkeyvalq *headers = req->input_headers;
struct evkeyval *header = headers->tqh_first;
while(header) {
// LOG(INFO) << "Header: " << header->key << ": " << header->value;
this->headers.insert(make_pair(header->key, header->value));
header = header->next.tqe_next;
}
}
void RequestEvent::buildQueryMap(evhttp_request *req) {
const char *q = evhttp_uri_get_query(req->uri_elems);
if(q) {
string query(q);
size_t from = 0;
string token = getNextQuery(query, 0);
while (token.size() != 0) {
string name, value;
if(token.find_first_of("=") != string::npos) {
name = token.substr(0, token.find_first_of("="));
value = token.substr(token.find_first_of("=") + 1);
} else {
name = token;
value = "";
}
LOG(INFO) << "Query: " << name << " = " << value;
this->query.insert(make_pair(name, value));
from += token.size() + 1;
token = getNextQuery(query, from);
}
}
}
RequestEvent::RequestEvent(Request *request) {
body = nullptr;
length = 0;
evhttp_request *req = request->getRequest();
buildHeaderMap(req);
buildQueryMap(req);
path = evhttp_uri_get_path(req->uri_elems);
this->request= request;
}
Request *RequestEvent::getRequest() {
return request;
}
HttpHeaders &RequestEvent::getHeaders() {
return headers;
}
void RequestEvent::setBody(void *body) {
this->body = body;
}
void RequestEvent::setLength(size_t length) {
this->length = length;
}
bool RequestEvent::hasBody() {
return body && length;
}
void *RequestEvent::getBody(){
return body;
}
size_t RequestEvent::getLength() {
return length;
}
HttpQuery &RequestEvent::getQuery() {
return query;
}
string &RequestEvent::getPath() {
return path;
}
OnRequest::OnRequest() {
onrequest = nullptr;
}
OnRequest &OnRequest::set(_OnRequest onrequest) {
this->onrequest = onrequest;
return *this;
}
void OnRequest::bind(void *this_) {
this->this_ = this_;
}
void OnRequest::fire(Request *request) {
if(this->onrequest) {
RequestEvent *event = new RequestEvent(request);
this->onrequest(event, this->this_);
delete event;
}
}
HttpThread::HttpThread(uint16_t port, ThreadGetJob getJob, void *this_) :
Thread(getJob, this_, true, HttpThread::_init, this,
HttpThread::_deinit, this),
mPort(port), evHttp(nullptr), evBoundSocket(nullptr) {
}
HttpThread::HttpThread(ThreadGetJob getJob, void *this_) :
Thread(getJob, this_, true, HttpThread::_init, this,
HttpThread::_deinit, this),
mPort(8888), evHttp(nullptr), evBoundSocket(nullptr) {
LOG(INFO) << "*****->HttpThread";
}
HttpThread::~HttpThread() {
LOG(INFO) << "*****~HttpThread";
}
void HttpThread::_onEvRequestComplete(struct evhttp_request *request, void *arg) {
Request *ctxt = (Request *) arg;
ctxt->getThreadCtxt()->onEvRequestComplete(ctxt);
}
void HttpThread::onEvRequestComplete(Request *request) {
request->accessLog();
}
void HttpThread::_onEvRequest(evhttp_request *request, void *arg) {
HttpThread *thread = (HttpThread *) arg;
thread->onEvRequest(request);
}
void HttpThread::onEvRequest(evhttp_request *request) {
Request *req = new Request(this, request);
request->on_complete_cb = HttpThread::_onEvRequestComplete;
request->on_complete_cb_arg = req;
onrequest.fire(req);
delete req;
}
void HttpThread::_init(void *this_) {
HttpThread *thread = (HttpThread *) this_;
thread->init();
}
void HttpThread::init() {
LOG(INFO) << "Http thread init port: " << mPort;
evHttp = evhttp_new(mEventBase);
evhttp_set_gencb(evHttp, HttpThread::_onEvRequest, this);
if(!HttpThread::evListenSocket) {
LOG(INFO) << "Listening on 0.0.0.0:" << mPort;
evListenSocket = evhttp_bind_socket_with_handle(evHttp, "0.0.0.0", mPort);
evBoundSocket = evListenSocket;
LOG(INFO) << "Created a new bound socket: " << evListenSocket;
} else {
LOG(INFO) << "Using exsiting bound socket: " << evListenSocket;
evutil_socket_t fd = evhttp_bound_socket_get_fd(evListenSocket);
evBoundSocket = evhttp_accept_socket_with_handle(evHttp, fd);
LOG(INFO) << "Bound socket registered for accept in this thread: " << evBoundSocket;
}
}
void HttpThread::_deinit(void *this_) {
HttpThread *thread = (HttpThread *) this_;
thread->deinit();
}
void HttpThread::deinit() {
LOG(INFO) << "Http thread deinit port: " << mPort;
evhttp_del_accept_socket(evHttp, evBoundSocket);
evhttp_free(evHttp);
}
void HttpThread::start() {
Thread::start();
}
OnRequest &HttpThread::onRequest(_OnRequest onrequest) {
return this->onrequest.set(onrequest);
}
} // End namespace Server.
} // End namespace Http.
} // End namespace ChCppUtils.
| 27.182156
| 86
| 0.678474
|
corehacker
|
a3b04fa905feac6403c4e9505fb5f87cb8774203
| 3,201
|
cpp
|
C++
|
src/rpc/Codec.cpp
|
evenleo/leo
|
67e148e04eb7b3af9890f907f24fb4f63d8405b0
|
[
"MIT"
] | null | null | null |
src/rpc/Codec.cpp
|
evenleo/leo
|
67e148e04eb7b3af9890f907f24fb4f63d8405b0
|
[
"MIT"
] | null | null | null |
src/rpc/Codec.cpp
|
evenleo/leo
|
67e148e04eb7b3af9890f907f24fb4f63d8405b0
|
[
"MIT"
] | null | null | null |
#include "Codec.h"
#include "Buffer.h"
#include <zlib.h>
namespace leo {
namespace rpc {
void ProtobufCodec::send(const MessagePtr& message) {
Buffer::ptr buf(new Buffer);
const std::string& typeName = message->GetTypeName();
int32_t nameLen = static_cast<int32_t>(typeName.size()+1);
buf->appendInt32(nameLen);
buf->append(typeName.c_str(), nameLen);
int byte_size = message->ByteSizeLong();
buf->ensureWritableBytes(byte_size);
uint8_t* start = reinterpret_cast<uint8_t*>(buf->beginWrite());
message->SerializeWithCachedSizesToArray(start);
buf->hasWritten(byte_size);
int32_t checkSum = static_cast<int32_t>(
::adler32(1,
reinterpret_cast<const Bytef*>(buf->peek()),
static_cast<int>(buf->readableBytes())));
buf->appendInt32(checkSum);
assert(buf->readableBytes() == sizeof nameLen + nameLen + byte_size + sizeof checkSum);
int32_t len = htobe32(static_cast<int32_t>(buf->readableBytes()));
buf->prepend(&len, sizeof len);
conn_->write(buf);
}
ProtobufCodec::ErrorCode ProtobufCodec::receive(MessagePtr& message) {
Buffer::ptr buf(new Buffer);
while (conn_->read(buf) > 0) {
if (buf->readableBytes() >= kHeaderlen + kMinMessageLen) {
const int32_t len = buf->peekInt32();
if (len > kMaxMessageLen || len < kMinMessageLen) {
return kInvalidLength;
} else if (buf->readableBytes() >= static_cast<size_t>(len + kHeaderlen)) {
ErrorCode errorcode = kNoError;
message = parse(buf->peek() + kHeaderlen, len, &errorcode);
return errorcode;
}
}
}
return kServerClosed;
}
int32_t asInt32(const char* buf) {
int32_t be32 = 0;
::memcpy(&be32, buf, sizeof(be32));
return be32toh(be32);
}
MessagePtr ProtobufCodec::parse(const char* buf, int len, ErrorCode* error) {
MessagePtr message;
int32_t expectedCheckSum = asInt32(buf + len - kHeaderlen);
int32_t checkSum = static_cast<int32_t>(
::adler32(1,
reinterpret_cast<const Bytef*>(buf),
static_cast<int>(len - kHeaderlen)));
if (checkSum == expectedCheckSum) {
// get message type name
int32_t nameLen = asInt32(buf);
if (nameLen >= 2 && nameLen <= len - 2 * kHeaderlen) {
std::string typeName(buf + kHeaderlen, buf + kHeaderlen + nameLen - 1);
// create message object
message.reset(createMessage(typeName));
if (message) {
// parse from buffer
const char* data = buf + kHeaderlen + nameLen;
int32_t dataLen = len - nameLen - 2 * kHeaderlen;
if (message->ParseFromArray(data, dataLen)) {
*error = kNoError;
} else {
*error = kParseError;
}
} else {
*error = kUnknownMessageType;
}
} else {
*error = kInvalidNameLength;
}
} else {
*error = kChedksumError;
}
return message;
}
google::protobuf::Message* ProtobufCodec::createMessage(const std::string& typeName) {
google::protobuf::Message* message = nullptr;
const google::protobuf::Descriptor* descriptor =
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(typeName);
if (descriptor) {
const google::protobuf::Message* prototype =
google::protobuf::MessageFactory::generated_factory()->GetPrototype(descriptor);
if (prototype) {
message = prototype->New();
}
}
return message;
}
} //rpc
} //leo
| 28.580357
| 88
| 0.692596
|
evenleo
|
a3b0d24e10ff0d861472b58b2f3e92c338779495
| 7,311
|
cpp
|
C++
|
src/libmw/test/tests/consensus/Test_KernelSumValidator.cpp
|
litecoin-foundation/litecoin
|
de61fa1580d0465edb16251a4db5267f6b1cd047
|
[
"MIT"
] | null | null | null |
src/libmw/test/tests/consensus/Test_KernelSumValidator.cpp
|
litecoin-foundation/litecoin
|
de61fa1580d0465edb16251a4db5267f6b1cd047
|
[
"MIT"
] | null | null | null |
src/libmw/test/tests/consensus/Test_KernelSumValidator.cpp
|
litecoin-foundation/litecoin
|
de61fa1580d0465edb16251a4db5267f6b1cd047
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2021 The Litecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <mw/consensus/KernelSumValidator.h>
#include <mw/consensus/Aggregation.h>
#include <mw/crypto/Pedersen.h>
#include <mw/node/CoinsView.h>
#include <test_framework/TestMWEB.h>
#include <test_framework/models/Tx.h>
#include <test_framework/Miner.h>
#include <test_framework/TxBuilder.h>
// FUTURE: Create official test vectors for the consensus rules being tested
BOOST_FIXTURE_TEST_SUITE(TestKernelSumValidator, MWEBTestingSetup)
BOOST_AUTO_TEST_CASE(ValidateState)
{
// Pegin transaction
test::Tx pegin_tx = test::TxBuilder()
.AddOutput(4'000'000)
.AddOutput(5'000'000)
.AddPeginKernel(9'000'000)
.Build();
// Standard transaction
test::Tx standard_tx = test::TxBuilder()
.AddInput(pegin_tx.GetOutputs()[0])
.AddOutput(2'950'000).AddOutput(1'000'000)
.AddPlainKernel(50'000)
.Build();
// Pegout Transaction
test::Tx pegout_tx = test::TxBuilder()
.AddInput(standard_tx.GetOutputs()[1])
.AddOutput(200'000)
.AddPegoutKernel(750'000, 50'000)
.Build();
std::vector<Commitment> utxo_commitments{
pegin_tx.GetOutputs()[1].GetCommitment(),
standard_tx.GetOutputs()[0].GetCommitment(),
pegout_tx.GetOutputs()[0].GetCommitment()
};
std::vector<Kernel> kernels{
pegin_tx.GetKernels().front(),
standard_tx.GetKernels().front(),
pegout_tx.GetKernels().front()
};
BlindingFactor total_offset = Blinds()
.Add(pegin_tx.GetKernelOffset())
.Add(standard_tx.GetKernelOffset())
.Add(pegout_tx.GetKernelOffset())
.Total();
// State is valid
KernelSumValidator::ValidateState(utxo_commitments, kernels, total_offset);
// Move pegout kernel before pegin kernel in list to make supply negative in the past
kernels = std::vector<Kernel>{
pegout_tx.GetKernels().front(),
pegin_tx.GetKernels().front(),
standard_tx.GetKernels().front()
};
// Consensus error should be thrown
BOOST_REQUIRE_THROW(KernelSumValidator::ValidateState(utxo_commitments, kernels, total_offset), ValidationException);
}
BOOST_AUTO_TEST_CASE(ValidateForBlock)
{
// Standard transaction - 2 inputs, 2 outputs, 1 kernel
mw::Transaction::CPtr tx1 = test::TxBuilder()
.AddInput(5'000'000).AddInput(6'000'000)
.AddOutput(4'000'000).AddOutput(6'500'000)
.AddPlainKernel(500'000)
.Build().GetTransaction();
KernelSumValidator::ValidateForTx(*tx1); // Sanity check
// Pegin transaction - 1 output, 1 kernel
mw::Transaction::CPtr tx2 = test::TxBuilder()
.AddOutput(8'000'000)
.AddPeginKernel(8'000'000)
.Build().GetTransaction();
KernelSumValidator::ValidateForTx(*tx2); // Sanity check
mw::Transaction::CPtr tx3 = test::TxBuilder()
.AddInput(1'234'567).AddInput(4'000'000)
.AddOutput(234'567)
.AddPegoutKernel(4'500'000, 500'000)
.Build().GetTransaction();
KernelSumValidator::ValidateForTx(*tx3); // Sanity check
BlindingFactor prev_total_offset = BlindingFactor::Random();
mw::Transaction::CPtr pAggregated = Aggregation::Aggregate({ tx1, tx2, tx3 });
KernelSumValidator::ValidateForTx(*pAggregated); // Sanity check
BlindingFactor total_offset = Pedersen::AddBlindingFactors({ prev_total_offset, pAggregated->GetKernelOffset() });
KernelSumValidator::ValidateForBlock(pAggregated->GetBody(), total_offset, prev_total_offset);
}
//
// This tests ValidateForBlock without using the TxBuilder utility, since in theory it could contain bugs.
// In the future, it would be even better to replace this with official test vectors, and avoid relying on Random entirely.
//
BOOST_AUTO_TEST_CASE(ValidateForBlockWithoutBuilder)
{
std::vector<Input> inputs;
std::vector<Output> outputs;
std::vector<Kernel> kernels;
// Add inputs
BlindingFactor input1_bf = BlindingFactor::Random();
SecretKey input1_key = SecretKey::Random();
SecretKey input1_output_key = SecretKey::Random();
inputs.push_back(test::TxInput::Create(input1_bf, input1_key, input1_output_key, 5'000'000).GetInput());
BlindingFactor input2_bf = BlindingFactor::Random();
SecretKey input2_key = SecretKey::Random();
SecretKey input2_output_key = SecretKey::Random();
inputs.push_back(test::TxInput::Create(input2_bf, input2_key, input2_output_key, 6'000'000).GetInput());
// Add outputs
SecretKey output1_sender_key = SecretKey::Random();
test::TxOutput output1 = test::TxOutput::Create(
output1_sender_key,
StealthAddress::Random(),
4'000'000
);
BlindingFactor output1_bf = output1.GetBlind();
outputs.push_back(output1.GetOutput());
SecretKey output2_sender_key = SecretKey::Random();
test::TxOutput output2 = test::TxOutput::Create(
output2_sender_key,
StealthAddress::Random(),
6'500'000
);
BlindingFactor output2_bf = output2.GetBlind();
outputs.push_back(output2.GetOutput());
// Kernel offset
mw::Hash prev_total_offset = mw::Hash::FromHex("0123456789abcdef0123456789abcdef00000000000000000000000000000000");
BlindingFactor tx_offset = BlindingFactor::Random();
BlindingFactor total_offset = Blinds().Add(prev_total_offset).Add(tx_offset).Total();
// Calculate kernel excess
BlindingFactor excess = Blinds()
.Add(output1_bf)
.Add(output2_bf)
.Sub(input1_bf)
.Sub(input2_bf)
.Sub(tx_offset)
.Total();
// Add kernel
const CAmount fee = 500'000;
kernels.push_back(Kernel::Create(excess, boost::none, fee, boost::none, std::vector<PegOutCoin>{}, boost::none));
// Create Transaction
auto pTransaction = mw::Transaction::Create(
tx_offset,
BlindingFactor::Random(),
inputs,
outputs,
kernels
);
KernelSumValidator::ValidateForBlock(pTransaction->GetBody(), total_offset, prev_total_offset);
}
BOOST_AUTO_TEST_CASE(ValidateForTx)
{
// Standard transaction - 2 inputs, 2 outputs, 1 kernel
mw::Transaction::CPtr tx1 = test::TxBuilder()
.AddInput(5'000'000).AddInput(6'000'000)
.AddOutput(4'000'000).AddOutput(6'500'000)
.AddPlainKernel(500'000)
.Build().GetTransaction();
KernelSumValidator::ValidateForTx(*tx1);
// Pegin transaction - 1 output, 1 kernel
mw::Transaction::CPtr tx2 = test::TxBuilder()
.AddOutput(8'000'000)
.AddPeginKernel(8'000'000)
.Build().GetTransaction();
KernelSumValidator::ValidateForTx(*tx2);
// Pegout transaction - 2 inputs, 1 output, 1 kernel
mw::Transaction::CPtr tx3 = test::TxBuilder()
.AddInput(1'234'567).AddInput(4'000'000)
.AddOutput(234'567)
.AddPegoutKernel(4'500'000, 500'000)
.Build().GetTransaction();
KernelSumValidator::ValidateForTx(*tx3);
// Aggregate all 3
mw::Transaction::CPtr pAggregated = Aggregation::Aggregate({ tx1, tx2, tx3 });
KernelSumValidator::ValidateForTx(*pAggregated);
}
BOOST_AUTO_TEST_SUITE_END()
| 35.663415
| 123
| 0.685542
|
litecoin-foundation
|
a3b2808a7cac11de58de9b98de6f7f5e223949e8
| 82,114
|
cpp
|
C++
|
cvdump/dumppdb.cpp
|
kyle-sylvestre/building-microsoft-pdb
|
547baaedb2908e996dc2446c400f12ee6ebe9b02
|
[
"MIT"
] | 1
|
2021-12-30T12:52:03.000Z
|
2021-12-30T12:52:03.000Z
|
cvdump/dumppdb.cpp
|
kyle-sylvestre/building-microsoft-pdb
|
547baaedb2908e996dc2446c400f12ee6ebe9b02
|
[
"MIT"
] | null | null | null |
cvdump/dumppdb.cpp
|
kyle-sylvestre/building-microsoft-pdb
|
547baaedb2908e996dc2446c400f12ee6ebe9b02
|
[
"MIT"
] | 1
|
2021-12-31T01:17:32.000Z
|
2021-12-31T01:17:32.000Z
|
/***********************************************************************
* Microsoft (R) Debugging Information Dumper
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* File Comments:
*
*
***********************************************************************/
#include "missing_impl.h"
#include "pdb.h"
#include "windows.h"
//#include "array.h" //@@@
//#include "map.h" //@@@
#include "cvdump.h"
// @@@ #include "_winnt2.h"
//#include <winnt.h>
#ifndef IMAGE_FILE_MACHINE_POWERPCBE
#define IMAGE_FILE_MACHINE_POWERPCBE 0x01F2 // IBM PowerPC Big-Endian
#endif
// Local include files
#include "utf8.h"
#include "mdalign.h"
// Cor include files
#include "corhdr.h"
#include "safestk.h"
#include "szst.h"
// module variables
bool fUtf8Symbols;
// LANGAPI shared files
//#define dassert assert
//#define precondition dassert
//#define postcondition dassert
#include "map_t.h"
DWORD dwMachine;
extern WORD CVDumpMachineType;
enum DbgInfoKind {
DIK_xScopeExport,
DIK_xScopeImport,
DIK_FuncTokenMap,
DIK_TypeTokenMap,
DIK_MergedAsmIn,
};
void (*pfn)(size_t, PB);
// map support for src file names
class CWsz {
wchar_t *m_wsz;
void Dealloc() {
if (m_wsz) {
free(m_wsz);
m_wsz = NULL;
}
}
public:
CWsz() {
m_wsz = NULL;
}
CWsz(_In_z_ wchar_t * wsz) {
m_wsz = _wcsdup(wsz);
}
CWsz(const CWsz & wsz) {
m_wsz = _wcsdup(wsz.m_wsz);
}
~CWsz() { Dealloc(); }
CWsz & operator=(const CWsz & wsz) {
Dealloc();
m_wsz = _wcsdup(wsz.m_wsz);
return *this;
}
bool operator==(const CWsz & wsz) {
return _wcsicmp(m_wsz, wsz.m_wsz) == 0;
}
bool operator==(const wchar_t *wsz) {
return _wcsicmp(m_wsz, wsz) == 0;
}
operator wchar_t *() {
return m_wsz;
}
LHASH operator()() {
if (m_wsz) {
wchar_t *wszUpper = _wcsdup(m_wsz);
_wcsupr_s(wszUpper, wcslen(wszUpper));
LHASH lhash = LHASH(SigForPbCb(PB(wszUpper), wcslen(wszUpper) * sizeof(wchar_t), 0));
free(wszUpper);
return lhash;
}
return 0;
}
static int __cdecl Wcmp(const void * pv1, const void * pv2) {
const CWsz *pcwsz1 = reinterpret_cast<const CWsz *>(pv1);
const CWsz *pcwsz2 = reinterpret_cast<const CWsz *>(pv2);
return _wcsicmp(pcwsz1->m_wsz, pcwsz2->m_wsz);
}
};
//@@@
//typedef HashClass<CWsz,hcCast> HcWsz;
//typedef Map<CWsz, BYTE, HcWsz> FileMap;
//typedef EnumMap<CWsz, BYTE, HcWsz> EnumFileMap;
//typedef Array<CWsz> RgCWsz;
void DumpGSI(GSI *pgsi)
{
cchIndent = 0;
BYTE *pb = NULL;
while (pb = pgsi->NextSym(pb)) {
DumpOneSymC7(NULL, pb, 0xFFFFFFFF);
}
StdOutPutc(L'\n');
}
void DumpPdbModules(DBI *pdbi)
{
Mod *pmod = NULL;
while (pdbi->QueryNextMod(pmod, &pmod) && pmod) {
USHORT imod;
if (!pmod->QueryImod(&imod)) {
continue;
}
if ((iModToList != 0) && (imod != iModToList)) {
continue;
}
StdOutPrintf(L"%04X", imod);
wchar_t wszFile[PDB_MAX_PATH];
long cb = _countof(wszFile);
if (!pmod->QueryFileW(wszFile, &cb)) {
StdOutPuts(L" *");
}
else {
StdOutPrintf(L" \"%s\"", wszFile);
}
wchar_t wszName[PDB_MAX_PATH];
cb = _countof(wszName);
if (!pmod->QueryNameW(wszName, &cb)) {
StdOutPuts(L" *");
}
else if (wcscmp(wszFile, wszName) == 0) {
// If file name matches module name that this isn't a library
}
else {
StdOutPrintf(L" \"%s\"", wszName);
}
StdOutPutc(L'\n');
}
}
const wchar_t *SzErrorFromEc(PDBErrors, _Out_opt_cap_(cchEc) wchar_t *szEc, size_t cchEc);
void DumpPdbPublics(PDB * ppdb, DBI *pdbi)
{
GSI *pgsi;
if (!pdbi->OpenPublics(&pgsi)) {
wchar_t szEc[11];
PDBErrors ec = PDBErrors(ppdb->QueryLastErrorExW(NULL, 0));
StdOutPrintf(L"DBI::OpenPublics failed (%s)\n", SzErrorFromEc(ec, szEc, _countof(szEc)));
return;
}
DumpGSI(pgsi);
pgsi->Close();
}
void DumpPdbTypes(PDB *ppdb, DBI *pdbi, bool fId)
{
for (unsigned itsm = 0; itsm < 256; itsm++) {
TPI *ptpi = 0;
if (!fId && !pdbi->QueryTypeServer((ITSM) itsm, &ptpi) && itsm) {
continue;
}
if (!ptpi) {
BOOL f = fId ? ppdb->OpenIpi(pdbRead pdbGetRecordsOnly, &ptpi)
: ppdb->OpenTpi(pdbRead pdbGetRecordsOnly, &ptpi);
if (!f) {
wchar_t wszErr[1024];
PDBErrors ec = PDBErrors(ppdb->QueryLastErrorExW(wszErr, 1024));
wchar_t szEc[32];
StdOutPrintf(L"Error on OpenTpi: '%s' (%d)\n", SzErrorFromEc(ec, szEc, _countof(szEc)), ec);
return;
}
if (!ptpi) {
StdOutPrintf(L"Error OpenTpi return true, but doesn't give us a TPI pointer!\n");
assert(false);
return;
}
}
fSupportsQueryUDT = ptpi->SupportQueryTiForUDT() != false;
if (!fId && ptpi->fIs16bitTypePool()) {
StdOutPuts(L"*** Converting 16-bit types to 32-bit equivalents\n\n");
}
TI tiMin = ptpi->QueryTiMin();
TI tiMac = ptpi->QueryTiMac();
for (TI ti = tiMin; ti < tiMac; ti++) {
TI tiT = (itsm << 24) | ti;
BYTE *pb;
BOOL fT = ptpi->QueryPbCVRecordForTi(tiT, &pb);
if (!fT) {
PDBErrors ec = PDBErrors(ppdb->QueryLastErrorExW(NULL, 0));
wchar_t szName[_MAX_PATH] = L"";
ppdb->QueryPDBNameExW(szName, _countof(szName));
wchar_t szEc[32];
StdOutPrintf(L"Error on QueryPbCVRecordForTI(0x%x): '%s' (%d) on '%s'\n",
tiT,
SzErrorFromEc(ec, szEc, _countof(szEc)),
ec,
szName);
return;
}
DumpTypRecC7(tiT, *(unsigned short *) pb, pb + sizeof(unsigned short), ptpi, ppdb);
}
if (fId) {
break;
}
// Don't close TPIs opened via DBI::QueryTypeServer()
}
}
void DumpPdbTypeWarnDuplicateUDTs(PDB *ppdb, DBI *pdbi)
{
TPI *ptpi = NULL;
if (!ppdb->OpenTpi(pdbRead pdbGetRecordsOnly, &ptpi)) {
PDBErrors ec = PDBErrors(ppdb->QueryLastErrorExW(NULL, 0));
wchar_t szEc[32];
StdOutPrintf(L"Error on OpenTpi: '%s' (%d)\n", SzErrorFromEc(ec, szEc, _countof(szEc)), ec);
return;
}
if (!ptpi) {
StdOutPrintf(L"Error OpenTpi return true, but doesn't give us a TPI pointer!\n");
assert(false);
return;
}
fSupportsQueryUDT = ptpi->SupportQueryTiForUDT() != false;
if (!fSupportsQueryUDT) {
wchar_t wszPdbName[PDB_MAX_PATH];
StdOutPrintf(L"This PDB '%s' does not support QueryUDT\n", ppdb->QueryPDBNameExW(wszPdbName, PDB_MAX_PATH));
return;
}
TI tiMin = ptpi->QueryTiMin();
TI tiMac = ptpi->QueryTiMac();
for (TI ti = tiMin; ti < tiMac; ti++) {
BYTE *pb;
BOOL fT = ptpi->QueryPbCVRecordForTi(ti, &pb);
if (!fT) {
PDBErrors ec = PDBErrors(ppdb->QueryLastErrorExW(NULL, 0));
wchar_t szName[_MAX_PATH] = L"";
ppdb->QueryPDBNameExW(szName, _countof(szName));
wchar_t szEc[32];
StdOutPrintf(L"Error on QueryPbCVRecordForTI(0x%x): '%s' (%d) on '%s'\n",
ti,
SzErrorFromEc(ec, szEc, _countof(szEc)),
ec,
szName);
return;
}
TYPPTR ptype = reinterpret_cast<TYPPTR>(pb);
unsigned leaf = ptype->leaf;
bool fIsESU = false;
const unsigned char *szName = NULL;
switch (leaf) {
CV_prop_t prop;
case LF_CLASS:
case LF_STRUCTURE: {
plfStructure plf = reinterpret_cast<plfStructure>(&ptype->leaf);
prop = plf->property;
fIsESU = !prop.fwdref;
if (fIsESU) {
szName = plf->data + SkipNumeric(plf->data);
}
break;
}
case LF_UNION: {
plfUnion plf = reinterpret_cast<plfUnion>(&ptype->leaf);
prop = plf->property;
fIsESU = !prop.fwdref;
if (fIsESU) {
szName = plf->data + SkipNumeric(plf->data);
}
break;
}
}
if (fIsESU) {
TI tiUdt;
if (ptpi->QueryTiForUDT(reinterpret_cast<const char*>(szName), true, &tiUdt)) {
if (tiUdt != ti) {
StdOutPrintf(L"WARNING: UDT mismatch for %S\n<<<<<<\n", szName);
DumpTypRecC7(ti, *(unsigned short *) pb, pb + sizeof(unsigned short), ptpi, ppdb);
StdOutPuts(L"******\n");
ptpi->QueryPbCVRecordForTi(tiUdt, &pb);
DumpTypRecC7(tiUdt, *(unsigned short *) pb, pb + sizeof(unsigned short), ptpi, ppdb);
StdOutPuts(L">>>>>>\n\n");
}
}
}
}
}
void DumpPdbCoffSymRVA(DBI *pdbi)
{
size_t cbBuf = 0x4000;
BYTE *pb = (BYTE *) malloc(cbBuf);
if (pb == NULL) {
StdOutPuts(L"malloc failed\n");
return;
}
Mod *pmod = NULL;
while (pdbi->QueryNextMod(pmod, &pmod) && pmod) {
USHORT imod;
if (iModToList && pmod->QueryImod(&imod) && (iModToList != imod)) {
continue;
}
wchar_t szName[PDB_MAX_PATH];
long cch = _countof(szName);
if (pmod->QueryNameW(szName, &cch)) {
StdOutPrintf(L"** Module: \"%s\"", szName);
wchar_t wszLibrary[PDB_MAX_PATH];
cch = _countof(wszLibrary);
if (!pmod->QueryFileW(wszLibrary, &cch)) {
}
else if (wcscmp(wszLibrary, szName) == 0) {
// If file name matches module name that this isn't a library
}
else {
StdOutPrintf(L" from \"%s\"", wszLibrary);
}
StdOutPutc(L'\n');
StdOutPutc(L'\n');
}
DWORD cb;
if (!pmod->QueryCoffSymRVAs(NULL, static_cast<DWORD *>(&cb))) {
StdOutPuts(L"Mod::QueryCoffSymRVAs failed\n");
continue;
}
if (cb == 0) {
continue;
}
if ((size_t) cb > cbBuf) {
BYTE *pb2 = (BYTE *) realloc(pb, (size_t) cb * 2);
if (pb2 == NULL) {
StdOutPuts(L"realloc failed\n");
continue;
}
pb = pb2;
cbBuf = cb * 2;
}
if (!pmod->QueryCoffSymRVAs(pb, static_cast<DWORD *>(&cb))) {
StdOutPuts(L"Mod::QueryCoffSymRVAs failed\n");
continue;
}
cchIndent = 0;
BYTE *pbT = pb;
const BYTE *pbEnd = pb + cb;
for (int i = 0; pbT < pbEnd; pbT += sizeof(DWORD), i++) {
if ((i % 8) == 0) {
if (i == 0) {
StdOutPuts(L" ");
} else {
StdOutPuts(L"\n ");
}
}
StdOutPrintf(L" %08X", *(UNALIGNED DWORD *) pbT);
}
StdOutPuts(L"\n\n");
}
free(pb);
}
void DumpPdbSyms(DBI *pdbi)
{
size_t cbBuf = 0x4000;
BYTE *pb = (BYTE *) malloc(cbBuf);
if (pb == NULL) {
StdOutPuts(L"malloc failed\n");
return;
}
Mod *pmod = NULL;
while (pdbi->QueryNextMod(pmod, &pmod) && pmod) {
USHORT imod;
if (iModToList && pmod->QueryImod(&imod) && (iModToList != imod)) {
continue;
}
wchar_t szName[PDB_MAX_PATH];
long cb = _countof(szName);
if (pmod->QueryNameW(szName, &cb)) {
StdOutPrintf(L"** Module: \"%s\"", szName);
wchar_t wszLibrary[PDB_MAX_PATH];
cb = _countof(wszLibrary);
if (!pmod->QueryFileW(wszLibrary, &cb)) {
}
else if (wcscmp(wszLibrary, szName) == 0) {
// If file name matches module name that this isn't a library
}
else {
StdOutPrintf(L" from \"%s\"", wszLibrary);
}
StdOutPutc(L'\n');
StdOutPutc(L'\n');
}
if (!pmod->QuerySymbols(NULL, &cb)) {
StdOutPuts(L"Mod::QuerySymbols failed\n");
continue;
}
if (cb == 0) {
continue;
}
if ((size_t) cb > cbBuf) {
BYTE *pb2 = (BYTE *) realloc(pb, (size_t) cb * 2);
if (pb2 == NULL) {
StdOutPuts(L"realloc failed\n");
continue;
}
pb = pb2;
cbBuf = cb * 2;
}
if (!pmod->QuerySymbols(pb, &cb)) {
StdOutPuts(L"Mod::QuerySymbols failed\n");
continue;
}
cchIndent = 0;
const BYTE *pbTmp;
const BYTE *pbEnd;
for (pbEnd = pb + cb, pbTmp = pb + sizeof(long); // skip signature
pbTmp < pbEnd;
pbTmp = (BYTE *) NextSym((SYMTYPE *) pbTmp)
) {
DumpOneSymC7(pmod, pbTmp, DWORD(pbTmp - pb));
}
StdOutPutc(L'\n');
}
free(pb);
}
void DumpPdbGlobals(PDB *ppdb, DBI *pdbi)
{
GSI *pgsi;
if (!pdbi->OpenGlobals(&pgsi)) {
PDBErrors ec = PDBErrors(ppdb->QueryLastErrorExW(NULL, 0));
wchar_t szEc[11];
StdOutPrintf(L"DBI::OpenGlobals failed (%s)\n", SzErrorFromEc(ec, szEc, _countof(szEc)));
return;
}
DumpGSI(pgsi);
pgsi->Close();
}
void DumpPdbInlineeLines(DBI *pdbi)
{
Mod *pmod = NULL;
while (pdbi->QueryNextMod(pmod, &pmod) && pmod) {
USHORT imod;
if (iModToList && pmod->QueryImod(&imod) && (iModToList != imod)) {
continue;
}
wchar_t szName[PDB_MAX_PATH];
long cb = _countof(szName);
if (pmod->QueryNameW(szName, &cb)) {
wchar_t wszLibrary[PDB_MAX_PATH];
cb = _countof(wszLibrary);
StdOutPrintf(L"** Module: \"%s\"", szName);
if (!pmod->QueryFileW(wszLibrary, &cb)) {
}
else if (wcscmp(wszLibrary, szName) == 0) {
// If file name matches module name that this isn't a library
}
else {
StdOutPrintf(L" from \"%s\"", wszLibrary);
}
StdOutPutc(L'\n');
StdOutPutc(L'\n');
}
if (!pmod->QueryInlineeLines(0, NULL, (DWORD *)&cb)) {
StdOutPuts(L"Mod::QueryInlineeLines failed\n\n");
continue;
}
if (cb == 0) {
continue;
}
PB pb = (PB) malloc(cb);
if (pb == NULL) {
StdOutPuts(L"malloc failed\n");
return;
}
if (!pmod->QueryInlineeLines(cb, pb, (DWORD *)&cb)) {
StdOutPuts(L"Mod::QueryInlineeLines failed\n\n");
continue;
}
DumpModInlineeSourceLines((DWORD)cb, pb);
free(pb);
StdOutPutc(L'\n');
}
}
void DumpPdbLines(DBI *pdbi, bool fIL)
{
size_t cbBuf = 0x4000;
BYTE *pb = (BYTE *) malloc(cbBuf);
if (pb == NULL) {
StdOutPuts(L"malloc failed\n");
return;
}
Mod *pmod = NULL;
while (pdbi->QueryNextMod(pmod, &pmod) && pmod) {
USHORT imod;
if (iModToList && pmod->QueryImod(&imod) && (iModToList != imod)) {
continue;
}
wchar_t szName[PDB_MAX_PATH];
long cb = _countof(szName);
if (pmod->QueryNameW(szName, &cb)) {
wchar_t wszLibrary[PDB_MAX_PATH];
cb = _countof(wszLibrary);
StdOutPrintf(L"** Module: \"%s\"", szName);
if (!pmod->QueryFileW(wszLibrary, &cb)) {
}
else if (wcscmp(wszLibrary, szName) == 0) {
// If file name matches module name that this isn't a library
}
else {
StdOutPrintf(L" from \"%s\"", wszLibrary);
}
StdOutPutc(L'\n');
StdOutPutc(L'\n');
}
DWORD flags;
if (fIL) {
if (!pmod->QueryILLineFlags(&flags)) {
flags = 0;
}
} else {
if (!pmod->QueryLineFlags(&flags)) {
flags = 0;
}
}
EnumLines *penum;
if (fIL) {
if (!pmod->GetEnumILLines(&penum)) {
StdOutPuts(L"Mod::GetEnumILLines failed\n\n");
continue;
}
} else {
if (!pmod->GetEnumLines(&penum)) {
StdOutPuts(L"Mod::GetEnumLines failed\n\n");
continue;
}
}
while (penum->next()) {
DWORD fileId;
DWORD offsetBase;
WORD seg;
DWORD cb;
DWORD cLines;
if (!penum->getLinesColumns(&fileId,
&offsetBase,
&seg,
&cb,
&cLines,
NULL,
NULL))
{
StdOutPrintf(L"Error: Line number corrupted: invalid file id %d\n", fileId);
continue;
}
wchar_t szName[_MAX_PATH];
DWORD cchName = _MAX_PATH;
DWORD checksumtype;
BYTE rgbChecksum[256];
DWORD cbChecksum = sizeof(rgbChecksum);
if (!pmod->QueryFileNameInfo(fileId,
szName,
&cchName,
&checksumtype,
rgbChecksum,
&cbChecksum))
{
StdOutPrintf(L"Error: Line number corrupted: invalid file id %d\n", fileId);
wcscpy_s(szName, _countof(szName), L"<Unknown>");
cbChecksum = 0;
}
StdOutPrintf(L" %s (", szName);
switch (checksumtype) {
case CHKSUM_TYPE_NONE :
StdOutPuts(L"None");
break;
case CHKSUM_TYPE_MD5 :
StdOutPuts(L"MD5");
break;
case CHKSUM_TYPE_SHA1 :
StdOutPuts(L"SHA1");
break;
case CHKSUM_TYPE_SHA_256 :
StdOutPuts(L"SHA_256");
break;
default :
StdOutPrintf(L"0x%X", checksumtype);
break;
}
if (cbChecksum != 0) {
StdOutPuts(L": ");
for (DWORD i = 0; i < cbChecksum; i++ ) {
StdOutPrintf(L"%02X", rgbChecksum[i]);
}
}
DWORD offsetMac = offsetBase + cb;
StdOutPrintf(L"), %04X:%08X-%08X, line/addr pairs = %u\n",
seg,
offsetBase,
offsetMac,
cLines);
if (cLines > 0) {
CV_Line_t *pLines = new CV_Line_t[cLines];
CV_Column_t *pColumns = new CV_Column_t[cLines];
if (!penum->getLinesColumns(&fileId,
&offsetBase,
&seg,
&cb,
&cLines,
pLines,
(flags & CV_LINES_HAVE_COLUMNS) ? pColumns : 0))
{
StdOutPuts(L"Error: Line/column number corrupted\n");
continue;
}
DWORD clinesOutofBounds = 0;
for (DWORD i = 0; i < cLines; i++) {
if (flags & CV_LINES_HAVE_COLUMNS) {
if ((i % 2) == 0) {
StdOutPutc(L'\n');
}
if (pColumns[i].offColumnEnd != 0) {
StdOutPrintf(L" %5u:%-5u-%5u:%-5u %08X",
pLines[i].linenumStart,
pColumns[i].offColumnStart,
pLines[i].linenumStart + pLines[i].deltaLineEnd,
pColumns[i].offColumnEnd,
pLines[i].offset + offsetBase);
}
else {
StdOutPrintf(
(pLines[i].linenumStart == 0xfeefee || pLines[i].linenumStart == 0xf00f00)
? L" %x:%-5u %08X" : L" %5u:%-5u %08X",
pLines[i].linenumStart,
pColumns[i].offColumnStart,
pLines[i].offset + offsetBase);
}
}
else {
if ((i % 4) == 0) {
StdOutPutc(L'\n');
}
StdOutPrintf(
(pLines[i].linenumStart == 0xfeefee || pLines[i].linenumStart == 0xf00f00)
? L" %x %08X" : L" %5u %08X",
pLines[i].linenumStart, pLines[i].offset + offsetBase);
}
// Check to see if we need to warn about out-of-bounds line numbers
if (pLines[i].offset + offsetBase >= offsetMac) {
clinesOutofBounds++;
}
}
if (clinesOutofBounds != 0) {
StdOutPrintf(
L"\n <<<< WARNING >>>> %u line/addr pairs are out of bounds!",
clinesOutofBounds );
}
StdOutPutc(L'\n');
delete [] pLines;
delete [] pColumns;
}
StdOutPutc(L'\n');
}
}
free(pb);
}
void DumpPdbSrcFiles(DBI *pdbi)
{
Mod *pmod = NULL;
while (pdbi->QueryNextMod(pmod, &pmod) && pmod) {
USHORT imod;
if (iModToList && pmod->QueryImod(&imod) && (iModToList != imod)) {
continue;
}
wchar_t szName[PDB_MAX_PATH];
long cb = _countof(szName);
if (pmod->QueryNameW(szName, &cb)) {
wchar_t wszLibrary[PDB_MAX_PATH];
cb = _countof(wszLibrary);
StdOutPrintf(L"** Module: \"%s\"", szName);
if (!pmod->QueryFileW(wszLibrary, &cb)) {
}
else if (wcscmp(wszLibrary, szName) == 0) {
// If file name matches module name that this isn't a library
}
else {
StdOutPrintf(L" from \"%s\"", wszLibrary);
}
StdOutPutc(L'\n');
StdOutPutc(L'\n');
}
DWORD fileId = 0;
for (;;) {
wchar_t szName[_MAX_PATH];
BYTE rgbChecksum[256];
DWORD len = _MAX_PATH;
DWORD cbChecksum = sizeof(rgbChecksum);
DWORD checksumtype;
if (!pmod->QueryFileNameInfo(fileId,
szName,
&len,
&checksumtype,
rgbChecksum,
&cbChecksum)) {
break;
}
StdOutPrintf(L" %4u %s (", fileId, szName);
switch (checksumtype) {
case CHKSUM_TYPE_NONE :
StdOutPrintf(L"None");
break;
case CHKSUM_TYPE_MD5 :
StdOutPrintf(L"MD5");
break;
case CHKSUM_TYPE_SHA1 :
StdOutPrintf(L"SHA1");
break;
case CHKSUM_TYPE_SHA_256 :
StdOutPrintf(L"SHA_256");
break;
default :
StdOutPrintf(L"0x%X", checksumtype);
break;
}
if (cbChecksum != 0) {
StdOutPrintf(L": ");
for (DWORD i = 0; i < cbChecksum; i++ ) {
StdOutPrintf(L"%02X", rgbChecksum[i]);
}
}
StdOutPrintf(L")\n");
fileId++;
}
if (fileId != 0) {
StdOutPutc(L'\n');
}
}
}
void DumpPdbSecContribs(DBI *pdbi)
{
EnumContrib *penumcontrib;
if (pdbi->getEnumContrib((Enum **) &penumcontrib)) {
StdOutPuts(L" Imod Address Size Characteristics\n");
while (penumcontrib->next()) {
WORD imod;
WORD sn;
long ib;
long cb;
DWORD grbit;
penumcontrib->get(&imod, &sn, &ib, &cb, &grbit);
StdOutPrintf(L" %04X %04X:%08X %08X %08X\n", imod, sn, ib, cb, grbit);
}
}
else if (pdbi->getEnumContrib2((Enum **) &penumcontrib)) {
StdOutPuts(L" Imod Address Size Characteristics IsecCOFF\n");
while (penumcontrib->next()) {
WORD imod;
WORD sn;
DWORD ib;
DWORD cb;
DWORD grbit;
DWORD snCoff;
penumcontrib->get2(&imod, &sn, &ib, &snCoff, &cb, &grbit);
StdOutPrintf(L" %04X %04X:%08X %08X %08X %08X\n", imod, sn, ib, cb, grbit, snCoff);
}
}
else {
StdOutPuts(L"DBI::getEnumContrib and DBI::getEnumContrib2 failed\n");
return;
}
penumcontrib->release();
return;
}
void DumpPdbSecMap(DBI *pdbi)
{
long cb;
if (!pdbi->QuerySecMap(NULL, &cb)) {
StdOutPuts(L"DBI::QuerySecMap failed\n");
return;
}
if (cb == 0) {
return;
}
BYTE *pb = new BYTE[cb];
if (pb == NULL) {
StdOutPuts(L"new failed\n");
return;
}
if (!pdbi->QuerySecMap(pb, &cb)) {
StdOutPuts(L"DBI::QuerySecMap failed\n");
delete [] pb;
return;
}
const OMFSegMap *posm = (OMFSegMap *) pb;
StdOutPrintf(L"Sec flags ovl grp frm sname cname offset cbSeg\n");
for (size_t iseg = 0; iseg < posm->cSeg; iseg++) {
StdOutPrintf(L" %02x %04x %04x %04x %04x %04x %04x %08x %08x\n",
iseg+1,
posm->rgDesc[iseg].flags.fAll,
posm->rgDesc[iseg].ovl,
posm->rgDesc[iseg].group,
posm->rgDesc[iseg].frame,
posm->rgDesc[iseg].iSegName,
posm->rgDesc[iseg].iClassName,
posm->rgDesc[iseg].offset,
posm->rgDesc[iseg].cbSeg);
}
delete [] pb;
}
bool FOpenDbg(DBI *pdbi, DBGTYPE dbgtype, const wchar_t *wszDbgtype, Dbg **ppdbg)
{
if (!pdbi->OpenDbg(dbgtype, ppdbg)) {
StdOutPrintf(L"DBIOpenDbg(, %s,) failed.\n", wszDbgtype);
return(false);
}
return(true);
}
void DumpPdbFpo(PDB *ppdb, DBI *pdbi)
{
// Dump Fpo data
Dbg *pdbg;
static const wchar_t * const wszFrameTypes[] = { L"fpo", L"trap", L"tss", L"std"};
if (FOpenDbg(pdbi, dbgtypeFPO, L"dbgtypeFPO", &pdbg)) {
ULONG celts;
if ((celts = pdbg->QuerySize()) > 0) {
StdOutPuts(L" Use Has Frame\n"
L" Address Proc Size Locals Prolog Regs BP SEH Type Params\n");
FPO_DATA data;
for (; pdbg->QueryNext(1, &data); pdbg->Skip(1)) {
StdOutPrintf(L"%08X %8X %8X %8X %8X %c %c %4s %4X\n",
data.ulOffStart,
data.cbProcSize,
data.cdwLocals,
data.cbProlog,
data.cbRegs,
data.fUseBP ? L'Y' : L'N',
data.fHasSEH ? L'Y' : L'N',
wszFrameTypes[data.cbFrame],
data.cdwParams * 4);
}
}
pdbg->Close();
}
if (FOpenDbg(pdbi, dbgtypeNewFPO, L"dbgtypeNewFPO", &pdbg)) {
ULONG celts;
if ((celts = pdbg->QuerySize()) > 0) {
StdOutPuts(L" Address Blk Size cbLocals cbParams cbStkMax cbProlog cbSavedRegs SEH C++EH FStart Program\n");
NameMap* pnm = NULL;
if (!NameMap::open(ppdb, FALSE, &pnm)) {
StdOutPuts(L"Error no namemap\n");
return;
}
FRAMEDATA data;
for (; pdbg->QueryNext(1, &data); pdbg->Skip(1)) {
wchar_t prog[1024] = L"<Error: Invalid NI>";
if (pnm->isValidNi(data.frameFunc)) {
size_t l = _countof(prog);
pnm->getNameW(data.frameFunc, prog, &l);
}
StdOutPrintf(L"%08X %8X %8X %8X %8X %8X %8X %c %c %c %s\n",
data.ulRvaStart,
data.cbBlock,
data.cbLocals,
data.cbParams,
data.cbStkMax,
data.cbProlog,
data.cbSavedRegs,
data.fHasSEH ? L'Y' : L'N',
data.fHasEH ? L'Y' : L'N',
data.fIsFunctionStart ? L'Y' : L'N',
prog);
}
}
pdbg->Close();
}
}
void DumpPdbFixup(DBI *pdbi)
{
// Dump debug fixups
Dbg *pdbg;
if (!FOpenDbg(pdbi, dbgtypeFixup, L"dbgtypeFixup", &pdbg)) {
return;
}
ULONG celts;
if ((celts = pdbg->QuerySize()) > 0) {
XFIXUP data;
StdOutPrintf(L"\nFixup Data (%u):\n\n", celts);
StdOutPuts(L" Type Rva RvaTarget\n"
L" ---- ---- -------- --------\n");
for (; pdbg->QueryNext(1, &data); pdbg->Skip(1)) {
StdOutPrintf(L" %04X %04X %08X %08X\n",
data.wType, data.wExtra, data.rva, data.rvaTarget);
}
}
pdbg->Close();
}
void DumpTokenMap(DBI *pdbi)
{
// Dump Token map data
Dbg *pdbg;
if (!FOpenDbg(pdbi, dbgtypeTokenRidMap, L"dbgtypeTokenRidMap", &pdbg)) {
return;
}
ULONG celts;
if ((celts = pdbg->QuerySize()) > 0) {
DWORD data;
StdOutPrintf(L"\nTokenMap Data (%d):\n\n", pdbg->QuerySize());
StdOutPuts(L" Rid In Rid Out\n"
L" -------- --------\n");
for (DWORD i = 0; pdbg->QueryNext(1, &data); pdbg->Skip(1), ++i) {
StdOutPrintf(L" %08X %08X\n", i, data);
}
}
pdbg->Close();
}
void DumpPdbOmap(DBI *pdbi, bool fFromSrc)
{
// Dump OMAP data
Dbg *pdbg;
if (!FOpenDbg(pdbi,
fFromSrc ? dbgtypeOmapFromSrc : dbgtypeOmapToSrc,
fFromSrc ? L"dbgtypeOmapFromSrc" : L"dbgtypeOmapToSrc",
&pdbg)) {
return;
}
ULONG celts;
if ((celts = pdbg->QuerySize()) > 0) {
OMAP data;
StdOutPrintf(L"\nOMAP Data (%s_SRC) - (%d):\n\n",
fFromSrc ? L"FROM" : L"TO", pdbg->QuerySize());
StdOutPuts(L" Rva RvaTo\n"
L" -------- --------\n");
for (; pdbg->QueryNext(1, &data); pdbg->Skip(1)) {
StdOutPrintf(L" %08X %08X\n", data.rva, data.rvaTo);
}
}
pdbg->Close();
}
// Unwind information structure definition.
//
// N.B. If the EHANDLER flag is set, personality routine should be called
// during search for an exception handler. If the UHANDLER flag is
// set, the personality routine should be called during the second
// unwind.
//
#define LINKER_UNW_FLAG_EHANDLER(x) ((x) & 0x1)
#define LINKER_UNW_FLAG_UHANDLER(x) ((x) & 0x2)
#define LINKER_UNW_PERSONALITY_PTR(x) ((x) & 0x3) // ehandler or uhandler
// Version 2 = soft2.3 conventions
// Version 3 = soft2.6 conventions
//
struct LINKER_UNWIND_INFO {
USHORT Version; // Version Number
USHORT Flags; // Flags
ULONG DataLength; // Length of Descriptor Data
};
struct AMD64_UNWIND_INFO {
BYTE bVer : 3;
BYTE grFlags : 5;
BYTE cbProlog;
BYTE cUnwindCodes;
BYTE iFrameReg : 4;
BYTE offFrameReg : 4;
USHORT rgUnwindCodes[0]; // based on cUnwindCodes above
//ULONG rvaExceptHandler; // optional
//BYTE rgbLangSpecHandlerData; // optional
};
typedef LINKER_UNWIND_INFO * PLUI;
typedef const LINKER_UNWIND_INFO * PCLUI;
enum REGION_TYPE {
REGION_UNKNOWN,
REGION_PROLOGUE,
REGION_BODY
};
DWORDLONG DwlDecodeULEB128(const BYTE *pb)
{
DWORDLONG dwl = 0;
size_t ib = 0;
do {
dwl += DWORDLONG(*pb & 0x7f) << (ib * 7);
ib++;
}
while ((*pb++ & 0x80) != 0);
return dwl;
}
size_t CbULEB128(const BYTE *pb)
{
// Return the number of bytes in the ULEB128
size_t cb = 0;
do {
cb++;
}
while ((*pb++ & 0x80) != 0);
return cb;
}
size_t CbDumpBytes(const BYTE *pb, size_t cb, size_t trailingULEB, const wchar_t *sz, ...)
{
#define DESCRIPTOR_COLUMNS 4
// Dump bytes and padding out to a fixed column. 'cb' is the fixed of bytes
// to dump, trailingULEB is a count of trailing ULEB entries to dump.
// Returns the number of bytes dumped.
va_list valist;
va_start(valist, sz);
size_t cbDumped = 0; // if we hit 4, we break and do the text label
bool fNeedIndent = false;
for (size_t ib = 0; ib < cb; ib++) {
if (fNeedIndent) {
StdOutPuts(L" ");
fNeedIndent = false;
}
StdOutPrintf(L"%02X ", *pb++);
++cbDumped;
if (cbDumped == DESCRIPTOR_COLUMNS) {
StdOutPuts(L" ");
StdOutVprintf(sz, valist);
}
if ((cbDumped % DESCRIPTOR_COLUMNS) == 0) {
StdOutPutc(L'\n');
fNeedIndent = true;
}
}
while (trailingULEB-- > 0) {
// First: a bunch with high bit set
while (*pb & 0x80) {
if (fNeedIndent) {
StdOutPuts(L" ");
fNeedIndent = false;
}
StdOutPrintf(L"%02X ", *pb++);
cbDumped++;
if (cbDumped == DESCRIPTOR_COLUMNS) {
StdOutPuts(L" ");
StdOutVprintf(sz, valist);
}
if ((cbDumped % DESCRIPTOR_COLUMNS) == 0) {
StdOutPutc(L'\n');
fNeedIndent = true;
}
}
// One last byte
if (fNeedIndent) {
StdOutPuts(L" ");
fNeedIndent = false;
}
StdOutPrintf(L"%02X ", *pb++);
cbDumped++;
if (cbDumped == DESCRIPTOR_COLUMNS) {
StdOutPuts(L" ");
StdOutVprintf(sz, valist);
}
if ((cbDumped % DESCRIPTOR_COLUMNS) == 0) {
StdOutPutc(L'\n');
fNeedIndent = true;
}
}
// Add at least one column of padding
if (cbDumped < DESCRIPTOR_COLUMNS) {
size_t cbT = cbDumped;
do {
StdOutPuts(L" ");
}
while (++cbT < DESCRIPTOR_COLUMNS);
StdOutPuts(L" ");
StdOutVprintf(sz, valist);
StdOutPutc(L'\n');
}
else if ((cbDumped % DESCRIPTOR_COLUMNS) != 0) {
// dump a newline if we haven't already
StdOutPutc(L'\n');
}
// else, it is divisible by DESCRIPTOR_COLUMNS, and we've already dumped the newline
va_end(valist);
return cbDumped;
}
void DumpXdataForRvaIA64(PCLUI pclui)
{
// Dump ia64 xdata
const BYTE * pb = reinterpret_cast<const BYTE *>(pclui + 1);
const BYTE * pbMax = pb + pclui->DataLength * 8;
REGION_TYPE region = REGION_UNKNOWN;
DWORDLONG cbCurRegion = 0;
StdOutPrintf(L" %04X Version\n"
L" %04X Flags\n"
L" %08X Data length\n",
pclui->Version,
pclui->Flags,
pclui->DataLength);
for (;;) {
BYTE b2;
BYTE b3;
BYTE b4;
unsigned r;
DWORDLONG rlen;
unsigned mask;
unsigned grsave;
unsigned brmask;
unsigned grmask;
unsigned frmask;
unsigned uleb_count;
DWORDLONG t = 0;
DWORDLONG size = 0;
DWORDLONG pspoff = 0;
DWORDLONG spoff = 0;
unsigned abi;
unsigned context;
DWORDLONG ecount;
size_t ibCur;
unsigned a;
unsigned reg;
unsigned x;
unsigned y;
unsigned treg;
unsigned qp;
unsigned gr;
unsigned rmask;
DWORDLONG imask_length;
DWORDLONG label;
if (pb == pbMax) {
// We've exhausted the unwind descriptor records
break;
}
if (pb > pbMax) {
// INTERNAL ERROR! We read too much!
break;
}
// Start with the correct indent
StdOutPuts(L" ");
BYTE b = *pb;
// First, look to see if we only have padding. There should be <= 7
// bytes of padding.
if (b == 0) {
const BYTE *pb2;
for (pb2 = pb+1; pb2 < pbMax; pb2++) {
if (*pb2 != 0) {
break;
}
}
if (pb2 == pbMax) {
pb += CbDumpBytes(pb, (size_t) (pbMax - pb), 0, L"padding");
break;
}
}
if ((b & 0x80) == 0x80) {
// A region descriptor record
// ASSERT(region != REGION_UNKNOWN);
if (region == REGION_PROLOGUE) {
// Check for prologue region descriptors
if ((b & 0xe0) == 0x80) {
// P1
brmask = (b & 0x1f);
pb += CbDumpBytes(pb, 1, 0, L"P1: brmask 0x%X", brmask);
}
else if ((b & 0xf0) == 0xa0) {
// P2
b2 = *(pb+1);
brmask = ((b & 0xf) << 1) | ((b2 & 0x80) >> 7);
gr = (b2 & 0x7f);
pb += CbDumpBytes(pb, 2, 0, L"P2: brmask 0x%X gr %u", brmask, gr);
}
else if ((b & 0xf8) == 0xb0) {
// P3
static const wchar_t * const P3_types[12] = {
L"psp_gr",
L"rp_gr",
L"pfs_gr",
L"preds_gr",
L"unat_gr",
L"lc_gr",
L"rp_br",
L"rnat_gr",
L"bsp_gr",
L"bspstore_gr",
L"fpsr_gr",
L"priunat_gr"
};
b2 = *(pb+1);
r = ((b & 0x7) << 1) | ((b2 & 0x80) >> 7);
if (r > 11) {
StdOutPuts(L"Error: unwind info is corrupt!\n");
break;
}
gr = (b2 & 0x7f);
pb += CbDumpBytes(pb, 2, 0, L"P3: %s %u", P3_types[r], gr);
}
else if (b == 0xb8) {
// P4
imask_length = (cbCurRegion * 2 + 7) / 8;
pb += CbDumpBytes(pb, (size_t) (1 + imask_length), 0, L"P4");
}
else if (b == 0xb9) {
// P5
b2 = *(pb+1);
b3 = *(pb+2);
b4 = *(pb+3);
grmask = (b2 & 0xf0) >> 4;
frmask = ((b2 & 0xf) << 16) | (b3 << 8) | b4;
pb += CbDumpBytes(pb, 4, 0, L"P5: grmask 0x%X frmask 0x%X", grmask, frmask);
}
else if ((b & 0xe0) == 0xc0) {
// P6
static const wchar_t * const P6_types[] = {
L"fr_mem",
L"gr_mem"
};
r = (b & 0x10) >> 4;
rmask = (b & 0xf);
pb += CbDumpBytes(pb, 1, 0, L"P6: %s rmask 0x%X", P6_types[r], rmask);
}
else if ((b & 0xf0) == 0xe0) {
// P7
enum P7_additional {
P7_t = 0x1,
P7_spoff = 0x2,
P7_pspoff = 0x4,
P7_size = 0x8
};
static const struct {
const wchar_t *szName;
unsigned options;
} P7_config[16] = {
{ L"mem_stack_f", P7_t | P7_size },
{ L"mem_stack_v", P7_t },
{ L"spill_base", P7_pspoff },
{ L"psp_sprel", P7_spoff },
{ L"rp_when", P7_t },
{ L"rp_psprel", P7_pspoff },
{ L"pfs_when", P7_t },
{ L"pfs_psprel", P7_pspoff },
{ L"preds_when", P7_t },
{ L"preds_psprel", P7_pspoff },
{ L"lc_when", P7_t },
{ L"lc_psprel", P7_pspoff },
{ L"unat_when", P7_t },
{ L"unat_psprel", P7_pspoff },
{ L"fpsr_when", P7_t },
{ L"fpsr_psprel", P7_pspoff },
};
r = (b & 0xf);
ibCur = 1;
uleb_count = 0;
if (P7_config[r].options & P7_t) {
uleb_count++;
t = DwlDecodeULEB128(pb + ibCur);
ibCur += CbULEB128(pb + ibCur);
}
if (P7_config[r].options & P7_size) {
uleb_count++;
size = DwlDecodeULEB128(pb + ibCur);
ibCur += CbULEB128(pb + ibCur);
}
if (P7_config[r].options & P7_pspoff) {
uleb_count++;
pspoff = DwlDecodeULEB128(pb + ibCur);
ibCur += CbULEB128(pb + ibCur);
}
if (P7_config[r].options & P7_spoff) {
uleb_count++;
spoff = DwlDecodeULEB128(pb + ibCur);
ibCur += CbULEB128(pb + ibCur);
}
// ASSERT uleb_count <= 2
wchar_t rgchOutput[100];
size_t cchOutput = swprintf_s(rgchOutput, _countof(rgchOutput), L"P7: %s", P7_config[r].szName);
if (P7_config[r].options & P7_t) {
cchOutput += swprintf_s(rgchOutput + cchOutput, _countof(rgchOutput) - cchOutput, L" time %I64u", t);
}
if (P7_config[r].options & P7_size) {
cchOutput += swprintf_s(rgchOutput + cchOutput, _countof(rgchOutput) - cchOutput, L" size %I64u", size);
}
if (P7_config[r].options & P7_pspoff) {
cchOutput += swprintf_s(rgchOutput + cchOutput, _countof(rgchOutput) - cchOutput, L" pspoff %I64u", pspoff);
}
if (P7_config[r].options & P7_spoff) {
cchOutput += swprintf_s(rgchOutput + cchOutput, _countof(rgchOutput) - cchOutput, L" spoff %I64u", spoff);
}
pb += CbDumpBytes(pb, 1, uleb_count, L"%s", rgchOutput);
}
else if (b == 0xf0) {
// P8
b2 = *(pb+1);
enum P8_additional {
P8_t = 0x1,
P8_spoff = 0x2,
P8_pspoff = 0x4
};
static const struct {
const char *szName;
unsigned options;
} P8_config[19 + 1] = {
{ NULL, 0 }, // unused
{ "rp_sprel", P8_spoff },
{ "pfs_sprel", P8_spoff },
{ "preds_sprel", P8_spoff },
{ "lc_sprel", P8_spoff },
{ "unat_sprel", P8_spoff },
{ "fpsr_sprel", P8_spoff },
{ "bsp_when", P8_t },
{ "bsp_psprel", P8_pspoff },
{ "bsp_sprel", P8_spoff },
{ "bspstore_when", P8_t },
{ "bspstore_psprel", P8_pspoff },
{ "bspstore_sprel", P8_spoff },
{ "rnat_when", P8_t },
{ "rnat_psprel", P8_pspoff },
{ "rnat_sprel", P8_spoff },
{ "priunat_when_gr", P8_t },
{ "priunat_psprel", P8_pspoff },
{ "priunat_sprel", P8_spoff },
{ "priunat_when_mem", P8_t }
};
r = b2;
if ((r < 1) || (r > 19)) {
StdOutPuts(L"Error: unwind info is corrupt!\n");
break;
}
if (P8_config[r].options & P8_t) {
t = DwlDecodeULEB128(pb + 2);
}
if (P8_config[r].options & P8_pspoff) {
pspoff = DwlDecodeULEB128(pb + 2);
}
if (P8_config[r].options & P8_spoff) {
spoff = DwlDecodeULEB128(pb + 2);
}
wchar_t rgchOutput[100];
size_t cchOutput = swprintf_s(rgchOutput, _countof(rgchOutput), L"P8: %s", P8_config[r].szName);
if (P8_config[r].options & P8_t) {
cchOutput += swprintf_s(rgchOutput + cchOutput, _countof(rgchOutput) - cchOutput, L" time %I64u", t);
}
if (P8_config[r].options & P8_pspoff) {
cchOutput += swprintf_s(rgchOutput + cchOutput, _countof(rgchOutput) - cchOutput, L" pspoff %I64u", pspoff);
}
if (P8_config[r].options & P8_spoff) {
cchOutput += swprintf_s(rgchOutput + cchOutput, _countof(rgchOutput) - cchOutput, L" spoff %I64u", spoff);
}
pb += CbDumpBytes(pb, 2, 1, L"%s", rgchOutput);
}
else if (b == 0xf1) {
// P9
b2 = *(pb+1);
b3 = *(pb+2);
if (((b2 & 0xf0) != 0) || ((b3 & 0x80) != 0)) {
StdOutPuts(L"Error: unwind info is corrupt!\n");
break;
}
grmask = (b2 & 0xf);
gr = (b3 & 0x7f);
pb += CbDumpBytes(pb, 3, 0, L"P9: grmask 0x%X gr %u", grmask, gr);
}
else if (b == 0xff) {
// P10
b2 = *(pb+1);
b3 = *(pb+2);
abi = b2;
context = b3;
pb += CbDumpBytes(pb, 3, 0, L"P10: abi %u context 0x%X", abi, context);
}
}
else if (region == REGION_BODY) {
// Check for body region descriptors
if ((b & 0xc0) == 0x80) {
// B1
static const wchar_t * const B1_types[] = {
L"label_state",
L"copy_state"
};
r = (b & 0x20) >> 5;
label = (b & 0x1f);
pb += CbDumpBytes(pb, 1, 0, L"B1: %s %I64u", B1_types[r], label);
}
else if ((b & 0xe0) == 0xc0) {
// B2
ecount = (b & 0x1f);
t = DwlDecodeULEB128(pb + 1);
pb += CbDumpBytes(pb, 1, 1, L"B2: ecount %I64u time %I64u", ecount, t);
}
else if (b == 0xe0) {
// B3
t = DwlDecodeULEB128(pb + 1);
ibCur = 1 + CbULEB128(pb + 1);
ecount = DwlDecodeULEB128(pb + ibCur);
pb += CbDumpBytes(pb, 1, 2, L"B3: ecount %I64u time %I64u", ecount, t);
}
else if ((b & 0xf7) == 0xf0) {
// B4
static const wchar_t * const B4_types[] = {
L"label_state",
L"copy_state"
};
r = (b & 0x8) >> 3;
label = DwlDecodeULEB128(pb + 1);
pb += CbDumpBytes(pb, 1, 1, L"B4: %s label %I64u", B4_types[r], label);
}
// Check for descriptors used in both body and prologue regions
else if (b == 0xf9) {
// X1
static const wchar_t * const X1_types[] = {
L"spill_psprel",
L"spill_sprel"
};
b2 = *(pb+1);
r = (b2 & 0x80) >> 7;
a = (b2 & 0x40) >> 6;
b = (b2 & 0x20) >> 5;
reg = (b2 & 0x1f);
t = DwlDecodeULEB128(pb + 2);
ibCur = 2 + CbULEB128(pb + 2);
spoff = DwlDecodeULEB128(pb + ibCur);
pb += CbDumpBytes(pb, 2, 2,
L"X1: %s a %u b %u reg %u time %I64u off %I64u",
X1_types[r],
a,
b,
reg,
t,
spoff);
}
else if (b == 0xfa) {
// X2
b2 = *(pb+1);
b3 = *(pb+2);
x = (b2 & 0x80) >> 7;
a = (b2 & 0x40) >> 6;
b = (b2 & 0x20) >> 5;
reg = (b2 & 0x1f);
y = (b3 & 0x80) >> 7;
treg = (b3 & 0x7f);
t = DwlDecodeULEB128(pb + 3);
pb += CbDumpBytes(pb, 3, 1,
L"X2: x %u a %u b %u y %u reg %u treg %u time %I64u",
x,
a,
b,
y,
reg,
treg,
t);
}
else if (b == 0xfb) {
// X3
static const wchar_t * const X3_types[] = {
L"spill_psprel_p",
L"spill_sprel_p"
};
b2 = *(pb+1);
b3 = *(pb+2);
if (((b2 & 0x40) != 0) || ((b3 & 0x80) != 0)) {
StdOutPuts(L"Error: unwind info is corrupt!\n");
break;
}
r = (b2 & 0x80) >> 7;
qp = (b2 & 0x3f);
a = (b3 & 0x40) >> 6;
b = (b3 & 0x20) >> 5;
reg = (b2 & 0x1f);
t = DwlDecodeULEB128(pb + 3);
ibCur = 3 + CbULEB128(pb + 3);
spoff = DwlDecodeULEB128(pb + ibCur);
pb += CbDumpBytes(pb, 3, 2,
L"X3: %s qp %u a %u b %u reg %u time %I64u off %I64u",
X3_types[r],
qp,
a,
b,
reg,
t,
spoff);
}
else if (b == 0xfc) {
// X4
b2 = *(pb+1);
b3 = *(pb+2);
b4 = *(pb+3);
if ((b2 & 0xc0) != 0) {
StdOutPuts(L"Error: unwind info is corrupt!\n");
break;
}
qp = (b2 & 0x3f);
x = (b3 & 0x80) >> 7;
a = (b3 & 0x40) >> 6;
b = (b3 & 0x20) >> 5;
reg = (b3 & 0x1f);
y = (b4 & 0x80) >> 7;
treg = (b4 & 0x7f);
t = DwlDecodeULEB128(pb + 3);
pb += CbDumpBytes(pb, 4, 1,
L"X4: qp %u x %u a %u b %u y %u reg %u treg %u time %I64u",
qp,
x,
a,
b,
y,
reg,
treg,
t);
}
}
else {
// If nothing matched, we have corrupt unwind info
StdOutPuts(L"Error: unwind info is corrupt!\n");
break;
}
}
else {
// A header record
if ((b & 0xc0) == 0) {
// R1
static const wchar_t * const R1_types[] = {
L"prologue",
L"body"
};
r = (b & 0x20) >> 5;
cbCurRegion = rlen = (b & 0x1f);
region = (r == 0) ? REGION_PROLOGUE : REGION_BODY;
pb += CbDumpBytes(pb, 1, 0, L"R1: %s size %I64u", R1_types[r], rlen);
}
else if ((b & 0xe0) == 0x40) {
// R2
if ((b & 0x18) != 0) {
StdOutPuts(L"Error: unwind info is corrupt!\n");
break;
}
b2 = *(pb+1);
mask = ((b & 0x7) << 1) | ((b2 & 0x80) >> 7);
grsave = (b2 & 0x7f);
cbCurRegion = rlen = DwlDecodeULEB128(pb + 2);
region = REGION_PROLOGUE;
pb += CbDumpBytes(pb, 2, 1, L"R2: size %I64u mask 0x%X grsave %u", rlen, mask, grsave);
}
else if ((b & 0xe0) == 0x60) {
// R3
static const wchar_t * const R3_types[] = {
L"prologue",
L"body"
};
if (((b & 0x1c) != 0) || ((b & 0x2) != 0)) {
StdOutPuts(L"Error: unwind info is corrupt!\n");
break;
}
r = (b & 0x3);
cbCurRegion = rlen = DwlDecodeULEB128(pb + 1);
region = (r == 0) ? REGION_PROLOGUE : REGION_BODY;
pb += CbDumpBytes(pb, 1, 1, L"R3: %s size %I64u", R3_types[r], rlen);
}
else {
// If nothing matched, we have corrupt unwind info
StdOutPuts(L"Error: unwind info is corrupt!\n");
break;
}
}
}
if (LINKER_UNW_PERSONALITY_PTR(pclui->Flags)) {
// Pointer to RVA of personality routine, if one
const DWORD *prvaPersonality = (DWORD *) pbMax;
StdOutPrintf(L" %08X Personality\n", *prvaPersonality);
}
StdOutPutc(L'\n');
}
void DumpPdbPdata(DBI *pdbi)
{
// Dump RISC function table
Dbg * pdbgPdata;
Dbg * pdbgXdata = NULL;
BYTE * pbXdata = NULL;
if (!FOpenDbg(pdbi, dbgtypePdata, L"dbgtypePdata", &pdbgPdata)) {
return;
}
DWORD cb;
const wchar_t *szMachine = L"Unknown";
const wchar_t *szPdataHdr = L" Begin End PrologEnd (defaulting to 3 RVA format)\n";
if ((cb = pdbgPdata->QuerySize()) > 0) {
DbgRvaVaBlob drvbPdata;
if (pdbgPdata->QueryNext(sizeof drvbPdata, &drvbPdata)) {
DWORD cbImgFE = sizeof IMAGE_FUNCTION_ENTRY;
switch (dwMachine) {
case IMAGE_FILE_MACHINE_IA64:
szMachine = L"IA64";
szPdataHdr = L" RVABegin RVAEnd RVAUnwindInfo\n";
cbImgFE = sizeof IMAGE_FUNCTION_ENTRY;
break;
case IMAGE_FILE_MACHINE_AMD64:
szMachine = L"x64";
szPdataHdr = L" RVABegin RVAEnd RVAUnwindInfo\n";
cbImgFE = sizeof IMAGE_FUNCTION_ENTRY;
break;
};
DbgRvaVaBlob drvbXdata = {0};
if (fXdata &&
FOpenDbg(pdbi, dbgtypeXdata, L"dbgtypeXdata", &pdbgXdata) &&
pdbgXdata->QueryNext(sizeof drvbXdata, &drvbXdata))
{
pdbgXdata->Skip(drvbXdata.cbHdr);
if (drvbXdata.cbData) {
pbXdata = new BYTE[drvbXdata.cbData];
if ( pbXdata && pdbgXdata->QueryNext(drvbXdata.cbData, pbXdata) ) {
}
else {
// skip it. why bother?
fXdata = false;
}
}
else {
fXdata = false;
}
}
else {
fXdata = false;
}
StdOutPrintf(L"\nFunction Table (%lu entries)\n"
L"\tMachine = %s\n"
L"\tHeader = {\n"
L"\t\tver = %d\n"
L"\t\tcbHdr = %d\n"
L"\t\tcbData = %d\n"
L"\t\trvaData = 0x%08x\n"
L"\t\tvaImage = 0x%016I64x\n"
L"\t\tdwRes1 = 0x%08x\n"
L"\t\tdwRes2 = 0x%08x\n"
L"\t};\n"
L"\n",
drvbPdata.cbData / cbImgFE,
szMachine,
drvbPdata.ver,
drvbPdata.cbHdr,
drvbPdata.cbData,
drvbPdata.rvaDataBase,
drvbPdata.vaImageBase,
drvbPdata.ulReserved1,
drvbPdata.ulReserved2);
if (fXdata) {
StdOutPrintf(L"Xdata header\n"
L"\tHeader = {\n"
L"\t\tver = %d\n"
L"\t\tcbHdr = %d\n"
L"\t\tcbData = %d\n"
L"\t\trvaData = 0x%08x\n"
L"\t\tvaImage = 0x%016I64x\n"
L"\t\tdwRes1 = 0x%08x\n"
L"\t\tdwRes2 = 0x%08x\n"
L"\t};\n\n",
drvbXdata.ver,
drvbXdata.cbHdr,
drvbXdata.cbData,
drvbXdata.rvaDataBase,
drvbXdata.vaImageBase,
drvbXdata.ulReserved1,
drvbXdata.ulReserved2);
}
StdOutPrintf(L"%s", szPdataHdr);
pdbgPdata->Skip(drvbPdata.cbHdr);
IMAGE_FUNCTION_ENTRY data;
DWORD ife = 0;
for (; pdbgPdata->QueryNext(cbImgFE, &data); pdbgPdata->Skip(cbImgFE)) {
StdOutPrintf(L"%08X %08X %08X %08X\n",
ife * sizeof(IMAGE_FUNCTION_ENTRY),
data.StartingAddress,
data.EndingAddress,
data.EndOfPrologue);
if (fXdata) {
switch (dwMachine) {
case IMAGE_FILE_MACHINE_IA64:
DumpXdataForRvaIA64(PCLUI(pbXdata + data.EndOfPrologue - drvbXdata.rvaDataBase));
break;
case IMAGE_FILE_MACHINE_AMD64:
StdOutPrintf(L"NYI\n");
break;
};
}
ife++;
}
}
}
pdbgPdata->Close();
if (pdbgXdata) {
pdbgXdata->Close();
}
if (pbXdata) {
delete [] pbXdata;
}
}
void DumpSectionHeader(SHORT i, const IMAGE_SECTION_HEADER *psh)
{
const wchar_t *name;
DWORD li, lj;
WORD memFlags;
StdOutPrintf(L"\n"
L"SECTION HEADER #%hX\n"
L"%8.8S name",
i,
psh->Name);
StdOutPrintf(L"\n"
L"%8X virtual size\n"
L"%8X virtual address\n"
L"%8X size of raw data\n"
L"%8X file pointer to raw data\n"
L"%8X file pointer to relocation table\n"
L"%8X file pointer to line numbers\n"
L"%8hX number of relocations\n"
L"%8hX number of line numbers\n"
L"%8X flags\n",
psh->Misc.PhysicalAddress,
psh->VirtualAddress,
psh->SizeOfRawData,
psh->PointerToRawData,
psh->PointerToRelocations,
psh->PointerToLinenumbers,
psh->NumberOfRelocations,
psh->NumberOfLinenumbers,
psh->Characteristics);
memFlags = 0;
li = psh->Characteristics;
// Clear the padding bits
li &= ~0x00F00000;
for (lj = 0L; li; li = li >> 1, lj++) {
if (li & 1) {
switch ((li & 1) << lj) {
case IMAGE_SCN_TYPE_NO_PAD : name = L"No Pad"; break;
case IMAGE_SCN_CNT_CODE : name = L"Code"; break;
case IMAGE_SCN_CNT_INITIALIZED_DATA : name = L"Initialized Data"; break;
case IMAGE_SCN_CNT_UNINITIALIZED_DATA : name = L"Uninitialized Data"; break;
case IMAGE_SCN_LNK_OTHER : name = L"Other"; break;
case IMAGE_SCN_LNK_INFO : name = L"Info"; break;
case IMAGE_SCN_LNK_REMOVE : name = L"Remove"; break;
case IMAGE_SCN_LNK_COMDAT : name = L"Communal"; break;
case IMAGE_SCN_LNK_NRELOC_OVFL : name = L"Extended relocations"; break;
case IMAGE_SCN_MEM_DISCARDABLE: name = L"Discardable"; break;
case IMAGE_SCN_MEM_NOT_CACHED: name = L"Not Cached"; break;
case IMAGE_SCN_MEM_NOT_PAGED: name = L"Not Paged"; break;
case IMAGE_SCN_MEM_SHARED : name = L"Shared"; break;
case IMAGE_SCN_MEM_EXECUTE : name = L""; memFlags |= 1; break;
case IMAGE_SCN_MEM_READ : name = L""; memFlags |= 2; break;
case IMAGE_SCN_MEM_WRITE : name = L""; memFlags |= 4; break;
case IMAGE_SCN_MEM_FARDATA : name = L"Far Data"; break;
case IMAGE_SCN_MEM_PURGEABLE: name = L"Purgeable or 16-Bit"; break;
case IMAGE_SCN_MEM_LOCKED : name = L"Locked"; break;
case IMAGE_SCN_MEM_PRELOAD : name = L"Preload"; break;
default : name = L"RESERVED - UNKNOWN";
}
if (*name) {
StdOutPrintf(L" %s\n", name);
}
}
}
// print alignment
switch (psh->Characteristics & 0x00F00000) {
case 0 : name = L"(no align specified)"; break;
case IMAGE_SCN_ALIGN_1BYTES : name = L"1 byte align"; break;
case IMAGE_SCN_ALIGN_2BYTES : name = L"2 byte align"; break;
case IMAGE_SCN_ALIGN_4BYTES : name = L"4 byte align"; break;
case IMAGE_SCN_ALIGN_8BYTES : name = L"8 byte align"; break;
case IMAGE_SCN_ALIGN_16BYTES : name = L"16 byte align"; break;
case IMAGE_SCN_ALIGN_32BYTES : name = L"32 byte align"; break;
case IMAGE_SCN_ALIGN_64BYTES : name = L"64 byte align"; break;
case IMAGE_SCN_ALIGN_128BYTES : name = L"128 byte align"; break;
case IMAGE_SCN_ALIGN_256BYTES : name = L"256 byte align"; break;
case IMAGE_SCN_ALIGN_512BYTES : name = L"512 byte align"; break;
case IMAGE_SCN_ALIGN_1024BYTES : name = L"1024 byte align"; break;
case IMAGE_SCN_ALIGN_2048BYTES : name = L"2048 byte align"; break;
case IMAGE_SCN_ALIGN_4096BYTES : name = L"4096 byte align"; break;
case IMAGE_SCN_ALIGN_8192BYTES : name = L"8192 byte align"; break;
default: name = L"(invalid align)"; break;
}
StdOutPrintf(L" %s\n", name);
if (memFlags) {
switch (memFlags) {
case 1 : name = L"Execute Only"; break;
case 2 : name = L"Read Only"; break;
case 3 : name = L"Execute Read"; break;
case 4 : name = L"Write Only"; break;
case 5 : name = L"Execute Write"; break;
case 6 : name = L"Read Write"; break;
case 7 : name = L"Execute Read Write"; break;
}
StdOutPrintf(L" %s\n", name);
}
}
void DumpPdbSectionHdr(DBI *pdbi)
{
// Dump image section headers
Dbg *pdbg;
if (!FOpenDbg(pdbi, dbgtypeSectionHdr, L"dbgtypeSectionHdr", &pdbg)) {
return;
}
ULONG celts;
if ((celts = pdbg->QuerySize()) > 0) {
IMAGE_SECTION_HEADER sh;
SHORT iHdr;
for (iHdr = 1; pdbg->QueryNext(1, &sh); pdbg->Skip(1)) {
DumpSectionHeader(iHdr, &sh);
iHdr++;
}
}
pdbg->Close();
}
void DumpPdbSectionHdrOrig(DBI *pdbi)
{
// Dump image section headers
Dbg *pdbg;
if (!FOpenDbg(pdbi, dbgtypeSectionHdrOrig, L"dbgtypeSectionHdrOrig", &pdbg)) {
return;
}
ULONG celts;
if ((celts = pdbg->QuerySize()) > 0) {
IMAGE_SECTION_HEADER sh;
SHORT iHdr;
for (iHdr = 1; pdbg->QueryNext(1, &sh); pdbg->Skip(1)) {
DumpSectionHeader(iHdr, &sh);
iHdr++;
}
}
pdbg->Close();
}
BOOL DumpPdbQueryModDebugInfo(Mod *pmod, enum DbgInfoKind e, DWORD cb, PB pb, DWORD *pcb)
{
switch (e) {
case DIK_xScopeExport:
return pmod->QueryCrossScopeExports(cb, pb, pcb);
case DIK_xScopeImport:
return pmod->QueryCrossScopeImports(cb, pb, pcb);
case DIK_FuncTokenMap:
return pmod->QueryFuncMDTokenMap(cb, pb, pcb);
case DIK_TypeTokenMap:
return pmod->QueryTypeMDTokenMap(cb, pb, pcb);
case DIK_MergedAsmIn:
return pmod->QueryMergedAssemblyInput(cb, pb, pcb);
}
return FALSE;
}
void DumpPdbModDbgInfo(DBI *pdbi, enum DbgInfoKind e)
{
Mod *pmod = NULL;
while (pdbi->QueryNextMod(pmod, &pmod) && pmod) {
USHORT imod;
if (iModToList && pmod->QueryImod(&imod) && (iModToList != imod)) {
continue;
}
wchar_t szName[PDB_MAX_PATH];
long cch = _countof(szName);
if (pmod->QueryNameW(szName, &cch)) {
wchar_t wszLibrary[PDB_MAX_PATH];
cch = _countof(wszLibrary);
StdOutPrintf(L"** Module: \"%s\"", szName);
if (!pmod->QueryFileW(wszLibrary, &cch)) {
}
else if (wcscmp(wszLibrary, szName) == 0) {
// If file name matches module name that this isn't a library
}
else {
StdOutPrintf(L" from \"%s\"", wszLibrary);
}
StdOutPutc(L'\n');
StdOutPutc(L'\n');
}
DWORD cb = 0;
if (!DumpPdbQueryModDebugInfo(pmod, e, 0, NULL, &cb)) {
StdOutPuts(L"Mod::QueryCrossScopeExports failed\n\n");
continue;
}
if (cb == 0) {
continue;
}
PB pb = (PB) malloc(cb);
if (pb == NULL) {
StdOutPuts(L"malloc failed\n");
return;
}
if (!DumpPdbQueryModDebugInfo(pmod, e, cb, pb, &cb)) {
StdOutPuts(L"Mod::QueryCrossScopeExports failed\n\n");
continue;
}
pfn(cb, pb);
free(pb);
StdOutPutc(L'\n');
}
}
void DumpPdbStringTable(PDB *ppdb)
{
NameMap* pnm = NULL;
if (!NameMap::open(ppdb, FALSE, &pnm)) {
StdOutPuts(L"NameMap::open failed\n");
return;
}
NI ni = 1;
const char *sz;
while (pnm->isValidNi(ni) && pnm->getName(ni, &sz)) {
StdOutPrintf(L"%08x ", ni);
PrintSt(true, reinterpret_cast<const unsigned char *>(sz));
ni += static_cast<NI>(strlen(sz) + 1);
}
}
ULONG cTokenMap;
DWORD *pTokenMap;
void LoadTokenMap(DBI* pdbi)
{
Dbg* pdbg;
cTokenMap = 0;
pTokenMap = NULL;
if ( pdbi->OpenDbg(dbgtypeTokenRidMap, &pdbg) ) {
if ( (cTokenMap = pdbg->QuerySize() ) > 0 ) {
pTokenMap = new DWORD[ cTokenMap ];
}
if (pTokenMap != NULL) {
pdbg->QueryNext( cTokenMap, pTokenMap );
}
else {
cTokenMap = 0;
}
pdbg->Close();
}
}
DWORD PdbMapToken( DWORD tokenOld )
{
if ( pTokenMap == NULL ) // no map
return tokenOld;
if ( TypeFromToken( tokenOld ) != mdtMethodDef ) // only support a method map
return tokenOld;
if ( RidFromToken( tokenOld ) < cTokenMap ) // in range
return TokenFromRid( TypeFromToken( tokenOld ), pTokenMap[ RidFromToken( tokenOld ) ] );
return tokenOld;
}
void UnloadTokenMap()
{
delete [] pTokenMap;
cTokenMap = 0;
pTokenMap = NULL;
}
void DumpPdb(PDB *ppdb)
{
fUtf8Symbols = (ppdb->QueryInterfaceVersion() >= PDBImpvVC70);
DBI *pdbi;
if (!ppdb->OpenDBI(NULL, pdbRead, &pdbi)) {
StdOutPuts(L"PDB::OpenDBI failed\n");
return;
}
// get the machine type set up. note that we also
// set the CVDumpMachineType based on it since we may
// have symbols embedded in types that need register
// enumerates setup properly (s_regrel32 embedded in
// lf_refsym types for Fortran).
dwMachine = pdbi->QueryMachineType();
switch (dwMachine) {
case IMAGE_FILE_MACHINE_AM33 :
CVDumpMachineType = CV_CFL_AM33;
break;
case IMAGE_FILE_MACHINE_AMD64 :
CVDumpMachineType = CV_CFL_X64;
break;
case IMAGE_FILE_MACHINE_ARM :
CVDumpMachineType = CV_CFL_ARM3;
break;
case IMAGE_FILE_MACHINE_ARM64 :
CVDumpMachineType = CV_CFL_ARM64;
break;
case IMAGE_FILE_MACHINE_ARMNT :
CVDumpMachineType = CV_CFL_ARMNT;
break;
case IMAGE_FILE_MACHINE_CEE :
CVDumpMachineType = CV_CFL_CEE;
break;
case IMAGE_FILE_MACHINE_EBC :
CVDumpMachineType = CV_CFL_EBC;
break;
case IMAGE_FILE_MACHINE_I386 :
CVDumpMachineType = CV_CFL_80386;
break;
case IMAGE_FILE_MACHINE_IA64 :
CVDumpMachineType = CV_CFL_IA64_1;
break;
case IMAGE_FILE_MACHINE_M32R :
CVDumpMachineType = CV_CFL_M32R;
break;
case IMAGE_FILE_MACHINE_MIPS16 :
case IMAGE_FILE_MACHINE_MIPSFPU :
case IMAGE_FILE_MACHINE_MIPSFPU16 :
case IMAGE_FILE_MACHINE_R3000 :
case IMAGE_FILE_MACHINE_R4000 :
case IMAGE_FILE_MACHINE_R10000 :
CVDumpMachineType = CV_CFL_MIPS;
break;
case IMAGE_FILE_MACHINE_POWERPC :
CVDumpMachineType = CV_CFL_PPC601;
break;
case IMAGE_FILE_MACHINE_POWERPCBE :
CVDumpMachineType = CV_CFL_PPCBE;
break;
case IMAGE_FILE_MACHINE_POWERPCFP :
CVDumpMachineType = CV_CFL_PPCFP;
break;
case IMAGE_FILE_MACHINE_SH3 :
CVDumpMachineType = CV_CFL_SH3;
break;
case IMAGE_FILE_MACHINE_SH3DSP :
CVDumpMachineType = CV_CFL_SH3DSP;
break;
case IMAGE_FILE_MACHINE_SH4 :
CVDumpMachineType = CV_CFL_SH4;
break;
case IMAGE_FILE_MACHINE_SH5 :
CVDumpMachineType = CV_CFL_SH4; // UNDONE
break;
case IMAGE_FILE_MACHINE_THUMB :
CVDumpMachineType = CV_CFL_THUMB;
break;
}
LoadTokenMap(pdbi);
if (fIDs) {
StdOutPuts(L"\n*** IDs\n\n");
DumpPdbTypes(ppdb, pdbi, true);
}
if (fMod) {
StdOutPuts(L"\n*** MODULES\n\n");
DumpPdbModules(pdbi);
}
if (fPub) {
StdOutPuts(L"\n*** PUBLICS\n\n");
DumpPdbPublics(ppdb, pdbi);
}
if (fTyp) {
StdOutPuts(L"\n*** TYPES\n\n");
DumpPdbTypes(ppdb, pdbi, false);
}
if (fTypMW) {
StdOutPuts(L"\n*** TYPES Mismatch Warnings\n\n");
DumpPdbTypeWarnDuplicateUDTs(ppdb, pdbi);
}
if (fSym) {
StdOutPuts(L"\n*** SYMBOLS\n\n");
DumpPdbSyms(pdbi);
}
if (fGPSym) {
StdOutPuts(L"\n*** GLOBALS\n\n");
DumpPdbGlobals(ppdb, pdbi);
}
if (fCoffSymRVA) {
StdOutPuts(L"\n*** COFF SYMBOL RVA\n\n");
DumpPdbCoffSymRVA(pdbi);
}
if (fInlineeLines) {
StdOutPuts(L"\n*** INLINEE LINES\n\n");
DumpPdbInlineeLines(pdbi);
}
if (fLines) {
StdOutPuts(L"\n*** LINES\n\n");
DumpPdbLines(pdbi, false);
}
if (fILLines) {
StdOutPuts(L"\n*** IL LINES\n\n");
DumpPdbLines(pdbi, true);
}
if (fSrcFiles) {
StdOutPuts(L"\n*** SOURCE FILES\n\n");
DumpPdbSrcFiles(pdbi);
}
if (fSecContribs) {
StdOutPuts(L"\n*** SECTION CONTRIBUTIONS\n\n");
DumpPdbSecContribs(pdbi);
}
if (fSegMap) {
StdOutPuts(L"\n*** SEGMENT MAP\n\n");
DumpPdbSecMap(pdbi);
}
if (fFpo) {
StdOutPuts(L"\n*** FPO\n\n");
DumpPdbFpo(ppdb, pdbi);
}
if (fTokenMap) {
StdOutPuts(L"\n*** TokenMap\n\n");
DumpTokenMap(pdbi);
}
if (fXFixup) {
StdOutPuts(L"\n*** FIXUPS\n\n");
DumpPdbFixup(pdbi);
}
if (fOmapf) {
StdOutPuts(L"\n*** OMAP FROM SRC\n\n");
DumpPdbOmap(pdbi, true);
}
if (fOmapt) {
StdOutPuts(L"\n*** OMAP TO SRC\n\n");
DumpPdbOmap(pdbi, false);
}
if (fPdata || fXdata) {
if (fXdata) {
StdOutPuts(L"\n*** PDATA/XDATA\n\n");
}
else {
StdOutPuts(L"\n*** PDATA\n\n");
}
DumpPdbPdata(pdbi);
}
if (fSectionHdr) {
StdOutPuts(L"\n*** SECTION HEADERS\n\n");
DumpPdbSectionHdr(pdbi);
StdOutPuts(L"\n*** ORIGINAL SECTION HEADERS\n\n");
DumpPdbSectionHdrOrig(pdbi);
}
if (fXModExportIDs) {
StdOutPuts(L"\n*** CROSS MODULE EXPORTS\n\n");
pfn = DumpModCrossScopeExports;
DumpPdbModDbgInfo(pdbi, DIK_xScopeExport);
}
if (fXModImportIDs) {
StdOutPuts(L"\n*** CROSS MODULE IMPORTS\n\n");
pfn = DumpModCrossScopeRefs;
DumpPdbModDbgInfo(pdbi, DIK_xScopeImport);
}
if (fFuncTokenMap) {
StdOutPuts(L"\n*** FUNCTION TOKEN MAP\n\n");
pfn = DumpModFuncTokenMap;
DumpPdbModDbgInfo(pdbi, DIK_FuncTokenMap);
}
if (fTypTokenMap) {
StdOutPuts(L"\n*** TYPE TOKEN MAP\n\n");
pfn = DumpModTypeTokenMap;
DumpPdbModDbgInfo(pdbi, DIK_TypeTokenMap);
}
if (fMergedAsmInput) {
StdOutPuts(L"\n*** MERGED ASSEMBLY INPUT\n\n");
pfn = DumpModMergedAssemblyInput;
DumpPdbModDbgInfo(pdbi, DIK_MergedAsmIn);
}
if (fStringTable) {
StdOutPuts(L"\n*** STRINGTABLE\n\n");
DumpPdbStringTable(ppdb);
}
UnloadTokenMap();
pdbi->Close();
}
void DumpPdbFile(const wchar_t *szFilename)
{
EC ec;
PDB *ppdb;
if (!PDB::Open2W(szFilename, pdbRead, &ec, NULL, 0, &ppdb)) {
return;
}
DumpPdb(ppdb);
ppdb->Close();
}
void ShowUdtTypeId(TPI *ptpi, const char *stName)
{
char *szName;
char szBuf[_MAX_PATH];
if (fUtf8Symbols) {
szName = (char *) stName;
}
else {
size_t cch = *(BYTE *) stName;
memcpy(szBuf, stName + 1, cch);
szBuf[cch] = 0;
szName = szBuf;
}
CV_typ_t ti;
if (ptpi->QueryTiForUDT(szName, TRUE, &ti)) {
StdOutPrintf(L", UDT(0x%08x)", (unsigned long) ti);
}
}
#ifdef _DEBUG
#ifdef _DEFINE_FAILASSERTION_
extern "C" void failAssertion(SZ_CONST szAssertFile, int line)
{
fprintf(stderr, "assertion failure: file %s, line %d\n", szAssertFile, line);
fflush(stderr);
DebugBreak();
}
extern "C" void failExpect(SZ_CONST szFile, int line)
{
fprintf(stderr, "expectation failure: file %s, line %d\n", szFile, line);
fflush(stderr);
}
extern "C" void failAssertionFunc(SZ_CONST szAssertFile, SZ_CONST szFunction, int line, SZ_CONST szCond)
{
fprintf(
stderr,
"assertion failure:\n\tfile: %s,\n\tfunction: %s,\n\tline: %d,\n\tcondition(%s)\n\n",
szAssertFile,
szFunction,
line,
szCond
);
fflush(stderr);
DebugBreak();
}
extern "C" void failExpectFunc(SZ_CONST szFile, SZ_CONST szFunction, int line, SZ_CONST szCond)
{
fprintf(
stderr,
"expectation failure:\n\tfile: %s,\n\tfunction: %s,\n\tline: %d,\n\tcondition(%s)\n\n",
szFile,
szFunction,
line,
szCond
);
fflush(stderr);
}
#endif
#endif
| 28.05398
| 132
| 0.430316
|
kyle-sylvestre
|
a3b4510144332fae8e26951b07addfd729a61342
| 2,943
|
cpp
|
C++
|
compiler-native/compiler/apps/bandwidth_recorder.cpp
|
SleepyToDeath/NetQRE
|
0176a31afa45faa4877974a4a0575a4e60534090
|
[
"MIT"
] | 2
|
2021-03-30T15:25:44.000Z
|
2021-05-14T07:22:25.000Z
|
compiler-native/compiler/apps/bandwidth_recorder.cpp
|
SleepyToDeath/NetQRE
|
0176a31afa45faa4877974a4a0575a4e60534090
|
[
"MIT"
] | null | null | null |
compiler-native/compiler/apps/bandwidth_recorder.cpp
|
SleepyToDeath/NetQRE
|
0176a31afa45faa4877974a4a0575a4e60534090
|
[
"MIT"
] | null | null | null |
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <arpa/inet.h>
#include <linux_compat.h>
#include <unordered_map>
#define ETHERNET_LINK_OFFSET 14
FILE *file = NULL;
long packet_cnt = 0;
bool debug_mode = false;
long bucket_bytes = 0;
long bucket_time_ms = 0;
static void close() {
fclose(file);
fflush(file);
printf("Processed %ld packets\n", packet_cnt);
printf("Exit now.\n");
}
static void handleCapturedPacket(u_char* arg, const struct pcap_pkthdr *header, u_char *packet) {
packet_cnt += 1;
if (packet_cnt % 1 == 0 && debug_mode) {
printf("In progress: %ld packets\n", packet_cnt);
}
long time_ms = header->ts.tv_sec*1000 + header->ts.tv_usec/1000;
if (bucket_time_ms == 0) {
bucket_time_ms = time_ms/100*100;
} else {
while (time_ms - bucket_time_ms >= 100) {
fprintf(file, "%ld %ld\n", bucket_time_ms, bucket_bytes*8); // bits from srcIP to dstIP in the last 100 ms
bucket_bytes = 0;
bucket_time_ms += 100;
if (bucket_time_ms % 1000 == 0)
fflush(file);
}
}
bucket_bytes += header->caplen;
}
int main(int argc, char *argv[]) {
pcap_t *handle; /* Session handle */
char *dev; /* The device to sniff on */
char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */
struct bpf_program fp; /* The compiled filter */
bpf_u_int32 mask; /* Our netmask */
bpf_u_int32 net; /* Our IP */
struct pcap_pkthdr header; /* The header that pcap gives us */
const u_char *packet; /* The actual packet */
int loop_num = 1;
bool is_offline = true;
file = fopen("bandwidth_record.log", "w");
if (argc < 3) {
printf("Usage: ./main mode path_to_file [loop_num] [debug_mode]\n");
return 0;
}
if (argc >= 4) {
loop_num = atoi(argv[3]);
}
if (argc >= 5) {
debug_mode = strcmp(argv[4], "debug") == 0;
}
if (strcmp(argv[1], "offline") == 0) {
is_offline = true;
} else if (strcmp(argv[1], "live") == 0) {
is_offline = false;
} else {
printf("Mode %s is not recognized\n", argv[1]);
return 0;
}
if (is_offline) {
for (int i=0; i<loop_num; i++) {
handle = pcap_open_offline(argv[2], errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open file %s: %s\n", argv[2], errbuf);
return(1);
}
if (pcap_loop(handle, -1, (pcap_handler) handleCapturedPacket, NULL) < 0) {
fprintf(stderr, "pcap_loop exited with error.\n");
exit(1);
}
}
} else {
handle = pcap_open_live(argv[2], 65535, 1, 10, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", argv[2], errbuf);
return(0);
}
if (pcap_loop(handle, -1, (pcap_handler) handleCapturedPacket, NULL) < 0) {
fprintf(stderr, "pcap_loop exited with error.\n");
exit(1);
}
}
close();
/* And close the session */
pcap_close(handle);
return(0);
}
| 25.37069
| 112
| 0.607883
|
SleepyToDeath
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.