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
108
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
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
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
9535f99c5aea44424a4d81fdec17454840a5d8cb
16,723
cpp
C++
clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
2
2018-01-16T20:08:24.000Z
2018-01-31T17:05:32.000Z
clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
18
2022-03-08T13:46:16.000Z
2022-03-23T15:30:29.000Z
clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
//===- unittests/Analysis/FlowSensitive/SingelVarConstantPropagation.cpp --===// // // 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 // //===----------------------------------------------------------------------===// // // This file defines a simplistic version of Constant Propagation as an example // of a forward, monotonic dataflow analysis. The analysis tracks all // variables in the scope, but lacks escape analysis. // //===----------------------------------------------------------------------===// #include "TestingSupport.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Expr.h" #include "clang/AST/Stmt.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h" #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h" #include "clang/Analysis/FlowSensitive/DataflowLattice.h" #include "clang/Analysis/FlowSensitive/MapLattice.h" #include "clang/Tooling/Tooling.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Error.h" #include "llvm/Testing/Support/Annotations.h" #include "llvm/Testing/Support/Error.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <cstdint> #include <memory> #include <ostream> #include <string> #include <utility> namespace clang { namespace dataflow { namespace { using namespace ast_matchers; // Models the value of an expression at a program point, for all paths through // the program. struct ValueLattice { // FIXME: change the internal representation to use a `std::variant`, once // clang admits C++17 constructs. enum class ValueState : bool { Undefined, Defined, }; // `State` determines the meaning of the lattice when `Value` is `None`: // * `Undefined` -> bottom, // * `Defined` -> top. ValueState State; // When `None`, the lattice is either at top or bottom, based on `State`. llvm::Optional<int64_t> Value; constexpr ValueLattice() : State(ValueState::Undefined), Value(llvm::None) {} constexpr ValueLattice(int64_t V) : State(ValueState::Defined), Value(V) {} constexpr ValueLattice(ValueState S) : State(S), Value(llvm::None) {} static constexpr ValueLattice bottom() { return ValueLattice(ValueState::Undefined); } static constexpr ValueLattice top() { return ValueLattice(ValueState::Defined); } friend bool operator==(const ValueLattice &Lhs, const ValueLattice &Rhs) { return Lhs.State == Rhs.State && Lhs.Value == Rhs.Value; } friend bool operator!=(const ValueLattice &Lhs, const ValueLattice &Rhs) { return !(Lhs == Rhs); } LatticeJoinEffect join(const ValueLattice &Other) { if (*this == Other || Other == bottom() || *this == top()) return LatticeJoinEffect::Unchanged; if (*this == bottom()) { *this = Other; return LatticeJoinEffect::Changed; } *this = top(); return LatticeJoinEffect::Changed; } }; std::ostream &operator<<(std::ostream &OS, const ValueLattice &L) { if (L.Value.hasValue()) return OS << *L.Value; switch (L.State) { case ValueLattice::ValueState::Undefined: return OS << "None"; case ValueLattice::ValueState::Defined: return OS << "Any"; } llvm_unreachable("unknown ValueState!"); } using ConstantPropagationLattice = VarMapLattice<ValueLattice>; constexpr char kDecl[] = "decl"; constexpr char kVar[] = "var"; constexpr char kInit[] = "init"; constexpr char kJustAssignment[] = "just-assignment"; constexpr char kAssignment[] = "assignment"; constexpr char kRHS[] = "rhs"; auto refToVar() { return declRefExpr(to(varDecl().bind(kVar))); } // N.B. This analysis is deliberately simplistic, leaving out many important // details needed for a real analysis. Most notably, the transfer function does // not account for the variable's address possibly escaping, which would // invalidate the analysis. It also could be optimized to drop out-of-scope // variables from the map. class ConstantPropagationAnalysis : public DataflowAnalysis<ConstantPropagationAnalysis, ConstantPropagationLattice> { public: explicit ConstantPropagationAnalysis(ASTContext &Context) : DataflowAnalysis<ConstantPropagationAnalysis, ConstantPropagationLattice>(Context) {} static ConstantPropagationLattice initialElement() { return ConstantPropagationLattice::bottom(); } void transfer(const Stmt *S, ConstantPropagationLattice &Vars, Environment &Env) { auto matcher = stmt(anyOf(declStmt(hasSingleDecl( varDecl(decl().bind(kVar), hasType(isInteger()), optionally(hasInitializer(expr().bind(kInit)))) .bind(kDecl))), binaryOperator(hasOperatorName("="), hasLHS(refToVar()), hasRHS(expr().bind(kRHS))) .bind(kJustAssignment), binaryOperator(isAssignmentOperator(), hasLHS(refToVar())) .bind(kAssignment))); ASTContext &Context = getASTContext(); auto Results = match(matcher, *S, Context); if (Results.empty()) return; const BoundNodes &Nodes = Results[0]; const auto *Var = Nodes.getNodeAs<clang::VarDecl>(kVar); assert(Var != nullptr); if (Nodes.getNodeAs<clang::VarDecl>(kDecl) != nullptr) { if (const auto *E = Nodes.getNodeAs<clang::Expr>(kInit)) { Expr::EvalResult R; Vars[Var] = (E->EvaluateAsInt(R, Context) && R.Val.isInt()) ? ValueLattice(R.Val.getInt().getExtValue()) : ValueLattice::top(); } else { // An unitialized variable holds *some* value, but we don't know what it // is (it is implementation defined), so we set it to top. Vars[Var] = ValueLattice::top(); } } else if (Nodes.getNodeAs<clang::Expr>(kJustAssignment)) { const auto *E = Nodes.getNodeAs<clang::Expr>(kRHS); assert(E != nullptr); Expr::EvalResult R; Vars[Var] = (E->EvaluateAsInt(R, Context) && R.Val.isInt()) ? ValueLattice(R.Val.getInt().getExtValue()) : ValueLattice::top(); } else if (Nodes.getNodeAs<clang::Expr>(kAssignment)) { // Any assignment involving the expression itself resets the variable to // "unknown". A more advanced analysis could try to evaluate the compound // assignment. For example, `x += 0` need not invalidate `x`. Vars[Var] = ValueLattice::top(); } } }; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; MATCHER_P(Var, name, (llvm::Twine(negation ? "isn't" : "is") + " a variable named `" + name + "`") .str()) { return arg->getName() == name; } MATCHER_P(HasConstantVal, v, "") { return arg.Value.hasValue() && *arg.Value == v; } MATCHER(Varies, "") { return arg == arg.top(); } MATCHER_P(HoldsCPLattice, m, ((negation ? "doesn't hold" : "holds") + llvm::StringRef(" a lattice element that ") + ::testing::DescribeMatcher<ConstantPropagationLattice>(m, negation)) .str()) { return ExplainMatchResult(m, arg.Lattice, result_listener); } class MultiVarConstantPropagationTest : public ::testing::Test { protected: template <typename Matcher> void RunDataflow(llvm::StringRef Code, Matcher Expectations) { ASSERT_THAT_ERROR( test::checkDataflow<ConstantPropagationAnalysis>( Code, "fun", [](ASTContext &C, Environment &) { return ConstantPropagationAnalysis(C); }, [&Expectations]( llvm::ArrayRef<std::pair< std::string, DataflowAnalysisState< ConstantPropagationAnalysis::Lattice>>> Results, ASTContext &) { EXPECT_THAT(Results, Expectations); }, {"-fsyntax-only", "-std=c++17"}), llvm::Succeeded()); } }; TEST_F(MultiVarConstantPropagationTest, JustInit) { std::string Code = R"( void fun() { int target = 1; // [[p]] } )"; RunDataflow(Code, UnorderedElementsAre( Pair("p", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(1))))))); } TEST_F(MultiVarConstantPropagationTest, Assignment) { std::string Code = R"( void fun() { int target = 1; // [[p1]] target = 2; // [[p2]] } )"; RunDataflow(Code, UnorderedElementsAre( Pair("p1", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(1))))), Pair("p2", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(2))))))); } TEST_F(MultiVarConstantPropagationTest, AssignmentCall) { std::string Code = R"( int g(); void fun() { int target; target = g(); // [[p]] } )"; RunDataflow(Code, UnorderedElementsAre( Pair("p", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies())))))); } TEST_F(MultiVarConstantPropagationTest, AssignmentBinOp) { std::string Code = R"( void fun() { int target; target = 2 + 3; // [[p]] } )"; RunDataflow(Code, UnorderedElementsAre( Pair("p", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(5))))))); } TEST_F(MultiVarConstantPropagationTest, PlusAssignment) { std::string Code = R"( void fun() { int target = 1; // [[p1]] target += 2; // [[p2]] } )"; RunDataflow(Code, UnorderedElementsAre( Pair("p1", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(1))))), Pair("p2", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies())))))); } TEST_F(MultiVarConstantPropagationTest, SameAssignmentInBranches) { std::string Code = R"cc( void fun(bool b) { int target; // [[p1]] if (b) { target = 2; // [[pT]] } else { target = 2; // [[pF]] } (void)0; // [[p2]] } )cc"; RunDataflow(Code, UnorderedElementsAre( Pair("p1", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies())))), Pair("pT", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), HasConstantVal(2))))), Pair("pF", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), HasConstantVal(2))))), Pair("p2", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), HasConstantVal(2))))))); } // Verifies that the analysis tracks multiple variables simultaneously. TEST_F(MultiVarConstantPropagationTest, TwoVariables) { std::string Code = R"( void fun() { int target = 1; // [[p1]] int other = 2; // [[p2]] target = 3; // [[p3]] } )"; RunDataflow(Code, UnorderedElementsAre( Pair("p1", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), HasConstantVal(1))))), Pair("p2", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), HasConstantVal(1)), Pair(Var("other"), HasConstantVal(2))))), Pair("p3", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), HasConstantVal(3)), Pair(Var("other"), HasConstantVal(2))))))); } TEST_F(MultiVarConstantPropagationTest, TwoVariablesInBranches) { std::string Code = R"cc( void fun(bool b) { int target; int other; // [[p1]] if (b) { target = 2; // [[pT]] } else { other = 3; // [[pF]] } (void)0; // [[p2]] } )cc"; RunDataflow(Code, UnorderedElementsAre( Pair("p1", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies()), Pair(Var("other"), Varies())))), Pair("pT", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), HasConstantVal(2)), Pair(Var("other"), Varies())))), Pair("pF", HoldsCPLattice(UnorderedElementsAre( Pair(Var("other"), HasConstantVal(3)), Pair(Var("target"), Varies())))), Pair("p2", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies()), Pair(Var("other"), Varies())))))); } TEST_F(MultiVarConstantPropagationTest, SameAssignmentInBranch) { std::string Code = R"cc( void fun(bool b) { int target = 1; // [[p1]] if (b) { target = 1; } (void)0; // [[p2]] } )cc"; RunDataflow(Code, UnorderedElementsAre( Pair("p1", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(1))))), Pair("p2", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(1))))))); } TEST_F(MultiVarConstantPropagationTest, NewVarInBranch) { std::string Code = R"cc( void fun(bool b) { if (b) { int target; // [[p1]] target = 1; // [[p2]] } else { int target; // [[p3]] target = 1; // [[p4]] } } )cc"; RunDataflow(Code, UnorderedElementsAre( Pair("p1", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies())))), Pair("p2", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(1))))), Pair("p3", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies())))), Pair("p4", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(1))))))); } TEST_F(MultiVarConstantPropagationTest, DifferentAssignmentInBranches) { std::string Code = R"cc( void fun(bool b) { int target; // [[p1]] if (b) { target = 1; // [[pT]] } else { target = 2; // [[pF]] } (void)0; // [[p2]] } )cc"; RunDataflow(Code, UnorderedElementsAre( Pair("p1", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies())))), Pair("pT", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(1))))), Pair("pF", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(2))))), Pair("p2", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies())))))); } TEST_F(MultiVarConstantPropagationTest, DifferentAssignmentInBranch) { std::string Code = R"cc( void fun(bool b) { int target = 1; // [[p1]] if (b) { target = 3; } (void)0; // [[p2]] } )cc"; RunDataflow(Code, UnorderedElementsAre( Pair("p1", HoldsCPLattice(UnorderedElementsAre(Pair( Var("target"), HasConstantVal(1))))), Pair("p2", HoldsCPLattice(UnorderedElementsAre( Pair(Var("target"), Varies())))))); } } // namespace } // namespace dataflow } // namespace clang
34.695021
80
0.550619
LaudateCorpus1
953c7e6d5196d4da6d09306a987e3b969dab7330
5,635
cpp
C++
Gems/PhysX/Code/Source/Pipeline/PrimitiveShapeFitter/Utils.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Gems/PhysX/Code/Source/Pipeline/PrimitiveShapeFitter/Utils.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/PhysX/Code/Source/Pipeline/PrimitiveShapeFitter/Utils.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <PhysX_precompiled.h> #include <AzCore/Math/MathUtils.h> #include <AzCore/Math/Matrix3x3.h> #include <Source/Pipeline/PrimitiveShapeFitter/Utils.h> namespace PhysX::Pipeline { Vector operator+(const Vector& lhs, const Vector& rhs) { return Vector{{ lhs[0] + rhs[0], lhs[1] + rhs[1], lhs[2] + rhs[2] }}; } Vector operator-(const Vector& lhs, const Vector& rhs) { return Vector{{ lhs[0] - rhs[0], lhs[1] - rhs[1], lhs[2] - rhs[2] }}; } Vector operator*(const Vector& vector, const double scalar) { return Vector{{ vector[0] * scalar, vector[1] * scalar, vector[2] * scalar }}; } Vector operator*(const double scalar, const Vector& vector) { return vector * scalar; } Vector operator/(const Vector& vector, const double scalar) { return Vector{{ vector[0] / scalar, vector[1] / scalar, vector[2] / scalar }}; } Vector Cross(const Vector& lhs, const Vector& rhs) { return Vector{{ lhs[1] * rhs[2] - lhs[2] * rhs[1], lhs[2] * rhs[0] - lhs[0] * rhs[2], lhs[0] * rhs[1] - lhs[1] * rhs[0] }}; } double Dot(const Vector& lhs, const Vector& rhs) { return lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2]; } double NormSquared(const Vector& vector) { return Dot(vector, vector); } double Norm(const Vector& vector) { return sqrt(NormSquared(vector)); } Vector ComputeAnyOrthogonalVector(const Vector& vector) { double invLength = 1.0; if (fabs(vector[0]) > fabs(vector[1])) { invLength /= sqrt(vector[0] * vector[0] + vector[2] * vector[2]); return Vector{{ -vector[2] * invLength, 0.0, vector[0] * invLength }}; } else { invLength /= sqrt(vector[1] * vector[1] + vector[2] * vector[2]); return Vector{{ 0.0, vector[2] * invLength, -vector[1] * invLength }}; } } AZ::Vector3 VecToAZVec3(const Vector& vector) { return AZ::Vector3((float)vector[0], (float)vector[1], (float)vector[2]); } AZ::Transform CreateTransformFromCoordinateSystem( const Vector& origin, const Vector& xAxis, const Vector& yAxis, const Vector& zAxis ) { return AZ::Transform::CreateFromMatrix3x3AndTranslation( AZ::Matrix3x3::CreateFromColumns( VecToAZVec3(xAxis), VecToAZVec3(yAxis), VecToAZVec3(zAxis)), VecToAZVec3(origin) ); } Vector RotationMatrixToEulerAngles(const Vector& xAxis, const Vector& yAxis, const Vector& zAxis) { Vector theta{{0.0, 0.0, 0.0}}; if (zAxis[0] < 1.0) { if (zAxis[0] > -1.0) { theta[1] = asin(zAxis[0]); theta[0] = atan2(-zAxis[1], zAxis[2]); theta[2] = atan2(-yAxis[0], xAxis[0]); } else { // Not a unique solution. theta[1] = -OneHalfPi; theta[0] = -atan2(xAxis[1], yAxis[1]); theta[2] = 0.0; } } else { // Not a unique solution. theta[1] = OneHalfPi; theta[0] = atan2(xAxis[1], yAxis[1]); theta[2] = 0.0; } return theta; } Vector EulerAnglesToBasisX(const Vector& theta) { return Vector{{ cos(theta[1]) * cos(theta[2]), cos(theta[2]) * sin(theta[0]) * sin(theta[1]) + cos(theta[0]) * sin(theta[2]), -cos(theta[0]) * cos(theta[2]) * sin(theta[1]) + sin(theta[0]) * sin(theta[2]) }}; } Vector EulerAnglesToBasisY(const Vector& theta) { return Vector{{ -cos(theta[1]) * sin(theta[2]), cos(theta[0]) * cos(theta[2]) - sin(theta[0]) * sin(theta[1]) * sin(theta[2]), cos(theta[2]) * sin(theta[0]) + cos(theta[0]) * sin(theta[1]) * sin(theta[2]) }}; } Vector EulerAnglesToBasisZ(const Vector& theta) { return Vector{{ sin(theta[1]), -cos(theta[1]) * sin(theta[0]), cos(theta[0]) * cos(theta[1]) }}; } bool IsAbsoluteValueWithinEpsilon(double value, const double epsilon) { // This function checks whether a value's magnitude is within a given threshold. The default value has been // chosen to be close enough to zero for all practical purposes but still be representable as a single precision // floating point number. value = fabs(value); return value <= epsilon; } bool IsAbsolueValueRatioWithinThreshold(double valueOne, double valueTwo, const double threshold) { // This function checks whether the magnitude of the ratio of two numbers is within a given threshold. valueOne = fabs(valueOne); valueTwo = fabs(valueTwo); if (valueTwo > valueOne) { AZStd::swap(valueOne, valueTwo); } return valueOne > 0.0 && valueTwo > 0.0 && valueTwo / valueOne >= threshold; } } // PhysX::Pipeline
28.175
158
0.526176
aaarsene
953c81db814c355d05cd288567701fae3eed1370
2,943
cpp
C++
snowtest/remote/extractpoint.cpp
jrising/hydronet
c6d7507e658a83fa3d6ddb5550c0a2489ad080cf
[ "MIT" ]
null
null
null
snowtest/remote/extractpoint.cpp
jrising/hydronet
c6d7507e658a83fa3d6ddb5550c0a2489ad080cf
[ "MIT" ]
null
null
null
snowtest/remote/extractpoint.cpp
jrising/hydronet
c6d7507e658a83fa3d6ddb5550c0a2489ad080cf
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <datastr/TimeSeries.h> #include <datastr/DividedRange.h> #include <datastr/FileFormats.h> #include <measure/Inds.h> #include <datastr/GeographicMap.h> #include <datastr/DelayedPartialConfidenceTemporalGeographicMap.h> #include <datastr/PartialConfidenceTemporalGeographicMap.h> using namespace openworld; int main(int argc, const char* argv[]) { const char* precipsOut = argv[1]; const char* tempsOut = argv[2]; double lat0 = atof(argv[3]); double lon0 = atof(argv[4]); DividedRange latitudes = DividedRange::withEnds(29.625, 33.875, .25, Inds::lat); DividedRange longitudes = DividedRange::withEnds(74.875, 85.125, .25, Inds::lon); cout << "Loading precipitation" << endl; PartialConfidenceTemporalGeographicMap<double>* precipitation = DelayedPartialConfidenceTemporalGeographicMap<double>::loadDelimited(latitudes, longitudes, DividedRange::withMax(DividedRange::toTime(1901, 1, 1), DividedRange::toTime(2010, 12, 31), // 2011, 1, 1 DividedRange::toTimespan(1).getValue(), Inds::unixtime), "../bhakra/mergeprecip.tsv", "../bhakra/mergeprecip_conf.tsv", NULL, '\t'); cout << "Loading temperature" << endl; PartialConfidenceTemporalGeographicMap<double>* surfaceTemp = DelayedPartialConfidenceTemporalGeographicMap<double>::loadDelimited(latitudes, longitudes, DividedRange::withMax(DividedRange::toTime(1948, 1, 1), DividedRange::toTime(2011, 2, 8), DividedRange::toTimespan(1).getValue(), Inds::unixtime), "../bhakra/mergetemps.tsv", "../bhakra/mergetemps_conf.tsv", NULL, '\t'); Measure lat0m(lat0, Inds::lat); Measure lon0m(lon0, Inds::lon); cout << "Extracting... " << lat0m << ", " << lon0m << endl; TimeSeries<double>* precips = precipitation->getTimeSeries(lat0m, lon0m); TimeSeries<double>* temps = surfaceTemp->getTimeSeries(lat0m, lon0m); cout << "Saving..." << endl; precips->saveDelimited(precipsOut); temps->saveDelimited(tempsOut); }
56.596154
174
0.488277
jrising
95422c9e7bdf98658f44e29ca7208534c93cb106
4,314
cpp
C++
src/qt/qtbase/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
src/qt/qtbase/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] // WRONG QSqlDatabase db = QSqlDatabase::database("sales"); QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db); QSqlDatabase::removeDatabase("sales"); // will output a warning // "db" is now a dangling invalid database connection, // "query" contains an invalid result set //! [0] //! [1] { QSqlDatabase db = QSqlDatabase::database("sales"); QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db); } // Both "db" and "query" are destroyed because they are out of scope QSqlDatabase::removeDatabase("sales"); // correct //! [1] //! [2] QSqlDatabase::registerSqlDriver("MYDRIVER", new QSqlDriverCreator<MyDatabaseDriver>); QSqlDatabase db = QSqlDatabase::addDatabase("MYDRIVER"); //! [2] //! [3] ... db = QSqlDatabase::addDatabase("QODBC"); db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=myaccessfile.mdb"); if (db.open()) { // success! } ... //! [3] //! [4] ... // MySQL connection db.setConnectOptions("SSL_KEY=client-key.pem;SSL_CERT=client-cert.pem;SSL_CA=ca-cert.pem;CLIENT_IGNORE_SPACE=1"); // use an SSL connection to the server if (!db.open()) { db.setConnectOptions(); // clears the connect option string ... } ... // PostgreSQL connection db.setConnectOptions("requiressl=1"); // enable PostgreSQL SSL connections if (!db.open()) { db.setConnectOptions(); // clear options ... } ... // ODBC connection db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON"); // set ODBC options if (!db.open()) { db.setConnectOptions(); // don't try to set this option ... } //! [4] //! [5] #include "qtdir/src/sql/drivers/psql/qsql_psql.cpp" //! [5] //! [6] PGconn *con = PQconnectdb("host=server user=bart password=simpson dbname=springfield"); QPSQLDriver *drv = new QPSQLDriver(con); QSqlDatabase db = QSqlDatabase::addDatabase(drv); // becomes the new default connection QSqlQuery query; query.exec("SELECT NAME, ID FROM STAFF"); ... //! [6] //! [7] unix:LIBS += -lpq win32:LIBS += libpqdll.lib //! [7] //! [8] QSqlDatabase db; qDebug() << db.isValid(); // Returns false db = QSqlDatabase::database("sales"); qDebug() << db.isValid(); // Returns \c true if "sales" connection exists QSqlDatabase::removeDatabase("sales"); qDebug() << db.isValid(); // Returns false //! [8]
31.720588
152
0.677793
power-electro
9542867f11b893d6483e1abe821d62884990acfd
8,466
hpp
C++
tracing/api/sys/trace/Logger.hpp
dterletskiy/carpc
c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5
[ "MIT" ]
6
2022-03-24T15:40:03.000Z
2022-03-30T09:40:20.000Z
tracing/api/sys/trace/Logger.hpp
dterletskiy/carpc
c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5
[ "MIT" ]
7
2022-03-24T18:53:52.000Z
2022-03-30T10:15:50.000Z
tracing/api/sys/trace/Logger.hpp
dterletskiy/carpc
c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5
[ "MIT" ]
1
2022-03-20T21:22:09.000Z
2022-03-20T21:22:09.000Z
#pragma once #include <string.h> #include <map> #include "api/sys/trace/Types.hpp" namespace carpc::trace { const std::size_t s_buffer_size = 2 * 1024; const char* const s_build_msg_error = "----- build message error -----\n"; const std::size_t s_build_msg_error_len = strlen( s_build_msg_error ); class Logger { private: Logger( ); Logger( const eLogStrategy&, const std::string& app_name, const std::size_t buffer_size = s_buffer_size ); static Logger* mp_instance; public: ~Logger( ); static Logger& instance( ); static Logger& instance( const eLogStrategy&, const std::string& app_name, const std::size_t buffer_size = s_buffer_size ); static bool init( const eLogStrategy&, const std::string& app_name, const std::size_t buffer_size = s_buffer_size ); static bool deinit( ); template< typename... Args > void message( const eLogLevel& log_level, const char* const format, Args... args ) { char message_buffer[ m_buffer_size ]; std::size_t size = ::snprintf( message_buffer, m_buffer_size, format, args... ); char* p_buffer = const_cast< char* >( message_buffer ); if( 0 >= size ) { size = s_build_msg_error_len; p_buffer = const_cast< char* >( s_build_msg_error ); } else if( size >= m_buffer_size ) { size = m_buffer_size; p_buffer[ size - 2 ] = '\n'; p_buffer[ size - 1 ] = '\0'; } switch( m_log_strategy ) { case eLogStrategy::CONSOLE: case eLogStrategy::CONSOLE_EXT: { ::write( STDOUT_FILENO, p_buffer, size ); break; } case eLogStrategy::DLT: { #ifdef USE_DLT DLT_LOG( dlt_context( ), to_dlt( log_level ), DLT_SIZED_CSTRING( p_buffer, size ) ); #endif // USE_DLT break; } case eLogStrategy::ANDROID_LOGCAT: { #if OS_TARGET == OS_ANDROID __android_log_print( to_android( log_level ), "TAG", "%s", p_buffer ); #endif // OS_TARGET == OS_ANDROID break; } default: break; } } template< typename... Args > void message_format( const eLogLevel& log_level, const char* const file, const char* const function, const int line, const char* const format, Args... args ) { const std::size_t full_format_max_size = 1024; switch( m_log_strategy ) { case eLogStrategy::CONSOLE: { char full_format[ full_format_max_size ] = { 0 }; strcat( full_format, PREFIX_FORMAT_MICROSECONDS_PID_TID_CODE ); strcat( full_format, to_color( log_level ) ); strcat( full_format, format ); strcat( full_format, RESET ); strcat( full_format, "\n" ); message( log_level, full_format, time( eGranularity::microseconds ), getpid( ), pthread_self( ), file, function, line, args... ); break; } case eLogStrategy::CONSOLE_EXT: { tm* time_tm; std::size_t milliseconds = 0; local_time_of_date( time_tm, milliseconds ); char full_format[ full_format_max_size ] = { 0 }; strcat( full_format, PREFIX_FORMAT_DATE_TIME_MILLISECONDS_PID_TID_CODE ); strcat( full_format, to_color( log_level ) ); strcat( full_format, format ); strcat( full_format, RESET ); strcat( full_format, "\n" ); message( log_level, full_format, time_tm->tm_year + 1900, time_tm->tm_mon + 1, time_tm->tm_mday, time_tm->tm_hour, time_tm->tm_min, time_tm->tm_sec, milliseconds, getpid( ), pthread_self( ), file, function, line, args... ); break; } case eLogStrategy::DLT: { char full_format[ full_format_max_size ] = { 0 }; strcat( full_format, "[%s:%s:%d] -> " ); strcat( full_format, format ); strcat( full_format, "\n" ); message( log_level, full_format, file, function, line, args... ); break; } case eLogStrategy::ANDROID_LOGCAT: { char full_format[ full_format_max_size ] = { 0 }; strcat( full_format, "[%s:%s:%d] -> " ); strcat( full_format, format ); strcat( full_format, "\n" ); message( log_level, full_format, file, function, line, args... ); break; } default: break; } } template< typename... Args > static void verbose( const char* const format, Args&... args ) { instance( ).message( eLogLevel::VERBOSE, format, args... ); } template< typename... Args > static void debug( const char* const format, Args&... args ) { instance( ).message( eLogLevel::DEBUG, format, args... ); } template< typename... Args > static void info( const char* const format, Args&... args ) { instance( ).message( eLogLevel::INFO, format, args... ); } template< typename... Args > static void warning( const char* const format, Args&... args ) { instance( ).message( eLogLevel::WARNING, format, args... ); } template< typename... Args > static void error( const char* const format, Args&... args ) { instance( ).message( eLogLevel::ERROR, format, args... ); } template< typename... Args > static void fatal( const char* const format, Args&... args ) { instance( ).message( eLogLevel::FATAL, format, args... ); } private: std::string mp_application_name = nullptr; std::size_t m_buffer_size = s_buffer_size; public: const eLogStrategy& log_strategy( ) const; void log_strategy( const eLogStrategy& ); private: #if OS_TARGET == OS_ANDROID eLogStrategy m_log_strategy = eLogStrategy::ANDROID_LOGCAT; #else eLogStrategy m_log_strategy = eLogStrategy::CONSOLE; #endif private: #ifdef USE_DLT DltContext& dlt_context( ); std::map< pthread_t, DltContext > m_context_map; #endif }; inline const eLogStrategy& Logger::log_strategy( ) const { return m_log_strategy; } inline void Logger::log_strategy( const eLogStrategy& _log_strategy ) { m_log_strategy = _log_strategy; #ifndef USE_DLT // Prevent DLT logging startegy in case of DLT is not used if( eLogStrategy::DLT == m_log_strategy ) { #if OS_TARGET == OS_ANDROID m_log_strategy = eLogStrategy::ANDROID_LOGCAT; #else m_log_strategy = eLogStrategy::CONSOLE; #endif } #endif #if OS_TARGET != OS_ANDROID if( eLogStrategy::ANDROID_LOGCAT == m_log_strategy ) m_log_strategy = eLogStrategy::CONSOLE; #endif } } // namespace carpc::trace #define CLASS_ABBR "MAIN" #define TRACE_LOG( LOG_LEVEL, USER_FORMAT, ... ) \ do { \ ::carpc::trace::Logger::instance( ).message_format( \ LOG_LEVEL, \ CLASS_ABBR, __FUNCTION__, __LINE__, \ "" USER_FORMAT, ##__VA_ARGS__ \ ); \ } while( false ) #undef CLASS_ABBR
33.330709
132
0.502599
dterletskiy
95443c4de09f8a89e341dfa094d10714a6c3b863
9,767
cpp
C++
GameEngine/ResourceManager.cpp
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
GameEngine/ResourceManager.cpp
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
GameEngine/ResourceManager.cpp
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
#define NOMINMAX #include "ResourceManager.h" #include "ModelLoader.h" #include "AudioManager.h" #include <algorithm> #include "RenderManager.h" std::vector<std::string> ResourceManager::usedModels; std::vector<std::string> ResourceManager::usedTextures; std::vector<std::string> ResourceManager::usedShaders; std::vector<std::string> ResourceManager::usedAudios; std::map<std::string, iModel *> ResourceManager::modelList; std::map<std::string, Texture *> ResourceManager::textureList; std::map<std::string, Shader *> ResourceManager::shaderList; std::map<std::string, Buffer *> ResourceManager::audioBufferList; std::map<std::string, int> ResourceManager::modelUsage; std::map<std::string, int> ResourceManager::audioBufferUsage; std::map<std::string, int> ResourceManager::shaderUsage; std::map<std::string, int> ResourceManager::textureUsage; //Loads model into game engine void ResourceManager::LoadModel(const std::string & modelName, const std::string & fileName) { if (find(usedModels.begin(), usedModels.end(), fileName) == usedModels.end()) { usedModels.push_back(fileName); } else { //TODO: Log that the model file already exists as a resource return; } if (modelList.find(modelName) != modelList.end()) { //TODO: Log that the model already exists as a resource return; } iModel * model = ModelLoader::LoadModel(fileName); if (model == nullptr) { //TODO: Log that the model failed to load return; } modelUsage.insert(std::pair<std::string, int>(modelName, 0)); modelList.insert(std::pair<std::string, iModel*>(modelName, model)); } //Loads texture into game engine void ResourceManager::LoadTexture(const std::string & textureName, const std::string & fileName) { if (find(usedTextures.begin(), usedTextures.end(), fileName) == usedTextures.end()) { usedTextures.push_back(fileName); } else { //TODO: Log that the texture file already exists as a resource return; } if (textureList.find(textureName) != textureList.end()) { //TODO: Log that the texture already exists as a resource return; } Texture * texture = RenderManager::Instance()->CreateTexture(fileName); if (!texture) { //TODO: Log that the texture failed to load return; } textureUsage.insert(std::pair<std::string, int>(textureName, 0)); textureList.insert(std::pair<std::string, Texture *>(textureName, texture)); } //Loads shader into game engine void ResourceManager::LoadShader(const std::string & shaderName, const std::string & vertexProgram, const std::string & fragmentProgram, const std::string & geometryProgram) { const std::string shaderConcat = vertexProgram + fragmentProgram + geometryProgram; if(find(usedShaders.begin(), usedShaders.end(), shaderConcat) == usedShaders.end()) { usedShaders.push_back(shaderConcat); } else { //TODO: Log that the shader programs already exists as a resource return; } if (shaderList.find(shaderName) != shaderList.end()) { //TODO: Log that the shader mapping name already exists return; } Shader * shader = RenderManager::Instance()->CreateShader(vertexProgram, fragmentProgram, geometryProgram); if (!shader) { //TODO: Log that the shader failed to compile return; } shaderUsage.insert(std::pair<std::string, int>(shaderName, 0)); shaderList.insert(std::pair<std::string, Shader *>(shaderName, shader)); } //Loads audio into game engine void ResourceManager::LoadAudio(const std::string & audioName, const std::string & fileName) { if (find(usedAudios.begin(), usedAudios.end(), fileName) == usedAudios.end()) { usedAudios.push_back(fileName); } else { //TODO: Log that the audio file already exists as a resource return; } if (audioBufferList.find(audioName) != audioBufferList.end()) { //TODO: Log that the audio already exists as a resource return; } Buffer * buffer = AudioManager::Instance()->GenerateBuffer(fileName); if (!buffer) { //TODO: Log that buffer failed to be created } audioBufferUsage.insert(std::pair<std::string, int>(audioName, 0)); audioBufferList.insert(std::pair<std::string, Buffer *>(audioName, buffer)); } //Gets model by model identity iModel * ResourceManager::GetModel(const std::string & model) { const std::map<std::string, iModel *>::iterator it = modelList.find(model); const std::map<std::string, int>::iterator count = modelUsage.find(model); if (it != modelList.end()) { count->second++; return it->second; } return nullptr; } //Gets shader by shader identity Shader * ResourceManager::GetShader(const std::string & shader) { const std::map<std::string, Shader *>::iterator it = shaderList.find(shader); const std::map<std::string, int>::iterator count = shaderUsage.find(shader); if (it != shaderList.end()) { count->second++; return it->second; } return nullptr; } //Gets texture by texture identity Texture * ResourceManager::GetTexture(const std::string & texture) { const std::map<std::string, Texture *>::iterator it = textureList.find(texture); const std::map<std::string, int>::iterator count = textureUsage.find(texture); if (it != textureList.end()) { count->second++; return it->second; } return nullptr; } //Gets audio by audio identity Source * ResourceManager::GetAudio(const std::string & audio) { const std::map<std::string, Buffer *>::iterator it = audioBufferList.find(audio); const std::map<std::string, int>::iterator count = audioBufferUsage.find(audio); if (it != audioBufferList.end()) { count->second++; Source * const source = AudioManager::Instance()->GenerateSource(it->second); return source; } return nullptr; } //Removes model void ResourceManager::RemoveModel(const iModel * const model) { std::map<std::string, iModel *>::iterator it; std::string modelName = ""; for (it = modelList.begin(); it != modelList.end(); it++) { if (it->second == model) { modelName = it->first; break; } } const std::map<std::string, int>::iterator count = modelUsage.find(modelName); if (count != modelUsage.end()) { count->second--; } } //Removes Shader void ResourceManager::RemoveShader(const Shader * const shader) { std::map<std::string, Shader *>::iterator it; std::string shaderName = ""; for (it = shaderList.begin(); it != shaderList.end(); it++) { if (it->second == shader) { shaderName = it->first; break; } } const std::map<std::string, int>::iterator count = shaderUsage.find(shaderName); if (count != shaderUsage.end()) { count->second--; } } //Removes texture void ResourceManager::RemoveTexture(const Texture * const texture) { std::map<std::string, Texture *>::iterator it; std::string textureName = ""; for (it = textureList.begin(); it != textureList.end(); it++) { if (it->second == texture) { textureName = it->first; break; } } const std::map<std::string, int>::iterator count = textureUsage.find(textureName); if (count != textureUsage.end()) { count->second--; } } //Removes audio void ResourceManager::RemoveAudio(const void * const audio) { std::map<std::string, Buffer *>::iterator it; std::string audioName = ""; for (it = audioBufferList.begin(); it != audioBufferList.end(); it++) { if (it->second == audio) { audioName = it->first; break; } } const std::map<std::string, int>::iterator count = audioBufferUsage.find(audioName); if (count != audioBufferUsage.end()) { count->second--; } } //Removes resources that are unused void ResourceManager::ClearResources() { usedModels.clear(); usedShaders.clear(); usedTextures.clear(); usedAudios.clear(); { std::map<std::string, iModel *>::iterator it; for (it = modelList.begin(); it != modelList.end();) { const std::map<std::string, int>::iterator count = modelUsage.find(it->first); if (count->second == 0) { delete it->second; it->second = nullptr; modelList.erase(it); modelUsage.erase(count); it = modelList.begin(); } else { it++; } } } { std::map<std::string, Texture *>::iterator it; for (it = textureList.begin(); it != textureList.end();) { const std::map<std::string, int>::iterator count = textureUsage.find(it->first); if (count->second == 0) { delete it->second; it->second = nullptr; textureList.erase(it); textureUsage.erase(count); it = textureList.begin(); } else { it++; } } } { std::map<std::string, Shader *>::iterator it; for (it = shaderList.begin(); it != shaderList.end();) { const std::map<std::string, int>::iterator count = shaderUsage.find(it->first); if (count->second == 0) { delete it->second; it->second = nullptr; shaderList.erase(it); shaderUsage.erase(count); it = shaderList.begin(); } else { it++; } } } } //Deletes all resources void ResourceManager::FinalClearResources() { usedModels.clear(); usedShaders.clear(); usedTextures.clear(); usedAudios.clear(); { std::map<std::string, iModel *>::iterator it; for (it = modelList.begin(); it != modelList.end(); it++) { delete it->second; it->second = nullptr; } modelList.clear(); } { std::map<std::string, Texture *>::iterator it; for (it = textureList.begin(); it != textureList.end(); it++) { delete it->second; it->second = nullptr; } textureList.clear(); } { std::map<std::string, Shader *>::iterator it; for (it = shaderList.begin(); it != shaderList.end(); it++) { delete it->second; it->second = nullptr; } shaderList.clear(); } { std::map<std::string, Buffer *>::iterator it; for (it = audioBufferList.begin(); it != audioBufferList.end(); it++) { AudioManager::Instance()->DeleteBuffer(it->second); it->second = nullptr; } audioBufferList.clear(); } }
22.661253
173
0.674516
BenMarshall98
95446e064c181e163d487889a847d6b6795e482a
10,654
cpp
C++
project1-tetris/project1-tetris/Source/ScreenDiffSelect.cpp
lSara-MM/project1-tetris
ab7bad2ee97a168eb547df1c1ad0419b265293e8
[ "MIT" ]
null
null
null
project1-tetris/project1-tetris/Source/ScreenDiffSelect.cpp
lSara-MM/project1-tetris
ab7bad2ee97a168eb547df1c1ad0419b265293e8
[ "MIT" ]
null
null
null
project1-tetris/project1-tetris/Source/ScreenDiffSelect.cpp
lSara-MM/project1-tetris
ab7bad2ee97a168eb547df1c1ad0419b265293e8
[ "MIT" ]
null
null
null
#include "ScreenDiffSelect.h" #include "Application.h" #include "ModuleTextures.h" #include "ModuleRender.h" #include "ModuleAudio.h" #include "ModuleInput.h" #include "ModuleFadeToBlack.h" #include "ModuleParticles.h" #include <iostream> using namespace std; uint Time = 0; uint delta_Time = 0; uint last_TickTime = 0; ScreenDiffSelect::ScreenDiffSelect(bool startEnabled) : Module(startEnabled) { } ScreenDiffSelect::~ScreenDiffSelect() { } // Load assets bool ScreenDiffSelect::Start() { LOG("Loading background assets"); bool ret = true; bg_texture = App->textures->Load("Assets/Diff_Select.png"); arrowleft_texture = App->textures->Load("Assets/arrow_left.png"); arrowright_texture = App->textures->Load("Assets/arrow_right.png"); App->render->camera.x = 0; App->render->camera.y = 0; p_pos.x = p_x; p_pos.y = p_y; p_pos2.x = p2_x; p_pos2.y = p2_y; yellow_rect_texture = App->textures->Load("Assets/Rect/yellow_rect.png"); orange_rect_texture = App->textures->Load("Assets/Rect/orange_rect.png"); white_rect_texture = App->textures->Load("Assets/Rect/white_rect.png"); pink_rect_texture = App->textures->Load("Assets/Rect/pink_rect.png"); red_rect_texture = App->textures->Load("Assets/Rect/red_rect.png"); fxAdd_Press_L_R = App->audio->LoadFx("Assets/Audio/FX/diff_selection_arrow.wav"); fxAdd_PressEnter = App->audio->LoadFx("Assets/Audio/FX/diff_selection_enter.wav"); return ret; } update_status ScreenDiffSelect::Update() { Time = SDL_GetTicks(); delta_Time += Time - last_TickTime; last_TickTime = Time; App->render->Blit(bg_texture, 0, 3, NULL); //key commands if (App->input->keys[SDL_SCANCODE_A] == KEY_STATE::KEY_DOWN) { switch (Index) { case 0: if (Index < 2) { Index++; p_x -= 235; p2_x -= 205; App->audio->PlayFx(fxAdd_Press_L_R); //Colour random pos_x = 245; pos_y = 130; pos_x1 = 245; pos_y1 = 244; pos_x2 = 245; pos_y2 = 365; pos_x3 = 422; pos_y3 = 365; pos_x4 = 422; pos_y4 = 365; pos_x5 = 422; pos_y5 = 130; } break; case 1: if (Index < 2) { Index++; p_x -= 210; p2_x -= 244; App->audio->PlayFx(fxAdd_Press_L_R); //Colour random pos_x = 22; pos_y = 130; pos_x1 = 22; pos_y1 = 244; pos_x2 = 22; pos_y2 = 365; pos_x3 = 200; pos_y3 = 365; pos_x4 = 200; pos_y4 = 365; pos_x5 = 200; pos_y5 = 130; } break; } } if (App->input->keys[SDL_SCANCODE_D] == KEY_STATE::KEY_DOWN) { switch (Index) { case 1: if (Index > 0) { Index--; p_x += 235; p2_x += 205; App->audio->PlayFx(fxAdd_Press_L_R); //Colour random pos_x = 470; pos_y = 130; pos_x1 = 470; pos_y1 = 244; pos_x2 = 470; pos_y2 = 365; pos_x3 = 648; pos_y3 = 365; pos_x4 = 648; pos_y4 = 365; pos_x5 = 648; pos_y5 = 130; } case 2: if (Index > 0) { Index--; p_x += 210; p2_x += 244; App->audio->PlayFx(fxAdd_Press_L_R); pos_x = 245; pos_y = 130; pos_x1 = 245; pos_y1 = 244; pos_x2 = 245; pos_y2 = 365; pos_x3 = 422; pos_y3 = 365; pos_x4 = 422; pos_y4 = 365; pos_x5 = 422; pos_y5 = 130; } } } if (App->input->keys[SDL_SCANCODE_SPACE] == KEY_STATE::KEY_DOWN) { if (Index == Easy) { App->fade->FadeToBlack(this, (Module*)App->sLvl_1, 0); App->audio->PlayFx(fxAdd_PressEnter); } } ColourRandom(); return update_status::UPDATE_CONTINUE; } int ScreenDiffSelect::ColourRandom() { Time = SDL_GetTicks(); delta_Time += Time - last_TickTime; last_TickTime = Time; colour = rand() % 9; if ((delta_Time >= 0) && (delta_Time <= 50)) { LOG("Loading"); if (colour == 1) { App->render->Blit(green_rect_texture, pos_x, pos_y, NULL); } else if (colour == 2) { App->render->Blit(blue_rect_texture, pos_x, pos_y, NULL); } else if (colour == 3) { App->render->Blit(orange_rect_texture, pos_x, pos_y, NULL); } else if (colour == 4) { App->render->Blit(white_rect_texture, pos_x, pos_y, NULL); } else if (colour == 5) { App->render->Blit(yellow_rect_texture, pos_x, pos_y, NULL); } else if (colour == 6) { App->render->Blit(pink_rect_texture, pos_x, pos_y, NULL); } else if (colour == 7) { App->render->Blit(bluedark_rect_texture, pos_x, pos_y, NULL); } else if (colour == 8) { App->render->Blit(red_rect_texture, pos_x, pos_y, NULL); } } colour = rand() % 9; if ((delta_Time >= 50) && (delta_Time <= 100)) { if (colour == 1) { App->render->Blit(green_rect_texture, pos_x1, pos_y1, NULL); } else if (colour == 2) { App->render->Blit(blue_rect_texture, pos_x1, pos_y1, NULL); } else if (colour == 3) { App->render->Blit(orange_rect_texture, pos_x1, pos_y1, NULL); } else if (colour == 4) { App->render->Blit(white_rect_texture, pos_x1, pos_y1, NULL); } else if (colour == 5) { App->render->Blit(yellow_rect_texture, pos_x1, pos_y1, NULL); } else if (colour == 6) { App->render->Blit(pink_rect_texture, pos_x1, pos_y1, NULL); } else if (colour == 7) { App->render->Blit(bluedark_rect_texture, pos_x1, pos_y1, NULL); } else if (colour == 8) { App->render->Blit(red_rect_texture, pos_x1, pos_y1, NULL); } } colour = rand() % 9; if ((delta_Time >= 100) && (delta_Time <= 150)) { if (colour == 1) { App->render->Blit(green_rect_texture, pos_x2, pos_y2, NULL); } else if (colour == 2) { App->render->Blit(blue_rect_texture, pos_x2, pos_y2, NULL); } else if (colour == 3) { App->render->Blit(orange_rect_texture, pos_x2, pos_y2, NULL); } else if (colour == 4) { App->render->Blit(white_rect_texture, pos_x2, pos_y2, NULL); } else if (colour == 5) { App->render->Blit(yellow_rect_texture, pos_x2, pos_y2, NULL); } else if (colour == 6) { App->render->Blit(pink_rect_texture, pos_x2, pos_y2, NULL); } else if (colour == 7) { App->render->Blit(bluedark_rect_texture, pos_x2, pos_y2, NULL); } else if (colour == 8) { App->render->Blit(red_rect_texture, pos_x2, pos_y2, NULL); } } colour = rand() % 9; if ((delta_Time >= 150) && (delta_Time <= 200)) { if (colour == 1) { App->render->Blit(green_rect_texture, pos_x3, pos_y3, NULL); } else if (colour == 2) { App->render->Blit(blue_rect_texture, pos_x3, pos_y3, NULL); } else if (colour == 3) { App->render->Blit(orange_rect_texture, pos_x3, pos_y3, NULL); } else if (colour == 4) { App->render->Blit(white_rect_texture, pos_x3, pos_y3, NULL); } else if (colour == 5) { App->render->Blit(yellow_rect_texture, pos_x3, pos_y3, NULL); } else if (colour == 6) { App->render->Blit(pink_rect_texture, pos_x3, pos_y3, NULL); } else if (colour == 7) { App->render->Blit(bluedark_rect_texture, pos_x3, pos_y3, NULL); } else if (colour == 8) { App->render->Blit(red_rect_texture, pos_x3, pos_y3, NULL); } } colour = rand() % 9; if ((delta_Time >= 200) && (delta_Time <= 250)) { if (colour == 1) { App->render->Blit(green_rect_texture, pos_x4, pos_y4, NULL); } else if (colour == 2) { App->render->Blit(blue_rect_texture, pos_x4, pos_y4, NULL); } else if (colour == 3) { App->render->Blit(orange_rect_texture, pos_x4, pos_y4, NULL); } else if (colour == 4) { App->render->Blit(white_rect_texture, pos_x4, pos_y4, NULL); } else if (colour == 5) { App->render->Blit(yellow_rect_texture, pos_x4, pos_y4, NULL); } else if (colour == 6) { App->render->Blit(pink_rect_texture, pos_x4, pos_y4, NULL); } else if (colour == 7) { App->render->Blit(bluedark_rect_texture, pos_x4, pos_y4, NULL); } else if (colour == 8) { App->render->Blit(red_rect_texture, pos_x4, pos_y4, NULL); } } colour = rand() % 9; if ((delta_Time >= 250) && (delta_Time <= 300)) { if (colour == 1) { App->render->Blit(green_rect_texture, pos_x5, pos_y5, NULL); } else if (colour == 2) { App->render->Blit(blue_rect_texture, pos_x5, pos_y5, NULL); } else if (colour == 3) { App->render->Blit(orange_rect_texture, pos_x5, pos_y5, NULL); } else if (colour == 4) { App->render->Blit(white_rect_texture, pos_x5, pos_y5, NULL); } else if (colour == 5) { App->render->Blit(yellow_rect_texture, pos_x5, pos_y5, NULL); } else if (colour == 6) { App->render->Blit(bluedark_rect_texture, pos_x5, pos_y5, NULL); } else if (colour == 7) { App->render->Blit(pink_rect_texture, pos_x5, pos_y5, NULL); } else if (colour == 8) { App->render->Blit(red_rect_texture, pos_x5, pos_y5, NULL); } } if ((delta_Time >= 350) && (delta_Time <= 400)) { delta_Time = 400; } if ((delta_Time > 400)) { delta_Time = 0; } return 0; } // Update: draw background update_status ScreenDiffSelect::PostUpdate() { App->render->Blit(arrowleft_texture, p_x, p_y, NULL); App->render->Blit(arrowright_texture, p2_x, p2_y, NULL); App->render->TextDraw("DIFFICULTY SELECT", 185, 12, 255, 0, 0, 255, 20); App->render->TextDraw("EASY", 82, 64, 255, 255, 255, 255, 15); App->render->TextDraw("MEDIUM", 292, 64, 255, 255, 255, 255, 15); App->render->TextDraw("HARD", 528, 64, 255, 255, 255, 255, 15); App->render->TextDraw("HANDICAP", 274, 208, 250, 250, 255, 255, 15); App->render->TextDraw("START", 306, 240, 255, 250, 250, 255, 15); App->render->TextDraw("RANDOM", 512, 208, 255, 250, 250, 255, 15); App->render->TextDraw("BLOCKS", 530, 240, 255, 250, 250, 255, 15); App->render->TextDraw("ROUND 1", 50, 432, 255, 255, 255, 255, 15); App->render->TextDraw("NO BONUS", 50, 448, 255, 255, 255, 255, 15); App->render->TextDraw("ROUND 4", 272, 432, 255, 255, 255, 255, 15); App->render->TextDraw("20000 BONUS", 242, 448, 255, 255, 255, 255, 15); App->render->TextDraw("ROUND 7", 496, 432, 255, 255, 255, 255, 15); App->render->TextDraw("40000 BONUS", 464, 448, 255, 255, 255, 255, 15); return update_status::UPDATE_CONTINUE; } bool ScreenDiffSelect::CleanUp() { App->textures->Unload(bg_texture); App->textures->Unload(arrowleft_texture); App->textures->Unload(arrowright_texture); App->textures->Unload(green_rect_texture); App->textures->Unload(blue_rect_texture); App->textures->Unload(bluedark_rect_texture); App->textures->Unload(yellow_rect_texture); App->textures->Unload(orange_rect_texture); App->textures->Unload(white_rect_texture); //audio? return true; }
16.416025
83
0.61667
lSara-MM
954623115fb0ddd595dc1d9579026aa66c136ca0
402
cpp
C++
Object Oriented Programming Concepts/CPP OOPS 2 - Classes, Data Members and Functions.cpp
sgpritam/cbcpp
192b55d8d6930091d1ceb883f6dccf06735a391f
[ "MIT" ]
2
2019-11-11T17:16:52.000Z
2020-10-04T06:05:49.000Z
Object Oriented Programming Concepts/CPP OOPS 2 - Classes, Data Members and Functions.cpp
codedevmdu/cbcpp
85c94d81d6e491f67e3cc1ea12534065b7cde16e
[ "MIT" ]
null
null
null
Object Oriented Programming Concepts/CPP OOPS 2 - Classes, Data Members and Functions.cpp
codedevmdu/cbcpp
85c94d81d6e491f67e3cc1ea12534065b7cde16e
[ "MIT" ]
4
2019-10-24T16:58:10.000Z
2020-10-04T06:05:47.000Z
#include<iostream> using namespace std; class Car { public: int price; int model_no; char name[20]; void start() { cout<<"Grr... starting the car "<<name<<endl; } }; int main() { Car C; //Initialization C.price=500; C.model_no=1001; C.name[0]='B'; C.name[1]='M'; C.name[2]='W'; C.name[3]='\0'; C.start(); }
14.888889
54
0.482587
sgpritam
954817ef00825813b9ec30d4471c2531bd2f4848
6,469
cpp
C++
env_brdf.cpp
hypernewbie/pbr_baker
2664582786ef4facdac89d56d94f831175deac7f
[ "Unlicense" ]
14
2019-10-15T08:42:19.000Z
2021-01-05T01:56:27.000Z
env_brdf.cpp
vinjn/pbr_baker
2664582786ef4facdac89d56d94f831175deac7f
[ "Unlicense" ]
null
null
null
env_brdf.cpp
vinjn/pbr_baker
2664582786ef4facdac89d56d94f831175deac7f
[ "Unlicense" ]
2
2020-12-31T13:42:28.000Z
2022-02-23T06:09:29.000Z
/* Copyright 2019 Xi Chen 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 "env_brdf.h" using namespace glm; #include <hammersley/hammersley.h> #include <hammersley/hammersley.c> #define ENVBRDF_SAMPLE_SIZE 1024 #define HAMMERSLEY_SEQUENCE_M 2 #define TEST_HAMMERSLEY false static bool MULTISCATTER_ENVBRDF = false; // Gloss parameterization similar to Call of Duty: Advanced Warfare // float ggx_GlossToAlpha2( float gloss ) { return 2.0f / ( 1.0f + pow( 2.0f, 18.0f * gloss ) ); } // src : https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf // vec3 ggx_ImportanceSampleGGX( vec2 xi, float alpha2, vec3 N ) { float phi = 2.0f * PI * xi.x; float cosTheta = sqrt( ( 1 - xi.y ) / ( 1 + ( alpha2 - 1 ) * xi.y ) ); float sinTheta = sqrt( 1 - cosTheta * cosTheta ); vec3 H( sinTheta * cos( phi ), sinTheta * sin( phi ), cosTheta ); vec3 up = abs( N.z ) < 0.999f ? vec3( 0, 0, 1 ) : vec3( 1, 0, 0 ); vec3 tangentX = normalize( cross( up, N ) ); vec3 tangentY = cross( N, tangentX ); return tangentX * H.x + tangentY * H.y + N * H.z; } // src: https://people.sc.fsu.edu/~jburkardt/cpp_src/hammersley/hammersley.html // vec2 noise_getHammersleyAtIdx( int idx, int N ) { static std::vector< vec2 > hmValues; if ( hmValues.size() != N ) { // Pre-calculate hammersley sequence. hmValues.resize( N ); auto v = hammersley_sequence( 0, N, HAMMERSLEY_SEQUENCE_M, N ); assert( v ); for( int i = 0; i < N; i++ ) { hmValues[i].x = v[i * 2 + 0]; hmValues[i].y = v[i * 2 + 1]; } free( v ); } return hmValues[ idx % N ]; } // src: https://schuttejoe.github.io/post/ggximportancesamplingpart1/ // float ggx_SmithGeom( float NdotL, float NdotV, float alpha2 ) { float denomA = NdotV * sqrt( alpha2 + ( 1.0f - alpha2 ) * NdotL * NdotL ); float denomB = NdotL * sqrt( alpha2 + ( 1.0f - alpha2 ) * NdotV * NdotV ); return 2.0f * NdotL * NdotV / ( denomA + denomB ); } // src : https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf // vec2 ggx_IntegrateBRDF( float alpha, float NdotV ) { vec3 V = vec3( sqrt( 1.0f - NdotV * NdotV ), // sin 0.0f, NdotV // cos ); vec3 N = vec3( 0, 0, 1 ); float A = 0.0; float B = 0.0; float alpha2 = alpha * alpha; for( uint i = 0; i < ENVBRDF_SAMPLE_SIZE; i++ ) { auto xi = noise_getHammersleyAtIdx( i, ENVBRDF_SAMPLE_SIZE ); auto H = ggx_ImportanceSampleGGX( xi, alpha2, N ); vec3 L = 2.0f * dot( V, H ) * H - V; float NdotL = saturate( L.z ); float NdotH = saturate( H.z ); float VdotH = saturate( dot( V, H ) ); if( NdotL > 0.0f ) { float G = ggx_SmithGeom( NdotL, NdotV, alpha2 ); float Gvis = G * VdotH / ( NdotH * NdotV ); float Fc = pow( 1 - VdotH, 5.0f ); A += ( 1 - Fc ) * Gvis; B += ( MULTISCATTER_ENVBRDF ? 1.0f : Fc ) * Gvis; // printf( "x %f y %f i %d = { A %f B %f G %f Gvis %f Fc %f } { NdotH %f NdotV %f } \n", gloss, NdotV, i, A, B, G, Gvis, Fc, NdotH, NdotV ); } } // printf( "x %f y %f = { A %f B %f }\n", gloss, NdotV, A / ENVBRDF_SAMPLE_SIZE, B / ENVBRDF_SAMPLE_SIZE ); return vec2( A, B ) / float( ENVBRDF_SAMPLE_SIZE ); } vec4 ggx_IntegrateBRDF_Function( float x, float y ) { float NdotV = max( y, EPS ); float alpha = x; auto v = ggx_IntegrateBRDF( alpha, NdotV ); return vec4( v.x, v.y, 0.0f, 1.0f ); } vec4 ggx_EvalGitEnvBRDF( float gloss, float NdotV ) { float x = NdotV, y = gloss; float y2 = y * y; float y3 = y2 * y; float y4 = y2 * y2; float y5 = y4 * y; float p = 109.82183929f * y5 - 291.94656688f * y4 + 262.87670289f * y3 - 88.27433503f * y2 + 11.16956904f * y - 0.87481312f; float q = -182.32941472f * y5 + 469.90565431f * y4 - 402.67303522f * y3 + 123.83971017f * y2 - 16.59005077f * y + 1.87103872f; float r = 71.84851046f * y5 - 173.69958023f * y4 + 132.48656983f * y3 - 32.65209286f * y2 + 7.80449807f * y - 1.60302536f; float z2 = p * x * x + q * x + r; p = -17.85712754f * y5 + 59.72998797f * y4 - 63.78537961f * y3 + 21.95229787f * y2 - 2.50508609f * y - 0.08256607f; q = 43.65809225f * y5 - 130.48400716f * y4 + 125.05400347f * y3 - 37.08717555f * y2 + 4.24345391f * y + 0.19560386f; r = 32.31212079f * y5 + 86.12066514f * y4 - 71.28450854f * y3 + 15.53854696f * y2 - 1.90410394f * y - 0.15284118f; float z1 = p * x * x + q * x + r; return clamp( vec4( z1, z2, 0.0f, 1.0f ), vec4( 0 ), vec4( 1 ) ); } void bake_envBRDF() { #if TEST_HAMMERSLEY for( int i = 0; i < 64; i++ ) { auto xi = noise_getHammersleyAtIdx( i, 64 ); printf("{ %.2f %.2f }\n", xi.x, xi.y ); } #endif // #if TEST_HAMMERSLEY MULTISCATTER_ENVBRDF = false; baker_imageFunction2D( ggx_IntegrateBRDF_Function, 256, "output/env_brdf.png" ); MULTISCATTER_ENVBRDF = true; baker_imageFunction2D( ggx_IntegrateBRDF_Function, 256, "output/env_brdf_multiscatter.png" ); baker_imageFunction2D( ggx_EvalGitEnvBRDF, 256, "output/env_brdf_fit.png" ); }
37.830409
215
0.602566
hypernewbie
954d1da60ca9f10554d66e0951ebc7fcfc6c47d8
42,218
cpp
C++
logdevice/common/test/ConfigurationTest.cpp
YangKian/LogDevice
e5c2168c11e9de867a1bcf519f95016e1c879b5c
[ "BSD-3-Clause" ]
1,831
2018-09-12T15:41:52.000Z
2022-01-05T02:38:03.000Z
logdevice/common/test/ConfigurationTest.cpp
YangKian/LogDevice
e5c2168c11e9de867a1bcf519f95016e1c879b5c
[ "BSD-3-Clause" ]
183
2018-09-12T16:14:59.000Z
2021-12-07T15:49:43.000Z
logdevice/common/test/ConfigurationTest.cpp
YangKian/LogDevice
e5c2168c11e9de867a1bcf519f95016e1c879b5c
[ "BSD-3-Clause" ]
228
2018-09-12T15:41:51.000Z
2022-01-05T08:12:09.000Z
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/configuration/Configuration.h" #include <memory> #include <string> #include <arpa/inet.h> #include <folly/FBString.h> #include <folly/dynamic.h> #include <folly/json.h> #include <folly/test/JsonTestUtil.h> #include <gtest/gtest.h> #include <netinet/in.h> #include "logdevice/common/NodeID.h" #include "logdevice/common/Semaphore.h" #include "logdevice/common/configuration/LocalLogsConfig.h" #include "logdevice/common/configuration/ParsingHelpers.h" #include "logdevice/common/configuration/logs/LogsConfigTree.h" #include "logdevice/common/configuration/nodes/utils.h" #include "logdevice/common/debug.h" #include "logdevice/common/test/TestUtil.h" #include "logdevice/common/types_internal.h" #include "logdevice/include/Err.h" #include "logdevice/include/types.h" // NOTE: file reading assumes the test is being run from the top-level fbcode // dir using facebook::logdevice::AuthenticationType; using facebook::logdevice::ConfigParserOptions; using facebook::logdevice::Configuration; using facebook::logdevice::E; using facebook::logdevice::err; using facebook::logdevice::LOGID_INVALID; using facebook::logdevice::logid_range_t; using facebook::logdevice::logid_t; using facebook::logdevice::node_index_t; using facebook::logdevice::NodeID; using facebook::logdevice::NodeLocation; using facebook::logdevice::NodeLocationScope; using facebook::logdevice::PermissionCheckerType; using facebook::logdevice::Semaphore; using facebook::logdevice::Sockaddr; using facebook::logdevice::Status; using facebook::logdevice::configuration::SecurityConfig; using namespace facebook::logdevice::configuration; using namespace facebook::logdevice; /** * Reads configs/sample_valid.conf and asserts some basic stuff. */ TEST(ConfigurationTest, SimpleValid) { std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("sample_valid.conf"))); ASSERT_NE(config, nullptr); ASSERT_EQ( true, (bool)std::dynamic_pointer_cast<LocalLogsConfig>(config->logsConfig())); ASSERT_TRUE(config->logsConfig()->isLocal()); auto logs_config = config->localLogsConfig(); EXPECT_EQ(nullptr, config->getLogGroupByIDShared(logid_t(7))); EXPECT_FALSE(config->logsConfig()->logExists(logid_t(7))); { Semaphore sem; LogsConfig::LogGroupNodePtr async_log_cfg; config->getLogGroupByIDAsync( logid_t(7), [&](const LogsConfig::LogGroupNodePtr log) { async_log_cfg = log; sem.post(); }); sem.wait(); EXPECT_EQ(nullptr, async_log_cfg); } const auto log = config->getLogGroupByIDShared(logid_t(3)); EXPECT_TRUE(log); auto log_shared = config->getLogGroupByIDShared(logid_t(3)); ASSERT_NE(log, nullptr); ASSERT_NE(log_shared, nullptr); ASSERT_TRUE(*log == *log_shared); ASSERT_TRUE(config->logsConfig()->logExists(logid_t(3))); { Semaphore sem; LogsConfig::LogGroupNodePtr async_log_cfg; config->getLogGroupByIDAsync( logid_t(3), [&](const LogsConfig::LogGroupNodePtr clog) { async_log_cfg = clog; sem.post(); }); sem.wait(); EXPECT_TRUE(*log == *async_log_cfg); } EXPECT_EQ(3, log->attrs().replicationFactor().value()); EXPECT_EQ(10, log->attrs().maxWritesInFlight().value()); EXPECT_TRUE(log->attrs().singleWriter().value()); EXPECT_EQ( NodeLocationScope::REGION, log->attrs().syncReplicationScope().value()); // all fields in the config should be recognized. ASSERT_FALSE(log->attrs().extras().hasValue()); auto check_log = [&](logid_t::raw_type log, const logsconfig::LogGroupInDirectory& gid_log) { const Configuration::LogAttributes& log_attrs = gid_log.log_group->attrs(); EXPECT_FALSE(log_attrs.backlogDuration().value().has_value()); EXPECT_EQ(log >= 11, log_attrs.replicateAcross().hasValue()); if (log >= 8 && log <= 10) { EXPECT_EQ(3, log_attrs.replicationFactor()); EXPECT_EQ(0, log_attrs.syncedCopies()); EXPECT_EQ(10, log_attrs.maxWritesInFlight()); } if (log != 3) { ASSERT_FALSE(log_attrs.syncReplicationScope().hasValue()); } }; { const int NLOGS = 9; logid_t::raw_type logids[NLOGS] = {1, 2, 3, 8, 9, 10, 11, 12, 13}; int i = 0; for (auto it = logs_config->logsBegin(); it != logs_config->logsEnd(); ++it) { ASSERT_LT(i, NLOGS); EXPECT_EQ(it->first, logids[i]); check_log(logids[i], it->second); i++; } ASSERT_EQ(i, NLOGS); i = NLOGS - 1; for (auto it = logs_config->logsRBegin(); it != logs_config->logsREnd(); ++it) { EXPECT_EQ(it->first, logids[i]); check_log(logids[i], it->second); --i; } ASSERT_EQ(i, -1); } { auto log = logs_config->getLogGroup("/with_replicate_across1"); EXPECT_EQ(2, log->attrs().replicationFactor().value()); EXPECT_FALSE(log->attrs().syncReplicationScope().hasValue()); EXPECT_EQ(Configuration::LogAttributes::ScopeReplicationFactors( {{NodeLocationScope::NODE, 2}}), log->attrs().replicateAcross().value()); EXPECT_EQ(ReplicationProperty({{NodeLocationScope::NODE, 2}}).toString(), ReplicationProperty::fromLogAttributes(log->attrs()).toString()); } { auto log = logs_config->getLogGroup("/with_replicate_across2"); EXPECT_EQ(4, log->attrs().replicationFactor().value()); EXPECT_FALSE(log->attrs().syncReplicationScope().hasValue()); EXPECT_EQ(Configuration::LogAttributes::ScopeReplicationFactors( {{NodeLocationScope::RACK, 3}}), log->attrs().replicateAcross().value()); EXPECT_EQ(ReplicationProperty( {{NodeLocationScope::NODE, 4}, {NodeLocationScope::RACK, 3}}) .toString(), ReplicationProperty::fromLogAttributes(log->attrs()).toString()); } { auto log = logs_config->getLogGroup("/with_replicate_across3"); EXPECT_FALSE(log->attrs().replicationFactor().hasValue()); EXPECT_FALSE(log->attrs().syncReplicationScope().hasValue()); EXPECT_EQ( Configuration::LogAttributes::ScopeReplicationFactors( {{NodeLocationScope::REGION, 2}, {NodeLocationScope::RACK, 3}}), log->attrs().replicateAcross().value()); EXPECT_EQ(ReplicationProperty({{NodeLocationScope::REGION, 2}, {NodeLocationScope::RACK, 3}}) .toString(), ReplicationProperty::fromLogAttributes(log->attrs()).toString()); } { const auto meta_nodeset = config->serverConfig()->getMetaDataNodeIndices(); const LogsConfig::LogAttributes& meta_attrs = config->serverConfig()->getMetaDataLogGroup()->attrs(); const std::vector<node_index_t> expected_nodeset{0, 1, 5}; EXPECT_EQ(expected_nodeset, meta_nodeset); EXPECT_EQ(2, meta_attrs.replicationFactor().value()); EXPECT_EQ(2, meta_attrs.syncedCopies().value()); EXPECT_EQ(2, meta_attrs.maxWritesInFlight().value()); EXPECT_EQ( NodeLocationScope::CLUSTER, meta_attrs.syncReplicationScope().value()); auto& ml_conf = config->serverConfig()->getMetaDataLogsConfig(); EXPECT_TRUE(ml_conf.metadata_version_to_write.has_value()); EXPECT_EQ(1, ml_conf.metadata_version_to_write.value()); EXPECT_EQ(NodeSetSelectorType::SELECT_ALL, ml_conf.nodeset_selector_type); } ASSERT_NE(nullptr, config->zookeeperConfig()); const std::string zookeeper_quorum = config->zookeeperConfig()->getQuorumString(); EXPECT_EQ(zookeeper_quorum, "1.2.3.4:2181,5.6.7.8:2181,9.10.11.12:2181"); const std::chrono::milliseconds zookeeper_timeout = config->zookeeperConfig()->getSessionTimeout(); EXPECT_EQ(zookeeper_timeout, std::chrono::milliseconds(30000)); EXPECT_NE(config->serverConfig()->getCustomFields(), nullptr); EXPECT_EQ(config->serverConfig()->getCustomFields().size(), 1); folly::dynamic fields = folly::dynamic::object("custom_field_for_testing", "custom_value"); EXPECT_EQ(config->serverConfig()->getCustomFields(), fields); auto timestamp = config->serverConfig()->getClusterCreationTime(); EXPECT_TRUE(timestamp.has_value()); EXPECT_EQ(timestamp.value().count(), 1467928224); } /** * Attempts to load configs with overlapping log id ranges must fail * with E::INVALID_CONFIG. */ TEST(ConfigurationTest, OverlappingLogIdRanges) { using facebook::logdevice::E; using facebook::logdevice::err; std::shared_ptr<Configuration> config; config = Configuration::fromJsonFile(TEST_CONFIG_FILE("overlap1.conf")); EXPECT_EQ(config->logsConfig(), nullptr); EXPECT_EQ(err, E::INVALID_CONFIG); config = Configuration::fromJsonFile(TEST_CONFIG_FILE("overlap2.conf")); EXPECT_EQ(config->logsConfig(), nullptr); EXPECT_EQ(err, E::INVALID_CONFIG); config = Configuration::fromJsonFile(TEST_CONFIG_FILE("overlap3.conf")); EXPECT_EQ(config->logsConfig(), nullptr); EXPECT_EQ(err, E::INVALID_CONFIG); } TEST(ConfigurationTest, NoNodesNoMetadata) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("no_nodes_no_metadata.conf"))); ASSERT_NE(config, nullptr); // Assert that serializing the config back doesn't crash. config->toString(); } namespace facebook { namespace logdevice { namespace configuration { namespace parser { extern std::pair<std::string, std::string> parseIpPort(const std::string&); }}}} // namespace facebook::logdevice::configuration::parser /** * Exercises parseIpPort() which is a helper used during configuration * parsing. */ TEST(ConfigurationTest, ParseIpPort) { typedef std::pair<std::string, std::string> strpair; using facebook::logdevice::configuration::parser::parseIpPort; // Basic cases EXPECT_EQ(strpair("127.0.0.1", "12345"), parseIpPort("127.0.0.1:12345")); EXPECT_EQ(strpair("123::abc", "12345"), parseIpPort("[123::abc]:12345")); EXPECT_EQ(strpair("::1", "0"), parseIpPort("[::1]:0")); // unspecified address EXPECT_EQ(strpair("::", "80"), parseIpPort("[::]:80")); // mixed form EXPECT_EQ(strpair("0:0:0:0:0:FFFF:129.144.52.38", "12345"), parseIpPort("[0:0:0:0:0:FFFF:129.144.52.38]:12345")); // Error cases EXPECT_EQ(strpair(), parseIpPort(":8080")); // no ip address EXPECT_EQ(strpair(), parseIpPort("]:8080")); // no ip address EXPECT_EQ(strpair(), parseIpPort("[:8080")); // no ip address EXPECT_EQ(strpair(), parseIpPort("[]:8080")); // no ip address EXPECT_EQ(strpair(), parseIpPort("127.0.0.1")); // no port EXPECT_EQ(strpair(), parseIpPort("127.0.0.1:")); // no port EXPECT_EQ(strpair(), parseIpPort("127.0.0.a:12345")); // illegal ipv4 digit EXPECT_EQ(strpair(), parseIpPort("[127::fffg]:12345")); // illegal ipv6 digit EXPECT_EQ(strpair(), parseIpPort("123::abc:12345")); // need brackets EXPECT_EQ(strpair(), parseIpPort("[123::abc]")); // no port EXPECT_EQ(strpair(), parseIpPort("123.123.0.0]:12345")); // no open bracket EXPECT_EQ(strpair(), parseIpPort("[123::abc:123")); // no closing bracket EXPECT_EQ(strpair(), parseIpPort("[123::abc]:")); // no port } TEST(ConfigurationTest, SockaddrDefaultConstructor) { facebook::logdevice::Sockaddr addr; ASSERT_FALSE(addr.valid()); ASSERT_EQ("INVALID", addr.toString()); ASSERT_FALSE(facebook::logdevice::Sockaddr::INVALID.valid()); } TEST(ConfigurationTest, NamedRanges) { std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("sample_valid.conf"))); ASSERT_NE(nullptr, config); std::pair<logid_t, logid_t> foo_range = config->logsConfig()->getLogRangeByName("foo"); EXPECT_EQ(foo_range.first, logid_t(8)); EXPECT_EQ(foo_range.second, logid_t(10)); std::pair<logid_t, logid_t> bar_range = config->logsConfig()->getLogRangeByName("bar"); EXPECT_EQ(bar_range.first, LOGID_INVALID); EXPECT_EQ(bar_range.second, LOGID_INVALID); Semaphore sem; Status st; std::pair<logid_t, logid_t> foo_range2; config->logsConfig()->getLogRangeByNameAsync( "foo", [&](Status err, decltype(foo_range2) r) { foo_range2 = r; st = err; sem.post(); }); sem.wait(); EXPECT_EQ(E::OK, st); EXPECT_EQ(foo_range, foo_range2); std::pair<logid_t, logid_t> no_range; config->logsConfig()->getLogRangeByNameAsync( "does_not_exist", [&](Status err, decltype(no_range) r) { no_range = r; st = err; sem.post(); }); sem.wait(); EXPECT_EQ(E::NOTFOUND, st); EXPECT_EQ(std::make_pair(logid_t(0), logid_t(0)), no_range); } TEST(ConfigurationTest, DuplicateRangeNames) { using facebook::logdevice::E; using facebook::logdevice::err; std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("dupname.conf"))); ASSERT_EQ(nullptr, config->logsConfig()); EXPECT_EQ(err, E::INVALID_CONFIG); } TEST(ConfigurationTest, NegativeReplicationFactor) { using namespace facebook::logdevice; std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("negative_replication.conf"))); ASSERT_EQ(nullptr, config->logsConfig()); EXPECT_EQ(err, E::INVALID_CONFIG); } TEST(ConfigurationTest, ReplicationFactorTooBig) { using namespace facebook::logdevice; std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("replication_too_big.conf"))); ASSERT_EQ(nullptr, config->logsConfig()); EXPECT_EQ(err, E::INVALID_CONFIG); } TEST(ConfigurationTest, DupMetaNodes) { using namespace facebook::logdevice; std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("dup_metanodes.conf"))); ASSERT_EQ(nullptr, config); EXPECT_EQ(err, E::INVALID_CONFIG); } TEST(ConfigurationTest, Defaults) { using namespace facebook::logdevice; std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("defaults.conf"))); ASSERT_NE(nullptr, config); LogsConfig::LogGroupNodePtr log; log = config->getLogGroupByIDShared(logid_t(1)); ASSERT_NE(nullptr, log); const auto& attrs = log->attrs(); ASSERT_TRUE(config->logsConfig()->logExists(logid_t(1))); EXPECT_EQ(2, *attrs.replicationFactor()); EXPECT_EQ(0, *attrs.syncedCopies()); EXPECT_EQ(1000, *attrs.maxWritesInFlight()); EXPECT_EQ(0, *attrs.singleWriter()); EXPECT_EQ(NodeLocationScope::RACK, *attrs.syncReplicationScope()); EXPECT_FALSE(attrs.backlogDuration().value().has_value()); EXPECT_EQ(3, *attrs.nodeSetSize()); EXPECT_EQ(std::chrono::milliseconds(10), *attrs.deliveryLatency()); EXPECT_TRUE(*attrs.scdEnabled()); auto range = config->logsConfig()->getLogRangeByName("weirdo"); EXPECT_EQ(91, range.first.val_); EXPECT_EQ(9911, range.second.val_); log = config->getLogGroupByIDShared(logid_t(2)); const auto& attrs2 = log->attrs(); EXPECT_TRUE(attrs2.backlogDuration().value().has_value()); EXPECT_EQ(std::chrono::seconds(3600 * 24 * 4), attrs2.backlogDuration().value().value()); log = config->getLogGroupByIDShared(logid_t(500)); const auto& attrs3 = log->attrs(); EXPECT_EQ(3, *attrs3.replicationFactor()); EXPECT_EQ(0, *attrs3.syncedCopies()); EXPECT_EQ(1001, *attrs3.maxWritesInFlight()); EXPECT_TRUE(*attrs3.singleWriter()); EXPECT_EQ(std::chrono::seconds(3600 * 24 * 5), *attrs3.backlogDuration()); EXPECT_EQ(4, *attrs3.nodeSetSize()); EXPECT_EQ(std::chrono::milliseconds(11), *attrs3.deliveryLatency()); EXPECT_EQ(1, *attrs3.scdEnabled()); EXPECT_NE(config->serverConfig()->getCustomFields(), nullptr); EXPECT_EQ(config->serverConfig()->getCustomFields().size(), 0); auto timestamp = config->serverConfig()->getClusterCreationTime(); EXPECT_FALSE(timestamp.has_value()); } TEST(ConfigurationTest, BadID) { using namespace facebook::logdevice; std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("bad_id.conf"))); ASSERT_EQ(nullptr, config->logsConfig()); EXPECT_EQ(err, E::INVALID_CONFIG); } TEST(ConfigurationTest, Serialization) { std::string read_str = parser::readFileIntoString(TEST_CONFIG_FILE("serialization_test.conf")); std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("serialization_test.conf"))); auto serialized_str = config->toString(); FOLLY_EXPECT_JSON_EQ(read_str, serialized_str); } /** * Checks that logs with a hierarchical namespace structure work */ TEST(ConfigurationTest, LogsWithNamespaces) { std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("namespaced_logs.conf"))); LogsConfig::NamespaceRangeLookupMap ranges; LogsConfig::NamespaceRangeLookupMap sub_ranges; ASSERT_NE(nullptr, config); auto range = config->logsConfig()->getLogRangeByName("ns1/sublog1"); ASSERT_EQ(1, range.first.val_); ASSERT_EQ(1, range.second.val_); auto log = config->getLogGroupInDirectoryByIDRaw(range.first); ASSERT_EQ(2, log->log_group->attrs().replicationFactor().value()); ranges[log->getFullyQualifiedName()] = range; range = config->logsConfig()->getLogRangeByName("ns1/ns2/subsublog1"); ASSERT_EQ(2, range.first.val_); ASSERT_EQ(3, range.second.val_); log = config->getLogGroupInDirectoryByIDRaw(range.first); ASSERT_EQ(3, log->log_group->attrs().replicationFactor().value()); ranges[log->getFullyQualifiedName()] = range; sub_ranges[log->getFullyQualifiedName()] = range; range = config->logsConfig()->getLogRangeByName("ns1/ns2/subsublog2"); ASSERT_EQ(4, range.first.val_); ASSERT_EQ(4, range.second.val_); log = config->getLogGroupInDirectoryByIDRaw(range.first); ASSERT_EQ(1, log->log_group->attrs().replicationFactor().value()); ranges[log->getFullyQualifiedName()] = range; sub_ranges[log->getFullyQualifiedName()] = range; range = config->logsConfig()->getLogRangeByName("log1"); ASSERT_EQ(95, range.first.val_); ASSERT_EQ(100, range.second.val_); log = config->getLogGroupInDirectoryByIDRaw(range.first); ASSERT_EQ(1, log->log_group->attrs().replicationFactor().value()); ranges[log->getFullyQualifiedName()] = range; range = config->logsConfig()->getLogRangeByName("log2"); ASSERT_EQ(101, range.first.val_); ASSERT_EQ(101, range.second.val_); log = config->getLogGroupInDirectoryByIDRaw(range.first); ASSERT_EQ(1, log->log_group->attrs().replicationFactor().value()); ranges[log->getFullyQualifiedName()] = range; // supposed to fetch all named logs auto fetched_ranges = config->logsConfig()->getLogRangesByNamespace(""); ASSERT_EQ(5, fetched_ranges.size()); ASSERT_EQ(ranges, fetched_ranges); Semaphore sem; Status st; config->logsConfig()->getLogRangesByNamespaceAsync( "", [&](Status err, decltype(ranges) r) { st = err; fetched_ranges = r; sem.post(); }); sem.wait(); ASSERT_EQ(ranges, fetched_ranges); ASSERT_EQ(E::OK, st); config->logsConfig()->getLogRangesByNamespaceAsync( "does_not_exist", [&](Status err, decltype(ranges) r) { st = err; fetched_ranges = r; sem.post(); }); sem.wait(); ASSERT_TRUE(fetched_ranges.empty()); ASSERT_EQ(E::NOTFOUND, st); EXPECT_NE(config->serverConfig()->getCustomFields(), nullptr); EXPECT_EQ(config->serverConfig()->getCustomFields().size(), 0); auto timestamp = config->serverConfig()->getClusterCreationTime(); EXPECT_FALSE(timestamp.has_value()); } /** * Checks that custom fields specified in log group config are read correctly */ TEST(ConfigurationTest, CustomFields) { using namespace facebook::logdevice; std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("custom_fields.conf"))); ASSERT_NE(nullptr, config); auto log = config->getLogGroupByIDShared(logid_t(1)); ASSERT_NE(nullptr, log); ASSERT_EQ(1, log->attrs().extras().value().size()); ASSERT_EQ("custom_value", log->attrs().extras().value().at("custom_key")); log = config->getLogGroupByIDShared(logid_t(2)); ASSERT_NE(nullptr, log); ASSERT_EQ(1, log->attrs().extras().value().size()); ASSERT_EQ("default_value", log->attrs().extras().value().at("custom_key")); EXPECT_NE(config->serverConfig()->getCustomFields(), nullptr); EXPECT_EQ(config->serverConfig()->getCustomFields().size(), 4); folly::dynamic customFields = folly::dynamic::object( "custom_field_test1", "custom_value1")( "custom_field_test2", "custom_value2")("custom_field_test3", 123)( "custom_field_test4", folly::dynamic::array("value_at_0", "value_at_1")); EXPECT_EQ(config->serverConfig()->getCustomFields(), customFields); auto timestamp = config->serverConfig()->getClusterCreationTime(); EXPECT_FALSE(timestamp.has_value()); } template <typename T> void test_wrapped_attribute( const logsconfig::Attribute<folly::Optional<T>>& val_a, const logsconfig::Attribute<folly::Optional<T>>& val_b) { ASSERT_EQ(val_a.hasValue(), val_b.hasValue()); if (val_a.hasValue()) { ASSERT_EQ(val_a.value().hasValue(), val_b.value().hasValue()); if (val_a.value().hasValue()) { ASSERT_EQ(*val_a.value(), *val_b.value()); } } } TEST(ConfigurationTest, LogsConfigSerialization) { using namespace facebook::logdevice; std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("defaults.conf"))); ASSERT_NE(nullptr, config); const LogsConfig::LogGroupInDirectory* log; log = config->getLogGroupInDirectoryByIDRaw(logid_t(1)); ASSERT_NE(nullptr, log); EXPECT_EQ(true, log->log_group->attrs().scdEnabled().value()); std::string json = log->toJson(); std::cout << json << std::endl; auto parsed = LogsConfig::LogGroupNode::createFromJson(json, "/"); ASSERT_NE(parsed, nullptr); // Following are always present ASSERT_EQ(std::make_pair(logid_t(1), logid_t(1)), parsed->range()); ASSERT_EQ(log->log_group->name(), parsed->name()); ASSERT_EQ(*log->log_group->attrs().replicationFactor(), *parsed->attrs().replicationFactor()); ASSERT_EQ( *log->log_group->attrs().syncedCopies(), *parsed->attrs().syncedCopies()); // Optional ones + double optional wrapping (to be fixed in T16481409) ASSERT_EQ(*log->log_group->attrs().maxWritesInFlight(), *parsed->attrs().maxWritesInFlight()); ASSERT_EQ( *log->log_group->attrs().singleWriter(), *parsed->attrs().singleWriter()); ASSERT_EQ( *log->log_group->attrs().scdEnabled(), *parsed->attrs().scdEnabled()); ASSERT_EQ(*log->log_group->attrs().shadow(), *parsed->attrs().shadow()); // Attributes which can be optional/null test_wrapped_attribute( log->log_group->attrs().backlogDuration(), parsed->attrs().backlogDuration()); /* test_wrapped_attribute(log->log_group->attrs().nodeSetSize(), parsed->attrs().nodeSetSize()); test_wrapped_attribute(log->log_group->attrs().deliveryLatency(), parsed->attrs().deliveryLatency()); test_wrapped_attribute(log->log_group->attrs().writeToken(), parsed->attrs().writeToken()); test_wrapped_attribute(log->log_group->attrs().sequencerAffinity(), parsed->attrs().sequencerAffinity());*/ } /** * Tests that parsing a valid config with security_info and permissions set */ TEST(ConfigurationTest, SecurityAndPermissionInfo) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("security_and_permission_info.conf"))); ASSERT_NE(nullptr, config); // check that all security_information fields are set correctly ASSERT_TRUE(config->serverConfig()->allowUnauthenticated()); ASSERT_EQ(AuthenticationType::SELF_IDENTIFICATION, config->serverConfig()->getAuthenticationType()); ASSERT_EQ(PermissionCheckerType::CONFIG, config->serverConfig()->getPermissionCheckerType()); ASSERT_EQ( true, config->serverConfig()->getSecurityConfig().aclCacheEnabled()); ASSERT_EQ(100, config->serverConfig()->getSecurityConfig().aclCacheMaxSize); ASSERT_EQ(std::chrono::seconds(120), config->serverConfig()->getSecurityConfig().aclCacheTtl); ASSERT_TRUE(config->logsConfig()->logExists(logid_t(1))); const auto log = config->getLogGroupByIDShared(logid_t(1)); ASSERT_NE(nullptr, log); const auto& permissions = log->attrs().permissions().value(); ASSERT_EQ(4, permissions.size()); // Check that custom permissions are intact auto it = permissions.find("allPass"); ASSERT_TRUE(it != permissions.end()); ASSERT_TRUE(it->second[0]); ASSERT_TRUE(it->second[1]); ASSERT_TRUE(it->second[2]); it = permissions.find("appendFail"); ASSERT_TRUE(it != permissions.end()); ASSERT_FALSE(it->second[0]); ASSERT_TRUE(it->second[1]); ASSERT_TRUE(it->second[2]); it = permissions.find("readFail"); ASSERT_TRUE(it != permissions.end()); ASSERT_TRUE(it->second[0]); ASSERT_FALSE(it->second[1]); ASSERT_TRUE(it->second[2]); it = permissions.find("trimFail"); ASSERT_TRUE(it != permissions.end()); ASSERT_TRUE(it->second[0]); ASSERT_TRUE(it->second[1]); ASSERT_FALSE(it->second[2]); // check that the default permissions are overwritten it = permissions.find("GlobalDefault"); ASSERT_TRUE(it == permissions.end()); it = permissions.find("unauthenticated"); ASSERT_TRUE(it == permissions.end()); // check that for logs that did not set any permissions, default permissions // propergate to them ASSERT_TRUE(config->logsConfig()->logExists(logid_t(11))); const auto log2 = config->getLogGroupByIDShared(logid_t(11)); ASSERT_NE(nullptr, log2); const auto& permissions2 = log2->attrs().permissions().value(); it = permissions2.find("GlobalDefault"); ASSERT_TRUE(it != permissions2.end()); ASSERT_EQ(2, permissions2.size()); ASSERT_TRUE(it->second[0]); ASSERT_FALSE(it->second[1]); ASSERT_FALSE(it->second[2]); it = permissions2.find("default"); ASSERT_TRUE(it != permissions2.end()); ASSERT_FALSE(it->second[0]); ASSERT_TRUE(it->second[1]); ASSERT_FALSE(it->second[2]); // check that admin list is parsed properly SecurityConfig securityConf = config->serverConfig()->getSecurityConfig(); auto admins = securityConf.admins; ASSERT_FALSE(admins.empty()); ASSERT_EQ(3, admins.size()); auto iter = admins.find("user1"); ASSERT_NE(iter, admins.end()); iter = admins.find("user2"); ASSERT_NE(iter, admins.end()); iter = admins.find("user3"); ASSERT_NE(iter, admins.end()); EXPECT_NE(config->serverConfig()->getCustomFields(), nullptr); EXPECT_EQ(config->serverConfig()->getCustomFields().size(), 0); auto timestamp = config->serverConfig()->getClusterCreationTime(); EXPECT_FALSE(timestamp.has_value()); } /** * Tests that permissions propagate properly with Namespaces */ TEST(ConfigurationTest, NamespacedConfigWithPermissions) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("namespaced_logs_with_permissions.conf"))); ASSERT_NE(nullptr, config); // check that all security_information fields are set correctly ASSERT_TRUE(config->serverConfig()->allowUnauthenticated()); ASSERT_EQ(AuthenticationType::SELF_IDENTIFICATION, config->serverConfig()->getAuthenticationType()); ASSERT_EQ(PermissionCheckerType::CONFIG, config->serverConfig()->getPermissionCheckerType()); LogsConfig::NamespaceRangeLookupMap ranges; LogsConfig::NamespaceRangeLookupMap sub_ranges; ASSERT_NE(nullptr, config); auto range = config->logsConfig()->getLogRangeByName("ns1/sublog1"); ASSERT_EQ(1, range.first.val_); ASSERT_EQ(1, range.second.val_); // check that ns1 still has GlobalDefault permissions auto log = config->getLogGroupByIDShared(range.first); auto it = (*log->attrs().permissions()).find("GlobalDefault"); ASSERT_TRUE(it != (*log->attrs().permissions()).end()); ASSERT_EQ(1, (*log->attrs().permissions()).size()); ASSERT_TRUE(it->second[0]); ASSERT_FALSE(it->second[1]); ASSERT_FALSE(it->second[2]); // check that ns2 has overwritten the GlobalDefault with a sub default range = config->logsConfig()->getLogRangeByName("ns1/ns2/subsublog1"); ASSERT_EQ(2, range.first.val_); ASSERT_EQ(3, range.second.val_); log = config->getLogGroupByIDShared(range.first); it = (*log->attrs().permissions()).find("ns2Default"); ASSERT_TRUE(it != (*log->attrs().permissions()).end()); ASSERT_EQ(1, (*log->attrs().permissions()).size()); ASSERT_FALSE(it->second[0]); ASSERT_FALSE(it->second[1]); ASSERT_TRUE(it->second[2]); // check that subsublog2 has overwritten all defaults range = config->logsConfig()->getLogRangeByName("ns1/ns2/subsublog2"); ASSERT_EQ(4, range.first.val_); ASSERT_EQ(4, range.second.val_); log = config->getLogGroupByIDShared(range.first); it = (*log->attrs().permissions()).find("log4"); ASSERT_TRUE(it != (*log->attrs().permissions()).end()); ASSERT_EQ(1, (*log->attrs().permissions()).size()); ASSERT_TRUE(it->second[0]); ASSERT_FALSE(it->second[1]); ASSERT_TRUE(it->second[2]); // Check that log 1 is unaffected by other namespaces range = config->logsConfig()->getLogRangeByName("log1"); ASSERT_EQ(95, range.first.val_); ASSERT_EQ(100, range.second.val_); log = config->getLogGroupByIDShared(range.first); it = (*log->attrs().permissions()).find("GlobalDefault"); ASSERT_TRUE(it != (*log->attrs().permissions()).end()); ASSERT_EQ(1, (*log->attrs().permissions()).size()); ASSERT_TRUE(it->second[0]); ASSERT_FALSE(it->second[1]); ASSERT_FALSE(it->second[2]); // check that log3 can overwrite global defaults range = config->logsConfig()->getLogRangeByName("log3"); ASSERT_EQ(101, range.first.val_); ASSERT_EQ(101, range.second.val_); log = config->getLogGroupByIDShared(range.first); it = (*log->attrs().permissions()).find("user101"); ASSERT_TRUE(it != (*log->attrs().permissions()).end()); ASSERT_EQ(1, (*log->attrs().permissions()).size()); ASSERT_TRUE(it->second[0]); ASSERT_TRUE(it->second[1]); ASSERT_TRUE(it->second[2]); } /** * Test that the config will fail to parse if "authentication_type" is missing * when from security_information */ TEST(ConfigurationTest, MissingAuthenticatorType) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("missing_auth_type_info.conf"))); ASSERT_EQ(nullptr, config); } /** * Checks that if the config contains a permission_checker_type that is * not defined in the parser, then the config is not created */ TEST(ConfigurationTest, MissingPermissionChckerType) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("invalid_permission_checker_type.conf"))); ASSERT_EQ(nullptr, config); } /** * Checks that if the config contains a authentication_type that is * not defined in the parser, then the config is not created */ TEST(ConfigurationTest, MissingAuthenticationChckerType) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("invalid_authenticator_type.conf"))); ASSERT_EQ(nullptr, config); } /** * Check that if the "permissions" field is included in the defaults section of * the config file and permission_checker_type is not set to "config" then * the Configuration object will not be created. */ TEST(ConfigurationTest, InvalidUseOfPermissionDefault) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("invalid_use_of_permission1.conf"))); ASSERT_EQ(nullptr, config->logsConfig()); } /** * Checks that if the "permissions" field is included in the logs section of the * config file, and the permission_checker_type is not set to "config" then * the Configuration object is not created. */ TEST(ConfigurationTest, InvalidUseOfPermissionLog) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("invalid_use_of_permission2.conf"))); ASSERT_EQ(nullptr, config->logsConfig()); } /** * Checks if there is an action that is not "READ", "APPEND" or "TRIM" * in the permission list, it fails to parse */ TEST(ConfigurationTest, InvalidActionInPermissions) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("config_permission_invalid_action.conf"))); ASSERT_EQ(nullptr, config->logsConfig()); } /** * A user log is within the internal range. */ TEST(ConfigurationTest, UserLogWithinInternalRange) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("user_log_within_internal_range.conf"))); ASSERT_EQ(nullptr, config->logsConfig()); } /** * An internal log is configured with a backlog duration, which is incorrect. */ TEST(ConfigurationTest, InternalLogIncorrectWithBacklog) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("internal_logs_incorrect_backlog.conf"))); ASSERT_EQ(nullptr, config); } TEST(ConfigurationTest, InternalLogCorrect) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("internal_logs_correct.conf"))); ASSERT_NE(nullptr, config); ASSERT_NE(nullptr, config->serverConfig()); } TEST(ConfigurationTest, DefaultDscp) { std::shared_ptr<Configuration> config( Configuration::fromJsonFile(TEST_CONFIG_FILE("dscp_default.conf"))); ASSERT_NE(nullptr, config); ASSERT_NE(nullptr, config->serverConfig()); const std::string server_default_dscp = config->serverConfig() ->getServerSettingsConfig() .find("server-default-dscp") ->second; EXPECT_STREQ("34", server_default_dscp.c_str()); const std::string client_default_dscp = config->serverConfig() ->getClientSettingsConfig() .find("client-default-dscp") ->second; EXPECT_STREQ("45", client_default_dscp.c_str()); } TEST(ConfigurationTest, MetaDataLogsConfig) { auto get_config = [](std::string metadata_log_fields) -> std::unique_ptr<Configuration> { ld_info("Generating config with metadata log fields: %s", metadata_log_fields.c_str()); std::string conf_str = R"( { "cluster": "test_cluster", "nodes": [)"; // Nodes config with 4 nodes. for (int i = 0; i < 4; ++i) { if (i) { conf_str += ","; } conf_str += R"( { "node_id": )" + std::to_string(i) + R"(, "name": "server-)" + std::to_string(i) + R"(", "location": "reg)" + std::to_string(i) + R"(.x.y.z.w", "host": "127.0.0.1:)" + std::to_string(4444 + i) + R"(", "generation": 1, "roles": [ "sequencer", "storage" ], "sequencer": true, "weight": 1, "num_shards": 2 })"; } conf_str += R"( ], "logs": [], "metadata_logs": { "nodeset": [0, 1, 2, 3], "replication_factor": 4 )"; if (!metadata_log_fields.empty()) { conf_str += ", " + metadata_log_fields; } conf_str += R"( }, })"; auto config_from_json_str = [](const std::string& str) { auto json = parser::parseJson(str); // Make sure the parsed string is actually an object ld_check(json.isObject()); return Configuration::fromJson(json, nullptr, ConfigParserOptions()); }; auto config = config_from_json_str(conf_str); if (!config) { return nullptr; } // Re-serializing and de-serializing the config again to verify that // serialization writes all the fields we have written std::string serialized_str = config->toString(); auto config2 = config_from_json_str(serialized_str); ld_check(config2); ld_check(config2->serverConfig()); return config2; }; { auto cfg = get_config(""); ASSERT_NE(cfg, nullptr); auto& ml_config = cfg->serverConfig()->getMetaDataLogsConfig(); ASSERT_FALSE(ml_config.metadata_version_to_write.has_value()); EXPECT_EQ(NodeSetSelectorType::CONSISTENT_HASHING, ml_config.nodeset_selector_type); ASSERT_EQ(epoch_metadata_version::CURRENT, epoch_metadata_version::versionToWrite(cfg->serverConfig())); } { auto cfg = get_config("\"metadata_version\": 1"); ASSERT_NE(cfg, nullptr); auto& ml_config = cfg->serverConfig()->getMetaDataLogsConfig(); ASSERT_TRUE(ml_config.metadata_version_to_write.has_value()); ASSERT_EQ(1, ml_config.metadata_version_to_write.value()); ASSERT_EQ(1, epoch_metadata_version::versionToWrite(cfg->serverConfig())); EXPECT_EQ(NodeSetSelectorType::CONSISTENT_HASHING, ml_config.nodeset_selector_type); } { auto cfg = get_config("\"nodeset_selector\": \"random-crossdomain\""); ASSERT_NE(cfg, nullptr); auto& ml_config = cfg->serverConfig()->getMetaDataLogsConfig(); ASSERT_FALSE(ml_config.metadata_version_to_write.has_value()); ASSERT_EQ(epoch_metadata_version::CURRENT, epoch_metadata_version::versionToWrite(cfg->serverConfig())); EXPECT_EQ(NodeSetSelectorType::RANDOM_CROSSDOMAIN, ml_config.nodeset_selector_type); } { auto cfg = get_config("\"nodeset_selector\": \"random\""); ASSERT_NE(cfg, nullptr); auto& ml_config = cfg->serverConfig()->getMetaDataLogsConfig(); ASSERT_FALSE(ml_config.metadata_version_to_write.has_value()); ASSERT_EQ(epoch_metadata_version::CURRENT, epoch_metadata_version::versionToWrite(cfg->serverConfig())); EXPECT_EQ(NodeSetSelectorType::RANDOM, ml_config.nodeset_selector_type); } { auto cfg = get_config("\"nodeset_selector\": \"select-all\""); ASSERT_NE(cfg, nullptr); auto& ml_config = cfg->serverConfig()->getMetaDataLogsConfig(); ASSERT_FALSE(ml_config.metadata_version_to_write.has_value()); ASSERT_EQ(epoch_metadata_version::CURRENT, epoch_metadata_version::versionToWrite(cfg->serverConfig())); EXPECT_EQ(NodeSetSelectorType::SELECT_ALL, ml_config.nodeset_selector_type); } { auto cfg = get_config("\"sync_replicate_across\": \"region\""); ASSERT_NE(cfg, nullptr); auto& ml_config = cfg->serverConfig()->getMetaDataLogsConfig(); ASSERT_EQ( NodeLocationScope::REGION, ml_config.metadata_log_group->attrs().syncReplicationScope().value()); ASSERT_EQ( NodeLocationScope::REGION, ml_config.metadata_log_group->attrs().syncReplicationScope().value()); } { auto cfg = get_config(R"("replicate_across": {"rack": 4, "region": 3})"); ASSERT_NE(cfg, nullptr); auto& ml_config = cfg->serverConfig()->getMetaDataLogsConfig(); ASSERT_FALSE(ml_config.metadata_log_group->attrs() .syncReplicationScope() .hasValue()); ASSERT_FALSE(ml_config.metadata_log_group->attrs() .syncReplicationScope() .hasValue()); ASSERT_EQ( Configuration::LogAttributes::ScopeReplicationFactors( {{NodeLocationScope::REGION, 3}, {NodeLocationScope::RACK, 4}}), ml_config.metadata_log_group->attrs().replicateAcross().value()); ASSERT_EQ(ReplicationProperty({{NodeLocationScope::REGION, 3}, {NodeLocationScope::RACK, 4}}) .toString(), ReplicationProperty::fromLogAttributes( ml_config.metadata_log_group->attrs()) .toString()); ASSERT_EQ(ReplicationProperty({{NodeLocationScope::REGION, 3}, {NodeLocationScope::RACK, 4}}) .toString(), ReplicationProperty::fromLogAttributes( ml_config.metadata_log_group->attrs()) .toString()); } { std::vector<std::string> invalid_params = { "\"metadata_version\": " + std::to_string(epoch_metadata_version::CURRENT + 1), "\"metadata_version\": 0", "\"metadata_version\": -1", "\"metadata_version\": \"2\"", "\"metadata_version\": \"abc\"", "\"nodeset_selector\": \"abc\"", "\"nodeset_selector\": 2", }; for (auto& params : invalid_params) { err = E::OK; auto cfg = get_config(params); ASSERT_EQ(nullptr, cfg); ASSERT_EQ(E::INVALID_CONFIG, err); } } } TEST(ConfigurationTest, ACLS) { std::shared_ptr<Configuration> config(Configuration::fromJsonFile( TEST_CONFIG_FILE("conf_permission_acl_test.conf"))); ASSERT_NE(nullptr, config); const auto log = config->getLogGroupByIDShared(logid_t(1)); ASSERT_NE(log, nullptr); const Configuration::LogAttributes& log_attrs = log->attrs(); EXPECT_EQ( Configuration::LogAttributes::ACLList({"SOME_CATEGORY.TestSomeACL"}), log_attrs.acls()); EXPECT_EQ(Configuration::LogAttributes::ACLList( {"SOME_CATEGORY.TestSomeACLShadow"}), log_attrs.aclsShadow()); } // Tests valid and invalid SequencerAffinity strings TEST(ConfigurationTest, SequencerAffinity) { using facebook::logdevice::E; using facebook::logdevice::err; std::shared_ptr<Configuration> config = Configuration::fromJsonFile( TEST_CONFIG_FILE("sequencer_affinity_2nodes.conf")); ASSERT_NE(config, nullptr); const auto log = config->getLogGroupByIDShared(logid_t(1)); ASSERT_NE(log, nullptr); const Configuration::LogAttributes& log_attrs = log->attrs(); ASSERT_TRUE(log_attrs.sequencerAffinity().hasValue()); EXPECT_EQ(log_attrs.sequencerAffinity().value(), "rgn1...."); // Sequencer affinity attribute does not have the proper format. See // NodeLocation::fromDomainString for valid formats. config = Configuration::fromJsonFile( TEST_CONFIG_FILE("invalid_sequencer_affinity.conf")); EXPECT_EQ(config->logsConfig(), nullptr); EXPECT_EQ(err, E::INVALID_CONFIG); }
37.196476
80
0.693496
YangKian
954e526da1a6c3d75dd2a3ef48d0c3b6a63fd761
2,526
cpp
C++
case-studies/PoDoFo/podofo/tools/podofouncompress/podofouncompress.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
30
2018-03-05T17:35:29.000Z
2022-03-17T18:59:34.000Z
podofo-0.9.6/tools/podofouncompress/podofouncompress.cpp
zia95/pdf-toolkit-console-
369d73f66f7d4c74a252e83d200acbb792a6b8d5
[ "MIT" ]
2
2016-05-26T04:47:13.000Z
2019-02-15T05:17:43.000Z
podofo-0.9.6/tools/podofouncompress/podofouncompress.cpp
zia95/pdf-toolkit-console-
369d73f66f7d4c74a252e83d200acbb792a6b8d5
[ "MIT" ]
5
2019-02-15T05:09:22.000Z
2021-04-14T12:10:16.000Z
/*************************************************************************** * Copyright (C) 2005 by Dominik Seichter * * domseichter@web.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "Uncompress.h" #include <podofo.h> #include <stdlib.h> #include <cstdio> using namespace PoDoFo; #ifdef _HAVE_CONFIG #include <config.h> #endif // _HAVE_CONFIG void print_help() { printf("Usage: podofouncompress [inputfile] [outputfile]\n\n"); printf(" This tool removes all compression from the PDF file.\n"); printf(" It is useful for debugging errors in PDF files or analysing their structure.\n"); printf("\nPoDoFo Version: %s\n\n", PODOFO_VERSION_STRING); } int main( int argc, char* argv[] ) { char* pszInput; char* pszOutput; UnCompress unc; if( argc != 3 ) { print_help(); exit( -1 ); } pszInput = argv[1]; pszOutput = argv[2]; // try { unc.Init( pszInput, pszOutput ); /* } catch( PdfError & e ) { fprintf( stderr, "Error: An error %i ocurred during uncompressing the pdf file.\n", e.GetError() ); e.PrintErrorMsg(); return e.GetError(); } */ printf("%s was successfully uncompressed to: %s\n", pszInput, pszOutput ); return 0; }
33.68
105
0.495249
satya-das
9555a3fb0a656ee3e2d01b117a51719ca0f19483
4,294
cpp
C++
inetcore/connectionwizard/icwconn/billopt.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/connectionwizard/icwconn/billopt.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/connectionwizard/icwconn/billopt.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//********************************************************************* //* Microsoft Windows ** //* Copyright(c) Microsoft Corp., 1994 ** //********************************************************************* // // BILLOPT.CPP - Functions for // // HISTORY: // // 05/13/98 donaldm Created. // //********************************************************************* #include "pre.h" const TCHAR cszBillOpt[] = TEXT("BILLOPT"); /******************************************************************* NAME: BillingOptInitProc SYNOPSIS: Called when page is displayed ENTRY: hDlg - dialog window fFirstInit - TRUE if this is the first time the dialog is initialized, FALSE if this InitProc has been called before (e.g. went past this page and backed up) ********************************************************************/ BOOL CALLBACK BillingOptInitProc ( HWND hDlg, BOOL fFirstInit, UINT *puNextPage ) { // if we've travelled through external apprentice pages, // it's easy for our current page pointer to get munged, // so reset it here for sanity's sake. gpWizardState->uCurrentPage = ORD_PAGE_BILLINGOPT; if (!fFirstInit) { ASSERT(gpWizardState->lpSelectedISPInfo); gpWizardState->lpSelectedISPInfo->DisplayTextWithISPName(GetDlgItem(hDlg,IDC_BILLINGOPT_INTRO), IDS_BILLINGOPT_INTROFMT, NULL); gpWizardState->pICWWebView->ConnectToWindow(GetDlgItem(hDlg, IDC_BILLINGOPT_HTML), PAGETYPE_BILLING); // Navigate to the Billing HTML gpWizardState->lpSelectedISPInfo->DisplayHTML(gpWizardState->lpSelectedISPInfo->get_szBillingFormPath()); // Load any previsouly saved state data for this page gpWizardState->lpSelectedISPInfo->LoadHistory((BSTR)A2W(cszBillOpt)); } return TRUE; } /******************************************************************* NAME: BillingOptOKProc SYNOPSIS: Called when Next or Back btns pressed from page ENTRY: hDlg - dialog window fForward - TRUE if 'Next' was pressed, FALSE if 'Back' puNextPage - if 'Next' was pressed, proc can fill this in with next page to go to. This parameter is ingored if 'Back' was pressed. pfKeepHistory - page will not be kept in history if proc fills this in with FALSE. EXIT: returns TRUE to allow page to be turned, FALSE to keep the same page. ********************************************************************/ BOOL CALLBACK BillingOptOKProc ( HWND hDlg, BOOL fForward, UINT *puNextPage, BOOL *pfKeepHistory ) { // Save any data data/state entered by the user gpWizardState->lpSelectedISPInfo->SaveHistory((BSTR)A2W(cszBillOpt)); if (fForward) { // Need to form Billing Query String TCHAR szBillingOptionQuery [INTERNET_MAX_URL_LENGTH]; // Clear the Query String. memset(szBillingOptionQuery, 0, sizeof(szBillingOptionQuery)); // Attach the walker to the curent page // Use the Walker to get the query string IWebBrowser2 *lpWebBrowser; gpWizardState->pICWWebView->get_BrowserObject(&lpWebBrowser); gpWizardState->pHTMLWalker->AttachToDocument(lpWebBrowser); gpWizardState->pHTMLWalker->get_FirstFormQueryString(szBillingOptionQuery); // Add the billing query to the ISPData object gpWizardState->pISPData->PutDataElement(ISPDATA_BILLING_OPTION, szBillingOptionQuery, ISPDATA_Validate_None); // detach the walker gpWizardState->pHTMLWalker->Detach(); DWORD dwFlag = gpWizardState->lpSelectedISPInfo->get_dwCFGFlag(); if (ICW_CFGFLAG_SIGNUP_PATH & dwFlag) { if (ICW_CFGFLAG_PAYMENT & dwFlag) { *puNextPage = ORD_PAGE_PAYMENT; return TRUE; } *puNextPage = ORD_PAGE_ISPDIAL; return TRUE; } } return TRUE; }
33.286822
136
0.545645
npocmaka
9555dd25ddadf76ef9a4e41b8add0f407c7fc158
104,664
hpp
C++
hpx/preprocessed/apply_10.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/preprocessed/apply_10.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/preprocessed/apply_10.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2013 Hartmut Kaiser // Copyright (c) 2012-2013 Thomas Heller // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // This file has been automatically generated using the Boost.Wave tool. // Do not edit manually. namespace hpx { template <typename F> bool apply(threads::executor& sched, BOOST_FWD_REF(F) f) { sched.add(boost::forward<F>(f), "hpx::apply"); return false; } template <typename F> bool apply(BOOST_FWD_REF(F) f) { threads::register_thread(boost::forward<F>(f), "hpx::apply"); return false; } template <typename F, typename A0> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 )), "hpx::apply"); return false; } template <typename F, typename A0> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9) , BOOST_FWD_REF(A10)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9) , BOOST_FWD_REF(A10)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9) , BOOST_FWD_REF(A10) , BOOST_FWD_REF(A11)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9) , BOOST_FWD_REF(A10) , BOOST_FWD_REF(A11)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )), "hpx::apply"); return false; } } namespace hpx { template < typename Action , typename T0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } } namespace hpx { template < typename Action , typename T0 , typename T1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename T1 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } } namespace hpx { template < typename Action , typename T0 , typename T1 , typename T2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } } namespace hpx { template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } } namespace hpx { template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } } namespace hpx { template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } } namespace hpx { template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } } namespace hpx { template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } } namespace hpx { template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } } namespace hpx { template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound) { return bound.apply(); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); } }
451.137931
19,599
0.678849
andreasbuhr
95589cd23a24a500ce6e8b4060128928696eedb6
89,701
cpp
C++
RotateIt/exiv2/src/basicio.cpp
Vitalii17/RotateIt
621089c334e740b99bc7686d5724b79655adfbad
[ "MIT" ]
1
2017-02-10T16:39:32.000Z
2017-02-10T16:39:32.000Z
RotateIt/exiv2/src/basicio.cpp
vitalii17/RotateIt
621089c334e740b99bc7686d5724b79655adfbad
[ "MIT" ]
null
null
null
RotateIt/exiv2/src/basicio.cpp
vitalii17/RotateIt
621089c334e740b99bc7686d5724b79655adfbad
[ "MIT" ]
null
null
null
// ***************************************************************** -*- C++ -*- /* * Copyright (C) 2004-2017 Andreas Huggel <ahuggel@gmx.net> * * This program is part of the Exiv2 distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA. */ /* File: basicio.cpp Version: $Rev$ */ // ***************************************************************************** #include "rcsid_int.hpp" EXIV2_RCSID("@(#) $Id$") // included header files #include "config.h" #include "datasets.hpp" #include "basicio.hpp" #include "futils.hpp" #include "types.hpp" #include "error.hpp" #include "http.hpp" #include "properties.hpp" // + standard includes #include <string> #include <memory> #include <iostream> #include <cstring> #include <cassert> #include <cstdio> // for remove, rename #include <cstdlib> // for alloc, realloc, free #include <sys/types.h> // for stat, chmod #include <sys/stat.h> // for stat, chmod #ifdef EXV_HAVE_SYS_MMAN_H # include <sys/mman.h> // for mmap and munmap #endif #ifdef EXV_HAVE_PROCESS_H # include <process.h> #endif #ifdef EXV_HAVE_UNISTD_H # include <unistd.h> // for getpid, stat #endif #if EXV_USE_CURL == 1 #include <curl/curl.h> #endif #if EXV_USE_SSH == 1 #include "ssh.hpp" #else #define mode_t unsigned short #endif // Platform specific headers for handling extended attributes (xattr) #if defined(__APPLE__) # include <sys/xattr.h> #endif #if defined(__MINGW__) || (defined(WIN32) && !defined(__CYGWIN)) // Windows doesn't provide nlink_t typedef short nlink_t; # include <windows.h> # include <io.h> #endif // ***************************************************************************** // class member definitions namespace Exiv2 { BasicIo::~BasicIo() { } //! Internal Pimpl structure of class FileIo. class FileIo::Impl { public: //! Constructor Impl(const std::string& path); #ifdef EXV_UNICODE_PATH //! Constructor accepting a unicode path in an std::wstring Impl(const std::wstring& wpath); #endif // Enumerations //! Mode of operation enum OpMode { opRead, opWrite, opSeek }; #ifdef EXV_UNICODE_PATH //! Used to indicate if the path is stored as a standard or unicode string enum WpMode { wpStandard, wpUnicode }; #endif // DATA std::string path_; //!< (Standard) path #ifdef EXV_UNICODE_PATH std::wstring wpath_; //!< Unicode path WpMode wpMode_; //!< Indicates which path is in use #endif std::string openMode_; //!< File open mode FILE *fp_; //!< File stream pointer OpMode opMode_; //!< File open mode #if defined WIN32 && !defined __CYGWIN__ HANDLE hFile_; //!< Duplicated fd HANDLE hMap_; //!< Handle from CreateFileMapping #endif byte* pMappedArea_; //!< Pointer to the memory-mapped area size_t mappedLength_; //!< Size of the memory-mapped area bool isMalloced_; //!< Is the mapped area allocated? bool isWriteable_; //!< Can the mapped area be written to? // TYPES //! Simple struct stat wrapper for internal use struct StructStat { StructStat() : st_mode(0), st_size(0), st_nlink(0) {} mode_t st_mode; //!< Permissions off_t st_size; //!< Size nlink_t st_nlink; //!< Number of hard links (broken on Windows, see winNumberOfLinks()) }; // #endif // METHODS /*! @brief Switch to a new access mode, reopening the file if needed. Optimized to only reopen the file when it is really necessary. @param opMode The mode to switch to. @return 0 if successful */ int switchMode(OpMode opMode); //! stat wrapper for internal use int stat(StructStat& buf) const; //! copy extended attributes (xattr) from another file void copyXattrFrom(const FileIo& src); #if defined WIN32 && !defined __CYGWIN__ // Windows function to determine the number of hardlinks (on NTFS) DWORD winNumberOfLinks() const; #endif private: // NOT IMPLEMENTED Impl(const Impl& rhs); //!< Copy constructor Impl& operator=(const Impl& rhs); //!< Assignment }; // class FileIo::Impl FileIo::Impl::Impl(const std::string& path) : path_(path), #ifdef EXV_UNICODE_PATH wpMode_(wpStandard), #endif fp_(0), opMode_(opSeek), #if defined WIN32 && !defined __CYGWIN__ hFile_(0), hMap_(0), #endif pMappedArea_(0), mappedLength_(0), isMalloced_(false), isWriteable_(false) { } #ifdef EXV_UNICODE_PATH FileIo::Impl::Impl(const std::wstring& wpath) : wpath_(wpath), wpMode_(wpUnicode), fp_(0), opMode_(opSeek), #if defined WIN32 && !defined __CYGWIN__ hFile_(0), hMap_(0), #endif pMappedArea_(0), mappedLength_(0), isMalloced_(false), isWriteable_(false) { } #endif int FileIo::Impl::switchMode(OpMode opMode) { assert(fp_ != 0); if (opMode_ == opMode) return 0; OpMode oldOpMode = opMode_; opMode_ = opMode; bool reopen = true; switch(opMode) { case opRead: // Flush if current mode allows reading, else reopen (in mode "r+b" // as in this case we know that we can write to the file) if (openMode_[0] == 'r' || openMode_[1] == '+') reopen = false; break; case opWrite: // Flush if current mode allows writing, else reopen if (openMode_[0] != 'r' || openMode_[1] == '+') reopen = false; break; case opSeek: reopen = false; break; } if (!reopen) { // Don't do anything when switching _from_ opSeek mode; we // flush when switching _to_ opSeek. if (oldOpMode == opSeek) return 0; // Flush. On msvcrt fflush does not do the job std::fseek(fp_, 0, SEEK_CUR); return 0; } // Reopen the file long offset = std::ftell(fp_); if (offset == -1) return -1; // 'Manual' open("r+b") to avoid munmap() if (fp_ != 0) { std::fclose(fp_); fp_= 0; } openMode_ = "r+b"; opMode_ = opSeek; #ifdef EXV_UNICODE_PATH if (wpMode_ == wpUnicode) { fp_ = ::_wfopen(wpath_.c_str(), s2ws(openMode_).c_str()); } else #endif { fp_ = std::fopen(path_.c_str(), openMode_.c_str()); } if (!fp_) return 1; return std::fseek(fp_, offset, SEEK_SET); } // FileIo::Impl::switchMode int FileIo::Impl::stat(StructStat& buf) const { int ret = 0; #ifdef EXV_UNICODE_PATH #ifdef _WIN64 struct _stat64 st; ret = ::_wstati64(wpath_.c_str(), &st); if (0 == ret) { buf.st_size = st.st_size; buf.st_mode = st.st_mode; buf.st_nlink = st.st_nlink; } #else struct _stat st; ret = ::_wstat(wpath_.c_str(), &st); if (0 == ret) { buf.st_size = st.st_size; buf.st_mode = st.st_mode; buf.st_nlink = st.st_nlink; } #endif else #endif { struct stat st; ret = ::stat(path_.c_str(), &st); if (0 == ret) { buf.st_size = st.st_size; buf.st_nlink = st.st_nlink; buf.st_mode = st.st_mode; } } return ret; } // FileIo::Impl::stat #if defined(__APPLE__) void FileIo::Impl::copyXattrFrom(const FileIo& src) #else void FileIo::Impl::copyXattrFrom(const FileIo&) #endif { #if defined(__APPLE__) # if defined(EXV_UNICODE_PATH) # error No xattr API for MacOS X with unicode support # endif ssize_t namebufSize = ::listxattr(src.p_->path_.c_str(), 0, 0, 0); if (namebufSize < 0) { throw Error(2, src.p_->path_, strError(), "listxattr"); } if (namebufSize == 0) { // No extended attributes in source file return; } char* namebuf = new char[namebufSize]; if (::listxattr(src.p_->path_.c_str(), namebuf, namebufSize, 0) != namebufSize) { throw Error(2, src.p_->path_, strError(), "listxattr"); } for (ssize_t namebufPos = 0; namebufPos < namebufSize;) { const char *name = namebuf + namebufPos; namebufPos += strlen(name) + 1; const ssize_t valueSize = ::getxattr(src.p_->path_.c_str(), name, 0, 0, 0, 0); if (valueSize < 0) { throw Error(2, src.p_->path_, strError(), "getxattr"); } char* value = new char[valueSize]; if (::getxattr(src.p_->path_.c_str(), name, value, valueSize, 0, 0) != valueSize) { throw Error(2, src.p_->path_, strError(), "getxattr"); } // #906. Mountain Lion 'sandbox' terminates the app when we call setxattr #ifndef __APPLE__ #ifdef DEBUG EXV_DEBUG << "Copying xattr \"" << name << "\" with value size " << valueSize << "\n"; #endif if (::setxattr(path_.c_str(), name, value, valueSize, 0, 0) != 0) { throw Error(2, path_, strError(), "setxattr"); } delete [] value; #endif } delete [] namebuf; #else // No xattr support for this platform. #endif } // FileIo::Impl::copyXattrFrom #if defined WIN32 && !defined __CYGWIN__ DWORD FileIo::Impl::winNumberOfLinks() const { DWORD nlink = 1; HANDLE hFd = (HANDLE)_get_osfhandle(fileno(fp_)); if (hFd != INVALID_HANDLE_VALUE) { typedef BOOL (WINAPI * GetFileInformationByHandle_t)(HANDLE, LPBY_HANDLE_FILE_INFORMATION); HMODULE hKernel = ::GetModuleHandleA("kernel32.dll"); if (hKernel) { GetFileInformationByHandle_t pfcn_GetFileInformationByHandle = (GetFileInformationByHandle_t)GetProcAddress(hKernel, "GetFileInformationByHandle"); if (pfcn_GetFileInformationByHandle) { BY_HANDLE_FILE_INFORMATION fi = {0,0,0,0,0,0,0,0,0,0,0,0,0}; if (pfcn_GetFileInformationByHandle(hFd, &fi)) { nlink = fi.nNumberOfLinks; } #ifdef DEBUG else EXV_DEBUG << "GetFileInformationByHandle failed\n"; #endif } #ifdef DEBUG else EXV_DEBUG << "GetProcAddress(hKernel, \"GetFileInformationByHandle\") failed\n"; #endif } #ifdef DEBUG else EXV_DEBUG << "GetModuleHandleA(\"kernel32.dll\") failed\n"; #endif } #ifdef DEBUG else EXV_DEBUG << "_get_osfhandle failed: INVALID_HANDLE_VALUE\n"; #endif return nlink; } // FileIo::Impl::winNumberOfLinks #endif // defined WIN32 && !defined __CYGWIN__ FileIo::FileIo(const std::string& path) : p_(new Impl(path)) { } #ifdef EXV_UNICODE_PATH FileIo::FileIo(const std::wstring& wpath) : p_(new Impl(wpath)) { } #endif FileIo::~FileIo() { close(); delete p_; } int FileIo::munmap() { int rc = 0; if (p_->pMappedArea_ != 0) { #if defined EXV_HAVE_MMAP && defined EXV_HAVE_MUNMAP if (::munmap(p_->pMappedArea_, p_->mappedLength_) != 0) { rc = 1; } #elif defined WIN32 && !defined __CYGWIN__ UnmapViewOfFile(p_->pMappedArea_); CloseHandle(p_->hMap_); p_->hMap_ = 0; CloseHandle(p_->hFile_); p_->hFile_ = 0; #else if (p_->isWriteable_) { seek(0, BasicIo::beg); write(p_->pMappedArea_, p_->mappedLength_); } if (p_->isMalloced_) { delete[] p_->pMappedArea_; p_->isMalloced_ = false; } #endif } if (p_->isWriteable_) { if (p_->fp_ != 0) p_->switchMode(Impl::opRead); p_->isWriteable_ = false; } p_->pMappedArea_ = 0; p_->mappedLength_ = 0; return rc; } byte* FileIo::mmap(bool isWriteable) { assert(p_->fp_ != 0); if (munmap() != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), strError().c_str(), "munmap"); } else #endif { throw Error(2, path(), strError(), "munmap"); } } p_->mappedLength_ = size(); p_->isWriteable_ = isWriteable; if (p_->isWriteable_ && p_->switchMode(Impl::opWrite) != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(16, wpath(), strError().c_str()); } else #endif { throw Error(16, path(), strError()); } } #if defined EXV_HAVE_MMAP && defined EXV_HAVE_MUNMAP int prot = PROT_READ; if (p_->isWriteable_) { prot |= PROT_WRITE; } void* rc = ::mmap(0, p_->mappedLength_, prot, MAP_SHARED, fileno(p_->fp_), 0); if (MAP_FAILED == rc) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), strError().c_str(), "mmap"); } else #endif { throw Error(2, path(), strError(), "mmap"); } } p_->pMappedArea_ = static_cast<byte*>(rc); #elif defined WIN32 && !defined __CYGWIN__ // Windows implementation // TODO: An attempt to map a file with a length of 0 (zero) fails with // an error code of ERROR_FILE_INVALID. // Applications should test for files with a length of 0 (zero) and // reject those files. DWORD dwAccess = FILE_MAP_READ; DWORD flProtect = PAGE_READONLY; if (isWriteable) { dwAccess = FILE_MAP_WRITE; flProtect = PAGE_READWRITE; } HANDLE hPh = GetCurrentProcess(); HANDLE hFd = (HANDLE)_get_osfhandle(fileno(p_->fp_)); if (hFd == INVALID_HANDLE_VALUE) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), "MSG1", "_get_osfhandle"); } else #endif { throw Error(2, path(), "MSG1", "_get_osfhandle"); } } if (!DuplicateHandle(hPh, hFd, hPh, &p_->hFile_, 0, false, DUPLICATE_SAME_ACCESS)) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), "MSG2", "DuplicateHandle"); } else #endif { throw Error(2, path(), "MSG2", "DuplicateHandle"); } } p_->hMap_ = CreateFileMapping(p_->hFile_, 0, flProtect, 0, (DWORD) p_->mappedLength_, 0); if (p_->hMap_ == 0 ) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), "MSG3", "CreateFileMapping"); } else #endif { throw Error(2, path(), "MSG3", "CreateFileMapping"); } } void* rc = MapViewOfFile(p_->hMap_, dwAccess, 0, 0, 0); if (rc == 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), "MSG4", "CreateFileMapping"); } else #endif { throw Error(2, path(), "MSG4", "CreateFileMapping"); } } p_->pMappedArea_ = static_cast<byte*>(rc); #else // Workaround for platforms without mmap: Read the file into memory DataBuf buf(static_cast<long>(p_->mappedLength_)); if (read(buf.pData_, buf.size_) != buf.size_) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), strError().c_str(), "FileIo::read"); } else #endif { throw Error(2, path(), strError(), "FileIo::read"); } } if (error()) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), strError().c_str(), "FileIo::mmap"); } else #endif { throw Error(2, path(), strError(), "FileIo::mmap"); } } p_->pMappedArea_ = buf.release().first; p_->isMalloced_ = true; #endif return p_->pMappedArea_; } void FileIo::setPath(const std::string& path) { close(); #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { std::wstring wpath; wpath.assign(path.begin(), path.end()); p_->wpath_ = wpath; } p_->path_ = path; #else p_->path_ = path; #endif } #ifdef EXV_UNICODE_PATH void FileIo::setPath(const std::wstring& wpath) { close(); if (p_->wpMode_ == Impl::wpStandard) { std::string path; path.assign(wpath.begin(), wpath.end()); p_->path_ = path; } else { p_->wpath_ = wpath; } } #endif long FileIo::write(const byte* data, long wcount) { assert(p_->fp_ != 0); if (p_->switchMode(Impl::opWrite) != 0) return 0; return (long)std::fwrite(data, 1, wcount, p_->fp_); } long FileIo::write(BasicIo& src) { assert(p_->fp_ != 0); if (static_cast<BasicIo*>(this) == &src) return 0; if (!src.isopen()) return 0; if (p_->switchMode(Impl::opWrite) != 0) return 0; byte buf[4096]; long readCount = 0; long writeCount = 0; long writeTotal = 0; while ((readCount = src.read(buf, sizeof(buf)))) { writeTotal += writeCount = (long)std::fwrite(buf, 1, readCount, p_->fp_); if (writeCount != readCount) { // try to reset back to where write stopped src.seek(writeCount-readCount, BasicIo::cur); break; } } return writeTotal; } void FileIo::transfer(BasicIo& src) { const bool wasOpen = (p_->fp_ != 0); const std::string lastMode(p_->openMode_); FileIo *fileIo = dynamic_cast<FileIo*>(&src); if (fileIo) { // Optimization if src is another instance of FileIo fileIo->close(); // Check if the file can be written to, if it already exists if (open("a+b") != 0) { // Remove the (temporary) file #ifdef EXV_UNICODE_PATH if (fileIo->p_->wpMode_ == Impl::wpUnicode) { ::_wremove(fileIo->wpath().c_str()); } else #endif { ::remove(fileIo->path().c_str()); } #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(10, wpath(), "a+b", strError().c_str()); } else #endif { throw Error(10, path(), "a+b", strError()); } } close(); bool statOk = true; mode_t origStMode = 0; std::string spf; char* pf = 0; #ifdef EXV_UNICODE_PATH std::wstring wspf; wchar_t* wpf = 0; if (p_->wpMode_ == Impl::wpUnicode) { wspf = wpath(); wpf = const_cast<wchar_t*>(wspf.c_str()); } else #endif { spf = path(); pf = const_cast<char*>(spf.c_str()); } // Get the permissions of the file, or linked-to file, on platforms which have lstat #ifdef EXV_HAVE_LSTAT # ifdef EXV_UNICODE_PATH # error EXV_UNICODE_PATH and EXV_HAVE_LSTAT are not compatible. Stop. # endif struct stat buf1; if (::lstat(pf, &buf1) == -1) { statOk = false; #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, pf, strError(), "::lstat") << "\n"; #endif } origStMode = buf1.st_mode; DataBuf lbuf; // So that the allocated memory is freed. Must have same scope as pf // In case path() is a symlink, get the path of the linked-to file if (statOk && S_ISLNK(buf1.st_mode)) { lbuf.alloc(buf1.st_size + 1); memset(lbuf.pData_, 0x0, lbuf.size_); pf = reinterpret_cast<char*>(lbuf.pData_); if (::readlink(path().c_str(), pf, lbuf.size_ - 1) == -1) { throw Error(2, path(), strError(), "readlink"); } // We need the permissions of the file, not the symlink if (::stat(pf, &buf1) == -1) { statOk = false; #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, pf, strError(), "::stat") << "\n"; #endif } origStMode = buf1.st_mode; } #else // EXV_HAVE_LSTAT Impl::StructStat buf1; if (p_->stat(buf1) == -1) { statOk = false; } origStMode = buf1.st_mode; #endif // !EXV_HAVE_LSTAT // MSVCRT rename that does not overwrite existing files #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { #if defined(WIN32) && defined(REPLACEFILE_IGNORE_MERGE_ERRORS) // Windows implementation that deals with the fact that ::rename fails // if the target filename still exists, which regularly happens when // that file has been opened with FILE_SHARE_DELETE by another process, // like a virus scanner or disk indexer // (see also http://stackoverflow.com/a/11023068) typedef BOOL (WINAPI * ReplaceFileW_t)(LPCWSTR, LPCWSTR, LPCWSTR, DWORD, LPVOID, LPVOID); HMODULE hKernel = ::GetModuleHandleA("kernel32.dll"); if (hKernel) { ReplaceFileW_t pfcn_ReplaceFileW = (ReplaceFileW_t)GetProcAddress(hKernel, "ReplaceFileW"); if (pfcn_ReplaceFileW) { BOOL ret = pfcn_ReplaceFileW(wpf, fileIo->wpath().c_str(), NULL, REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL); if (ret == 0) { if (GetLastError() == ERROR_FILE_NOT_FOUND) { if (::_wrename(fileIo->wpath().c_str(), wpf) == -1) { throw WError(17, fileIo->wpath(), wpf, strError().c_str()); } ::_wremove(fileIo->wpath().c_str()); } else { throw WError(17, fileIo->wpath(), wpf, strError().c_str()); } } } else { if (fileExists(wpf) && ::_wremove(wpf) != 0) { throw WError(2, wpf, strError().c_str(), "::_wremove"); } if (::_wrename(fileIo->wpath().c_str(), wpf) == -1) { throw WError(17, fileIo->wpath(), wpf, strError().c_str()); } ::_wremove(fileIo->wpath().c_str()); } } #else if (fileExists(wpf) && ::_wremove(wpf) != 0) { throw WError(2, wpf, strError().c_str(), "::_wremove"); } if (::_wrename(fileIo->wpath().c_str(), wpf) == -1) { throw WError(17, fileIo->wpath(), wpf, strError().c_str()); } ::_wremove(fileIo->wpath().c_str()); #endif // Check permissions of new file struct _stat buf2; if (statOk && ::_wstat(wpf, &buf2) == -1) { statOk = false; #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, wpf, strError(), "::_wstat") << "\n"; #endif } if (statOk && origStMode != buf2.st_mode) { // Set original file permissions if (::_wchmod(wpf, origStMode) == -1) { #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, wpf, strError(), "::_wchmod") << "\n"; #endif } } } // if (p_->wpMode_ == Impl::wpUnicode) else #endif // EXV_UNICODE_PATH { #if defined(WIN32) && defined(REPLACEFILE_IGNORE_MERGE_ERRORS) // Windows implementation that deals with the fact that ::rename fails // if the target filename still exists, which regularly happens when // that file has been opened with FILE_SHARE_DELETE by another process, // like a virus scanner or disk indexer // (see also http://stackoverflow.com/a/11023068) typedef BOOL (WINAPI * ReplaceFileA_t)(LPCSTR, LPCSTR, LPCSTR, DWORD, LPVOID, LPVOID); HMODULE hKernel = ::GetModuleHandleA("kernel32.dll"); if (hKernel) { ReplaceFileA_t pfcn_ReplaceFileA = (ReplaceFileA_t)GetProcAddress(hKernel, "ReplaceFileA"); if (pfcn_ReplaceFileA) { BOOL ret = pfcn_ReplaceFileA(pf, fileIo->path().c_str(), NULL, REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL); if (ret == 0) { if (GetLastError() == ERROR_FILE_NOT_FOUND) { if (::rename(fileIo->path().c_str(), pf) == -1) { throw Error(17, fileIo->path(), pf, strError()); } ::remove(fileIo->path().c_str()); } else { throw Error(17, fileIo->path(), pf, strError()); } } } else { if (fileExists(pf) && ::remove(pf) != 0) { throw Error(2, pf, strError(), "::remove"); } if (::rename(fileIo->path().c_str(), pf) == -1) { throw Error(17, fileIo->path(), pf, strError()); } ::remove(fileIo->path().c_str()); } } #else if (fileExists(pf) && ::remove(pf) != 0) { throw Error(2, pf, strError(), "::remove"); } if (::rename(fileIo->path().c_str(), pf) == -1) { throw Error(17, fileIo->path(), pf, strError()); } ::remove(fileIo->path().c_str()); #endif // Check permissions of new file struct stat buf2; if (statOk && ::stat(pf, &buf2) == -1) { statOk = false; #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, pf, strError(), "::stat") << "\n"; #endif } if (statOk && origStMode != buf2.st_mode) { // Set original file permissions if (::chmod(pf, origStMode) == -1) { #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, pf, strError(), "::chmod") << "\n"; #endif } } } } // if (fileIo) else { // Generic handling, reopen both to reset to start if (open("w+b") != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(10, wpath(), "w+b", strError().c_str()); } else #endif { throw Error(10, path(), "w+b", strError()); } } if (src.open() != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(9, src.wpath(), strError().c_str()); } else #endif { throw Error(9, src.path(), strError()); } } write(src); src.close(); } if (wasOpen) { if (open(lastMode) != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(10, wpath(), lastMode.c_str(), strError().c_str()); } else #endif { throw Error(10, path(), lastMode, strError()); } } } else close(); if (error() || src.error()) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(18, wpath(), strError().c_str()); } else #endif { throw Error(18, path(), strError()); } } } // FileIo::transfer int FileIo::putb(byte data) { assert(p_->fp_ != 0); if (p_->switchMode(Impl::opWrite) != 0) return EOF; return putc(data, p_->fp_); } #if defined(_MSC_VER) int FileIo::seek( int64_t offset, Position pos ) { assert(p_->fp_ != 0); int fileSeek = 0; switch (pos) { case BasicIo::cur: fileSeek = SEEK_CUR; break; case BasicIo::beg: fileSeek = SEEK_SET; break; case BasicIo::end: fileSeek = SEEK_END; break; } if (p_->switchMode(Impl::opSeek) != 0) return 1; #ifdef _WIN64 return _fseeki64(p_->fp_, offset, fileSeek); #else return std::fseek(p_->fp_,static_cast<long>(offset), fileSeek); #endif } #else int FileIo::seek(long offset, Position pos) { assert(p_->fp_ != 0); int fileSeek = 0; switch (pos) { case BasicIo::cur: fileSeek = SEEK_CUR; break; case BasicIo::beg: fileSeek = SEEK_SET; break; case BasicIo::end: fileSeek = SEEK_END; break; } if (p_->switchMode(Impl::opSeek) != 0) return 1; return std::fseek(p_->fp_, offset, fileSeek); } #endif long FileIo::tell() const { assert(p_->fp_ != 0); return std::ftell(p_->fp_); } size_t FileIo::size() const { // Flush and commit only if the file is open for writing if (p_->fp_ != 0 && (p_->openMode_[0] != 'r' || p_->openMode_[1] == '+')) { std::fflush(p_->fp_); #if defined WIN32 && !defined __CYGWIN__ // This is required on msvcrt before stat after writing to a file _commit(_fileno(p_->fp_)); #endif } Impl::StructStat buf; int ret = p_->stat(buf); if (ret != 0) return -1; return buf.st_size; } int FileIo::open() { // Default open is in read-only binary mode return open("rb"); } int FileIo::open(const std::string& mode) { close(); p_->openMode_ = mode; p_->opMode_ = Impl::opSeek; #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { p_->fp_ = ::_wfopen(wpath().c_str(), s2ws(mode).c_str()); } else #endif { p_->fp_ = ::fopen(path().c_str(), mode.c_str()); } if (!p_->fp_) return 1; return 0; } bool FileIo::isopen() const { return p_->fp_ != 0; } int FileIo::close() { int rc = 0; if (munmap() != 0) rc = 2; if (p_->fp_ != 0) { if (std::fclose(p_->fp_) != 0) rc |= 1; p_->fp_= 0; } return rc; } DataBuf FileIo::read(long rcount) { assert(p_->fp_ != 0); DataBuf buf(rcount); long readCount = read(buf.pData_, buf.size_); buf.size_ = readCount; return buf; } long FileIo::read(byte* buf, long rcount) { assert(p_->fp_ != 0); if (p_->switchMode(Impl::opRead) != 0) return 0; return (long)std::fread(buf, 1, rcount, p_->fp_); } int FileIo::getb() { assert(p_->fp_ != 0); if (p_->switchMode(Impl::opRead) != 0) return EOF; return getc(p_->fp_); } int FileIo::error() const { return p_->fp_ != 0 ? ferror(p_->fp_) : 0; } bool FileIo::eof() const { assert(p_->fp_ != 0); return feof(p_->fp_) != 0 || tell() >= (long) size() ; } std::string FileIo::path() const { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { return ws2s(p_->wpath_); } #endif return p_->path_; } #ifdef EXV_UNICODE_PATH std::wstring FileIo::wpath() const { if (p_->wpMode_ == Impl::wpStandard) { return s2ws(p_->path_); } return p_->wpath_; } #endif void FileIo::populateFakeData() { } //! Internal Pimpl structure of class MemIo. class MemIo::Impl { public: Impl(); //!< Default constructor Impl(const byte* data, long size); //!< Constructor 2 // DATA byte* data_; //!< Pointer to the start of the memory area long idx_; //!< Index into the memory area long size_; //!< Size of the memory area long sizeAlloced_; //!< Size of the allocated buffer bool isMalloced_; //!< Was the buffer allocated? bool eof_; //!< EOF indicator // METHODS void reserve(long wcount); //!< Reserve memory private: // NOT IMPLEMENTED Impl(const Impl& rhs); //!< Copy constructor Impl& operator=(const Impl& rhs); //!< Assignment }; // class MemIo::Impl MemIo::Impl::Impl() : data_(0), idx_(0), size_(0), sizeAlloced_(0), isMalloced_(false), eof_(false) { } MemIo::Impl::Impl(const byte* data, long size) : data_(const_cast<byte*>(data)), idx_(0), size_(size), sizeAlloced_(0), isMalloced_(false), eof_(false) { } void MemIo::Impl::reserve(long wcount) { long need = wcount + idx_; if (!isMalloced_) { // Minimum size for 1st block is 32kB long size = EXV_MAX(32768 * (1 + need / 32768), size_); byte* data = (byte*)std::malloc(size); std::memcpy(data, data_, size_); data_ = data; sizeAlloced_ = size; isMalloced_ = true; } if (need > size_) { if (need > sizeAlloced_) { // Allocate in blocks of 32kB long want = 32768 * (1 + need / 32768); data_ = (byte*)std::realloc(data_, want); sizeAlloced_ = want; isMalloced_ = true; } size_ = need; } } MemIo::MemIo() : p_(new Impl()) { } MemIo::MemIo(const byte* data, long size) : p_(new Impl(data, size)) { } MemIo::~MemIo() { if (p_->isMalloced_) { std::free(p_->data_); } delete p_; } long MemIo::write(const byte* data, long wcount) { p_->reserve(wcount); assert(p_->isMalloced_); std::memcpy(&p_->data_[p_->idx_], data, wcount); p_->idx_ += wcount; return wcount; } void MemIo::transfer(BasicIo& src) { MemIo *memIo = dynamic_cast<MemIo*>(&src); if (memIo) { // Optimization if src is another instance of MemIo if (p_->isMalloced_) { std::free(p_->data_); } p_->idx_ = 0; p_->data_ = memIo->p_->data_; p_->size_ = memIo->p_->size_; p_->isMalloced_ = memIo->p_->isMalloced_; memIo->p_->idx_ = 0; memIo->p_->data_ = 0; memIo->p_->size_ = 0; memIo->p_->isMalloced_ = false; } else { // Generic reopen to reset position to start if (src.open() != 0) { throw Error(9, src.path(), strError()); } p_->idx_ = 0; write(src); src.close(); } if (error() || src.error()) throw Error(19, strError()); } long MemIo::write(BasicIo& src) { if (static_cast<BasicIo*>(this) == &src) return 0; if (!src.isopen()) return 0; byte buf[4096]; long readCount = 0; long writeTotal = 0; while ((readCount = src.read(buf, sizeof(buf)))) { write(buf, readCount); writeTotal += readCount; } return writeTotal; } int MemIo::putb(byte data) { p_->reserve(1); assert(p_->isMalloced_); p_->data_[p_->idx_++] = data; return data; } #if defined(_MSC_VER) int MemIo::seek( int64_t offset, Position pos ) { uint64_t newIdx = 0; switch (pos) { case BasicIo::cur: newIdx = p_->idx_ + offset; break; case BasicIo::beg: newIdx = offset; break; case BasicIo::end: newIdx = p_->size_ + offset; break; } p_->idx_ = static_cast<long>(newIdx); //not very sure about this. need more test!! - note by Shawn fly2xj@gmail.com //TODO p_->eof_ = false; return 0; } #else int MemIo::seek(long offset, Position pos) { long newIdx = 0; switch (pos) { case BasicIo::cur: newIdx = p_->idx_ + offset; break; case BasicIo::beg: newIdx = offset; break; case BasicIo::end: newIdx = p_->size_ + offset; break; } if (newIdx < 0) return 1; p_->idx_ = newIdx; p_->eof_ = false; return 0; } #endif byte* MemIo::mmap(bool /*isWriteable*/) { return p_->data_; } int MemIo::munmap() { return 0; } long MemIo::tell() const { return p_->idx_; } size_t MemIo::size() const { return p_->size_; } int MemIo::open() { p_->idx_ = 0; p_->eof_ = false; return 0; } bool MemIo::isopen() const { return true; } int MemIo::close() { return 0; } DataBuf MemIo::read(long rcount) { DataBuf buf(rcount); long readCount = read(buf.pData_, buf.size_); buf.size_ = readCount; return buf; } long MemIo::read(byte* buf, long rcount) { long avail = EXV_MAX(p_->size_ - p_->idx_, 0); long allow = EXV_MIN(rcount, avail); std::memcpy(buf, &p_->data_[p_->idx_], allow); p_->idx_ += allow; if (rcount > avail) p_->eof_ = true; return allow; } int MemIo::getb() { if (p_->idx_ >= p_->size_) { p_->eof_ = true; return EOF; } return p_->data_[p_->idx_++]; } int MemIo::error() const { return 0; } bool MemIo::eof() const { return p_->eof_; } std::string MemIo::path() const { return "MemIo"; } #ifdef EXV_UNICODE_PATH std::wstring MemIo::wpath() const { return EXV_WIDEN("MemIo"); } #endif void MemIo::populateFakeData() { } #if EXV_XPATH_MEMIO XPathIo::XPathIo(const std::string& path) { Protocol prot = fileProtocol(path); if (prot == pStdin) ReadStdin(); else if (prot == pDataUri) ReadDataUri(path); } #ifdef EXV_UNICODE_PATH XPathIo::XPathIo(const std::wstring& wpath) { std::string path; path.assign(wpath.begin(), wpath.end()); Protocol prot = fileProtocol(path); if (prot == pStdin) ReadStdin(); else if (prot == pDataUri) ReadDataUri(path); } #endif void XPathIo::ReadStdin() { if (isatty(fileno(stdin))) throw Error(53); #ifdef _O_BINARY // convert stdin to binary if (_setmode(_fileno(stdin), _O_BINARY) == -1) throw Error(54); #endif char readBuf[100*1024]; std::streamsize readBufSize = 0; do { std::cin.read(readBuf, sizeof(readBuf)); readBufSize = std::cin.gcount(); if (readBufSize > 0) { write((byte*)readBuf, (long)readBufSize); } } while(readBufSize); } void XPathIo::ReadDataUri(const std::string& path) { size_t base64Pos = path.find("base64,"); if (base64Pos == std::string::npos) throw Error(1, "No base64 data"); std::string data = path.substr(base64Pos+7); char* decodeData = new char[data.length()]; long size = base64decode(data.c_str(), decodeData, data.length()); if (size > 0) write((byte*)decodeData, size); else throw Error(1, "Unable to decode base 64."); delete[] decodeData; } #else const std::string XPathIo::TEMP_FILE_EXT = ".exiv2_temp"; const std::string XPathIo::GEN_FILE_EXT = ".exiv2"; XPathIo::XPathIo(const std::string& orgPath) : FileIo(XPathIo::writeDataToFile(orgPath)) { isTemp_ = true; tempFilePath_ = path(); } #ifdef EXV_UNICODE_PATH XPathIo::XPathIo(const std::wstring& wOrgPathpath) : FileIo(XPathIo::writeDataToFile(wOrgPathpath)) { isTemp_ = true; tempFilePath_ = path(); } #endif XPathIo::~XPathIo() { if (isTemp_ && remove(tempFilePath_.c_str()) != 0) { // error when removing file // printf ("Warning: Unable to remove the temp file %s.\n", tempFilePath_.c_str()); } } void XPathIo::transfer(BasicIo& src) { if (isTemp_) { // replace temp path to gent path. std::string currentPath = path(); setPath(ReplaceStringInPlace(currentPath, XPathIo::TEMP_FILE_EXT, XPathIo::GEN_FILE_EXT)); // rename the file tempFilePath_ = path(); if (rename(currentPath.c_str(), tempFilePath_.c_str()) != 0) { // printf("Warning: Failed to rename the temp file. \n"); } isTemp_ = false; // call super class method FileIo::transfer(src); } } std::string XPathIo::writeDataToFile(const std::string& orgPath) { Protocol prot = fileProtocol(orgPath); // generating the name for temp file. std::time_t timestamp = std::time(NULL); std::stringstream ss; ss << timestamp << XPathIo::TEMP_FILE_EXT; std::string path = ss.str(); std::ofstream fs(path.c_str(), std::ios::out | std::ios::binary | std::ios::trunc); if (prot == pStdin) { if (isatty(fileno(stdin))) throw Error(53); #if defined(_MSC_VER) || defined(__MINGW__) // convert stdin to binary if (_setmode(_fileno(stdin), _O_BINARY) == -1) throw Error(54); #endif // read stdin and write to the temp file. char readBuf[100*1024]; std::streamsize readBufSize = 0; do { std::cin.read(readBuf, sizeof(readBuf)); readBufSize = std::cin.gcount(); if (readBufSize > 0) { fs.write (readBuf, readBufSize); } } while(readBufSize); } else if (prot == pDataUri) { // read data uri and write to the temp file. size_t base64Pos = orgPath.find("base64,"); if (base64Pos == std::string::npos) throw Error(1, "No base64 data"); std::string data = orgPath.substr(base64Pos+7); char* decodeData = new char[data.length()]; long size = base64decode(data.c_str(), decodeData, data.length()); if (size > 0) fs.write(decodeData, size); else throw Error(1, "Unable to decode base 64."); delete[] decodeData; } fs.close(); return path; } #ifdef EXV_UNICODE_PATH std::string XPathIo::writeDataToFile(const std::wstring& wOrgPath) { std::string orgPath; orgPath.assign(wOrgPath.begin(), wOrgPath.end()); return XPathIo::writeDataToFile(orgPath); } #endif #endif //! Internal Pimpl abstract structure of class RemoteIo. class RemoteIo::Impl { public: //! Constructor Impl(const std::string& path, size_t blockSize); #ifdef EXV_UNICODE_PATH //! Constructor accepting a unicode path in an std::wstring Impl(const std::wstring& wpath, size_t blockSize); #endif //! Destructor. Releases all managed memory. virtual ~Impl(); // DATA std::string path_; //!< (Standard) path #ifdef EXV_UNICODE_PATH std::wstring wpath_; //!< Unicode path #endif size_t blockSize_; //!< Size of the block memory. BlockMap* blocksMap_; //!< An array contains all blocksMap size_t size_; //!< The file size long idx_; //!< Index into the memory area bool isMalloced_; //!< Was the blocksMap_ allocated? bool eof_; //!< EOF indicator Protocol protocol_; //!< the protocol of url uint32_t totalRead_; //!< bytes requested from host // METHODS /*! @brief Get the length (in bytes) of the remote file. @return Return -1 if the size is unknown. Otherwise it returns the length of remote file (in bytes). @throw Error if the server returns the error code. */ virtual long getFileLength() = 0; /*! @brief Get the data by range. @param lowBlock The start block index. @param highBlock The end block index. @param response The data from the server. @throw Error if the server returns the error code. @note Set lowBlock = -1 and highBlock = -1 to get the whole file content. */ virtual void getDataByRange(long lowBlock, long highBlock, std::string& response) = 0; /*! @brief Submit the data to the remote machine. The data replace a part of the remote file. The replaced part of remote file is indicated by from and to parameters. @param data The data are submitted to the remote machine. @param size The size of data. @param from The start position in the remote file where the data replace. @param to The end position in the remote file where the data replace. @note The write access is available on some protocols. HTTP and HTTPS require the script file on the remote machine to handle the data. SSH requires the permission to edit the file. @throw Error if it fails. */ virtual void writeRemote(const byte* data, size_t size, long from, long to) = 0; /*! @brief Get the data from the remote machine and write them to the memory blocks. @param lowBlock The start block index. @param highBlock The end block index. @return Number of bytes written to the memory block successfully @throw Error if it fails. */ virtual size_t populateBlocks(size_t lowBlock, size_t highBlock); }; // class RemoteIo::Impl RemoteIo::Impl::Impl(const std::string& url, size_t blockSize) : path_(url), blockSize_(blockSize), blocksMap_(0), size_(0), idx_(0), isMalloced_(false), eof_(false), protocol_(fileProtocol(url)),totalRead_(0) { } #ifdef EXV_UNICODE_PATH RemoteIo::Impl::Impl(const std::wstring& wurl, size_t blockSize) : wpath_(wurl), blockSize_(blockSize), blocksMap_(0), size_(0), idx_(0), isMalloced_(false), eof_(false), protocol_(fileProtocol(wurl)) { } #endif size_t RemoteIo::Impl::populateBlocks(size_t lowBlock, size_t highBlock) { assert(isMalloced_); // optimize: ignore all true blocks on left & right sides. while(!blocksMap_[lowBlock].isNone() && lowBlock < highBlock) lowBlock++; while(!blocksMap_[highBlock].isNone() && highBlock > lowBlock) highBlock--; size_t rcount = 0; if (blocksMap_[highBlock].isNone()) { std::string data; getDataByRange( (long) lowBlock, (long) highBlock, data); rcount = (size_t)data.length(); if (rcount == 0) { throw Error(1, "Data By Range is empty. Please check the permission."); } byte* source = (byte*)data.c_str(); size_t remain = rcount, totalRead = 0; size_t iBlock = (rcount == size_) ? 0 : lowBlock; while (remain) { size_t allow = EXV_MIN(remain, blockSize_); blocksMap_[iBlock].populate(&source[totalRead], allow); remain -= allow; totalRead += allow; iBlock++; } } return rcount; } RemoteIo::Impl::~Impl() { if (blocksMap_) delete[] blocksMap_; } RemoteIo::~RemoteIo() { if (p_) { close(); delete p_; } } int RemoteIo::open() { close(); // reset the IO position bigBlock_ = NULL; if (p_->isMalloced_ == false) { long length = p_->getFileLength(); if (length < 0) { // unable to get the length of remote file, get the whole file content. std::string data; p_->getDataByRange(-1, -1, data); p_->size_ = (size_t) data.length(); size_t nBlocks = (p_->size_ + p_->blockSize_ - 1) / p_->blockSize_; p_->blocksMap_ = new BlockMap[nBlocks]; p_->isMalloced_ = true; byte* source = (byte*)data.c_str(); size_t remain = p_->size_, iBlock = 0, totalRead = 0; while (remain) { size_t allow = EXV_MIN(remain, p_->blockSize_); p_->blocksMap_[iBlock].populate(&source[totalRead], allow); remain -= allow; totalRead += allow; iBlock++; } } else if (length == 0) { // file is empty throw Error(1, "the file length is 0"); } else { p_->size_ = (size_t) length; size_t nBlocks = (p_->size_ + p_->blockSize_ - 1) / p_->blockSize_; p_->blocksMap_ = new BlockMap[nBlocks]; p_->isMalloced_ = true; } } return 0; // means OK } int RemoteIo::close() { if (p_->isMalloced_) { p_->eof_ = false; p_->idx_ = 0; } #ifdef DEBUG std::cerr << "RemoteIo::close totalRead_ = " << p_->totalRead_ << std::endl; #endif if ( bigBlock_ ) { delete [] bigBlock_; bigBlock_=NULL; } return 0; } long RemoteIo::write(const byte* /* unused data*/, long /* unused wcount*/) { return 0; // means failure } long RemoteIo::write(BasicIo& src) { assert(p_->isMalloced_); if (!src.isopen()) return 0; /* * The idea is to compare the file content, find the different bytes and submit them to the remote machine. * To simplify it, it: * + goes from the left, find the first different position -> $left * + goes from the right, find the first different position -> $right * The different bytes are [$left-$right] part. */ size_t left = 0; size_t right = 0; size_t blockIndex = 0; size_t i = 0; size_t readCount = 0; size_t blockSize = 0; byte* buf = (byte*) std::malloc(p_->blockSize_); size_t nBlocks = (p_->size_ + p_->blockSize_ - 1) / p_->blockSize_; // find $left src.seek(0, BasicIo::beg); bool findDiff = false; while (blockIndex < nBlocks && !src.eof() && !findDiff) { blockSize = p_->blocksMap_[blockIndex].getSize(); bool isFakeData = p_->blocksMap_[blockIndex].isKnown(); // fake data readCount = src.read(buf, blockSize); byte* blockData = p_->blocksMap_[blockIndex].getData(); for (i = 0; (i < readCount) && (i < blockSize) && !findDiff; i++) { if ((!isFakeData && buf[i] != blockData[i]) || (isFakeData && buf[i] != 0)) { findDiff = true; } else { left++; } } blockIndex++; } // find $right findDiff = false; blockIndex = nBlocks - 1; blockSize = p_->blocksMap_[blockIndex].getSize(); while ((blockIndex + 1 > 0) && right < src.size() && !findDiff) { if(src.seek(-1 * (blockSize + right), BasicIo::end)) { findDiff = true; } else { bool isFakeData = p_->blocksMap_[blockIndex].isKnown(); // fake data readCount = src.read(buf, blockSize); byte* blockData = p_->blocksMap_[blockIndex].getData(); for (i = 0; (i < readCount) && (i < blockSize) && !findDiff; i++) { if ((!isFakeData && buf[readCount - i - 1] != blockData[blockSize - i - 1]) || (isFakeData && buf[readCount - i - 1] != 0)) { findDiff = true; } else { right++; } } } blockIndex--; blockSize = (long)p_->blocksMap_[blockIndex].getSize(); } // free buf if (buf) std::free(buf); // submit to the remote machine. long dataSize = src.size() - left - right; if (dataSize > 0) { byte* data = (byte*) std::malloc(dataSize); src.seek(left, BasicIo::beg); src.read(data, dataSize); p_->writeRemote(data, (size_t)dataSize, left, (long) p_->size_ - right); if (data) std::free(data); } return src.size(); } int RemoteIo::putb(byte /*unused data*/) { return 0; } DataBuf RemoteIo::read(long rcount) { DataBuf buf(rcount); long readCount = read(buf.pData_, buf.size_); buf.size_ = readCount; return buf; } long RemoteIo::read(byte* buf, long rcount) { assert(p_->isMalloced_); if (p_->eof_) return 0; p_->totalRead_ += rcount; size_t allow = EXV_MIN(rcount, (long)( p_->size_ - p_->idx_)); size_t lowBlock = p_->idx_ /p_->blockSize_; size_t highBlock = (p_->idx_ + allow)/p_->blockSize_; // connect to the remote machine & populate the blocks just in time. p_->populateBlocks(lowBlock, highBlock); byte* fakeData = (byte*) std::calloc(p_->blockSize_, sizeof(byte)); if (!fakeData) { throw Error(1, "Unable to allocate data"); } size_t iBlock = lowBlock; size_t startPos = p_->idx_ - lowBlock*p_->blockSize_; size_t totalRead = 0; do { byte* data = p_->blocksMap_[iBlock++].getData(); if (data == NULL) data = fakeData; size_t blockR = EXV_MIN(allow, p_->blockSize_ - startPos); std::memcpy(&buf[totalRead], &data[startPos], blockR); totalRead += blockR; startPos = 0; allow -= blockR; } while(allow); if (fakeData) std::free(fakeData); p_->idx_ += (long) totalRead; p_->eof_ = (p_->idx_ == (long) p_->size_); return (long) totalRead; } int RemoteIo::getb() { assert(p_->isMalloced_); if (p_->idx_ == (long)p_->size_) { p_->eof_ = true; return EOF; } size_t expectedBlock = (p_->idx_ + 1)/p_->blockSize_; // connect to the remote machine & populate the blocks just in time. p_->populateBlocks(expectedBlock, expectedBlock); byte* data = p_->blocksMap_[expectedBlock].getData(); return data[p_->idx_++ - expectedBlock*p_->blockSize_]; } void RemoteIo::transfer(BasicIo& src) { if (src.open() != 0) { throw Error(1, "unable to open src when transferring"); } write(src); src.close(); } #if defined(_MSC_VER) int RemoteIo::seek( int64_t offset, Position pos ) { assert(p_->isMalloced_); uint64_t newIdx = 0; switch (pos) { case BasicIo::cur: newIdx = p_->idx_ + offset; break; case BasicIo::beg: newIdx = offset; break; case BasicIo::end: newIdx = p_->size_ + offset; break; } if ( /*newIdx < 0 || */ newIdx > static_cast<uint64_t>(p_->size_) ) return 1; p_->idx_ = static_cast<long>(newIdx); //not very sure about this. need more test!! - note by Shawn fly2xj@gmail.com //TODO p_->eof_ = false; return 0; } #else int RemoteIo::seek(long offset, Position pos) { assert(p_->isMalloced_); long newIdx = 0; switch (pos) { case BasicIo::cur: newIdx = p_->idx_ + offset; break; case BasicIo::beg: newIdx = offset; break; case BasicIo::end: newIdx = p_->size_ + offset; break; } // #1198. Don't return 1 when asked to seek past EOF. Stay calm and set eof_ // if (newIdx < 0 || newIdx > (long) p_->size_) return 1; p_->idx_ = newIdx; p_->eof_ = newIdx > (long) p_->size_; if ( p_->idx_ > (long) p_->size_ ) p_->idx_= (long) p_->size_; return 0; } #endif byte* RemoteIo::mmap(bool /*isWriteable*/) { size_t nRealData = 0 ; if ( !bigBlock_ ) { size_t blockSize = p_->blockSize_; size_t blocks = (p_->size_ + blockSize -1)/blockSize ; bigBlock_ = new byte[blocks*blockSize] ; for ( size_t block = 0 ; block < blocks ; block ++ ) { void* p = p_->blocksMap_[block].getData(); if ( p ) { nRealData += blockSize ; memcpy(bigBlock_+(block*blockSize),p,blockSize); } } #ifdef DEBUG std::cerr << "RemoteIo::mmap nRealData = " << nRealData << std::endl; #endif } return bigBlock_; } int RemoteIo::munmap() { return 0; } long RemoteIo::tell() const { return p_->idx_; } size_t RemoteIo::size() const { return (long) p_->size_; } bool RemoteIo::isopen() const { return p_->isMalloced_; } int RemoteIo::error() const { return 0; } bool RemoteIo::eof() const { return p_->eof_; } std::string RemoteIo::path() const { return p_->path_; } #ifdef EXV_UNICODE_PATH std::wstring RemoteIo::wpath() const { return p_->wpath_; } #endif void RemoteIo::populateFakeData() { assert(p_->isMalloced_); size_t nBlocks = (p_->size_ + p_->blockSize_ - 1) / p_->blockSize_; for (size_t i = 0; i < nBlocks; i++) { if (p_->blocksMap_[i].isNone()) p_->blocksMap_[i].markKnown(p_->blockSize_); } } //! Internal Pimpl structure of class HttpIo. class HttpIo::HttpImpl : public Impl { public: //! Constructor HttpImpl(const std::string& path, size_t blockSize); #ifdef EXV_UNICODE_PATH //! Constructor accepting a unicode path in an std::wstring HttpImpl(const std::wstring& wpath, size_t blockSize); #endif Exiv2::Uri hostInfo_; //!< the host information extracted from the path // METHODS /*! @brief Get the length (in bytes) of the remote file. @return Return -1 if the size is unknown. Otherwise it returns the length of remote file (in bytes). @throw Error if the server returns the error code. */ long getFileLength(); /*! @brief Get the data by range. @param lowBlock The start block index. @param highBlock The end block index. @param response The data from the server. @throw Error if the server returns the error code. @note Set lowBlock = -1 and highBlock = -1 to get the whole file content. */ void getDataByRange(long lowBlock, long highBlock, std::string& response); /*! @brief Submit the data to the remote machine. The data replace a part of the remote file. The replaced part of remote file is indicated by from and to parameters. @param data The data are submitted to the remote machine. @param size The size of data. @param from The start position in the remote file where the data replace. @param to The end position in the remote file where the data replace. @note The data are submitted to the remote machine via POST. This requires the script file on the remote machine to receive the data and edit the remote file. The server-side script may be specified with the environment string EXIV2_HTTP_POST. The default value is "/exiv2.php". More info is available at http://dev.exiv2.org/wiki/exiv2 @throw Error if it fails. */ void writeRemote(const byte* data, size_t size, long from, long to); protected: // NOT IMPLEMENTED HttpImpl(const HttpImpl& rhs); //!< Copy constructor HttpImpl& operator=(const HttpImpl& rhs); //!< Assignment }; // class HttpIo::HttpImpl HttpIo::HttpImpl::HttpImpl(const std::string& url, size_t blockSize):Impl(url, blockSize) { hostInfo_ = Exiv2::Uri::Parse(url); Exiv2::Uri::Decode(hostInfo_); } #ifdef EXV_UNICODE_PATH HttpIo::HttpImpl::HttpImpl(const std::wstring& wurl, size_t blockSize):Impl(wurl, blockSize) { std::string url; url.assign(wurl.begin(), wurl.end()); path_ = url; hostInfo_ = Exiv2::Uri::Parse(url); Exiv2::Uri::Decode(hostInfo_); } #endif long HttpIo::HttpImpl::getFileLength() { Exiv2::Dictionary response; Exiv2::Dictionary request; std::string errors; request["server"] = hostInfo_.Host; request["page" ] = hostInfo_.Path; if (hostInfo_.Port != "") request["port"] = hostInfo_.Port; request["verb"] = "HEAD"; long serverCode = (long)http(request, response, errors); if (serverCode < 0 || serverCode >= 400 || errors.compare("") != 0) { throw Error(55, "Server", serverCode); } Exiv2::Dictionary_i lengthIter = response.find("Content-Length"); return (lengthIter == response.end()) ? -1 : atol((lengthIter->second).c_str()); } void HttpIo::HttpImpl::getDataByRange(long lowBlock, long highBlock, std::string& response) { Exiv2::Dictionary responseDic; Exiv2::Dictionary request; request["server"] = hostInfo_.Host; request["page" ] = hostInfo_.Path; if (hostInfo_.Port != "") request["port"] = hostInfo_.Port; request["verb"] = "GET"; std::string errors; if (lowBlock > -1 && highBlock > -1) { std::stringstream ss; ss << "Range: bytes=" << lowBlock * blockSize_ << "-" << ((highBlock + 1) * blockSize_ - 1) << "\r\n"; request["header"] = ss.str(); } long serverCode = (long)http(request, responseDic, errors); if (serverCode < 0 || serverCode >= 400 || errors.compare("") != 0) { throw Error(55, "Server", serverCode); } response = responseDic["body"]; } void HttpIo::HttpImpl::writeRemote(const byte* data, size_t size, long from, long to) { std::string scriptPath(getEnv(envHTTPPOST)); if (scriptPath == "") { throw Error(1, "Please set the path of the server script to handle http post data to EXIV2_HTTP_POST environmental variable."); } // standadize the path without "/" at the beginning. std::size_t protocolIndex = scriptPath.find("://"); if (protocolIndex == std::string::npos && scriptPath[0] != '/') { scriptPath = "/" + scriptPath; } Exiv2::Dictionary response; Exiv2::Dictionary request; std::string errors; Uri scriptUri = Exiv2::Uri::Parse(scriptPath); request["server"] = scriptUri.Host == "" ? hostInfo_.Host : scriptUri.Host; if (scriptUri.Port != "") request["port"] = scriptUri.Port; request["page"] = scriptUri.Path; request["verb"] = "POST"; // encode base64 size_t encodeLength = ((size + 2) / 3) * 4 + 1; char* encodeData = new char[encodeLength]; base64encode(data, size, encodeData, encodeLength); // url encode char* urlencodeData = urlencode(encodeData); delete[] encodeData; std::stringstream ss; ss << "path=" << hostInfo_.Path << "&" << "from=" << from << "&" << "to=" << to << "&" << "data=" << urlencodeData; std::string postData = ss.str(); delete[] urlencodeData; // create the header ss.str(""); ss << "Content-Length: " << postData.length() << "\n" << "Content-Type: application/x-www-form-urlencoded\n" << "\n" << postData << "\r\n"; request["header"] = ss.str(); int serverCode = http(request, response, errors); if (serverCode < 0 || serverCode >= 400 || errors.compare("") != 0) { throw Error(55, "Server", serverCode); } } HttpIo::HttpIo(const std::string& url, size_t blockSize) { p_ = new HttpImpl(url, blockSize); } #ifdef EXV_UNICODE_PATH HttpIo::HttpIo(const std::wstring& wurl, size_t blockSize) { p_ = new HttpImpl(wurl, blockSize); } #endif #if EXV_USE_CURL == 1 //! Internal Pimpl structure of class RemoteIo. class CurlIo::CurlImpl : public Impl { public: //! Constructor CurlImpl(const std::string& path, size_t blockSize); #ifdef EXV_UNICODE_PATH //! Constructor accepting a unicode path in an std::wstring CurlImpl(const std::wstring& wpath, size_t blockSize); #endif //! Destructor. Cleans up the curl pointer and releases all managed memory. ~CurlImpl(); CURL* curl_; //!< libcurl pointer // METHODS /*! @brief Get the length (in bytes) of the remote file. @return Return -1 if the size is unknown. Otherwise it returns the length of remote file (in bytes). @throw Error if the server returns the error code. */ long getFileLength(); /*! @brief Get the data by range. @param lowBlock The start block index. @param highBlock The end block index. @param response The data from the server. @throw Error if the server returns the error code. @note Set lowBlock = -1 and highBlock = -1 to get the whole file content. */ void getDataByRange(long lowBlock, long highBlock, std::string& response); /*! @brief Submit the data to the remote machine. The data replace a part of the remote file. The replaced part of remote file is indicated by from and to parameters. @param data The data are submitted to the remote machine. @param size The size of data. @param from The start position in the remote file where the data replace. @param to The end position in the remote file where the data replace. @throw Error if it fails. @note The write access is only available on HTTP & HTTPS protocols. The data are submitted to server via POST method. It requires the script file on the remote machine to receive the data and edit the remote file. The server-side script may be specified with the environment string EXIV2_HTTP_POST. The default value is "/exiv2.php". More info is available at http://dev.exiv2.org/wiki/exiv2 */ void writeRemote(const byte* data, size_t size, long from, long to); protected: // NOT IMPLEMENTED CurlImpl(const CurlImpl& rhs); //!< Copy constructor CurlImpl& operator=(const CurlImpl& rhs); //!< Assignment private: long timeout_; //!< The number of seconds to wait while trying to connect. }; // class RemoteIo::Impl CurlIo::CurlImpl::CurlImpl(const std::string& url, size_t blockSize):Impl(url, blockSize) { // init curl pointer curl_ = curl_easy_init(); if(!curl_) { throw Error(1, "Uable to init libcurl."); } // The default block size for FTP is much larger than other protocols // the reason is that getDataByRange() in FTP always creates the new connection, // so we need the large block size to reduce the overhead of creating the connection. if (blockSize_ == 0) { blockSize_ = protocol_ == pFtp ? 102400 : 1024; } std::string timeout = getEnv(envTIMEOUT); timeout_ = atol(timeout.c_str()); if (timeout_ == 0) { throw Error(1, "Timeout Environmental Variable must be a positive integer."); } } #ifdef EXV_UNICODE_PATH CurlIo::CurlImpl::CurlImpl(const std::wstring& wurl, size_t blockSize):Impl(wurl, blockSize) { std::string url; url.assign(wurl.begin(), wurl.end()); path_ = url; // init curl pointer curl_ = curl_easy_init(); if(!curl_) { throw Error(1, "Uable to init libcurl."); } // The default block size for FTP is much larger than other protocols // the reason is that getDataByRange() in FTP always creates the new connection, // so we need the large block size to reduce the overhead of creating the connection. if (blockSize_ == 0) { blockSize_ = protocol_ == pFtp ? 102400 : 1024; } } #endif long CurlIo::CurlImpl::getFileLength() { curl_easy_reset(curl_); // reset all options std::string response; curl_easy_setopt(curl_, CURLOPT_URL, path_.c_str()); curl_easy_setopt(curl_, CURLOPT_NOBODY, 1); // HEAD curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curlWriter); curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response); curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, timeout_); //curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1); // debugging mode /* Perform the request, res will get the return code */ CURLcode res = curl_easy_perform(curl_); if(res != CURLE_OK) { // error happends throw Error(1, curl_easy_strerror(res)); } // get return code long returnCode; curl_easy_getinfo (curl_, CURLINFO_RESPONSE_CODE, &returnCode); // get code if (returnCode >= 400 || returnCode < 0) { throw Error(55, "Server", returnCode); } // get length double temp; curl_easy_getinfo(curl_, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &temp); // return -1 if unknown return (long) temp; } void CurlIo::CurlImpl::getDataByRange(long lowBlock, long highBlock, std::string& response) { curl_easy_reset(curl_); // reset all options curl_easy_setopt(curl_, CURLOPT_URL, path_.c_str()); curl_easy_setopt(curl_, CURLOPT_NOPROGRESS, 1L); // no progress meter please curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curlWriter); curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response); curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, timeout_); curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, 0L); //curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1); // debugging mode if (lowBlock > -1 && highBlock> -1) { std::stringstream ss; ss << lowBlock * blockSize_ << "-" << ((highBlock + 1) * blockSize_ - 1); std::string range = ss.str(); curl_easy_setopt(curl_, CURLOPT_RANGE, range.c_str()); } /* Perform the request, res will get the return code */ CURLcode res = curl_easy_perform(curl_); if(res != CURLE_OK) { throw Error(1, curl_easy_strerror(res)); } else { long serverCode; curl_easy_getinfo (curl_, CURLINFO_RESPONSE_CODE, &serverCode); // get code if (serverCode >= 400 || serverCode < 0) { throw Error(55, "Server", serverCode); } } } void CurlIo::CurlImpl::writeRemote(const byte* data, size_t size, long from, long to) { std::string scriptPath(getEnv(envHTTPPOST)); if (scriptPath == "") { throw Error(1, "Please set the path of the server script to handle http post data to EXIV2_HTTP_POST environmental variable."); } Exiv2::Uri hostInfo = Exiv2::Uri::Parse(path_); // add the protocol and host to the path std::size_t protocolIndex = scriptPath.find("://"); if (protocolIndex == std::string::npos) { if (scriptPath[0] != '/') scriptPath = "/" + scriptPath; scriptPath = hostInfo.Protocol + "://" + hostInfo.Host + scriptPath; } curl_easy_reset(curl_); // reset all options curl_easy_setopt(curl_, CURLOPT_NOPROGRESS, 1L); // no progress meter please //curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1); // debugging mode curl_easy_setopt(curl_, CURLOPT_URL, scriptPath.c_str()); curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0L); // encode base64 size_t encodeLength = ((size + 2) / 3) * 4 + 1; char* encodeData = new char[encodeLength]; base64encode(data, size, encodeData, encodeLength); // url encode char* urlencodeData = urlencode(encodeData); delete[] encodeData; std::stringstream ss; ss << "path=" << hostInfo.Path << "&" << "from=" << from << "&" << "to=" << to << "&" << "data=" << urlencodeData; std::string postData = ss.str(); delete[] urlencodeData; curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, postData.c_str()); // Perform the request, res will get the return code. CURLcode res = curl_easy_perform(curl_); if(res != CURLE_OK) { throw Error(1, curl_easy_strerror(res)); } else { long serverCode; curl_easy_getinfo (curl_, CURLINFO_RESPONSE_CODE, &serverCode); if (serverCode >= 400 || serverCode < 0) { throw Error(55, "Server", serverCode); } } } CurlIo::CurlImpl::~CurlImpl() { curl_easy_cleanup(curl_); } long CurlIo::write(const byte* data, long wcount) { if (p_->protocol_ == pHttp || p_->protocol_ == pHttps) { return RemoteIo::write(data, wcount); } else { throw Error(1, "doesnt support write for this protocol."); } } long CurlIo::write(BasicIo& src) { if (p_->protocol_ == pHttp || p_->protocol_ == pHttps) { return RemoteIo::write(src); } else { throw Error(1, "doesnt support write for this protocol."); } } CurlIo::CurlIo(const std::string& url, size_t blockSize) { p_ = new CurlImpl(url, blockSize); } #ifdef EXV_UNICODE_PATH CurlIo::CurlIo(const std::wstring& wurl, size_t blockSize) { p_ = new CurlImpl(wurl, blockSize); } #endif #endif #if EXV_USE_SSH == 1 //! Internal Pimpl structure of class RemoteIo. class SshIo::SshImpl : public Impl { public: //! Constructor SshImpl(const std::string& path, size_t blockSize); #ifdef EXV_UNICODE_PATH //! Constructor accepting a unicode path in an std::wstring SshImpl(const std::wstring& wpath, size_t blockSize); #endif //! Destructor. Closes ssh session and releases all managed memory. ~SshImpl(); Exiv2::Uri hostInfo_; //!< host information extracted from path SSH* ssh_; //!< SSH pointer sftp_file fileHandler_; //!< sftp file handler // METHODS /*! @brief Get the length (in bytes) of the remote file. @return Return -1 if the size is unknown. Otherwise it returns the length of remote file (in bytes). @throw Error if the server returns the error code. */ long getFileLength(); /*! @brief Get the data by range. @param lowBlock The start block index. @param highBlock The end block index. @param response The data from the server. @throw Error if the server returns the error code. @note Set lowBlock = -1 and highBlock = -1 to get the whole file content. */ void getDataByRange(long lowBlock, long highBlock, std::string& response); /*! @brief Submit the data to the remote machine. The data replace a part of the remote file. The replaced part of remote file is indicated by from and to parameters. @param data The data are submitted to the remote machine. @param size The size of data. @param from The start position in the remote file where the data replace. @param to The end position in the remote file where the data replace. @note The write access is only available on the SSH protocol. It requires the write permission to edit the remote file. @throw Error if it fails. */ void writeRemote(const byte* data, size_t size, long from, long to); protected: // NOT IMPLEMENTED SshImpl(const SshImpl& rhs); //!< Copy constructor SshImpl& operator=(const SshImpl& rhs); //!< Assignment }; // class RemoteIo::Impl SshIo::SshImpl::SshImpl(const std::string& url, size_t blockSize):Impl(url, blockSize) { hostInfo_ = Exiv2::Uri::Parse(url); Exiv2::Uri::Decode(hostInfo_); // remove / at the beginning of the path if (hostInfo_.Path[0] == '/') { hostInfo_.Path = hostInfo_.Path.substr(1); } ssh_ = new SSH(hostInfo_.Host, hostInfo_.Username, hostInfo_.Password, hostInfo_.Port); if (protocol_ == pSftp) { ssh_->getFileSftp(hostInfo_.Path, fileHandler_); if (fileHandler_ == NULL) throw Error(1, "Unable to open the file"); } else { fileHandler_ = NULL; } } #ifdef EXV_UNICODE_PATH SshIo::SshImpl::SshImpl(const std::wstring& wurl, size_t blockSize):Impl(wurl, blockSize) { std::string url; url.assign(wurl.begin(), wurl.end()); path_ = url; hostInfo_ = Exiv2::Uri::Parse(url); Exiv2::Uri::Decode(hostInfo_); // remove / at the beginning of the path if (hostInfo_.Path[0] == '/') { hostInfo_.Path = hostInfo_.Path.substr(1); } ssh_ = new SSH(hostInfo_.Host, hostInfo_.Username, hostInfo_.Password, hostInfo_.Port); if (protocol_ == pSftp) { ssh_->getFileSftp(hostInfo_.Path, fileHandler_); if (fileHandler_ == NULL) throw Error(1, "Unable to open the file"); } else { fileHandler_ = NULL; } } #endif long SshIo::SshImpl::getFileLength() { long length = 0; if (protocol_ == pSftp) { // sftp sftp_attributes attributes = sftp_fstat(fileHandler_); length = (long)attributes->size; } else { // ssh std::string response; //std::string cmd = "stat -c %s " + hostInfo_.Path; std::string cmd = "declare -a x=($(ls -alt " + hostInfo_.Path + ")); echo ${x[4]}"; if (ssh_->runCommand(cmd, &response) != 0) { throw Error(1, "Unable to get file length."); } else { length = atol(response.c_str()); if (length == 0) { throw Error(1, "File is empty or not found."); } } } return length; } void SshIo::SshImpl::getDataByRange(long lowBlock, long highBlock, std::string& response) { if (protocol_ == pSftp) { if (sftp_seek(fileHandler_, (uint32_t) (lowBlock * blockSize_)) < 0) throw Error(1, "SFTP: unable to sftp_seek"); size_t buffSize = (highBlock - lowBlock + 1) * blockSize_; char* buffer = new char[buffSize]; long nBytes = (long) sftp_read(fileHandler_, buffer, buffSize); if (nBytes < 0) throw Error(1, "SFTP: unable to sftp_read"); response.assign(buffer, buffSize); delete[] buffer; } else { std::stringstream ss; if (lowBlock > -1 && highBlock > -1) { ss << "dd if=" << hostInfo_.Path << " ibs=" << blockSize_ << " skip=" << lowBlock << " count=" << (highBlock - lowBlock) + 1<< " 2>/dev/null"; } else { ss << "dd if=" << hostInfo_.Path << " ibs=" << blockSize_ << " 2>/dev/null"; } std::string cmd = ss.str(); if (ssh_->runCommand(cmd, &response) != 0) { throw Error(1, "Unable to get data by range."); } } } void SshIo::SshImpl::writeRemote(const byte* data, size_t size, long from, long to) { if (protocol_ == pSftp) throw Error(1, "not support SFTP write access."); //printf("ssh update size=%ld from=%ld to=%ld\n", (long)size, from, to); assert(isMalloced_); std::string tempFile = hostInfo_.Path + ".exiv2tmp"; std::string response; std::stringstream ss; // copy the head (byte 0 to byte fromByte) of original file to filepath.exiv2tmp ss << "head -c " << from << " " << hostInfo_.Path << " > " << tempFile; std::string cmd = ss.str(); if (ssh_->runCommand(cmd, &response) != 0) { throw Error(1, "SSH: Unable to cope the head of file to temp"); } // upload the data (the byte ranges which are different between the original // file and the new file) to filepath.exiv2datatemp if (ssh_->scp(hostInfo_.Path + ".exiv2datatemp", data, size) != 0) { throw Error(1, "SSH: Unable to copy file"); } // concatenate the filepath.exiv2datatemp to filepath.exiv2tmp cmd = "cat " + hostInfo_.Path + ".exiv2datatemp >> " + tempFile; if (ssh_->runCommand(cmd, &response) != 0) { throw Error(1, "SSH: Unable to copy the rest"); } // copy the tail (from byte toByte to the end of file) of original file to filepath.exiv2tmp ss.str(""); ss << "tail -c+" << (to + 1) << " " << hostInfo_.Path << " >> " << tempFile; cmd = ss.str(); if (ssh_->runCommand(cmd, &response) != 0) { throw Error(1, "SSH: Unable to copy the rest"); } // replace the original file with filepath.exiv2tmp cmd = "mv " + tempFile + " " + hostInfo_.Path; if (ssh_->runCommand(cmd, &response) != 0) { throw Error(1, "SSH: Unable to copy the rest"); } // remove filepath.exiv2datatemp cmd = "rm " + hostInfo_.Path + ".exiv2datatemp"; if (ssh_->runCommand(cmd, &response) != 0) { throw Error(1, "SSH: Unable to copy the rest"); } } SshIo::SshImpl::~SshImpl() { if (fileHandler_) sftp_close(fileHandler_); if (ssh_) delete ssh_; } SshIo::SshIo(const std::string& url, size_t blockSize) { p_ = new SshImpl(url, blockSize); } #ifdef EXV_UNICODE_PATH SshIo::SshIo(const std::wstring& wurl, size_t blockSize) { p_ = new SshImpl(wurl, blockSize); } #endif #endif // ************************************************************************* // free functions DataBuf readFile(const std::string& path) { FileIo file(path); if (file.open("rb") != 0) { throw Error(10, path, "rb", strError()); } struct stat st; if (0 != ::stat(path.c_str(), &st)) { throw Error(2, path, strError(), "::stat"); } DataBuf buf(st.st_size); long len = file.read(buf.pData_, buf.size_); if (len != buf.size_) { throw Error(2, path, strError(), "FileIo::read"); } return buf; } #ifdef EXV_UNICODE_PATH DataBuf readFile(const std::wstring& wpath) { FileIo file(wpath); if (file.open("rb") != 0) { throw WError(10, wpath, "rb", strError().c_str()); } struct _stat st; if (0 != ::_wstat(wpath.c_str(), &st)) { throw WError(2, wpath, strError().c_str(), "::_wstat"); } DataBuf buf(st.st_size); long len = file.read(buf.pData_, buf.size_); if (len != buf.size_) { throw WError(2, wpath, strError().c_str(), "FileIo::read"); } return buf; } #endif long writeFile(const DataBuf& buf, const std::string& path) { FileIo file(path); if (file.open("wb") != 0) { throw Error(10, path, "wb", strError()); } return file.write(buf.pData_, buf.size_); } #ifdef EXV_UNICODE_PATH long writeFile(const DataBuf& buf, const std::wstring& wpath) { FileIo file(wpath); if (file.open("wb") != 0) { throw WError(10, wpath, "wb", strError().c_str()); } return file.write(buf.pData_, buf.size_); } #endif std::string ReplaceStringInPlace(std::string subject, const std::string& search, const std::string& replace) { size_t pos = 0; while((pos = subject.find(search, pos)) != std::string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } #ifdef EXV_UNICODE_PATH std::wstring ReplaceStringInPlace(std::wstring subject, const std::wstring& search, const std::wstring& replace) { std::wstring::size_type pos = 0; while((pos = subject.find(search, pos)) != std::wstring::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } #endif #if EXV_USE_CURL == 1 size_t curlWriter(char* data, size_t size, size_t nmemb, std::string* writerData) { if (writerData == NULL) return 0; writerData->append(data, size*nmemb); return size * nmemb; } #endif } // namespace Exiv2
33.977652
163
0.530206
Vitalii17
955e642c5037f566bf8e6c34c4062e4dba681223
1,118
cpp
C++
algorithms/cpp/Problems 101-200/_132_PalindromicPartitioningII.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
algorithms/cpp/Problems 101-200/_132_PalindromicPartitioningII.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
algorithms/cpp/Problems 101-200/_132_PalindromicPartitioningII.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
/* Source - https://leetcode.com/problems/palindrome-partitioning-ii/ Author - Shivam Arora */ #include <bits/stdc++.h> using namespace std; int minCut(string s) { int n = s.length(); bool pre[n][n]; memset(pre, false, sizeof(pre)); for(int k = 0; k < n; k++) { for(int i = 0, j = k; j < n; i++, j++) { if(k == 0) pre[i][j] = true; else if(k == 1) pre[i][j] = s[i] == s[j]; else if(s[i] == s[j]) pre[i][j] = pre[i + 1][j - 1]; } } if(pre[0][n - 1]) return 0; int dp[n]; for(int i = 0; i < n; i++) { if(pre[0][i]) dp[i] = 0; else { dp[i] = INT_MAX; for(int j = i; j > 0; j--) { if(pre[j][i]) dp[i] = min(dp[i], 1 + dp[j - 1]); } } } return dp[n - 1]; } int main() { string s; cout<<"Enter a string: "; cin>>s; cout<<"Minimum cuts in the string such that each part is a palindrome: "<<minCut(s)<<endl; }
21.5
94
0.392665
shivamacs
9560a707872099649b187238b06465d99aae547e
5,616
hpp
C++
SocketAdapter.hpp
Sologala/socket_cvMat
d3ffa4e68badb29f168f955261671ba316ed586b
[ "BSD-2-Clause" ]
null
null
null
SocketAdapter.hpp
Sologala/socket_cvMat
d3ffa4e68badb29f168f955261671ba316ed586b
[ "BSD-2-Clause" ]
null
null
null
SocketAdapter.hpp
Sologala/socket_cvMat
d3ffa4e68badb29f168f955261671ba316ed586b
[ "BSD-2-Clause" ]
null
null
null
#ifndef SOCKETADAPTER_H #define SOCKETADAPTER_H #pragma once #include <arpa/inet.h> #include <sys/socket.h> #include <unistd.h> #include <cstring> #include "msg.pb.h" #define IMG_BUFFER_SIZE 5000 * 5000 * 4 * 3 #define MSG_HEAD_SIZE 8 enum SocketAdapter_Mode { SERVER = 0, CLIENT = 1 }; template <class DATA, class MSG, class WRAPER, class DEWRAPER> class SocketAdapter { public: SocketAdapter(SocketAdapter_Mode _mode, int port = 9999, const char *server_id = NULL); ~SocketAdapter(); bool is_connected() { return connected_; } void Send(DATA data); DATA Recv(); protected: int Create_connection_server(); int Create_connection_client(); protected: int port_; SocketAdapter_Mode mode_; int sock; struct sockaddr_in serv_addr; char target_ip[100]; // for server int opt = 1; bool connected_ = false; private: unsigned char *out_buffer; unsigned char *in_buffer; }; template <class DATA, class MSG, class WRAPER, class DEWRAPER> void SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::Send(DATA data) { if (!connected_) { printf("\n not connected \n"); return; } proto_cv::msgHead msg_head; MSG msg = WRAPER()(data); msg_head.set_len(msg.ByteSize()); memset(out_buffer, 0, IMG_BUFFER_SIZE); msg_head.SerializeToArray(out_buffer, msg_head.ByteSize()); while (send(sock, out_buffer, MSG_HEAD_SIZE, 0) != MSG_HEAD_SIZE) ; // send data assert(msg.ByteSize() <= IMG_BUFFER_SIZE); // cout << msg_head.ByteSize() << " " << msg.ByteSize() << endl; msg.SerializeToArray(out_buffer, msg.ByteSize()); while (send(sock, out_buffer, msg.ByteSize(), 0) != msg.ByteSize()) ; } template <class DATA, class MSG, class WRAPER, class DEWRAPER> DATA SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::Recv() { if (!connected_) { printf("\n not connected \n"); return DATA(); } MSG msg; msg.Clear(); proto_cv::msgHead msg_head; // proto_cv::Mat_Head msg_head; memset(in_buffer, 0, IMG_BUFFER_SIZE); while (recv(sock, in_buffer, MSG_HEAD_SIZE, MSG_WAITALL) != MSG_HEAD_SIZE) ; msg_head.ParseFromArray(in_buffer, MSG_HEAD_SIZE); while (recv(sock, in_buffer, msg_head.len(), MSG_WAITALL) != msg_head.len()) ; msg.ParseFromArray(in_buffer, msg_head.len()); DATA data; data = DEWRAPER()(msg); return data; } template <class DATA, class MSG, class WRAPER, class DEWRAPER> int SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::Create_connection_server() { int server_fd; int opt = 1; int addrlen = sizeof(serv_addr); // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); return -1; } // Forcefully attaching socket to the port 8080 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port_); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { perror("bind failed"); return -1; } if (listen(server_fd, 3) < 0) { perror("listen"); return -1; } // server 的 accept 方法会阻塞 函数 printf("wait for client connection\n"); if ((sock = accept(server_fd, (struct sockaddr *)&serv_addr, (socklen_t *)&addrlen)) < 0) { perror("accept"); return -1; } printf("client connected\n"); return 0; } template <class DATA, class MSG, class WRAPER, class DEWARPRE> int SocketAdapter<DATA, MSG, WRAPER, DEWARPRE>::Create_connection_client() { if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port_); // Convert IPv4 and IPv6 addresses from text to binary form assert(strlen(target_ip) != 0); if (inet_pton(AF_INET, target_ip, &serv_addr.sin_addr) <= 0) { printf("\nInvalid address/ Address not supported \n"); return -1; } int retry_cnt = 1000; while (retry_cnt) { if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); retry_cnt--; usleep(200000); } else { break; } } if (retry_cnt == 0) { printf("\n retry 100 times without success! exit"); return -1; } printf("\n create connection success\n"); return 0; } template <class DATA, class MSG, class WRAPER, class DEWRAPER> SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::SocketAdapter(SocketAdapter_Mode _mode, int port, const char *server_id) : port_(port), mode_(_mode) { bool res = 0; if (_mode == SocketAdapter_Mode::SERVER) { res = Create_connection_server(); } else { memset(target_ip, 0, sizeof(target_ip)); memcpy(target_ip, server_id, strlen(server_id)); res = Create_connection_client(); } if (res == 0) { connected_ = true; } else { connected_ = false; } out_buffer = new unsigned char[IMG_BUFFER_SIZE]; in_buffer = new unsigned char[IMG_BUFFER_SIZE]; } template <class DATA, class MSG, class WRAPER, class DEWRAPER> SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::~SocketAdapter() { delete[] out_buffer; delete[] in_buffer; } #endif
28.507614
116
0.637642
Sologala
956142c39f615464d087e03ddc11dda0ce9545ef
9,468
cpp
C++
unittests/http/test_buffered_reader.cpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
unittests/http/test_buffered_reader.cpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
unittests/http/test_buffered_reader.cpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- unittests/http/test_buffered_reader.cpp ----------------------------===// //* _ __ __ _ _ * //* | |__ _ _ / _|/ _| ___ _ __ ___ __| | _ __ ___ __ _ __| | ___ _ __ * //* | '_ \| | | | |_| |_ / _ \ '__/ _ \/ _` | | '__/ _ \/ _` |/ _` |/ _ \ '__| * //* | |_) | |_| | _| _| __/ | | __/ (_| | | | | __/ (_| | (_| | __/ | * //* |_.__/ \__,_|_| |_| \___|_| \___|\__,_| |_| \___|\__,_|\__,_|\___|_| * //* * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "pstore/http/buffered_reader.hpp" // Standard Library includes #include <algorithm> #include <cerrno> #include <cstring> #include <string> #include <vector> // 3rd party includes #include "gmock/gmock.h" // Local includes #include "buffered_reader_mocks.hpp" using pstore::error_or; using pstore::error_or_n; using pstore::in_place; using pstore::maybe; using pstore::gsl::span; using pstore::http::make_buffered_reader; using testing::_; using testing::Invoke; TEST (HttpdBufferedReader, Span) { using byte_span = pstore::gsl::span<std::uint8_t>; auto refill = [] (int io, byte_span const & sp) { std::fill (std::begin (sp), std::end (sp), std::uint8_t{0}); return pstore::error_or_n<int, byte_span::iterator>{pstore::in_place, io, sp.end ()}; }; constexpr auto buffer_size = std::size_t{0}; constexpr auto requested_size = std::size_t{1}; auto br = pstore::http::make_buffered_reader<int> (refill, buffer_size); std::vector<std::uint8_t> v (requested_size, std::uint8_t{0xFF}); pstore::error_or_n<int, byte_span> res = br.get_span (0, pstore::gsl::make_span (v)); ASSERT_TRUE (res); auto const & sp = std::get<1> (res); ASSERT_EQ (sp.size (), 1); EXPECT_EQ (sp[0], std::uint8_t{0}); } TEST (HttpdBufferedReader, GetcThenEOF) { refiller r; EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ())); EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("a"))); auto io = 0; auto br = make_buffered_reader<int> (r.refill_function ()); { getc_result_type const c1 = br.getc (io); ASSERT_TRUE (static_cast<bool> (c1)); io = std::get<0> (*c1); maybe<char> const char1 = std::get<1> (*c1); ASSERT_TRUE (char1.has_value ()); EXPECT_EQ (char1.value (), 'a'); } { getc_result_type const c2 = br.getc (io); ASSERT_TRUE (static_cast<bool> (c2)); // Uncomment the next line if adding further blocks to this test! // io = std::get<0> (*c2); maybe<char> const char2 = std::get<1> (*c2); ASSERT_FALSE (char2.has_value ()); } } TEST (HttpdBufferedReader, GetTwoStringsLFThenEOF) { refiller r; EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ())); EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\ndef"))); auto io = 0; auto br = make_buffered_reader<int> (r.refill_function ()); { gets_result_type const s1 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s1)); maybe<std::string> str1; std::tie (io, str1) = *s1; ASSERT_TRUE (str1.has_value ()); EXPECT_EQ (str1.value (), "abc"); } { gets_result_type const s2 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s2)); maybe<std::string> str2; std::tie (io, str2) = *s2; ASSERT_TRUE (str2.has_value ()); EXPECT_EQ (str2.value (), "def"); } { gets_result_type const s3 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s3)); maybe<std::string> str3; std::tie (io, str3) = *s3; ASSERT_FALSE (str3.has_value ()); } } TEST (HttpdBufferedReader, StringCRLF) { refiller r; EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ())); EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\r\ndef"))); auto io = 0; auto br = make_buffered_reader<int> (r.refill_function ()); { gets_result_type const s1 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s1)) << "There was an unexpected error: " << s1.get_error (); maybe<std::string> str1; std::tie (io, str1) = *s1; ASSERT_TRUE (str1.has_value ()); EXPECT_EQ (str1.value (), "abc"); } { gets_result_type const s2 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s2)) << "There was an unexpected error: " << s2.get_error (); maybe<std::string> str2; std::tie (io, str2) = *s2; ASSERT_TRUE (str2.has_value ()); EXPECT_EQ (str2.value (), "def"); } { gets_result_type const s3 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s3)) << "There was an unexpected error: " << s3.get_error (); maybe<std::string> str3; std::tie (io, str3) = *s3; ASSERT_FALSE (str3.has_value ()); } } TEST (HttpdBufferedReader, StringCRNoLFThenEOF) { refiller r; EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ())); EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\r"))); auto io = 0; auto br = make_buffered_reader<int> (r.refill_function ()); { gets_result_type const s1 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s1)) << "There was an unexpected error: " << s1.get_error (); maybe<std::string> str1; std::tie (io, str1) = *s1; ASSERT_TRUE (str1.has_value ()); EXPECT_EQ (str1.value (), "abc"); } { gets_result_type const s2 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s2)) << "There was an unexpected error: " << s2.get_error (); maybe<std::string> str2; std::tie (io, str2) = *s2; ASSERT_FALSE (str2.has_value ()); } } TEST (HttpdBufferedReader, StringCRNoLFChars) { refiller r; EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ())); EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\rdef"))); auto io = 0; auto br = make_buffered_reader<int> (r.refill_function ()); { gets_result_type const s1 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s1)) << "There was an unexpected error: " << s1.get_error (); maybe<std::string> str1; std::tie (io, str1) = *s1; ASSERT_TRUE (str1.has_value ()); EXPECT_EQ (str1.value (), "abc"); } { gets_result_type const s2 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s2)) << "There was an unexpected error: " << s2.get_error (); maybe<std::string> str2; std::tie (io, str2) = *s2; ASSERT_TRUE (str2.has_value ()); EXPECT_EQ (str2.value (), "def"); } } TEST (HttpdBufferedReader, SomeCharactersThenAnError) { refiller r; EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\nd"))); EXPECT_CALL (r, fill (1, _)).WillOnce (Invoke ([] (int, span<std::uint8_t> const &) { return refiller_result_type (std::make_error_code (std::errc::operation_not_permitted)); })); auto io = 0; auto br = make_buffered_reader<int> (r.refill_function ()); { gets_result_type const s1 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s1)) << "Error: " << s1.get_error (); maybe<std::string> str1; std::tie (io, str1) = *s1; ASSERT_TRUE (str1.has_value ()); EXPECT_EQ (str1.value (), "abc"); } { gets_result_type const s2 = br.gets (io); ASSERT_FALSE (static_cast<bool> (s2)) << "An error was expected"; EXPECT_EQ (s2.get_error (), (std::make_error_code (std::errc::operation_not_permitted))); } } TEST (HttpdBufferedReader, MaxLengthString) { using pstore::http::max_string_length; std::string const max_length_string (max_string_length, 'a'); refiller r; EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ())); EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string (max_length_string))); auto io = 0; auto br = make_buffered_reader<int> (r.refill_function (), max_string_length); error_or_n<int, maybe<std::string>> const s1 = br.gets (io); ASSERT_TRUE (static_cast<bool> (s1)) << "Error: " << s1.get_error (); maybe<std::string> str1; std::tie (io, str1) = *s1; ASSERT_TRUE (str1.has_value ()); EXPECT_EQ (str1.value (), max_length_string); } TEST (HttpdBufferedReader, StringTooLong) { using pstore::http::max_string_length; refiller r; EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ())); EXPECT_CALL (r, fill (0, _)) .WillOnce (Invoke (yield_string (std::string (max_string_length + 1U, 'a')))); auto io = 0; auto br = make_buffered_reader<int> (r.refill_function (), max_string_length + 1U); error_or_n<int, maybe<std::string>> const s2 = br.gets (io); EXPECT_EQ (s2.get_error (), make_error_code (pstore::http::error_code::string_too_long)); }
36.555985
97
0.575201
paulhuggett
956792a122ceac7ce969482efac081aae8ce55b1
15,229
cpp
C++
windows/subwnd/dclock.cpp
whitehara/NP2kai
72117d7a5def7e6c735f6780d53322c044e2b1d3
[ "MIT" ]
170
2017-08-15T17:02:36.000Z
2022-03-30T20:02:26.000Z
windows/subwnd/dclock.cpp
whitehara/NP2kai
72117d7a5def7e6c735f6780d53322c044e2b1d3
[ "MIT" ]
138
2017-07-09T13:18:51.000Z
2022-03-20T17:53:43.000Z
windows/subwnd/dclock.cpp
whitehara/NP2kai
72117d7a5def7e6c735f6780d53322c044e2b1d3
[ "MIT" ]
53
2017-07-17T10:27:42.000Z
2022-03-15T01:09:05.000Z
/** * @file dclock.cpp * @brief 時刻表示クラスの動作の定義を行います */ #include <compiler.h> #include "dclock.h" #include <common/parts.h> #include <np2.h> #include <scrnmng.h> #include <timemng.h> #include <vram/scrndraw.h> #include <vram/palettes.h> //! 唯一のインスタンスです DispClock DispClock::sm_instance; /** * @brief パターン構造体 */ struct DispClockPattern { UINT8 cWidth; /*!< フォント サイズ */ UINT8 cMask; /*!< マスク */ UINT8 cPosition[6]; /*!< 位置 */ void (*fnInitialize)(UINT8* lpBuffer, UINT8 nDegits); /*!< 初期化関数 */ UINT8 font[11][16]; /*!< フォント */ }; /** * 初期化-1 * @param[out] lpBuffer バッファ * @param[in] nDegits 桁数 */ static void InitializeFont1(UINT8* lpBuffer, UINT8 nDegits) { if (nDegits) { const UINT32 pat = (nDegits <= 4) ? 0x00008001 : 0x30008001; *(UINT32 *)(lpBuffer + 1 + ( 4 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + ( 5 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat; } } /** * 初期化-2 * @param[out] lpBuffer バッファ * @param[in] nDegits 桁数 */ static void InitializeFont2(UINT8* lpBuffer, UINT8 nDegits) { if (nDegits) { UINT32 pat = (nDegits <= 4) ? 0x00000002 : 0x00020002; *(UINT32 *)(lpBuffer + 1 + ( 4 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + ( 5 * DCLOCK_YALIGN)) = pat; pat <<= 1; *(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat; } } /** * 初期化-3 * @param[out] lpBuffer バッファ * @param[in] nDegits 桁数 */ static void InitializeFont3(UINT8* lpBuffer, UINT8 nDegits) { if (nDegits) { const UINT32 pat = (nDegits <= 4) ? 0x00000010 : 0x00400010; *(UINT32 *)(lpBuffer + 1 + ( 4 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + ( 5 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat; } } /** * 初期化-4 * @param[out] lpBuffer バッファ * @param[in] nDegits 桁数 */ static void InitializeFont4(UINT8* lpBuffer, UINT8 nDegits) { if (nDegits) { const UINT32 pat = (nDegits <= 4) ? 0x00000004 : 0x00040004; *(UINT32 *)(lpBuffer + 1 + ( 5 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + ( 6 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat; } } /** * 初期化-5 * @param[out] lpBuffer バッファ * @param[in] nDegits 桁数 */ static void InitializeFont5(UINT8* lpBuffer, UINT8 nDegits) { if (nDegits) { const UINT32 pat = (nDegits <= 4) ? 0x00000006 : 0x00030006; *(UINT32 *)(lpBuffer + 1 + ( 6 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + ( 7 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat; } } /** * 初期化-6 * @param[out] lpBuffer バッファ * @param[in] nDegits 桁数 */ static void InitializeFont6(UINT8* lpBuffer, UINT8 nDegits) { if (nDegits) { const UINT32 pat = (nDegits <= 4) ? 0x00000020 : 0x00000220; *(UINT32 *)(lpBuffer + 1 + ( 8 * DCLOCK_YALIGN)) = pat; *(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat; } } /** * パターン */ static const DispClockPattern s_pattern[6] = { // FONT-1 { 6, 0xfc, {0, 7, 19, 26, 38, 45}, InitializeFont1, { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}, {0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x78,}, {0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,}, {0x78, 0xcc, 0xcc, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0xfc,}, {0xfc, 0x18, 0x30, 0x70, 0x18, 0x0c, 0x0c, 0xcc, 0x78,}, {0x18, 0x38, 0x78, 0xd8, 0xd8, 0xfc, 0x18, 0x18, 0x18,}, {0xfc, 0xc0, 0xc0, 0xf8, 0x0c, 0x0c, 0x0c, 0x8c, 0x78,}, {0x38, 0x60, 0xc0, 0xf8, 0xcc, 0xcc, 0xcc, 0xcc, 0x78,}, {0xfc, 0x0c, 0x0c, 0x18, 0x18, 0x18, 0x30, 0x30, 0x30,}, {0x78, 0xcc, 0xcc, 0xcc, 0x78, 0xcc, 0xcc, 0xcc, 0x78,}, {0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0x18, 0x70,} } }, // FONT-2 { 6, 0xfc, {0, 6, 16, 22, 32, 38}, InitializeFont2, { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}, {0x00, 0x00, 0x30, 0x48, 0x88, 0x88, 0x88, 0x88, 0x70,}, {0x10, 0x30, 0x10, 0x10, 0x10, 0x20, 0x20, 0x20, 0x20,}, {0x38, 0x44, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xf8,}, {0x7c, 0x08, 0x10, 0x30, 0x10, 0x08, 0x08, 0x90, 0x60,}, {0x20, 0x40, 0x40, 0x88, 0x88, 0x90, 0x78, 0x10, 0x20,}, {0x3c, 0x20, 0x20, 0x70, 0x08, 0x08, 0x08, 0x90, 0x60,}, {0x10, 0x10, 0x20, 0x70, 0x48, 0x88, 0x88, 0x90, 0x60,}, {0x7c, 0x04, 0x08, 0x08, 0x10, 0x10, 0x20, 0x20, 0x40,}, {0x38, 0x44, 0x44, 0x48, 0x30, 0x48, 0x88, 0x88, 0x70,}, {0x18, 0x24, 0x40, 0x44, 0x48, 0x38, 0x10, 0x20, 0x20,} } }, // FONT-3 { 4, 0xf0, {0, 5, 14, 19, 28, 33}, InitializeFont3, { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}, {0x60, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x60,}, {0x20, 0x60, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,}, {0x60, 0x90, 0x90, 0x10, 0x20, 0x40, 0x40, 0x80, 0xf0,}, {0x60, 0x90, 0x90, 0x10, 0x60, 0x10, 0x90, 0x90, 0x60,}, {0x20, 0x60, 0x60, 0xa0, 0xa0, 0xa0, 0xf0, 0x20, 0x20,}, {0xf0, 0x80, 0x80, 0xe0, 0x90, 0x10, 0x90, 0x90, 0x60,}, {0x60, 0x90, 0x90, 0x80, 0xe0, 0x90, 0x90, 0x90, 0x60,}, {0xf0, 0x10, 0x10, 0x20, 0x20, 0x20, 0x40, 0x40, 0x40,}, {0x60, 0x90, 0x90, 0x90, 0x60, 0x90, 0x90, 0x90, 0x60,}, {0x60, 0x90, 0x90, 0x90, 0x70, 0x10, 0x90, 0x90, 0x60,} } }, // FONT-4 { 5, 0xf8, {0, 6, 16, 22, 32, 38}, InitializeFont4, { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}, {0x00, 0x70, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x70,}, {0x00, 0x60, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70,}, {0x00, 0x70, 0x88, 0x08, 0x08, 0x30, 0x40, 0x88, 0xf8,}, {0x00, 0x70, 0x88, 0x08, 0x30, 0x08, 0x08, 0x08, 0xf0,}, {0x00, 0x10, 0x30, 0x50, 0x50, 0x90, 0xf8, 0x10, 0x10,}, {0x00, 0x38, 0x40, 0x60, 0x10, 0x08, 0x08, 0x08, 0xf0,}, {0x00, 0x18, 0x20, 0x40, 0xb0, 0xc8, 0x88, 0x88, 0x70,}, {0x00, 0x70, 0x88, 0x88, 0x10, 0x10, 0x10, 0x20, 0x20,}, {0x00, 0x70, 0x88, 0x88, 0x70, 0x50, 0x88, 0x88, 0x70,}, {0x00, 0x70, 0x88, 0x88, 0x88, 0x78, 0x10, 0x20, 0xc0,} } }, // FONT-5 { 5, 0xf8, {0, 6, 17, 23, 34, 40}, InitializeFont5, { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}, {0x00, 0x00, 0x70, 0x88, 0x88, 0x88, 0x88, 0x88, 0x70,}, {0x00, 0x00, 0x20, 0x60, 0x20, 0x20, 0x20, 0x20, 0x20,}, {0x00, 0x00, 0x70, 0x88, 0x08, 0x10, 0x20, 0x40, 0xf8,}, {0x00, 0x00, 0xf8, 0x10, 0x20, 0x10, 0x08, 0x88, 0x70,}, {0x00, 0x00, 0x30, 0x50, 0x50, 0x90, 0xf8, 0x10, 0x10,}, {0x00, 0x00, 0xf8, 0x80, 0xf0, 0x08, 0x08, 0x88, 0x70,}, {0x00, 0x00, 0x30, 0x40, 0xf0, 0x88, 0x88, 0x88, 0x70,}, {0x00, 0x00, 0xf8, 0x08, 0x10, 0x20, 0x20, 0x40, 0x40,}, {0x00, 0x00, 0x70, 0x88, 0x88, 0x70, 0x88, 0x88, 0x70,}, {0x00, 0x00, 0x70, 0x88, 0x88, 0x88, 0x78, 0x10, 0x60,} } }, // FONT-6 { 4, 0xf0, {0, 5, 12, 17, 24, 29}, InitializeFont6, { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}, {0x00, 0x00, 0x00, 0x60, 0x90, 0x90, 0x90, 0x90, 0x60,}, {0x00, 0x00, 0x00, 0x20, 0x60, 0x20, 0x20, 0x20, 0x20,}, {0x00, 0x00, 0x00, 0x60, 0x90, 0x10, 0x20, 0x40, 0xf0,}, {0x00, 0x00, 0x00, 0xf0, 0x20, 0x60, 0x10, 0x90, 0x60,}, {0x00, 0x00, 0x00, 0x40, 0x80, 0xa0, 0xa0, 0xf0, 0x20,}, {0x00, 0x00, 0x00, 0xf0, 0x80, 0x60, 0x10, 0x90, 0x60,}, {0x00, 0x00, 0x00, 0x40, 0x80, 0xe0, 0x90, 0x90, 0x60,}, {0x00, 0x00, 0x00, 0xe0, 0x10, 0x10, 0x20, 0x20, 0x40,}, {0x00, 0x00, 0x00, 0x60, 0x90, 0x60, 0x90, 0x90, 0x60,}, {0x00, 0x00, 0x00, 0x60, 0x90, 0x90, 0x70, 0x20, 0x40,} } } }; /** * コンストラクタ */ DispClock::DispClock() { ZeroMemory(this, sizeof(*this)); } /** * 初期化 */ void DispClock::Initialize() { ::pal_makegrad(m_pal32, 4, np2oscfg.clk_color1, np2oscfg.clk_color2); } /** * パレット設定 * @param[in] bpp 色 */ void DispClock::SetPalettes(UINT bpp) { switch (bpp) { case 8: SetPalette8(); break; case 16: SetPalette16(); break; } } /** * 8bpp パレット設定 */ void DispClock::SetPalette8() { for (UINT i = 0; i < 16; i++) { UINT nBits = 0; for (UINT j = 1; j < 0x10; j <<= 1) { nBits <<= 8; if (i & j) { nBits |= 1; } } for (UINT j = 0; j < 4; j++) { m_pal8[j][i] = nBits * (START_PALORG + j); } } } /** * 16bpp パレット設定 */ void DispClock::SetPalette16() { for (UINT i = 0; i < 4; i++) { m_pal16[i] = scrnmng_makepal16(m_pal32[i]); } } /** * リセット */ void DispClock::Reset() { if (np2oscfg.clk_x) { if (np2oscfg.clk_x <= 4) { np2oscfg.clk_x = 4; } else if (np2oscfg.clk_x <= 6) { np2oscfg.clk_x = 6; } else { np2oscfg.clk_x = 0; } } if (np2oscfg.clk_fnt >= _countof(s_pattern)) { np2oscfg.clk_fnt = 0; } ZeroMemory(m_cTime, sizeof(m_cTime)); ZeroMemory(m_cLastTime, sizeof(m_cLastTime)); ZeroMemory(m_buffer, sizeof(m_buffer)); m_pPattern = &s_pattern[np2oscfg.clk_fnt]; m_cCharaters = np2oscfg.clk_x; (*m_pPattern->fnInitialize)(m_buffer, m_cCharaters); Update(); Redraw(); } /** * 更新 */ void DispClock::Update() { if ((scrnmng_isfullscreen()) && (m_cCharaters)) { _SYSTIME st; timemng_gettime(&st); UINT8 buf[6]; buf[0] = (st.hour / 10) + 1; buf[1] = (st.hour % 10) + 1; buf[2] = (st.minute / 10) + 1; buf[3] = (st.minute % 10) + 1; if (m_cCharaters > 4) { buf[4] = (st.second / 10) + 1; buf[5] = (st.second % 10) + 1; } UINT8 count = 13; for (int i = m_cCharaters; i--; ) { if (m_cTime[i] != buf[i]) { m_cTime[i] = buf[i]; m_nCounter.b[i] = count; m_cDirty |= (1 << i); count += 4; } } } } /** * 再描画 */ void DispClock::Redraw() { m_cDirty = 0x3f; } /** * 描画が必要? * @retval true 描画中 * @retval false 非描画 */ bool DispClock::IsDisplayed() const { return ((m_cDirty != 0) || (m_nCounter.q != 0)); } //! オフセット テーブル static const UINT8 s_dclocky[13] = {0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3}; /** * 位置計算 * @param[in] nCount カウント値 * @return オフセット */ UINT8 DispClock::CountPos(UINT nCount) { if (nCount < _countof(s_dclocky)) { return s_dclocky[nCount]; } else { return 255; } } /** * カウントダウン処理 * @param[in] nFrames フレーム数 */ void DispClock::CountDown(UINT nFrames) { if ((m_cCharaters == 0) || (m_nCounter.q == 0)) { return; } if (nFrames == 0) { nFrames = 1; } for (UINT i = 0; i < m_cCharaters; i++) { UINT nRemain = m_nCounter.b[i]; if (nRemain == 0) { continue; } const UINT8 y = CountPos(nRemain); if (nFrames < nRemain) { nRemain -= nFrames; } else { nRemain = 0; } if (y != CountPos(nRemain)) { m_cDirty |= (1 << i); } m_nCounter.b[i] = nRemain; } } /** * バッファに描画 * @retval true 更新あり * @retval false 更新なし */ bool DispClock::Make() { if ((m_cCharaters == 0) || (m_cDirty == 0)) { return false; } for (UINT i = 0; i < m_cCharaters; i++) { if ((m_cDirty & (1 << i)) == 0) { continue; } UINT nNumber = m_cTime[i]; UINT nPadding = 3; const UINT nRemain = m_nCounter.b[i]; if (nRemain == 0) { m_cLastTime[i] = nNumber; } else if (nRemain < _countof(s_dclocky)) { nPadding -= s_dclocky[nRemain]; } else { nNumber = this->m_cLastTime[i]; } UINT8* q = m_buffer + (m_pPattern->cPosition[i] >> 3); const UINT8 cShifter = m_pPattern->cPosition[i] & 7; const UINT8 cMask0 = ~(m_pPattern->cMask >> cShifter); const UINT8 cMask1 = ~(m_pPattern->cMask << (8 - cShifter)); for (UINT y = 0; y < nPadding; y++) { q[0] = (q[0] & cMask0); q[1] = (q[1] & cMask1); q += DCLOCK_YALIGN; } const UINT8* p = m_pPattern->font[nNumber]; for (UINT y = 0; y < 9; y++) { q[0] = (q[0] & cMask0) | (p[y] >> cShifter); q[1] = (q[1] & cMask1) | (p[y] << (8 - cShifter)); q += DCLOCK_YALIGN; } } m_cDirty = 0; return true; } /** * 描画 * @param[in] nBpp 色数 * @param[out] lpBuffer 描画ポインタ * @param[in] nYAlign アライメント */ void DispClock::Draw(UINT nBpp, void* lpBuffer, int nYAlign) const { switch (nBpp) { case 8: Draw8(lpBuffer, nYAlign); break; case 16: Draw16(lpBuffer, nYAlign); break; case 24: Draw24(lpBuffer, nYAlign); break; case 32: Draw32(lpBuffer, nYAlign); break; } } /** * 描画(8bpp) * @param[out] lpBuffer 描画ポインタ * @param[in] nYAlign アライメント */ void DispClock::Draw8(void* lpBuffer, int nYAlign) const { const UINT8* p = m_buffer; for (UINT i = 0; i < 4; i++) { const UINT32* pPattern = m_pal8[i]; for (UINT j = 0; j < 3; j++) { for (UINT x = 0; x < DCLOCK_YALIGN; x++) { (static_cast<UINT32*>(lpBuffer))[x * 2 + 0] = pPattern[p[x] >> 4]; (static_cast<UINT32*>(lpBuffer))[x * 2 + 1] = pPattern[p[x] & 15]; } p += DCLOCK_YALIGN; lpBuffer = reinterpret_cast<void*>(reinterpret_cast<INTPTR>(lpBuffer) + nYAlign); } } } /** * 描画(16bpp) * @param[out] lpBuffer 描画ポインタ * @param[in] nYAlign アライメント */ void DispClock::Draw16(void* lpBuffer, int nYAlign) const { const UINT8* p = m_buffer; for (UINT i = 0; i < 4; i++) { const RGB16 pal = m_pal16[i]; for (UINT j = 0; j < 3; j++) { for (UINT x = 0; x < (8 * DCLOCK_YALIGN); x++) { (static_cast<UINT16*>(lpBuffer))[x] = (p[x >> 3] & (0x80 >> (x & 7))) ? pal : 0; } p += DCLOCK_YALIGN; lpBuffer = reinterpret_cast<void*>(reinterpret_cast<INTPTR>(lpBuffer) + nYAlign); } } } /** * 描画(24bpp) * @param[out] lpBuffer 描画ポインタ * @param[in] nYAlign アライメント */ void DispClock::Draw24(void* lpBuffer, int nYAlign) const { const UINT8* p = m_buffer; UINT8* q = static_cast<UINT8*>(lpBuffer); for (UINT i = 0; i < 4; i++) { const RGB32 pal = m_pal32[i]; for (UINT j = 0; j < 3; j++) { for (UINT x = 0; x < (8 * DCLOCK_YALIGN); x++) { if (p[x >> 3] & (0x80 >> (x & 7))) { q[0] = pal.p.b; q[1] = pal.p.g; q[2] = pal.p.g; } else { q[0] = 0; q[1] = 1; q[2] = 2; } q += 3; } p += DCLOCK_YALIGN; q += nYAlign - (8 * DCLOCK_YALIGN) * 3; } } } /** * 描画(32bpp) * @param[out] lpBuffer 描画ポインタ * @param[in] nYAlign アライメント */ void DispClock::Draw32(void* lpBuffer, int nYAlign) const { const UINT8* p = m_buffer; for (UINT i = 0; i < 4; i++) { const UINT32 pal = m_pal32[i].d; for (UINT j = 0; j < 3; j++) { for (UINT x = 0; x < (8 * DCLOCK_YALIGN); x++) { (static_cast<UINT32*>(lpBuffer))[x] = (p[x >> 3] & (0x80 >> (x & 7))) ? pal : 0; } p += DCLOCK_YALIGN; lpBuffer = reinterpret_cast<void*>(reinterpret_cast<INTPTR>(lpBuffer) + nYAlign); } } }
22.729851
85
0.547836
whitehara
9568620f0215bcd0d9656ed4e34466b9dbe3f2a2
394
cpp
C++
SDK/lib/include/global_color.cpp
ghsecuritylab/CppSDK
50da768a887241d4e670b3ef73c041b21645620e
[ "Unlicense" ]
1
2019-12-15T12:26:52.000Z
2019-12-15T12:26:52.000Z
SDK/lib/include/global_color.cpp
ghsecuritylab/CppSDK
50da768a887241d4e670b3ef73c041b21645620e
[ "Unlicense" ]
null
null
null
SDK/lib/include/global_color.cpp
ghsecuritylab/CppSDK
50da768a887241d4e670b3ef73c041b21645620e
[ "Unlicense" ]
1
2020-03-07T20:47:45.000Z
2020-03-07T20:47:45.000Z
/* * include/global_color.cpp */ #include "global.h" Color::ARGB Color::fromArgb(u8 red, u8 green, u8 blue, u8 alpha) { Color::ARGB color; color.R = red; color.G = green; color.B = blue; color.A = alpha; return color; } Color::ARGB Color::fromArgb(u8 red, u8 green, u8 blue) { Color::ARGB color; color.R = red; color.G = green; color.B = blue; color.A = 0xFF; return color; }
15.153846
64
0.64467
ghsecuritylab
956b8a555709785c6b7346a21d97242325e4d89a
1,925
cpp
C++
code/shared/lz4_compressor.cpp
LiamTyler/Progression
35680b47dcd4481fe80e2310c722354ccfa53ed8
[ "MIT" ]
3
2020-01-30T19:20:05.000Z
2021-06-30T13:24:51.000Z
code/shared/lz4_compressor.cpp
LiamTyler/Progression
35680b47dcd4481fe80e2310c722354ccfa53ed8
[ "MIT" ]
1
2021-03-31T16:12:45.000Z
2021-03-31T16:12:45.000Z
code/shared/lz4_compressor.cpp
LiamTyler/Progression
35680b47dcd4481fe80e2310c722354ccfa53ed8
[ "MIT" ]
2
2020-03-30T05:18:46.000Z
2021-03-31T16:13:08.000Z
#include "utils/lz4_compressor.hpp" #include "core/assert.hpp" #include "utils/logger.hpp" #include "lz4/lz4.h" #include "memory_map/MemoryMapped.h" #include <fstream> char* LZ4CompressBuffer( const char* uncompressedData, size_t size, int& compressedSize ) { return nullptr; } char* LZ4DecompressBuffer( const char* compressedData, int compressedSize, int uncompressedSize ) { // char* uncompressedBuffer = (char*) malloc( uncompressedSize ); // const int decompressedSize = LZ4_decompress_safe( compressedData, uncompressedBuffer, compressedSize, uncompressedSize ); return nullptr; } bool LZ4CompressFile( const std::string& inputFilename, const std::string& outputFilename ) { MemoryMapped memMappedFile; if ( !memMappedFile.open( inputFilename, MemoryMapped::WholeFile, MemoryMapped::Normal ) ) { LOG_ERR( "Could not open file: '%s'", inputFilename.c_str() ); return false; } char* src = (char*) memMappedFile.getData(); const int srcSize = (int) memMappedFile.size(); const int maxDstSize = LZ4_compressBound( srcSize ); char* compressedData = (char*) malloc( maxDstSize ); const int compressedDataSize = LZ4_compress_default( src, compressedData, srcSize, maxDstSize ); memMappedFile.close(); if ( compressedDataSize <= 0 ) { LOG_ERR( "Error while trying to compress the file. LZ4 returned: %d", compressedDataSize ); return false; } if ( compressedDataSize > 0 ) { LOG( "Compressed file size ratio: %.3f", (float) compressedDataSize / srcSize ); } std::ofstream out( outputFilename, std::ios::binary ); if ( !out ) { LOG_ERR( "Failed to open file '%s' for writing compressed results", outputFilename.c_str() ); return false; } out.write( (char*)&srcSize, sizeof( srcSize ) ); out.write( compressedData, compressedDataSize ); return true; }
31.557377
128
0.684675
LiamTyler
956d4445e1b746e5786fb41996266325e3d939d4
6,930
cpp
C++
recipes-cbc/cbc/cbc/examples/link.cpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-cbc/cbc/cbc/examples/link.cpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-cbc/cbc/cbc/examples/link.cpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
// Copyright (C) 2005, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #include <cassert> #include <iomanip> #include "CoinPragma.hpp" // For Branch and bound #include "OsiSolverInterface.hpp" #include "CbcModel.hpp" #include "CoinModel.hpp" // For Linked Ordered Sets #include "CbcBranchLink.hpp" #include "OsiClpSolverInterface.hpp" #include "CoinTime.hpp" /************************************************************************ This shows how we can define a new branching method to solve problems with nonlinearities and discontinuities. We are going to solve the problem minimize 10.0*x + y + z - w where x, y are continuous between 1 and 10, z can take the values 0, 0.1, 0.2 up to 1.0 and w can take the values 0 or 1. There is one constraint w <= x*z**2 + y*sqrt(z) One could try to use logarithms to make the problem separable but that is a very weak formulation as we want to branch on z directly. The answer is the concept of linked special ordered sets. The generalization with column generation can be even more powerful but here we are limiting z to discrete values to avoid column generation. The idea is simple: A linear variable is a convex combination of its lower bound and upper bound! If x must lie between 2 and 10 then we can substitute for x as x == 2.0*xl + 10.0*xu where xl + xu == 1.0. At first this looks cumbersome but if we have xl0, xl1, ... xl10 and corresponding xu and yl and yu then we can write: x == sum 2.0*xl[i] + 10.0* xu[i] where sum xl[i] + xu[i] == 1.0 and x*z**2 == 0.02*xl1 + 0.1*xu1 + 0.08*xl2 + 0.4*xu2 .... + 2.0*xl10 + 10.0*xu10 with similar substitutions for y and y*sqrt(z) And now the problem is satisfied if w is 0 or 1 and xl[i], xu[i], yl[i] and yu[i] are only nonzero for one i. So this is just like a special ordered set of type 1 but on four sets simultaneously. Also note that convexity requirements for any non-linear functions are not needed. So we need a new branching method to do that - see CbcBranchLink.?pp We are going to need a CbcBranchLink method to see whether we are satisfied etc and also to create another branching object which knows how to fix variables. We might be able to use an existing method for the latter but let us create two methods CbcLink and CbcLinkBranchingObject. For CbcLink we will need the following methods: Constructot/Destructor infeasibility - returns 0.0 if feasible otherwise some measure of infeasibility feasibleRegion - sets bounds to contain current solution createBranch - creates a CbcLinkBranchingObject For CbcLinkBranchingObject we need: Constructor/Destructor branch - does actual fixing print - optional for debug purposes. The easiest way to do this is to cut and paste from CbcBranchActual to get current SOS stuff and then modify that. ************************************************************************/ int main(int argc, const char *argv[]) { OsiClpSolverInterface solver1; // Create model CoinModel build; // Keep x,y and z for reporting purposes in rows 0,1,2 // Do these double value = 1.0; int row = -1; // x row = 0; build.addColumn(1, &row, &value, 1.0, 10.0, 10.0); // y row = 1; build.addColumn(1, &row, &value, 1.0, 10.0, 1.0); // z row = 2; build.addColumn(1, &row, &value, 0.0, 1.0, 1.0); // w row = 3; build.addColumn(1, &row, &value, 0.0, 1.0, -1.0); build.setInteger(3); // Do columns so we know where each is int i; for (i = 4; i < 4 + 44; i++) build.setColumnBounds(i, 0.0, 1.0); // Now do rows // x build.setRowBounds(0, 0.0, 0.0); for (i = 0; i < 11; i++) { // xl build.setElement(0, 4 + 4 * i, -1.0); // xu build.setElement(0, 4 + 4 * i + 1, -10.0); } // y build.setRowBounds(1, 0.0, 0.0); for (i = 0; i < 11; i++) { // yl build.setElement(1, 4 + 4 * i + 2, -1.0); // yu build.setElement(1, 4 + 4 * i + 3, -10.0); } // z - just use x part build.setRowBounds(2, 0.0, 0.0); for (i = 0; i < 11; i++) { // xl build.setElement(2, 4 + 4 * i, -0.1 * i); // xu build.setElement(2, 4 + 4 * i + 1, -0.1 * i); } // w <= x*z**2 + y* sqrt(z) build.setRowBounds(3, -COIN_DBL_MAX, 0.0); for (i = 0; i < 11; i++) { double value = 0.1 * i; // xl * z**2 build.setElement(3, 4 + 4 * i, -1.0 * value * value); // xu * z**2 build.setElement(3, 4 + 4 * i + 1, -10.0 * value * value); // yl * sqrt(z) build.setElement(3, 4 + 4 * i + 2, -1.0 * sqrt(value)); // yu * sqrt(z) build.setElement(3, 4 + 4 * i + 3, -10.0 * sqrt(value)); } // and convexity for x and y // x build.setRowBounds(4, 1.0, 1.0); for (i = 0; i < 11; i++) { // xl build.setElement(4, 4 + 4 * i, 1.0); // xu build.setElement(4, 4 + 4 * i + 1, 1.0); } // y build.setRowBounds(5, 1.0, 1.0); for (i = 0; i < 11; i++) { // yl build.setElement(5, 4 + 4 * i + 2, 1.0); // yu build.setElement(5, 4 + 4 * i + 3, 1.0); } solver1.loadFromCoinModel(build); // To make CbcBranchLink simpler assume that all variables with same i are consecutive double time1 = CoinCpuTime(); solver1.initialSolve(); solver1.writeMps("bad"); CbcModel model(solver1); model.solver()->setHintParam(OsiDoReducePrint, true, OsiHintTry); // Although just one set - code as if more CbcObject **objects = new CbcObject *[1]; /* Format is number in sets, number in each link, first variable in matrix) and then a weight for each in set to say where to branch. Finally a set number as ID. */ double where[] = { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 }; objects[0] = new CbcLink(&model, 11, 4, 4, where, 0); model.addObjects(1, objects); delete objects[0]; delete[] objects; // Do complete search model.branchAndBound(); std::cout << "took " << CoinCpuTime() - time1 << " seconds, " << model.getNodeCount() << " nodes with objective " << model.getObjValue() << (!model.status() ? " Finished" : " Not finished") << std::endl; if (model.getMinimizationObjValue() < 1.0e50) { const double *solution = model.bestSolution(); // check correct int which = -1; for (int i = 0; i < 11; i++) { for (int j = 4 + 4 * i; j < 4 + 4 * i + 4; j++) { double value = solution[j]; if (fabs(value) > 1.0e-7) { if (which == -1) which = i; else assert(which == i); } } } double x = solution[0]; double y = solution[1]; double z = solution[2]; double w = solution[3]; // check z assert(fabs(z - 0.1 * ((double)which)) < 1.0e-7); printf("Optimal solution when x is %g, y %g, z %g and w %g\n", x, y, z, w); printf("solution should be %g\n", 10.0 * x + y + z - w); } return 0; }
31.5
99
0.607504
Justin790126
956e8b30e37e2abf5f9820a5a43f4be46f879c76
1,641
cpp
C++
HW1/Problem 2/main.cpp
alakh125/csci2270
84c5f34721f67604c5ddc9ac6028d42f9ee1813f
[ "MIT" ]
null
null
null
HW1/Problem 2/main.cpp
alakh125/csci2270
84c5f34721f67604c5ddc9ac6028d42f9ee1813f
[ "MIT" ]
null
null
null
HW1/Problem 2/main.cpp
alakh125/csci2270
84c5f34721f67604c5ddc9ac6028d42f9ee1813f
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <sstream> struct Park{ std::string parkname; std::string state; int area; }; void addPark (Park parks[], std::string parkname, std::string state, int area, int length); void printList(const Park parks[], int length); using namespace std; int main(int argc, char** argv){ string iFileName = argv[0]; string oFileName = argv[1]; int lowerBound = stoi(argv[2]); int upperBound = stoi(argv[3]); Park parks[100]; ifstream iFile; iFile.open(iFileName); string line,parkname,state,areaTemp; int area; int i = 0; while(getline(iFile,line)){ istringstream s(line); getline(s,parkname,','); getline(s,state,','); getline(s,areaTemp,','); area = stoi(areaTemp); addPark(parks,parkname,state,area,i); i++; } printList(parks, i); ofstream oFile; oFile.open(oFileName); for(int j = 0; j < i; j++){ Park a = parks[j]; if(a.area >= lowerBound && a.area <= upperBound){ oFile << a.parkname << ',' << a.state << ',' << a.area << endl; } } } void addPark(Park parks[], string parkname, string state, int area, int length){ Park a; a.parkname = parkname; a.state = state; a.area = area; parks[length] = a; } using namespace std; void printList(const Park parks[], int length){ for(int i = 0; i < length; i++){ Park a = parks[i]; cout << a.parkname << " [" << a.state << "] area: " << a.area << endl; } }
26.047619
92
0.550274
alakh125
9571c7f718f9d07933026224b6f5dd33639490cb
13,042
cpp
C++
DFNs/BundleAdjustment/SvdDecomposition.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
7
2019-02-26T15:09:50.000Z
2021-09-30T07:39:01.000Z
DFNs/BundleAdjustment/SvdDecomposition.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
null
null
null
DFNs/BundleAdjustment/SvdDecomposition.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
1
2020-12-06T12:09:05.000Z
2020-12-06T12:09:05.000Z
/** * @author Alessandro Bianco */ /** * @addtogroup DFNs * @{ */ #include "SvdDecomposition.hpp" #include <Converters/FrameToMatConverter.hpp> #include <Macros/YamlcppMacros.hpp> #include <Errors/Assert.hpp> #include <stdlib.h> #include <fstream> using namespace Helpers; using namespace Converters; using namespace CorrespondenceMap2DWrapper; using namespace PoseWrapper; using namespace BaseTypesWrapper; namespace CDFF { namespace DFN { namespace BundleAdjustment { SvdDecomposition::SvdDecomposition() { parameters = DEFAULT_PARAMETERS; parametersHelper.AddParameter<float>("LeftCameraMatrix", "FocalLengthX", parameters.leftCameraMatrix.focalLengthX, DEFAULT_PARAMETERS.leftCameraMatrix.focalLengthX); parametersHelper.AddParameter<float>("LeftCameraMatrix", "FocalLengthY", parameters.leftCameraMatrix.focalLengthY, DEFAULT_PARAMETERS.leftCameraMatrix.focalLengthY); parametersHelper.AddParameter<float>("LeftCameraMatrix", "PrincipalPointX", parameters.leftCameraMatrix.principalPointX, DEFAULT_PARAMETERS.leftCameraMatrix.principalPointX); parametersHelper.AddParameter<float>("LeftCameraMatrix", "PrincipalPointY", parameters.leftCameraMatrix.principalPointY, DEFAULT_PARAMETERS.leftCameraMatrix.principalPointY); parametersHelper.AddParameter<float>("RightCameraMatrix", "FocalLengthX", parameters.rightCameraMatrix.focalLengthX, DEFAULT_PARAMETERS.rightCameraMatrix.focalLengthX); parametersHelper.AddParameter<float>("RightCameraMatrix", "FocalLengthY", parameters.rightCameraMatrix.focalLengthY, DEFAULT_PARAMETERS.rightCameraMatrix.focalLengthY); parametersHelper.AddParameter<float>("RightCameraMatrix", "PrincipalPointX", parameters.rightCameraMatrix.principalPointX, DEFAULT_PARAMETERS.rightCameraMatrix.principalPointX); parametersHelper.AddParameter<float>("RightCameraMatrix", "PrincipalPointY", parameters.rightCameraMatrix.principalPointY, DEFAULT_PARAMETERS.rightCameraMatrix.principalPointY); parametersHelper.AddParameter<float>("GeneralParameters", "Baseline", parameters.baseline, DEFAULT_PARAMETERS.baseline); configurationFilePath = ""; } SvdDecomposition::~SvdDecomposition() { } void SvdDecomposition::configure() { parametersHelper.ReadFile(configurationFilePath); ValidateParameters(); leftCameraMatrix = CameraMatrixToCvMatrix(parameters.leftCameraMatrix); rightCameraMatrix = CameraMatrixToCvMatrix(parameters.rightCameraMatrix); leftCameraMatrixInverse = leftCameraMatrix.inv(); rightCameraMatrixInverse = rightCameraMatrix.inv(); leftAbsoluteConicImage = leftCameraMatrix.t() * leftCameraMatrixInverse; rightAbsoluteConicImage = rightCameraMatrix.t() * rightCameraMatrixInverse; } void SvdDecomposition::process() { cv::Mat measurementMatrix = correspondencesSequenceConverter.Convert(&inCorrespondenceMapsSequence); if (measurementMatrix.cols < 4) //Not enough points available. { outSuccess = false; return; } cv::Mat centroidMatrix = ComputeMeasuresCentroid(measurementMatrix); cv::Mat translationMatrix = ComputeTranslationMatrix(centroidMatrix); CentreMeasurementMatrix(centroidMatrix, measurementMatrix); cv::Mat compatibleRotationMatrix, compatiblePositionMatrix; DecomposeMeasurementMatrix(measurementMatrix, compatibleRotationMatrix, compatiblePositionMatrix); ConvertRotationTranslationMatricesToPosesSequence(translationMatrix, compatibleRotationMatrix, outPosesSequence); outError = -1; outSuccess = true; } const SvdDecomposition::SvdDecompositionOptionsSet SvdDecomposition::DEFAULT_PARAMETERS = { //.leftCameraMatrix = { /*.focalLengthX =*/ 1, /*.focalLengthY =*/ 1, /*.principalPointX =*/ 0, /*.principalPointY =*/ 0, }, //.rightCameraMatrix = { /*.focalLengthX =*/ 1, /*.focalLengthY =*/ 1, /*.principalPointX =*/ 0, /*.principalPointY =*/ 0, }, /*.baseline =*/ 1.0 }; cv::Mat SvdDecomposition::CameraMatrixToCvMatrix(const CameraMatrix& cameraMatrix) { cv::Mat cvCameraMatrix(3, 3, CV_32FC1, cv::Scalar(0)); cvCameraMatrix.at<float>(0,0) = cameraMatrix.focalLengthX; cvCameraMatrix.at<float>(1,1) = cameraMatrix.focalLengthY; cvCameraMatrix.at<float>(2,0) = cameraMatrix.principalPointX; cvCameraMatrix.at<float>(2,1) = cameraMatrix.principalPointY; cvCameraMatrix.at<float>(2,2) = 1.0; return cvCameraMatrix; } void SvdDecomposition::ConvertRotationTranslationMatricesToPosesSequence(cv::Mat translationMatrix, cv::Mat rotationMatrix, PoseWrapper::Poses3DSequence& posesSequence) { ASSERT( translationMatrix.rows == rotationMatrix.rows/2, "Translation Matrix and rotation Matrix sizes do not match"); // the rotation matrix is an affine rotation matrix, it needs to be multipled on the right by an appropriate 3x3 matrix. // ComputeMetricRotationMatrix finds the matrix according to section 10.4.2 of "Multiple View Geometry in Computer Vision" by Richard Hartley, and Andrew Zisserman. cv::Mat finalRotationMatrix, firstMetricRotationMatrix; { // x = M X + t for the first camera matrix, M is given by the first two row of the rotation matrix and t is given by the first centroid; // The rotation matrix of the projective 3x4 transformation matrix P = [M'|m]. M' is given by the first two columns of M concatenated with t, concatenated with a final row (0, 0, 1). int firstPoseIndex = 0; cv::Mat firstProjectionMatrixColumns[4]; firstProjectionMatrixColumns[0] = (cv::Mat_<float>(3, 1, CV_32FC1) << rotationMatrix.at<float>(2*firstPoseIndex, 0), rotationMatrix.at<float>(2*firstPoseIndex+1, 0), 0); firstProjectionMatrixColumns[1] = (cv::Mat_<float>(3, 1, CV_32FC1) << rotationMatrix.at<float>(2*firstPoseIndex, 1), rotationMatrix.at<float>(2*firstPoseIndex+1, 1), 0); firstProjectionMatrixColumns[2] = (cv::Mat_<float>(3, 1, CV_32FC1) << translationMatrix.at<float>(firstPoseIndex, 0), translationMatrix.at<float>(firstPoseIndex, 1), 1); firstProjectionMatrixColumns[3] = (cv::Mat_<float>(3, 1, CV_32FC1) << rotationMatrix.at<float>(2*firstPoseIndex, 2), rotationMatrix.at<float>(2*firstPoseIndex+1, 2), 0); cv::Mat firstProjectionMatrix; cv::hconcat(firstProjectionMatrixColumns, 4, firstProjectionMatrix); firstMetricRotationMatrix = ComputeMetricRotationMatrix(firstProjectionMatrix(cv::Rect(0, 0, 3, 3)), firstPoseIndex); finalRotationMatrix = rotationMatrix * firstMetricRotationMatrix; } AffineTransform inverseOfFirstCameraTransform; for(int poseIndex = 0; poseIndex < translationMatrix.rows; poseIndex++) { Eigen::Matrix3f eigenRotationMatrix; eigenRotationMatrix << finalRotationMatrix.at<float>(2*poseIndex, 0), finalRotationMatrix.at<float>(2*poseIndex, 1), finalRotationMatrix.at<float>(2*poseIndex, 2), finalRotationMatrix.at<float>(2*poseIndex+1, 0), finalRotationMatrix.at<float>(2*poseIndex+1, 1), finalRotationMatrix.at<float>(2*poseIndex+1, 2), 0, 0, 0; Eigen::Quaternion<float> eigenRotation(eigenRotationMatrix); eigenRotation.normalize(); Eigen::Translation<float, 3> translation(translationMatrix.at<float>(poseIndex,0), translationMatrix.at<float>(poseIndex,1), translationMatrix.at<float>(poseIndex, 2)); AffineTransform affineTransform = translation * eigenRotation; // We put the transforms in the reference frame of the first camera. if (poseIndex == 0) { inverseOfFirstCameraTransform = affineTransform.inverse(); } affineTransform = affineTransform * inverseOfFirstCameraTransform; AffineTransform cameraTransform = affineTransform.inverse(); Pose3D newPose; SetPosition(newPose, cameraTransform.translation()(0), cameraTransform.translation()(1), cameraTransform.translation()(2)); Eigen::Quaternion<float> outputQuaternion( cameraTransform.rotation() ); SetOrientation(newPose, outputQuaternion.x(), outputQuaternion.y(), outputQuaternion.z(), outputQuaternion.w()); PRINT_TO_LOG("newPose", ToString(newPose)); AddPose(posesSequence, newPose); } } void SvdDecomposition::DecomposeMeasurementMatrix(cv::Mat measurementMatrix, cv::Mat& compatibleRotationMatrix, cv::Mat& compatiblePositionMatrix) { //This is the algorithm of Tomasi and Kanade as describe in page 437 of "Multiple View Geometry in Computer Vision" by Richard Hartley, and Andrew Zisserman. cv::Mat leftSingularVectorsMatrix, singularValuesMatrix, rightSingularVectorsMatrix; cv::SVD::compute(measurementMatrix, singularValuesMatrix, leftSingularVectorsMatrix, rightSingularVectorsMatrix); ASSERT(singularValuesMatrix.cols == 1 && singularValuesMatrix.rows == measurementMatrix.cols && singularValuesMatrix.type() == CV_32FC1, "Something went wrong in the svd decomposition"); ASSERT(leftSingularVectorsMatrix.rows == measurementMatrix.rows, "Unexpected result in svd decomposition"); cv::Mat rotationMatrixColumnsList[3]; for(int columnIndex = 0; columnIndex < 3; columnIndex++) { rotationMatrixColumnsList[columnIndex] = leftSingularVectorsMatrix(cv::Rect(columnIndex, 0, 1, leftSingularVectorsMatrix.rows)) * singularValuesMatrix.at<float>(columnIndex, 0); } cv::hconcat(rotationMatrixColumnsList, 3, compatibleRotationMatrix); compatiblePositionMatrix = rightSingularVectorsMatrix( cv::Rect(0, 0, rightSingularVectorsMatrix.cols, 3) ); } cv::Mat SvdDecomposition::ComputeTranslationMatrix(cv::Mat centroidMatrix) { //the centroid matrix contains the translation direction vectors. In order to find the vector expressed in meters we use the measure of the baseline provided as an input parameter. float estimatedBaselineX = centroidMatrix.at<float>(0, 0) - centroidMatrix.at<float>(1, 0); float estimatedBaselineY = centroidMatrix.at<float>(0, 1) - centroidMatrix.at<float>(1, 1); float estimatedBaseline = std::sqrt( estimatedBaselineX*estimatedBaselineX + estimatedBaselineY*estimatedBaselineY); float metricCoefficient = parameters.baseline / estimatedBaseline; cv::Mat temporaryImagesList[2] = {centroidMatrix, cv::Mat::ones(centroidMatrix.rows, 1, CV_32FC1)}; cv::Mat translationMatrix; cv::hconcat(temporaryImagesList, 2, translationMatrix); translationMatrix = translationMatrix * metricCoefficient; return translationMatrix; } cv::Mat SvdDecomposition::ComputeMeasuresCentroid(cv::Mat measurementMatrix) { cv::Mat centroidMatrix(measurementMatrix.rows/2, 2, CV_32FC1); for(int imageIndex = 0; imageIndex < centroidMatrix.rows; imageIndex++) { float centroidX = 0; float centroidY = 0; for(int measureIndex = 0; measureIndex < measurementMatrix.cols; measureIndex++) { centroidX += measurementMatrix.at<float>(2*imageIndex, measureIndex); centroidY += measurementMatrix.at<float>(2*imageIndex+1, measureIndex); } centroidX /= (float)measurementMatrix.cols; centroidY /= (float)measurementMatrix.cols; centroidMatrix.at<float>(imageIndex, 0) = centroidX; centroidMatrix.at<float>(imageIndex, 1) = centroidY; } return centroidMatrix; } void SvdDecomposition::CentreMeasurementMatrix(cv::Mat centroidMatrix, cv::Mat& measurementMatrix) { ASSERT( centroidMatrix.rows == measurementMatrix.rows/2, "Centroid Matrix and measurement Matrix sizes do not match"); for(int imageIndex = 0; imageIndex < centroidMatrix.rows; imageIndex++) { float centroidX = centroidMatrix.at<float>(imageIndex, 0); float centroidY = centroidMatrix.at<float>(imageIndex, 1); for(int measureIndex = 0; measureIndex < measurementMatrix.cols; measureIndex++) { measurementMatrix.at<float>(2*imageIndex, measureIndex) -= centroidX; measurementMatrix.at<float>(2*imageIndex+1, measureIndex) -= centroidY; } } } cv::Mat SvdDecomposition::ComputeMetricRotationMatrix(cv::Mat rotationMatrix, int poseIndex) { // computation of the metric matrix according to section 10.4.2 of "Multiple View Geometry in Computer Vision" by Richard Hartley, and Andrew Zisserman. ASSERT(rotationMatrix.cols == 3 && rotationMatrix.rows == 3 && rotationMatrix.type() == CV_32FC1, "unexpected rotation matrix format"); cv::Mat matrixToDecompose; if (poseIndex % 2 == 0) { matrixToDecompose = ( rotationMatrix.t() * leftAbsoluteConicImage * rotationMatrix).inv(); } else { matrixToDecompose = ( rotationMatrix.t() * rightAbsoluteConicImage * rotationMatrix).inv(); } cv::Cholesky((float*)matrixToDecompose.ptr(), matrixToDecompose.cols*sizeof(float), 3, NULL, 0, 0); return matrixToDecompose; } void SvdDecomposition::ValidateParameters() { ASSERT(parameters.leftCameraMatrix.focalLengthX > 0 && parameters.leftCameraMatrix.focalLengthY > 0, "SvdDecomposition Configuration error: left focal length has to be positive"); ASSERT(parameters.rightCameraMatrix.focalLengthX > 0 && parameters.rightCameraMatrix.focalLengthY > 0, "SvdDecomposition Configuration error: right focal length has to be positive"); ASSERT(parameters.baseline > 0, "SvdDecomposition Configuration error: stereo camera baseline has to be positive"); } void SvdDecomposition::ValidateInputs() { int n = GetNumberOfCorrespondenceMaps(inCorrespondenceMapsSequence); ASSERT( n == 6 || n == 15 || n == 28, "SvdDecomposition Error: you should provide correspondence maps for either 2, 3 or 4 pairs of stereo camera images"); } } } } /** @} */
46.74552
187
0.783392
H2020-InFuse
9576856d827def72924012e2ecb87a8ab7648b67
13,033
cpp
C++
libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_arithmetic_promote.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_arithmetic_promote.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_arithmetic_promote.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file unit_test_fnd_type_traits_arithmetic_promote.cpp * * @brief arithmetic_promote のテスト * * @author myoukaku */ #include <bksge/fnd/type_traits/arithmetic_promote.hpp> #include <bksge/fnd/type_traits/is_same.hpp> #include <gtest/gtest.h> #define BKSGE_ARITHMETIC_PROMOTE_TEST(T, ...) \ static_assert(bksge::is_same<T, bksge::arithmetic_promote<__VA_ARGS__>::type>::value, ""); \ static_assert(bksge::is_same<T, bksge::arithmetic_promote_t<__VA_ARGS__>>::value, "") BKSGE_ARITHMETIC_PROMOTE_TEST(float, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(int, int); BKSGE_ARITHMETIC_PROMOTE_TEST(char, char); BKSGE_ARITHMETIC_PROMOTE_TEST(short, short); BKSGE_ARITHMETIC_PROMOTE_TEST(long, long); BKSGE_ARITHMETIC_PROMOTE_TEST(long long, long long); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned char, unsigned char); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned short, unsigned short); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned long, unsigned long); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned long long, unsigned long long); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, int); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, unsigned int); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, unsigned char); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, unsigned int); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, unsigned char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, unsigned int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, unsigned char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, char); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, int, unsigned int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, unsigned char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, char); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, char, unsigned int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, unsigned char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, unsigned int, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, unsigned int, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, unsigned int, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int, int); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int, char); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int, unsigned int); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int, unsigned char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, unsigned char, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, unsigned char, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, unsigned char, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(int, unsigned char, int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, unsigned char, char); BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned char, unsigned int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, unsigned char, unsigned char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, float, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, float, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, float, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, float, int); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, float, char); BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, int, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, int, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, int, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, int, int); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, int, char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, char, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, char, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, char, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, char, int); BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, char, char); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, float, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float, int); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float, char); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, int, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int, int); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int, char); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, char, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char, int); BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, float, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, float, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, float, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, float, int); BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, float, char); BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, int, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, int, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, int, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, int, int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, int, char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, char, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, char, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, char, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, char, int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, char, char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, float, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, float, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, float, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, float, int); BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, float, char); BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, float); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, int); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, int, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, int, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, int, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, int, int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, int, char); BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, char, float); BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, char, double); BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, char, long double); BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, char, int); BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, char, char); #undef BKSGE_ARITHMETIC_PROMOTE_TEST
59.784404
94
0.778792
myoukaku
95872f9d2e6c0ecb3dd86b81e596e689b63c4f51
1,120
hpp
C++
src/storage/DataPoint.hpp
spencercjh/LIBBLE-PS
ca6259ccf20d6ef7f683b2d4bc00d846da127c2c
[ "Apache-2.0" ]
null
null
null
src/storage/DataPoint.hpp
spencercjh/LIBBLE-PS
ca6259ccf20d6ef7f683b2d4bc00d846da127c2c
[ "Apache-2.0" ]
1
2021-07-06T12:08:21.000Z
2021-07-06T12:08:21.000Z
src/storage/DataPoint.hpp
spencercjh/LIBBLE-PS
ca6259ccf20d6ef7f683b2d4bc00d846da127c2c
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2017 LIBBLE team supervised by Dr. Wu-Jun LI at Nanjing University. * 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. */ #ifndef _DATA_POINT_HPP_ #define _DATA_POINT_HPP_ #include <cstddef> #include "../util/include_util.hpp" class DataPoint { public: double label; std::vector<int> key; std::vector<double> value; DataPoint() {} ~DataPoint() {} DataPoint(const DataPoint &d) = delete; DataPoint &operator=(const DataPoint &d) = delete; }; #endif
29.473684
91
0.658929
spencercjh
958b2f5869c8acdc23c1f098b29acb1eb98cda0c
1,972
cpp
C++
test/core/utility/UnicodeTest.cpp
mark-online/sne
92190c78a1710778acf16dd3a83af064db5c269b
[ "MIT" ]
null
null
null
test/core/utility/UnicodeTest.cpp
mark-online/sne
92190c78a1710778acf16dd3a83af064db5c269b
[ "MIT" ]
null
null
null
test/core/utility/UnicodeTest.cpp
mark-online/sne
92190c78a1710778acf16dd3a83af064db5c269b
[ "MIT" ]
null
null
null
#include "CoreTestPCH.h" #include <sne/core/utility/Unicode.h> using namespace sne; using namespace sne::core; // Visual Studio에서 한글 문자열이 포함된 코드를 실행하기 위해서 // "UTF-8 with BOM"으로 저장해야 함 /** * @class UnicodeTest * * Unicode Test */ class UnicodeTest : public testing::Test { private: void testEnglish(); void testKorean(); void testInvalidUtf8(); }; TEST_F(UnicodeTest, testEnglish) { { const std::string expected("You aren't gonna need it!"); ASSERT_EQ(expected, toUtf8(L"You aren't gonna need it!")) << "UCS to UTF-8"; } { const std::wstring expected(L"You aren't gonna need it!"); ASSERT_TRUE(wcscmp(expected.c_str(), fromUtf8("You aren't gonna need it!").c_str()) == 0) << "UTF-8 to UCS"; } } TEST_F(UnicodeTest, testKorean) { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4566) { const std::string expected("\xEC\x95\x84\xED\x96\x8F\xED\x96\x8F"); ASSERT_EQ(expected, toUtf8(L"아햏햏")) << "UCS to UTF-8"; } { const std::wstring expected(L"아햏햏"); ASSERT_EQ(expected, fromUtf8("\xEC\x95\x84\xED\x96\x8F\xED\x96\x8F")) << "UTF-8 to UCS"; } #pragma warning(pop) #else // GCC의 경우 유니코드 문자열을 바로 입력할 경우 컴파일러가 제대로 // 파싱하지 못하는 문제가 발생한다. { const std::string expected("\xEC\x95\x84\xED\x96\x8F\xED\x96\x8F"); ASSERT_EQ(expected, toUtf8(fromUtf8(expected))) << "utf-8 -> ucs -> utf-8"; } #endif } TEST_F(UnicodeTest, testInvalidUtf8) { const std::wstring str(L"1234567890ABCDEFGHIZKLMNOPQRSTUVWXYZ"); const std::string utf8(toUtf8(str)); const size_t strLen = 10; std::string invalidUtf8; for (std::string::size_type i = 0; i < strLen; ++i) { invalidUtf8.push_back(utf8[i]); } const std::wstring converted(fromUtf8(invalidUtf8)); ASSERT_TRUE(wcscmp(L"1234567890", converted.c_str()) == 0) << "converting"; }
24.04878
80
0.615619
mark-online
958cc3d74bfa6a54c74c93d8a43a04993317516b
114
cpp
C++
src/entrypoint.cpp
juha-hovi/Jam3D
71b7d10c9cfccb7a376ae9d1753277e0ed45f853
[ "MIT" ]
null
null
null
src/entrypoint.cpp
juha-hovi/Jam3D
71b7d10c9cfccb7a376ae9d1753277e0ed45f853
[ "MIT" ]
null
null
null
src/entrypoint.cpp
juha-hovi/Jam3D
71b7d10c9cfccb7a376ae9d1753277e0ed45f853
[ "MIT" ]
null
null
null
#include "application.h" int main() { Jam3D::Application application; application.Run(); return 0; }
14.25
35
0.649123
juha-hovi
958f6d03a90c76bf3f35058237e52e1e13e0ad42
309
cpp
C++
Ejercicios/Ejercicio19-do-while/do-while.cpp
Nelson-Chacon/cpp
21332e2ecaa815acc116eead80dd5b05cc35b710
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio19-do-while/do-while.cpp
Nelson-Chacon/cpp
21332e2ecaa815acc116eead80dd5b05cc35b710
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio19-do-while/do-while.cpp
Nelson-Chacon/cpp
21332e2ecaa815acc116eead80dd5b05cc35b710
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(int argc, char const *argv[]) { int a = 2; int b =1; while (a>b) { cout<<"(while) A > B"<< endl; break; } do{ cout<<"(do while) A > B"<< endl; break; }while (a>b); return 0; }
14.045455
40
0.433657
Nelson-Chacon
d2e51d6e4bb90c5a9b5f20ee1c8125b5adc19760
5,246
hpp
C++
nRF24L01+/nrf24L01.hpp
Jordieboyz/nRF24L01
18db91377c1b48418b64e4ce1d1f947109220267
[ "BSL-1.0" ]
null
null
null
nRF24L01+/nrf24L01.hpp
Jordieboyz/nRF24L01
18db91377c1b48418b64e4ce1d1f947109220267
[ "BSL-1.0" ]
null
null
null
nRF24L01+/nrf24L01.hpp
Jordieboyz/nRF24L01
18db91377c1b48418b64e4ce1d1f947109220267
[ "BSL-1.0" ]
null
null
null
#ifndef NRF24_HPP #define NRF24_HPP #include "hwlib.hpp" #include "registers.hpp" enum pipeInfo : uint8_t { ERX_P0 = 0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5, RX_ADDR_P0 = 0x0A, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5, RX_PW_P0 = 0x11, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5 }; enum dataRate : uint8_t { dBm_18 = 0, dBm_12, dBm_6, dBm_0 }; /// @file /// \brief /// nRF24L01+ driver /// \details /// This driver is a driver for the nRF24L01+ /// It's a fairly easy library using the most significant functions /// of the nRF24L01+ class NRF24 { private: hwlib::spi_bus & spi; hwlib::pin_out & ce; hwlib::pin_out & csn; uint8_t data_size; const uint8_t pipeEnable[6] = { ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5 }; const uint8_t pipeAdress[6] = { RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5 }; const uint8_t pipeWidth[6] = { RX_PW_P0, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5 }; protected: /// \brief /// Read from a regsiter /// \details /// This funtion reads one byte from the given register uint8_t read_register(uint8_t reg); /// \brief /// Write to a regsiter /// \details /// This funtion writes one byte to the given register void write_register(uint8_t reg, uint8_t byte); /// \brief /// Reads multiple bytes from a single register /// \details /// This function reads the an x amount of incoming bytes (from the MISO pin) void read_register(uint8_t reg, std::array<uint8_t, 5> & bytes); /// \brief /// Writes multiple bytes to a register /// \details /// This function writes n bytes to one of the registers of the nRF24L01+ void write_register(uint8_t reg, std::array<uint8_t, 5> & bytes); /// \brief /// Read incoming data /// \details /// This function reads the data from the RX_PLD (arrived data on the RX FIFO) /// and saves it in the given array for further use void read_payload(std::array<uint8_t, 32> & payload); /// \brief /// Write data to payload /// \details /// This function writes the given payload to the payload queque void write_payload(std::array<uint8_t, 32> & payload); /// \brief /// Flush RX /// \details /// This function flushes the RX queue void flush_RX(); /// \brief /// Flush TX /// \details /// This function flushes the TX queue void flush_TX(); /// \brief /// Enable the features /// \details /// This function enables the right featuers on the nRF24L01+ for example /// the no_ack functionality void enable_features(); /// \brief /// Reset enabled pipes /// \details /// This function resets all pipes 2-5, but keeps pipe 0 and 1 enabled void reset_enabled_pipes(); public: /// \brief /// Constructor nRF24L01+ /// \details /// The nRF24L01+ needs a ce and csn pin defenition to work NRF24(hwlib::spi_bus & spi, hwlib::pin_out & ce, hwlib::pin_out & csn) : spi( spi ), ce( ce ), csn( csn ), data_size( 32 ) {} /// \brief /// The start of the nRF24L01+ /// \details /// This funtion gets the chip ready to write and read from the nRF24L01+ /// This funtion also ensures there are correct values in a couple registers /// make sure this is the first function you call on the nRF24L01+ void start_up_chip(); /// \brief /// Set a channel /// \details /// This funtion sets the channel whereover the nRF24L01+ will communicate void set_channel(int channel); /// \brief /// Set the data rate /// \details /// This funtion sets the speed of the output data going through the air void set_data_rate( dataRate rate ); /// \brief /// Trigger receive mode /// \details /// This function forces the nRF24L01+ to operate in the RX ( receive ) mode void RX_mode(); /// \brief /// Trigger transmit mode /// \details /// This function forces the nRF24L01+ to operate in the TX ( transmit ) mode void TX_mode(); /// \brief /// Set the transmit adress /// \details /// This function writes the given adress to the registers so the nRF24L01+ /// can communicate with another nRF24L01+ void write_adress_TX(std::array<uint8_t, 5> & adress); /// \brief /// Set the receive adress /// \details /// This funtion enables the given pipe and writes the give adress to the /// right registers so the nRF24L01+ can listen to the transmitted data on the right pipe void write_adress_RX(uint8_t pipe, std::array<uint8_t, 5> & adress); /// \brief /// Read incoming data /// \details /// reads the incoming data and returns the first byte void read(std::array<uint8_t, 32> & payload ); /// \brief /// Write data (without ack) /// \details /// This funtion writes the data to the transmit queue, depending on the mode of /// the nRF24L01+ module, the data will automaticly dissappear from the queue void write_noack(std::array<uint8_t, 32> & payload); }; #endif // NRF24_HPP
29.977143
109
0.634769
Jordieboyz
d2e56f87ced7c4b8300c4a05f3ebcc6c522bedc6
1,509
cpp
C++
6. Tree/16.A1110.cpp
huangjiayu-zju/PAT-A
ecb07409727c56d556a5af1b201158bab0d0d2e8
[ "MIT" ]
null
null
null
6. Tree/16.A1110.cpp
huangjiayu-zju/PAT-A
ecb07409727c56d556a5af1b201158bab0d0d2e8
[ "MIT" ]
null
null
null
6. Tree/16.A1110.cpp
huangjiayu-zju/PAT-A
ecb07409727c56d556a5af1b201158bab0d0d2e8
[ "MIT" ]
null
null
null
#include<cstdio> #include<cstring> #include<queue> using namespace std; const int maxn = 30; //进行层序遍历,让空结点也入队,如果在访问完N个非空结点之前访问到了空结点,那么说明不是完全二叉树 bool isRoot[maxn];//节点是否是根结点 struct Node{ int left, right;//左右结点的下标 } node[maxn]; //input函数输入数据 int input(){ char id[3]; scanf("%s", id); if(id[0] == '-'){ return -1; }else if(strlen(id) == 1){ return id[0] - '0'; }else{ return (id[0] - '0') * 10 + (id[1] - '0'); } } //找到根结点函数编号 int findRoot(int n){ for (int i = 0; i < n; i++){ if(isRoot[i]){ return i; } } return -1; } //BFS判断完全二叉树,root为根结点编号,last是最后一个结点编号(注意引用),n为结点个数 bool BFS(int root, int &last, int n){ queue<int> q; q.push(root); while(n){ int front = q.front(); q.pop(); if(front == -1){ return false; //访问到空结点,一定是非完全二叉树 } n--; last = front; //记录最后一个非空结点编号 q.push(node[front].left); q.push(node[front].right); } return true; } int main(){ int n; scanf("%d", &n); memset(isRoot, true, sizeof(isRoot)); for (int i = 0; i < n; i++){ int left = input(), right = input(); isRoot[left] = isRoot[right] = false; node[i].left = left; node[i].right = right; } int root = findRoot(n), last; bool isCompleteTree = BFS(root, last, n); if(isCompleteTree){ printf("YES %d\n", last); }else{ printf("NO %d\n", root); } return 0; }
20.671233
50
0.513585
huangjiayu-zju
d2e620cfdf1ca1e0009e62153d96a522fa9e2fb4
5,857
cc
C++
deps/v8/src/arm/fast-codegen-arm.cc
ekg/node
c77964760047f734c58dab49143ff6487f938c6e
[ "MIT" ]
2
2021-06-29T21:07:26.000Z
2022-01-25T02:50:14.000Z
deps/v8/src/arm/fast-codegen-arm.cc
ekg/node
c77964760047f734c58dab49143ff6487f938c6e
[ "MIT" ]
null
null
null
deps/v8/src/arm/fast-codegen-arm.cc
ekg/node
c77964760047f734c58dab49143ff6487f938c6e
[ "MIT" ]
1
2019-12-19T16:28:13.000Z
2019-12-19T16:28:13.000Z
// Copyright 2009 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "codegen-inl.h" #include "fast-codegen.h" namespace v8 { namespace internal { #define __ ACCESS_MASM(masm_) // Generate code for a JS function. On entry to the function the receiver // and arguments have been pushed on the stack left to right. The actual // argument count matches the formal parameter count expected by the // function. // // The live registers are: // o r1: the JS function object being called (ie, ourselves) // o cp: our context // o fp: our caller's frame pointer // o sp: stack pointer // o lr: return address // // The function builds a JS frame. Please see JavaScriptFrameConstants in // frames-arm.h for its layout. void FastCodeGenerator::Generate(FunctionLiteral* fun) { function_ = fun; // ARM does NOT call SetFunctionPosition. __ stm(db_w, sp, r1.bit() | cp.bit() | fp.bit() | lr.bit()); // Adjust fp to point to caller's fp. __ add(fp, sp, Operand(2 * kPointerSize)); { Comment cmnt(masm_, "[ Allocate locals"); int locals_count = fun->scope()->num_stack_slots(); if (locals_count > 0) { __ LoadRoot(ip, Heap::kUndefinedValueRootIndex); } if (FLAG_check_stack) { __ LoadRoot(r2, Heap::kStackLimitRootIndex); } for (int i = 0; i < locals_count; i++) { __ push(ip); } } if (FLAG_check_stack) { // Put the lr setup instruction in the delay slot. The kInstrSize is // added to the implicit 8 byte offset that always applies to operations // with pc and gives a return address 12 bytes down. Comment cmnt(masm_, "[ Stack check"); __ add(lr, pc, Operand(Assembler::kInstrSize)); __ cmp(sp, Operand(r2)); StackCheckStub stub; __ mov(pc, Operand(reinterpret_cast<intptr_t>(stub.GetCode().location()), RelocInfo::CODE_TARGET), LeaveCC, lo); } { Comment cmnt(masm_, "[ Body"); VisitStatements(fun->body()); } { Comment cmnt(masm_, "[ return <undefined>;"); // Emit a 'return undefined' in case control fell off the end of the // body. __ LoadRoot(r0, Heap::kUndefinedValueRootIndex); SetReturnPosition(fun); __ RecordJSReturn(); __ mov(sp, fp); __ ldm(ia_w, sp, fp.bit() | lr.bit()); int num_parameters = function_->scope()->num_parameters(); __ add(sp, sp, Operand((num_parameters + 1) * kPointerSize)); __ Jump(lr); } } void FastCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) { Comment cmnt(masm_, "[ ExpressionStatement"); SetStatementPosition(stmt); Visit(stmt->expression()); } void FastCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) { Comment cmnt(masm_, "[ ReturnStatement"); SetStatementPosition(stmt); Visit(stmt->expression()); __ pop(r0); __ RecordJSReturn(); __ mov(sp, fp); __ ldm(ia_w, sp, fp.bit() | lr.bit()); int num_parameters = function_->scope()->num_parameters(); __ add(sp, sp, Operand((num_parameters + 1) * kPointerSize)); __ Jump(lr); } void FastCodeGenerator::VisitVariableProxy(VariableProxy* expr) { Comment cmnt(masm_, "[ VariableProxy"); Expression* rewrite = expr->var()->rewrite(); ASSERT(rewrite != NULL); Slot* slot = rewrite->AsSlot(); ASSERT(slot != NULL); { Comment cmnt(masm_, "[ Slot"); if (expr->location().is_temporary()) { __ ldr(ip, MemOperand(fp, SlotOffset(slot))); __ push(ip); } else { ASSERT(expr->location().is_nowhere()); } } } void FastCodeGenerator::VisitLiteral(Literal* expr) { Comment cmnt(masm_, "[ Literal"); if (expr->location().is_temporary()) { __ mov(ip, Operand(expr->handle())); __ push(ip); } else { ASSERT(expr->location().is_nowhere()); } } void FastCodeGenerator::VisitAssignment(Assignment* expr) { Comment cmnt(masm_, "[ Assignment"); ASSERT(expr->op() == Token::ASSIGN || expr->op() == Token::INIT_VAR); Visit(expr->value()); Variable* var = expr->target()->AsVariableProxy()->AsVariable(); ASSERT(var != NULL && var->slot() != NULL); if (expr->location().is_temporary()) { __ ldr(ip, MemOperand(sp)); } else { ASSERT(expr->location().is_nowhere()); __ pop(ip); } __ str(ip, MemOperand(fp, SlotOffset(var->slot()))); } } } // namespace v8::internal
33.090395
77
0.678504
ekg
d2e78785ed9f3d01e875fec26b0436d5b8383246
16,719
hpp
C++
include/rxcpp/rx-util.hpp
schiebel/dVO
2096230d4ee677b9c548d57b702a44b87caef10d
[ "Apache-2.0" ]
null
null
null
include/rxcpp/rx-util.hpp
schiebel/dVO
2096230d4ee677b9c548d57b702a44b87caef10d
[ "Apache-2.0" ]
null
null
null
include/rxcpp/rx-util.hpp
schiebel/dVO
2096230d4ee677b9c548d57b702a44b87caef10d
[ "Apache-2.0" ]
null
null
null
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once #include "rx-includes.hpp" #if !defined(CPPRX_RX_UTIL_HPP) #define CPPRX_RX_UTIL_HPP #if !defined(RXCPP_THREAD_LOCAL) #if defined(_MSC_VER) #define RXCPP_THREAD_LOCAL __declspec(thread) #else #define RXCPP_THREAD_LOCAL __thread #endif #endif #if !defined(RXCPP_SELECT_ANY) #if defined(_MSC_VER) #define RXCPP_SELECT_ANY __declspec(selectany) #else #define RXCPP_SELECT_ANY #endif #endif #define RXCPP_CONCAT(Prefix, Suffix) Prefix ## Suffix #define RXCPP_CONCAT_EVALUATE(Prefix, Suffix) RXCPP_CONCAT(Prefix, Suffix) #define RXCPP_MAKE_IDENTIFIER(Prefix) RXCPP_CONCAT_EVALUATE(Prefix, __LINE__) namespace rxcpp { namespace util { template<class Type> struct identity { typedef Type type; Type operator()(const Type& left) const {return left;} }; template <class T> class maybe { bool is_set; typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type storage; public: maybe() : is_set(false) { } maybe(T value) : is_set(false) { new (reinterpret_cast<T*>(&storage)) T(value); is_set = true; } maybe(const maybe& other) : is_set(false) { if (other.is_set) { new (reinterpret_cast<T*>(&storage)) T(*other.get()); is_set = true; } } maybe(maybe&& other) : is_set(false) { if (other.is_set) { new (reinterpret_cast<T*>(&storage)) T(std::move(*other.get())); is_set = true; other.reset(); } } ~maybe() { reset(); } void reset() { if (is_set) { is_set = false; reinterpret_cast<T*>(&storage)->~T(); } } T* get() { return is_set ? reinterpret_cast<T*>(&storage) : 0; } const T* get() const { return is_set ? reinterpret_cast<const T*>(&storage) : 0; } void set(T value) { if (is_set) { *reinterpret_cast<T*>(&storage) = std::move(value); } else { new (reinterpret_cast<T*>(&storage)) T(std::move(value)); is_set = true; } } T& operator*() { return *get(); } const T& operator*() const { return *get(); } T* operator->() { return get(); } const T* operator->() const { return get(); } maybe& operator=(const T& other) { set(other); return *this; } maybe& operator=(const maybe& other) { if (const T* pother = other.get()) { set(*pother); } else { reset(); } return *this; } // boolean-like operators operator T*() { return get(); } operator const T*() const { return get(); } private: }; template<class T> struct reveal_type {private: reveal_type();}; #if RXCPP_USE_VARIADIC_TEMPLATES template <int... Indices> struct tuple_indices; template <> struct tuple_indices<-1> { // for an empty std::tuple<> there is no entry typedef tuple_indices<> type; }; template <int... Indices> struct tuple_indices<0, Indices...> { // stop the recursion when 0 is reached typedef tuple_indices<0, Indices...> type; }; template <int Index, int... Indices> struct tuple_indices<Index, Indices...> { // recursively build a sequence of indices typedef typename tuple_indices<Index - 1, Index, Indices...>::type type; }; template <typename T> struct make_tuple_indices { typedef typename tuple_indices<std::tuple_size<T>::value - 1>::type type; }; namespace detail { template<class T> struct tuple_dispatch; template<size_t... DisptachIndices> struct tuple_dispatch<tuple_indices<DisptachIndices...>> { template<class F, class T> static auto call(F&& f, T&& t) -> decltype (std::forward<F>(f)(std::get<DisptachIndices>(std::forward<T>(t))...)) { return std::forward<F>(f)(std::get<DisptachIndices>(std::forward<T>(t))...); } };} template<class F, class T> auto tuple_dispatch(F&& f, T&& t) -> decltype(detail::tuple_dispatch<typename make_tuple_indices<typename std::decay<T>::type>::type>::call(std::forward<F>(f), std::forward<T>(t))) { return detail::tuple_dispatch<typename make_tuple_indices<typename std::decay<T>::type>::type>::call(std::forward<F>(f), std::forward<T>(t)); } namespace detail { template<class T> struct tuple_tie; template<size_t... TIndices> struct tuple_tie<tuple_indices<TIndices...>> { template<class T> static auto tie(T&& t) -> decltype (std::tie(std::get<TIndices>(std::forward<T>(t))...)) { return std::tie(std::get<TIndices>(std::forward<T>(t))...); } };} template<class T> auto tuple_tie(T&& t) -> decltype(detail::tuple_tie<typename make_tuple_indices<typename std::decay<T>::type>::type>::tie(std::forward<T>(t))) { return detail::tuple_tie<typename make_tuple_indices<typename std::decay<T>::type>::type>::tie(std::forward<T>(t)); } struct as_tuple { template<class... AsTupleNext> auto operator()(AsTupleNext... x) -> decltype(std::make_tuple(std::move(x)...)) { return std::make_tuple(std::move(x)...);} template<class... AsTupleNext> auto operator()(AsTupleNext... x) const -> decltype(std::make_tuple(std::move(x)...)) { return std::make_tuple(std::move(x)...);} }; #else namespace detail { template<size_t TupleSize> struct tuple_dispatch; template<> struct tuple_dispatch<0> { template<class F, class T> static auto call(F&& f, T&& ) -> decltype (std::forward<F>(f)()) { return std::forward<F>(f)();} }; template<> struct tuple_dispatch<1> { template<class F, class T> static auto call(F&& f, T&& t) -> decltype (std::forward<F>(f)(std::get<0>(std::forward<T>(t)))) { return std::forward<F>(f)(std::get<0>(std::forward<T>(t)));} }; template<> struct tuple_dispatch<2> { template<class F, class T> static auto call(F&& f, T&& t) -> decltype (std::forward<F>(f)( std::get<0>(std::forward<T>(t)), std::get<1>(std::forward<T>(t)))) { return std::forward<F>(f)( std::get<0>(std::forward<T>(t)), std::get<1>(std::forward<T>(t)));} }; template<> struct tuple_dispatch<3> { template<class F, class T> static auto call(F&& f, T&& t) -> decltype (std::forward<F>(f)( std::get<0>(std::forward<T>(t)), std::get<1>(std::forward<T>(t)), std::get<2>(std::forward<T>(t)))) { return std::forward<F>(f)( std::get<0>(std::forward<T>(t)), std::get<1>(std::forward<T>(t)), std::get<2>(std::forward<T>(t)));} }; template<> struct tuple_dispatch<4> { template<class F, class T> static auto call(F&& f, T&& t) -> decltype (std::forward<F>(f)( std::get<0>(std::forward<T>(t)), std::get<1>(std::forward<T>(t)), std::get<2>(std::forward<T>(t)), std::get<3>(std::forward<T>(t)))) { return std::forward<F>(f)( std::get<0>(std::forward<T>(t)), std::get<1>(std::forward<T>(t)), std::get<2>(std::forward<T>(t)), std::get<3>(std::forward<T>(t)));} }; template<> struct tuple_dispatch<5> { template<class F, class T> static auto call(F&& f, T&& t) -> decltype (std::forward<F>(f)( std::get<0>(std::forward<T>(t)), std::get<1>(std::forward<T>(t)), std::get<2>(std::forward<T>(t)), std::get<3>(std::forward<T>(t)), std::get<4>(std::forward<T>(t)))) { return std::forward<F>(f)( std::get<0>(std::forward<T>(t)), std::get<1>(std::forward<T>(t)), std::get<2>(std::forward<T>(t)), std::get<3>(std::forward<T>(t)), std::get<4>(std::forward<T>(t)));} }; } template<class F, class T> auto tuple_dispatch(F&& f, T&& t) -> decltype(detail::tuple_dispatch<std::tuple_size<typename std::decay<T>::type>::value>::call(std::forward<F>(f), std::forward<T>(t))) { return detail::tuple_dispatch<std::tuple_size<typename std::decay<T>::type>::value>::call(std::forward<F>(f), std::forward<T>(t)); } struct as_tuple { auto operator()() -> decltype(std::make_tuple()) { return std::make_tuple();} template<class AsTupleNext> auto operator()(AsTupleNext x) -> decltype(std::make_tuple(std::move(x))) { return std::make_tuple(std::move(x));} template< class AsTupleNext1, class AsTupleNext2> auto operator()( AsTupleNext1 x1, AsTupleNext2 x2) -> decltype(std::make_tuple( std::move(x1), std::move(x2))) { return std::make_tuple( std::move(x1), std::move(x2));} template< class AsTupleNext1, class AsTupleNext2, class AsTupleNext3> auto operator()( AsTupleNext1 x1, AsTupleNext2 x2, AsTupleNext3 x3) -> decltype(std::make_tuple( std::move(x1), std::move(x2), std::move(x3))) { return std::make_tuple( std::move(x1), std::move(x2), std::move(x3));} template< class AsTupleNext1, class AsTupleNext2, class AsTupleNext3, class AsTupleNext4> auto operator()( AsTupleNext1 x1, AsTupleNext2 x2, AsTupleNext3 x3, AsTupleNext4 x4) -> decltype(std::make_tuple( std::move(x1), std::move(x2), std::move(x3), std::move(x4))) { return std::make_tuple( std::move(x1), std::move(x2), std::move(x3), std::move(x4));} template< class AsTupleNext1, class AsTupleNext2, class AsTupleNext3, class AsTupleNext4, class AsTupleNext5> auto operator()( AsTupleNext1 x1, AsTupleNext2 x2, AsTupleNext3 x3, AsTupleNext4 x4, AsTupleNext5 x5) -> decltype(std::make_tuple( std::move(x1), std::move(x2), std::move(x3), std::move(x4), std::move(x5))) { return std::make_tuple( std::move(x1), std::move(x2), std::move(x3), std::move(x4), std::move(x5));} auto operator()() const -> decltype(std::make_tuple()) { return std::make_tuple();} template<class AsTupleNext> auto operator()(AsTupleNext x) const -> decltype(std::make_tuple(std::move(x))) { return std::make_tuple(std::move(x));} template< class AsTupleNext1, class AsTupleNext2> auto operator()( AsTupleNext1 x1, AsTupleNext2 x2) const -> decltype(std::make_tuple( std::move(x1), std::move(x2))) { return std::make_tuple( std::move(x1), std::move(x2));} template< class AsTupleNext1, class AsTupleNext2, class AsTupleNext3> auto operator()( AsTupleNext1 x1, AsTupleNext2 x2, AsTupleNext3 x3) const -> decltype(std::make_tuple( std::move(x1), std::move(x2), std::move(x3))) { return std::make_tuple( std::move(x1), std::move(x2), std::move(x3));} template< class AsTupleNext1, class AsTupleNext2, class AsTupleNext3, class AsTupleNext4> auto operator()( AsTupleNext1 x1, AsTupleNext2 x2, AsTupleNext3 x3, AsTupleNext4 x4) const -> decltype(std::make_tuple( std::move(x1), std::move(x2), std::move(x3), std::move(x4))) { return std::make_tuple( std::move(x1), std::move(x2), std::move(x3), std::move(x4));} template< class AsTupleNext1, class AsTupleNext2, class AsTupleNext3, class AsTupleNext4, class AsTupleNext5> auto operator()( AsTupleNext1 x1, AsTupleNext2 x2, AsTupleNext3 x3, AsTupleNext4 x4, AsTupleNext5 x5) const -> decltype(std::make_tuple( std::move(x1), std::move(x2), std::move(x3), std::move(x4), std::move(x5))) { return std::make_tuple( std::move(x1), std::move(x2), std::move(x3), std::move(x4), std::move(x5));} }; #endif //RXCPP_USE_VARIADIC_TEMPLATES struct pass_through { template<class X> typename std::decay<X>::type operator()(X&& x) {return std::forward<X>(x);} template<class X> typename std::decay<X>::type operator()(X&& x) const {return std::forward<X>(x);} }; struct pass_through_second { template<class X, class Y> typename std::decay<Y>::type operator()(X&& , Y&& y) {return std::forward<Y>(y);} template<class X, class Y> typename std::decay<Y>::type operator()(X&& , Y&& y) const {return std::forward<Y>(y);} }; template<typename Function> class unwinder { public: ~unwinder() { if (!!function) { try { (*function)(); } catch (...) { std::unexpected(); } } } explicit unwinder(Function* functionArg) : function(functionArg) { } void dismiss() { function = nullptr; } private: unwinder(); unwinder(const unwinder&); unwinder& operator=(const unwinder&); Function* function; }; }} #define RXCPP_UNWIND(Name, Function) \ RXCPP_UNWIND_EXPLICIT(uwfunc_ ## Name, Name, Function) #define RXCPP_UNWIND_AUTO(Function) \ RXCPP_UNWIND_EXPLICIT(RXCPP_MAKE_IDENTIFIER(uwfunc_), RXCPP_MAKE_IDENTIFIER(unwind_), Function) #define RXCPP_UNWIND_EXPLICIT(FunctionName, UnwinderName, Function) \ auto FunctionName = (Function); \ rxcpp::util::unwinder<decltype(FunctionName)> UnwinderName(std::addressof(FunctionName)) #endif
32.846758
157
0.479574
schiebel
d2e7b98ec8ccc4359595183dba360d00a0802797
4,253
hh
C++
opticksgeo/OpticksGen.hh
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
11
2020-07-05T02:39:32.000Z
2022-03-20T18:52:44.000Z
opticksgeo/OpticksGen.hh
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
null
null
null
opticksgeo/OpticksGen.hh
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
4
2020-09-03T20:36:32.000Z
2022-01-19T07:42:21.000Z
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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 class OpticksHub ; class OpticksGun ; class Opticks ; template <typename T> class NPY ; template <typename T> class OpticksCfg ; class NLookup ; class NCSG ; class GGeo ; class GGeoBase ; class GBndLib ; class GenstepNPY ; class TorchStepNPY ; class FabStepNPY ; class NEmitPhotonsNPY ; #include "OKGEO_API_EXPORT.hh" #include "plog/Severity.h" /** OpticksGen : High level genstep control ========================================== Canonical instance m_gen is member of OpticksHub and is instanciated by OpticksHub::init after geometry has been loaded or adopted. m_gen pointers are available in the principal users * okop/OpMgr * ok/OKMgr * okg4/OKG4Mgr Hmm seems not used in G4Opticks world, so its in decline ? **/ class OKGEO_API OpticksGen { static const plog::Severity LEVEL ; friend class OpMgr ; // for setInputGensteps friend class OpticksHub ; // for getTorchstep getGenstepNPY getG4GunConfig friend class CGenerator ; // for getTorchstep getGenstepNPY getG4GunConfig friend struct OpSeederTest ; // for makeFabstep public: OpticksGen(OpticksHub* hub); public: unsigned getSourceCode() const ; public: Opticks* getOpticks() const ; NPY<float>* getInputPhotons() const ; // currently only used for NCSG emitter testing NPY<float>* getInputGensteps() const ; private: static int Preinit() ; FabStepNPY* getFabStep() const ; TorchStepNPY* getTorchstep() const ; GenstepNPY* getGenstepNPY() const ; std::string getG4GunConfig() const ; private: NEmitPhotonsNPY* getEmitter() const ; private: FabStepNPY* makeFabstep(); private: void init(); unsigned initSourceCode() const ; void initFromLegacyGensteps(); void initFromDirectGensteps(); void initFromEmitterGensteps(); private: NPY<float>* makeLegacyGensteps(unsigned gencode); NPY<float>* loadLegacyGenstepFile(const char* label); TorchStepNPY* makeTorchstep(unsigned gencode); private: // FabStepNPY and TorchStepNPY are specializations of GenstepNPY void targetGenstep( GenstepNPY* gs ); void setMaterialLine( GenstepNPY* gs ); private: void setLegacyGensteps(NPY<float>* igs); void setInputPhotons(NPY<float>* iox); private: int m_preinit ; OpticksHub* m_hub ; OpticksGun* m_gun ; Opticks* m_ok ; OpticksCfg<Opticks>* m_cfg ; GGeo* m_ggeo ; GGeoBase* m_ggb ; GBndLib* m_blib ; NLookup* m_lookup ; TorchStepNPY* m_torchstep ; FabStepNPY* m_fabstep ; NCSG* m_csg_emit ; bool m_dbgemit ; // --dbgemit NEmitPhotonsNPY* m_emitter ; NPY<float>* m_input_photons ; unsigned m_tagoffset ; NPY<float>* m_direct_gensteps ; NPY<float>* m_legacy_gensteps ; unsigned m_source_code ; };
32.715385
106
0.582177
hanswenzel
d2ed5a4e3897ff6ee3114771e5b733a9c69c1683
7,612
cpp
C++
Chapter_12/Figures/Fig_12_5.cpp
mtrdazzo/Deitel
4efc02147a1768125d2e27d7d68f664c4628cdc5
[ "MIT" ]
1
2021-09-07T19:23:24.000Z
2021-09-07T19:23:24.000Z
Chapter_12/Figures/Fig_12_5.cpp
mtrdazzo/Deitel
4efc02147a1768125d2e27d7d68f664c4628cdc5
[ "MIT" ]
null
null
null
Chapter_12/Figures/Fig_12_5.cpp
mtrdazzo/Deitel
4efc02147a1768125d2e27d7d68f664c4628cdc5
[ "MIT" ]
null
null
null
/** * @file Fig_12_5.cpp * @author Matthew J Randazzo (mtrdazzo@gmail.com) * @brief Show example of dynamic polymorhpism * @version 0.1 * @date 2020-07-14 * * @copyright Copyright (c) 2020 * */ #include <iostream> #include <iomanip> #include "CommissionEmployee2.h" #include "BasePlusCommissionEmployee2.h" /** * @brief Construct a new Commission Employee:: Commission Employee object * * @param first first name of employee * @param last last name of employee * @param ssn social security number of employee * @param sales the gross sales amount * @param rate the commission rate */ CommissionEmployee::CommissionEmployee(const std::string& first, const std::string&last, const std::string& ssn, double sales, double rate) { setFirstName(first); setLastName(last); setSocialSecurityNumber(ssn); setGrossSales(sales); setCommissionRate(rate); } /** * @brief Set the first name of the employee * * @param first first name of employee */ void CommissionEmployee::setFirstName(const std::string& first) { if (!first.length()) throw std::invalid_argument("empty first name"); else if (first.length() > MAX_INPUT_LENGTH) firstName = first.substr(0, MAX_INPUT_LENGTH); else firstName = first; } /** * @brief Get the first name of the employee * * @return std::string first name of the employee */ std::string CommissionEmployee::getFirstName() const { return firstName; } /** * @brief Set the last name of the employee * * @param last last name of employee */ void CommissionEmployee::setLastName(const std::string& last) { if (!last.length()) throw std::invalid_argument("empty last name"); else if (last.length() > MAX_INPUT_LENGTH) lastName = last.substr(0, MAX_INPUT_LENGTH); else lastName = last; } /** * @brief Get the last name of the employee * * @return std::string last name of the employee */ std::string CommissionEmployee::getLastName() const { return lastName; } /** * @brief Set the social security number of the employee * * @param ssn 9 digit social security number */ void CommissionEmployee::setSocialSecurityNumber(const std::string &ssn) { if (ssn.length() != SSN_LENGTH) { throw std::invalid_argument("invalid ssn, must be nine digits"); } else { for (size_t index{0}; index < SSN_LENGTH; ++index) if (!std::isdigit(ssn.at(index))) { throw std::invalid_argument("invalid ssn, must be nine digits"); } } socialSecurityNumber = ssn; } /** * @brief Get the social security number of the employee * * @return std::string 9-digit social secutity number */ std::string CommissionEmployee::getSocialSecurityNumber() const { return socialSecurityNumber; } /** * @brief Set the employee's commission rate * * @param rate Employee commission rate (%) */ void CommissionEmployee::setCommissionRate(double rate) { if (rate <= 0.0 || rate >= 1.0) throw std::invalid_argument("commission rate must be > 0.0 and < 1.0"); commissionRate = rate; } /** * @brief Get the employee's commission rate * * @return double Employee commission rate (%) */ double CommissionEmployee::getCommissionRate() const { return commissionRate; } /** * @brief Set the gross sales in dollars * * @param sales Gross sales in dollars */ void CommissionEmployee::setGrossSales(double sales) { if (sales < 0.0) throw std::invalid_argument("gross sales must be >= 0.0"); grossSales = sales; } /** * @brief Get the gross sales of the employee * * @return double Gross sales in dollars */ double CommissionEmployee::getGrossSales() const { return grossSales; } /** * @brief Output the employee information * * @return std::string */ std::string CommissionEmployee::toString() const { std::ostringstream output; output << std::fixed << std::setprecision(2); output << "commission employee: " << firstName << " " << lastName << "\nsocial security number: " << socialSecurityNumber << "\ngross sales: " << grossSales << "\ncommission rate: " << commissionRate; return output.str(); } /** * @brief Total earnings of the employee * * @return double earnings in dollars */ double CommissionEmployee::earnings() const { return grossSales * commissionRate; } /** * @brief Construct a new Commission Employee:: Commission Employee object * * @param first first name of employee * @param last last name of employee * @param ssn social security number of employee * @param sales the gross sales amount * @param rate the commission rate * @param base the base salary of the employee */ BasePlusCommissionEmployee::BasePlusCommissionEmployee(const std::string& first, const std::string&last, const std::string& ssn, double sales, double rate, double base) : CommissionEmployee(first, last, ssn, sales, rate) { setBaseSalary(base); } /** * @brief Output the employee information * * @return std::string */ std::string BasePlusCommissionEmployee::toString() const { std::ostringstream output; output << CommissionEmployee::toString() << "\nbase salary: " << baseSalary; return output.str(); } /** * @brief Total earnings of the employee * * @return double earnings in dollars */ double BasePlusCommissionEmployee::earnings() const { return baseSalary + CommissionEmployee::earnings(); } /** * @brief Set the base salary of the employee * * @param base Base salary in dollars */ void BasePlusCommissionEmployee::setBaseSalary(double base) { if (base <= 0.0) throw std::invalid_argument("base salary must be >= 0.0"); baseSalary = base; } /** * @brief Get the base salary of the employee * * @return double base salary in dollars */ double BasePlusCommissionEmployee::getBaseSalary() const { return baseSalary; } int main() { CommissionEmployee commissionEmployee{"Sue", "Jones", "222222222", 10000, .06}; BasePlusCommissionEmployee basePlusCommissionEmployee{"Bob", "Lewis", "333333333", 5000, .04, 300}; std::cout << std::fixed << std::setprecision(2) << "\n"; std::cout << "DISPLAY BASE-CLASS AND DERIVED-CLASS OBJECTS:\n" << commissionEmployee.toString() << "\n\n" << basePlusCommissionEmployee.toString(); /* natural: aim base-class pointer at base-class object */ CommissionEmployee *commissionEmployeePtr{&commissionEmployee}; std::cout << "\n\nCALLING TOSTRING WITH BASE-CLASS POINTER TO " << "\nBASE-CLASS OBJECT INVOKES BASE-CLASS TOSTRING FUNCTION:\n" << commissionEmployeePtr->toString(); /* natural: aim derived-class pointer to derived-class object */ BasePlusCommissionEmployee *basePlusCommissionEmployeePtr{&basePlusCommissionEmployee}; std::cout << "\n\nCALLING TOSTRING WITH DERIVED-CLASS POINTER TO " << "\nDERIVED-CLASS OBJECT INVOKES DERIVED-CLASS TOSTRING FUNCTION:\n" << basePlusCommissionEmployeePtr->toString(); /* aim base-class pointer to derived-class object */ commissionEmployeePtr = &basePlusCommissionEmployee; /* polymorphism: invokes BasePlusCommissionEmployee's toString via base-class pointer, example of dynamic polymorphism */ std::cout << "\n\nCALLING TOSTRING WITH BASE-CLASS POINTER TO " << "\nDERIVED-CLASS OBJECT\nINVOKES DERIVED-CLASS TOSTRING FUNCTION ON THAT DERIVED-CLASS OBJECT:\n" << commissionEmployeePtr->toString() << "\n" << std::endl; return EXIT_SUCCESS; }
28.942966
125
0.679191
mtrdazzo
d2ed706f8b363b7cd001fd30e1fa19c3e986bfe1
106
cc
C++
index_test/test_seek.cc
PudgeXD/courseForLeveldb
5321a35f3a1b1ef2ee6e82cca069d72ae803d1c0
[ "BSD-3-Clause" ]
null
null
null
index_test/test_seek.cc
PudgeXD/courseForLeveldb
5321a35f3a1b1ef2ee6e82cca069d72ae803d1c0
[ "BSD-3-Clause" ]
null
null
null
index_test/test_seek.cc
PudgeXD/courseForLeveldb
5321a35f3a1b1ef2ee6e82cca069d72ae803d1c0
[ "BSD-3-Clause" ]
null
null
null
// // Created by rui on 19-6-10. // #include <iostream> using namespace std; int main(){ return 0; }
8.833333
29
0.613208
PudgeXD
d2ed736990e1208ac482d11c480f9fd230cc1596
6,270
hpp
C++
cpp-projects/exvr-designer/data/states.hpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
cpp-projects/exvr-designer/data/states.hpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
cpp-projects/exvr-designer/data/states.hpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
/*********************************************************************************** ** exvr-designer ** ** MIT License ** ** Copyright (c) [2018] [Florian Lance][EPFL-LNCO] ** ** 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 // base #include "utility/tuple_array.hpp" // qt-utility #include "data/unity_types.hpp" // local #include "element.hpp" namespace tool::ex { using namespace std::literals::string_view_literals; enum class ExpLauncherCommand : int{ Load=0, Play, Pause, Stop, Next, Previous, UpdateComponent, UpdateConnector, Quit, Action, GoToSpecificInstanceElement, PlayPause, PlayDelay, Error, Clean, SizeEnum }; enum class ExpLauncherState : int{ NotStarted=0, Starting, Idle, LoadingExperiment, Closing, SizeEnum }; enum class ExpState : int{ NotLoaded = 0, Loaded, Running, Paused, SizeEnum }; using Description = std::string_view; using TExpLauncherState = std::tuple<ExpLauncherState, Description>; static constexpr TupleArray<ExpLauncherState::SizeEnum, TExpLauncherState> expLauncherStates = {{ TExpLauncherState {ExpLauncherState::NotStarted, "[ExVR-exp] ExVR-exp not launched."sv}, {ExpLauncherState::Starting, "[ExVR-exp] ExVR-exp is starting."sv}, {ExpLauncherState::Idle, "[ExVR-exp] Idle."sv}, {ExpLauncherState::LoadingExperiment, "[ExVR-exp] ExVR-exp is loading an experiment..."sv}, {ExpLauncherState::Closing, "[ExVR-exp] ExVR-exp is closing."sv}, }}; [[maybe_unused]] static Description get_description(ExpLauncherState s) { return expLauncherStates.at<0,1>(s); } using TExpState = std::tuple<ExpState, Description>; static constexpr TupleArray<ExpState::SizeEnum, TExpState> expStates = {{ TExpState {ExpState::NotLoaded, "[ExVR-exp] <b>No experiment loaded.</b>"sv}, {ExpState::Loaded, "[ExVR-exp] <b>Experiment loaded</b>"sv}, {ExpState::Running, "[ExVR-exp] <b>Experiment is running</b>"sv}, {ExpState::Paused, "[ExVR-exp] <b>Experiment paused</b>"sv}, }}; [[maybe_unused]] static Description get_description(ExpState s) { return expStates.at<0,1>(s); } [[maybe_unused]] static QString to_command_id(ExpLauncherCommand cmd){ return QString::number(static_cast<int>(cmd)); } enum class FontStyle : int { Normal = 0, Bold = 1, Italic =2, Bold_and_italic =3, SizeEnum}; enum class Alignment : int { UpperLeft = 0, UpperCenter = 1, UpperRight =2, MiddleLeft =3, MiddleCenter = 4, MiddleRight = 5, LowerLeft = 6, LowerCenter =7, LowerRight = 8, SizeEnum}; enum class TextOverlflow : int { Wrap = 0, Overflow = 1, SizeEnum}; struct States{ States(QString nVersion) : numVersion(nVersion){ auto split = numVersion.split("."); majorNumVersion = split[0].toInt(); minorNumVersion = split[1].toInt(); } void reset(){ neverLoaded = true; currentElementKey = -1; currentConditionKey = -1; currentElementName = ""; currentTypeSpecificInfo = ""; experimentTimeS = 0.0; currentElementTimeS = 0.0; currentIntervalEndTimeS = 0.0; currentOrder = ""; nbCalls = ""; } const QString numVersion; int majorNumVersion; int minorNumVersion; int maximumDeepLevel = -1; unsigned int randomizationSeed = 0; QString loadedExpDesignerVersion = "unknow"; QString designerPathUsedForLoadedExp = "unknow"; QString currentExpfilePath; QString currentName = "unknow"; QString currentMode = "designer"; QString currentInstanceName = "debug-instance.xml"; ExpLauncherState explauncherState = ExpLauncherState::NotStarted; ExpState expState = ExpState::NotLoaded; bool followsCurrentCondition = false; bool neverLoaded = true; int currentElementKey=-1; int currentConditionKey=-1; Element::Type currentElementType; QString currentElementName = ""; QString currentTypeSpecificInfo = ""; double experimentTimeS = 0.0; double currentElementTimeS = 0.0; double currentIntervalEndTimeS = 0.0; QString currentOrder = ""; QString nbCalls = ""; }; }
37.771084
151
0.568262
FlorianLance
d2f0a3d686afb1cab613fb674d44c04eb5dd68a7
2,402
cpp
C++
core/utils/Params.cpp
dillonl/ComprehensiveVCFMerge
dee320975c13ba6765fb844b00b90fb56dcff7b2
[ "MIT" ]
null
null
null
core/utils/Params.cpp
dillonl/ComprehensiveVCFMerge
dee320975c13ba6765fb844b00b90fb56dcff7b2
[ "MIT" ]
null
null
null
core/utils/Params.cpp
dillonl/ComprehensiveVCFMerge
dee320975c13ba6765fb844b00b90fb56dcff7b2
[ "MIT" ]
null
null
null
#include "Params.h" #include "Utility.h" namespace cvm { Params::Params(int argc, char** argv) : m_options("CVM", " - Comprehensive VCF Merger (CVM) merges multiple VCF files into a single VCF. CVM reconstructs the sequence of each VCF's alleles with the reference sequence and compares them across all VCFs to discover duplicate variants no matter how the alleles are distributed.") { parse(argc, argv); } Params::~Params() { } void Params::parse(int argc, char** argv) { this->m_options.add_options() ("h,help","Print help message") ("s,silent", "Run without reports") ("r,reference", "Path to input reference (FASTA) file [required]", cxxopts::value< std::string >()) ("v,vcfs", "Path to input VCF files, separate multiple files by space [required]", cxxopts::value< std::vector< std::string > >()) ("l,labels", "Labels for VCF files, separate multiple labels by space [required]", cxxopts::value< std::vector< std::string > >()) ("o,output_vcf", "Output VCF file name [required]", cxxopts::value< std::string >()); this->m_options.parse(argc, argv); } std::vector< std::string > Params::getUsageErrors() { std::vector< std::string > errorMessages; auto vcfCount = m_options.count("v"); auto labelCount = m_options.count("l"); if (vcfCount <= 1 || labelCount <= 1) { errorMessages.emplace_back("You must provide at least 2 vcfs and labels"); } if (vcfCount != labelCount) { errorMessages.emplace_back("Please provide a label for every vcf"); } return errorMessages; } bool Params::showHelp() { return m_options.count("h"); } bool Params::isSilent() { return m_options.count("s"); } std::string Params::getHelpMessage() { return this->m_options.help(); } std::vector< std::string > Params::getInVCFPaths() { auto vcfPaths = m_options["v"].as< std::vector< std::string > >(); validateFilePaths(vcfPaths, true); return vcfPaths; } std::vector< std::string > Params::getInVCFLabels() { return m_options["l"].as< std::vector< std::string > >(); } std::string Params::getReferencePath() { return m_options["r"].as< std::string >(); } std::string Params::getOutVCFPath() { return m_options["o"].as< std::string >(); } void Params::validateFilePaths(const std::vector< std::string >& paths, bool exitOnFailure) { for (auto path : paths) { fileExists(path, exitOnFailure); } } }
27.295455
327
0.669858
dillonl
d2f2cab2889c5bb9c9899bf92bc3b16b8b1d6343
3,917
cc
C++
xls/fuzzer/ast_generator_test.cc
briansrls/xls
35fd94eff68611d510288938469ee620a38e1976
[ "Apache-2.0" ]
null
null
null
xls/fuzzer/ast_generator_test.cc
briansrls/xls
35fd94eff68611d510288938469ee620a38e1976
[ "Apache-2.0" ]
null
null
null
xls/fuzzer/ast_generator_test.cc
briansrls/xls
35fd94eff68611d510288938469ee620a38e1976
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The XLS Authors // // 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 "xls/fuzzer/ast_generator.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "xls/common/init_xls.h" #include "xls/common/logging/log_lines.h" #include "xls/common/status/matchers.h" #include "xls/dslx/command_line_utils.h" #include "xls/dslx/parse_and_typecheck.h" namespace xls::dslx { namespace { // Parses and typechecks the given text to ensure it's valid -- prints errors to // the screen in a useful way for debugging if they fail parsing / typechecking. absl::Status ParseAndTypecheck(absl::string_view text, absl::string_view module_name) { XLS_LOG_LINES(INFO, text); std::string filename = absl::StrCat(module_name, ".x"); auto get_file_contents = [&](absl::string_view path) -> absl::StatusOr<std::string> { XLS_CHECK_EQ(path, filename); return std::string(text); }; ImportCache import_cache; absl::StatusOr<TypecheckedModule> parsed_or = ParseAndTypecheck( text, /*path=*/filename, /*module_name=*/module_name, &import_cache); TryPrintError(parsed_or.status(), get_file_contents); XLS_ASSIGN_OR_RETURN(TypecheckedModule parsed, parsed_or); XLS_RETURN_IF_ERROR(parsed.module->GetFunctionOrError("main").status()); return absl::OkStatus(); } // Simply tests that we generate a bunch of valid functions using seed 0 (that // parse and typecheck). TEST(AstGeneratorTest, GeneratesValidFunctions) { std::mt19937 rng(0); AstGeneratorOptions options; options.short_samples = true; for (int64 i = 0; i < 32; ++i) { AstGenerator g(options, &rng); XLS_LOG(INFO) << "Generating sample: " << i; std::string module_name = absl::StrFormat("sample_%d", i); XLS_ASSERT_OK_AND_ASSIGN(auto generated, g.GenerateFunctionInModule("main", module_name)); std::string text = generated.second->ToString(); // Parses/typechecks as well, which is primarily what we're testing here. XLS_ASSERT_OK(ParseAndTypecheck(text, module_name)); } } // Helper function that is used in a TEST_P so we can shard the work. static void TestRepeatable(int64 seed) { AstGeneratorOptions options; options.short_samples = true; // Capture first output at a given seed for comparison. absl::optional<std::string> first; // Try 32 generations at a given seed. for (int64 i = 0; i < 32; ++i) { std::mt19937 rng(seed); AstGenerator g(options, &rng); XLS_ASSERT_OK_AND_ASSIGN(auto generated, g.GenerateFunctionInModule("main", "test")); std::string text = generated.second->ToString(); if (first.has_value()) { ASSERT_EQ(text, *first) << "sample " << i << " seed " << seed; } else { first = text; // Parse and typecheck for good measure. XLS_ASSERT_OK(ParseAndTypecheck(text, "test")); } } } class AstGeneratorRepeatableTest : public testing::TestWithParam<int64> {}; TEST_P(AstGeneratorRepeatableTest, GenerationRepeatableAtSeed) { TestRepeatable(/*seed=*/GetParam()); } INSTANTIATE_TEST_SUITE_P(AstGeneratorRepeatableTestInstance, AstGeneratorRepeatableTest, testing::Range(int64{0}, int64{1024})); } // namespace } // namespace xls::dslx int main(int argc, char* argv[]) { xls::InitXls(argv[0], argc, argv); return RUN_ALL_TESTS(); }
35.93578
80
0.695941
briansrls
d2f9f0259bea14a23a0c25a5b9f2f6c8da1e5a76
5,250
hpp
C++
common/StringLinq.hpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
18
2018-10-22T10:30:20.000Z
2021-12-10T06:29:39.000Z
common/StringLinq.hpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
null
null
null
common/StringLinq.hpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
4
2019-06-04T14:04:43.000Z
2021-07-16T01:41:48.000Z
#pragma once #include "Linq2.hpp" #include "SharedString.hpp" #include "StrBase.hpp" #include <string> #include <string_view> namespace common::str { namespace detail { template<typename Char, typename Judger> struct SplitSource { public: using OutType = std::basic_string_view<Char>; static constexpr bool ShouldCache = false; static constexpr bool InvolveCache = false; static constexpr bool IsCountable = false; static constexpr bool CanSkipMultiple = false; std::basic_string_view<Char> Source; Judger Splitter; size_t CurPos, LastPos; bool KeepBlank; constexpr SplitSource(std::basic_string_view<Char> source, Judger&& splitter, const bool keepBlank) noexcept : Source(source), Splitter(std::forward<Judger>(splitter)), CurPos(0), LastPos(0), KeepBlank(keepBlank) { FindNextSplitPoint(); } [[nodiscard]] constexpr OutType GetCurrent() const noexcept { return Source.substr(LastPos, CurPos - LastPos); } constexpr void MoveNext() noexcept { LastPos = ++CurPos; FindNextSplitPoint(); } [[nodiscard]] constexpr bool IsEnd() const noexcept { return LastPos > Source.size(); } private: constexpr void FindNextSplitPoint() noexcept { for (; CurPos < Source.size(); CurPos++) { if (Splitter(Source[CurPos])) { if (KeepBlank || CurPos != LastPos) return; else // !KeepBlank && Cur==Last LastPos++; // skip this part } } // Cur==Last means already reaches end, but if Cur==Size, it will report non-end for empty endpart if (CurPos == LastPos && !KeepBlank) CurPos++, LastPos++; } }; template<typename T, typename Char, typename Judger> struct ContainedSplitSource : public common::linq::detail::ObjCache<T>, public SplitSource<Char, Judger> { constexpr ContainedSplitSource(T&& obj, Judger&& splitter, const bool keepBlank) noexcept : common::linq::detail::ObjCache<T>(std::move(obj)), SplitSource<Char, Judger>(ToStringView(this->Obj()), std::forward<Judger>(splitter), keepBlank) { } }; template<typename Char, typename T, typename Judger> [[nodiscard]] inline constexpr auto ToSplitStream(T&& source, Judger&& judger, const bool keepblank) noexcept { if constexpr (!std::is_invocable_r_v<bool, Judger, Char>) { if constexpr (std::is_same_v<Char, std::decay_t<Judger>>) return ToSplitStream<Char>(std::forward<T>(source), [=](const Char ch) noexcept { return ch == judger; }, keepblank); else static_assert(!common::AlwaysTrue<T>, "Judger should be delim of Char or a callable that check if Char is a delim"); //static_assert(std::is_invocable_r_v<bool, Judger, Char>, "Splitter should accept char and return (bool) if should split here."); } else { using U = std::decay_t<T>; if constexpr (std::is_same_v<U, std::basic_string_view<Char>>) return common::linq::ToEnumerable(SplitSource<Char, Judger> (std::move(source), std::forward<Judger>(judger), keepblank)); else return common::linq::ToEnumerable(ContainedSplitSource<U, Char, Judger> (std::move(source), std::forward<Judger>(judger), keepblank)); } } } /** ** @brief split source into an enumerable using judger ** @param src string source ** @param judger a delim or a function that accepts one element and return (bool) whether it is delim ** @param keepblank whether should keep blank slice ** @return an enumerable that can retrieve slices **/ template<typename T, typename Judger> [[nodiscard]] inline constexpr auto SplitStream(T&& source, Judger&& judger, const bool keepblank = true) noexcept { using U = std::decay_t<T>; if constexpr (std::is_pointer_v<U>) { auto sv = std::basic_string_view(source); using Char = typename decltype(sv)::value_type; return detail::ToSplitStream<Char>(sv, std::forward<Judger>(judger), keepblank); } else if constexpr (common::has_valuetype_v<U>) { using Char = typename U::value_type; if constexpr (std::is_rvalue_reference_v<T>) { return detail::ToSplitStream<Char>(std::move(source), std::forward<Judger>(judger), keepblank); } else { return detail::ToSplitStream<Char>(ToStringView(std::forward<T>(source)), std::forward<Judger>(judger), keepblank); } } else { static_assert(!common::AlwaysTrue<T>, "unsupportted Source type"); } } /** ** @brief split source into a vector of slice using judger ** @param src string source ** @param judger a delim or a function that accepts one element and return (bool) whether it is delim ** @param keepblank whether should keep blank slice ** @return an vector that contains all slices **/ template<typename T, typename Judger> [[nodiscard]] inline constexpr auto Split(T&& source, Judger&& judger, const bool keepblank = true) noexcept { return SplitStream(std::forward<T>(source), std::forward<Judger>(judger), keepblank) .ToVector(); } }
33.870968
138
0.651429
mfkiwl
d2fcc65acb0ec4dbb237827ea399e216cbf7cd16
5,286
hpp
C++
include/RootMotion/FinalIK/RagdollUtility_Child.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/RootMotion/FinalIK/RagdollUtility_Child.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/RootMotion/FinalIK/RagdollUtility_Child.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// 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: RootMotion.FinalIK.RagdollUtility #include "RootMotion/FinalIK/RagdollUtility.hpp" // Including type: UnityEngine.Vector3 #include "UnityEngine/Vector3.hpp" // Including type: UnityEngine.Quaternion #include "UnityEngine/Quaternion.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: UnityEngine namespace UnityEngine { // Forward declaring type: Transform class Transform; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::RootMotion::FinalIK::RagdollUtility::Child); DEFINE_IL2CPP_ARG_TYPE(::RootMotion::FinalIK::RagdollUtility::Child*, "RootMotion.FinalIK", "RagdollUtility/Child"); // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Size: 0x34 #pragma pack(push, 1) // Autogenerated type: RootMotion.FinalIK.RagdollUtility/RootMotion.FinalIK.Child // [TokenAttribute] Offset: FFFFFFFF class RagdollUtility::Child : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // public UnityEngine.Transform t // Size: 0x8 // Offset: 0x10 ::UnityEngine::Transform* t; // Field size check static_assert(sizeof(::UnityEngine::Transform*) == 0x8); // public UnityEngine.Vector3 localPosition // Size: 0xC // Offset: 0x18 ::UnityEngine::Vector3 localPosition; // Field size check static_assert(sizeof(::UnityEngine::Vector3) == 0xC); // public UnityEngine.Quaternion localRotation // Size: 0x10 // Offset: 0x24 ::UnityEngine::Quaternion localRotation; // Field size check static_assert(sizeof(::UnityEngine::Quaternion) == 0x10); public: // Get instance field reference: public UnityEngine.Transform t ::UnityEngine::Transform*& dyn_t(); // Get instance field reference: public UnityEngine.Vector3 localPosition ::UnityEngine::Vector3& dyn_localPosition(); // Get instance field reference: public UnityEngine.Quaternion localRotation ::UnityEngine::Quaternion& dyn_localRotation(); // public System.Void .ctor(UnityEngine.Transform transform) // Offset: 0x1F71B84 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RagdollUtility::Child* New_ctor(::UnityEngine::Transform* transform) { static auto ___internal__logger = ::Logger::get().WithContext("::RootMotion::FinalIK::RagdollUtility::Child::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RagdollUtility::Child*, creationType>(transform))); } // public System.Void FixTransform(System.Single weight) // Offset: 0x1F727CC void FixTransform(float weight); // public System.Void StoreLocalState() // Offset: 0x1F7277C void StoreLocalState(); }; // RootMotion.FinalIK.RagdollUtility/RootMotion.FinalIK.Child #pragma pack(pop) static check_size<sizeof(RagdollUtility::Child), 36 + sizeof(::UnityEngine::Quaternion)> __RootMotion_FinalIK_RagdollUtility_ChildSizeCheck; static_assert(sizeof(RagdollUtility::Child) == 0x34); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: RootMotion::FinalIK::RagdollUtility::Child::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: RootMotion::FinalIK::RagdollUtility::Child::FixTransform // Il2CppName: FixTransform template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::RagdollUtility::Child::*)(float)>(&RootMotion::FinalIK::RagdollUtility::Child::FixTransform)> { static const MethodInfo* get() { static auto* weight = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::RagdollUtility::Child*), "FixTransform", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{weight}); } }; // Writing MetadataGetter for method: RootMotion::FinalIK::RagdollUtility::Child::StoreLocalState // Il2CppName: StoreLocalState template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::RagdollUtility::Child::*)()>(&RootMotion::FinalIK::RagdollUtility::Child::StoreLocalState)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::RagdollUtility::Child*), "StoreLocalState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
47.621622
192
0.723231
RedBrumbler
d2fd3a734d71d5af651bcceb133dbba657137ea1
2,216
hpp
C++
include/mlcmst_subnet_solver.hpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
include/mlcmst_subnet_solver.hpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
include/mlcmst_subnet_solver.hpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <vector> #include <unordered_map> #include <mlcmst_solver.hpp> #include <network/mlcst.hpp> #include <network/mlcc_network.hpp> namespace MLCMST { class MLCMST_SubnetSolver final { public: struct Result { double cost; network::MLCST mlcmst; std::vector<int> mapping; }; explicit MLCMST_SubnetSolver(std::unique_ptr<MLCMST_Solver> solver); ~MLCMST_SubnetSolver(); std::pair<network::MLCST, std::vector<int>> subnetTree( const network::MLCCNetwork& network, const std::vector<int>& subnet_vertices); double subnetTreeCost(const network::MLCCNetwork& network, const std::vector<int>& subnet_vertices); std::unordered_map<int, std::pair< network::MLCST, std::vector<int> >> allSubnetTrees( const network::MLCCNetwork& network, const std::vector<int>& vertex_subnet); std::unordered_map<int, double> allSubnetTreeCosts( const network::MLCCNetwork& network, const std::vector<int>& vertex_subnet); std::unordered_map<int, std::pair< network::MLCST, std::vector<int> > >allSubnetTrees( const network::MLCCNetwork& network, const std::unordered_map<int,std::vector<int>>& groups); std::unordered_map<int, double> allSubnetTreeCosts( const network::MLCCNetwork& network, const std::unordered_map<int,std::vector<int>>& groups); std::unordered_map<int, Result> solveAllSubnets( const network::MLCCNetwork& network, const std::vector<int>& subnet_vertices); std::unordered_map<int, Result> solveAllSubnets( const network::MLCCNetwork& network, const std::unordered_map<int, std::vector<int>>& groups); Result solveSubnet(const network::MLCCNetwork& network, std::vector<int> subnet_vertices); network::MLCST solveMLCMST(const network::MLCCNetwork& network, const std::vector<int>& vertex_subnet); network::MLCST solveMLCMST( const network::MLCCNetwork& network, const std::unordered_map<int, std::vector<int>>& groups); private: std::unique_ptr< MLCMST_Solver > solver_; std::unordered_map<int, std::vector<int>> createGroups(int center, const std::vector<int>& vertex_subnet); }; }
37.559322
110
0.707581
qaskai
d2fd7683f392dccc2ae25fe42c300accb25f55e8
1,329
cpp
C++
Divide and Conquer/Median of Arrays/median.cpp
Subrato-oid/cs-algorithms
4a04fe49f513c439b641a8e4e783a98cd99dc909
[ "MIT" ]
239
2019-10-07T11:01:56.000Z
2022-01-27T19:08:55.000Z
Divide and Conquer/Median of Arrays/median.cpp
ashfreakingoyal/cs-algorithms
08f5aba5c3379e17d03b899fc36efcdccebd181c
[ "MIT" ]
176
2019-10-07T06:59:49.000Z
2020-09-30T08:16:22.000Z
Divide and Conquer/Median of Arrays/median.cpp
ashfreakingoyal/cs-algorithms
08f5aba5c3379e17d03b899fc36efcdccebd181c
[ "MIT" ]
441
2019-10-07T07:34:08.000Z
2022-03-15T07:19:58.000Z
#include <bits/stdc++.h> using namespace std; int getMedian(int arr1[], int arr2[], int n, int m) { int i = 0; int j = 0; int c; int m1 = -1, m2 = -1; if((m + n) % 2 == 1) { for (c = 0; c <= (n + m)/2; c++) { if(i != n && j != m) { m1 = (arr1[i] > arr2[j]) ? arr2[j++] : arr1[i++]; } else if(i < n) { m1 = arr1[i++]; } else { m1 = arr1[j++]; } } return m1; } else { for (c = 0; c <= (n + m)/2; c++) { m2 = m1; if(i != n && j != m) { m1 = (arr1[i] > arr2[j]) ? arr2[j++] : arr1[i++]; } else if(i < n) { m1 = arr1[i++]; } else { m1 = arr1[j++]; } } return (m1 + m2)/2; } } int main() { int arr1[] = {900}; int arr2[] = {5, 9, 10, 20}; int n1 = sizeof(arr1)/sizeof(arr1[0]); int n2 = sizeof(arr2)/sizeof(arr2[0]); cout << getMedian(arr1, arr2, n1, n2); return 0; }
20.765625
67
0.274643
Subrato-oid
d2fde39d3312861e422d572705ab0f367ecd058e
896
cpp
C++
libcxx/test/libcxx/inclusions/algorithm.inclusions.compile.pass.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
libcxx/test/libcxx/inclusions/algorithm.inclusions.compile.pass.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
libcxx/test/libcxx/inclusions/algorithm.inclusions.compile.pass.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // WARNING: This test was generated by generate_header_inclusion_tests.py // and should not be edited manually. // // clang-format off // <algorithm> // Test that <algorithm> includes all the other headers it's supposed to. #include <algorithm> #include "test_macros.h" #if !defined(_LIBCPP_ALGORITHM) # error "<algorithm> was expected to define _LIBCPP_ALGORITHM" #endif #if TEST_STD_VER > 03 && !defined(_LIBCPP_INITIALIZER_LIST) # error "<algorithm> should include <initializer_list> in C++11 and later" #endif
33.185185
80
0.610491
mkinsner
96008798fa441c14a9ebc14e9f8bc85a8d7a7bbd
5,245
cpp
C++
c_plus_plus/multiround/communicationobjects/sendplanepositionscommobj.cpp
temp-byte/planes
025eddfe5ff52ed5ca65cedfea0ce4f346a78b65
[ "MIT" ]
18
2018-07-24T20:07:14.000Z
2022-02-06T23:17:10.000Z
c_plus_plus/multiround/communicationobjects/sendplanepositionscommobj.cpp
temp-byte/planes
025eddfe5ff52ed5ca65cedfea0ce4f346a78b65
[ "MIT" ]
18
2020-05-25T17:50:36.000Z
2022-01-12T12:39:51.000Z
c_plus_plus/multiround/communicationobjects/sendplanepositionscommobj.cpp
temp-byte/planes
025eddfe5ff52ed5ca65cedfea0ce4f346a78b65
[ "MIT" ]
5
2018-07-25T00:47:00.000Z
2022-01-10T07:16:17.000Z
#include "sendplanepositionscommobj.h" #include <QMessageBox> #include "viewmodels/planespositionsviewmodel.h" #include "multiplayerround.h" bool SendPlanePositionsCommObj::makeRequest() { if (m_GlobalData->m_UserData.m_UserName.isEmpty()) { QMessageBox msgBox(m_ParentWidget); msgBox.setText("No user logged in"); msgBox.exec(); return false; } PlanesPositionsViewModel planesPositionsData; planesPositionsData.m_GameId = m_GlobalData->m_GameData.m_GameId; planesPositionsData.m_RoundId = m_GlobalData->m_GameData.m_RoundId; planesPositionsData.m_OwnUserId = m_GlobalData->m_UserData.m_UserId; planesPositionsData.m_OpponentUserId = m_GlobalData->m_GameData.m_OtherUserId; Plane pl1; Plane pl2; Plane pl3; m_MultiRound->getPlayerPlaneNo(0, pl1); m_MultiRound->getPlayerPlaneNo(1, pl2); m_MultiRound->getPlayerPlaneNo(2, pl3); planesPositionsData.m_Plane1X = pl1.row(); planesPositionsData.m_Plane1Y = pl1.col(); planesPositionsData.m_Plane1Orient = pl1.orientation(); planesPositionsData.m_Plane2X = pl2.row(); planesPositionsData.m_Plane2Y = pl2.col(); planesPositionsData.m_Plane2Orient = pl2.orientation(); planesPositionsData.m_Plane3X = pl3.row(); planesPositionsData.m_Plane3Y = pl3.col(); planesPositionsData.m_Plane3Orient = pl3.orientation(); //qDebug() << "Plane 1 " << pl1.row() << " " << pl1.col() << " " << (int)pl1.orientation(); //qDebug() << "Plane 2 " << pl2.row() << " " << pl2.col() << " " << (int)pl2.orientation(); //qDebug() << "Plane 3 " << pl3.row() << " " << pl3.col() << " " << (int)pl3.orientation(); m_RequestData = planesPositionsData.toJson(); makeRequestBasis(true); return true; } void SendPlanePositionsCommObj::finishedRequest() { QJsonObject retJson; if (!finishRequestHelper(retJson)) return; bool roundCancelled = retJson.value("cancelled").toBool(); if (roundCancelled) { m_MultiRound->setRoundCancelled(); //activateStartGameTab(); emit roundCancelled; return; } bool otherPositionsExist = retJson.value("otherExist").toBool(); if (otherPositionsExist) { int plane1_x = retJson.value("plane1_x").toInt(); int plane1_y = retJson.value("plane1_y").toInt(); int plane1_orient = retJson.value("plane1_orient").toInt(); int plane2_x = retJson.value("plane2_x").toInt(); int plane2_y = retJson.value("plane2_y").toInt(); int plane2_orient = retJson.value("plane2_orient").toInt(); int plane3_x = retJson.value("plane3_x").toInt(); int plane3_y = retJson.value("plane3_y").toInt(); int plane3_orient = retJson.value("plane3_orient").toInt(); //qDebug() << "Plane 1 from opponent " << plane1_x << " " << plane1_y << " " << plane1_orient; //qDebug() << "Plane 2 from opponent" << plane2_x << " " << plane2_y << " " << plane2_orient; //qDebug() << "Plane 3 from opponent" << plane3_x << " " << plane3_y << " " << plane3_orient; bool setOk = m_MultiRound->setComputerPlanes(plane1_x, plane1_y, (Plane::Orientation)plane1_orient, plane2_x, plane2_y, (Plane::Orientation)plane2_orient, plane3_x, plane3_y, (Plane::Orientation)plane3_orient); if (!setOk) { QMessageBox msgBox(m_ParentWidget); msgBox.setText("Planes positions from opponent are not valid"); msgBox.exec(); return; } emit opponentPlanePositionsReceived(); } else { m_MultiRound->setCurrentStage(AbstractPlaneRound::GameStages::WaitForOpponentPlanesPositions); emit waitForOpponentPlanePositions(); } } bool SendPlanePositionsCommObj::validateReply(const QJsonObject& reply) { if (!((reply.contains("otherExist") && reply.contains("cancelled") && reply.contains("plane1_x") && reply.contains("plane1_y") && reply.contains("plane1_orient") && reply.contains("plane2_x") && reply.contains("plane2_y") && reply.contains("plane2_orient") && reply.contains("plane3_x") && reply.contains("plane3_y") && reply.contains("plane3_orient")))) return false; if (!reply.value("otherExist").isBool() || !reply.value("cancelled").isBool()) return false; if (!reply.value("plane1_x").isDouble() || !reply.value("plane1_y").isDouble() && !reply.value("plane1_orient").isDouble() || !reply.value("plane2_x").isDouble() || !reply.value("plane2_y").isDouble() || !reply.value("plane2_orient").isDouble() || !reply.value("plane3_x").isDouble() || !reply.value("plane3_y").isDouble() || !reply.value("plane3_orient").isDouble()) return false; if (!checkInt(reply.value("plane1_x")) || !checkInt(reply.value("plane1_y")) && !checkInt(reply.value("plane1_orient")) || !checkInt(reply.value("plane2_x")) || !checkInt(reply.value("plane2_y")) || !checkInt(reply.value("plane2_orient")) || !checkInt(reply.value("plane3_x")) || !checkInt(reply.value("plane3_y")) || !checkInt(reply.value("plane3_orient"))) return false; return true; }
45.608696
218
0.647092
temp-byte
9601782884722b4a1c497fbb5e7b9cf01da189da
309
cpp
C++
LearnOpenGL/SimpleTriangles.cpp
VestLee/LearnOpenGL
68e93a1f7516b797febe90c87261f0ff3c571d7e
[ "MIT" ]
null
null
null
LearnOpenGL/SimpleTriangles.cpp
VestLee/LearnOpenGL
68e93a1f7516b797febe90c87261f0ff3c571d7e
[ "MIT" ]
null
null
null
LearnOpenGL/SimpleTriangles.cpp
VestLee/LearnOpenGL
68e93a1f7516b797febe90c87261f0ff3c571d7e
[ "MIT" ]
null
null
null
#include <Windows.h> #include <stdio.h> #include <GL/glut.h> int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(300, 300); glutCreateWindow("OpenGL"); printf("OpenGL version: %s\n", glGetString(GL_VERSION)); return 0; }
23.769231
58
0.721683
VestLee
960273e0d5fa342a9a7801f5c029da7b14da3bec
32,700
hh
C++
include/cagey-math/old/BasePoint.hh
theycallmecoach/cagey-math
e3a70d6e26abad90bbbaf6bc5f4e7da89651ab59
[ "MIT" ]
1
2019-05-10T23:34:08.000Z
2019-05-10T23:34:08.000Z
include/cagey-math/old/BasePoint.hh
theycallmecoach/cagey-math
e3a70d6e26abad90bbbaf6bc5f4e7da89651ab59
[ "MIT" ]
null
null
null
include/cagey-math/old/BasePoint.hh
theycallmecoach/cagey-math
e3a70d6e26abad90bbbaf6bc5f4e7da89651ab59
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // cagey-math - C++-17 Vector Math Library // Copyright (c) 2016 Kyle Girard <theycallmecoach@gmail.com> // // The MIT License (MIT) // // 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 <type_traits> //for std::is_arithmetic #include <array> //for std::array #include <utility> //for std::index_sequence #include <algorithm> //for std::transform, std::negate, std::equal #include <numeric> //for std::numeric_limits #include <iostream> namespace cagey::math { template <template <typename, std::size_t> class D, typename T, std::size_t N> class BasePoint { public: /** @cond doxygen has some issues with static assert */ static_assert(N != 0, "BasePoint cannot have zero elements"); static_assert(std::is_arithmetic<T>::value, "Underlying type must be a number"); /** @endcond */ /// The underlying type of this Point using Type = T; /// The number of elements in this Point const static std::size_t Size = N; /** * Construct a Point with all elements initialized to Zero */ constexpr BasePoint() noexcept; /** * Construct a Point with all elements initialized to the given value * * @param v the value to assign to all elements of this Point */ explicit BasePoint(T const v) noexcept; /** * Construct a Point using the given pointer. Note: It assumed the given * pointer contains N values; */ explicit BasePoint(T *const v) noexcept; /** * Construct a Point using the values from the given std::array * * @param vals vals[0] is assigned to data[0] etc. etc. */ constexpr explicit BasePoint(std::array<T, Size> const &vals) noexcept; /** * Conversion Copy Constructor. Construct a Point using a Point with a * different * underlying type. Only simple type conversion is performed */ template <typename U, typename I = std::make_index_sequence<Size>> constexpr explicit BasePoint(BasePoint<D, U, Size> const &other) noexcept; /** * Index operator * * @param i index into this Point * @return a reference to the element at index i */ constexpr auto operator[](std::size_t i) noexcept -> T &; /** * Index operator * * @param i index into this Point * @return a reference to the element at index i */ constexpr auto operator[](std::size_t i) const noexcept -> T const &; /** * Return an iterator to the first element of this Point * * @return an iterator pointing to the begining of this Point */ constexpr auto begin() noexcept -> T *; /** * Return an iterator to the first element of this Point * * @return an iterator pointing to the begining of this Point */ constexpr auto begin() const noexcept -> T *; /** * Return an iterator to the end of this Point. * * @return an iterator pointing to the end of this Point */ constexpr auto end() noexcept -> T *; /** * Return an iterator to the end of this Point. * * @return an iterator pointing to the end of this Point */ constexpr auto end() const noexcept -> T *; private: template <class U, std::size_t... I> constexpr explicit BasePoint(BasePoint<D, U, Size> const &other, std::index_sequence<I...>) noexcept; public: /// Array containing Point elements std::array<T, N> data; }; /** * Point two element specialization */ template <template <typename, std::size_t> class D, typename T> class BasePoint<D, T, 2> { /** @cond doxygen has issues with static_assert */ static_assert(std::is_arithmetic<T>::value, "Underlying type must be a number"); /** @endcond */ public: /// The underlying type of this Point using Type = T; /// The number of elements in this Point const static std::size_t Size = 2; /** * Construct a Point with all elements initialized to Zero */ constexpr BasePoint() noexcept; /** * Construct a Point with all elements initialized to the given value * * @param v the value to assign to all elements of this Point */ constexpr explicit BasePoint(T const v) noexcept; /** * Construct a Point with the given elements a and b are assigned to x and y * respectively */ constexpr BasePoint(T const a, T const b) noexcept; /** * Construct a Point using the given pointer. Note: It assumed the given * pointer contains two values; */ explicit BasePoint(T *const v) noexcept; /** * Construct a Point using the values from the given std::array * * @param vals vals[0] is assigned to data[0] etc. etc. */ constexpr explicit BasePoint(std::array<T, Size> const &vals) noexcept; /** * Conversion Copy Constructor. Construct a Point using a Point with a * different * underlying type. Only simple type conversion is performed */ template <typename U> constexpr explicit BasePoint(BasePoint<D, U, Size> const &other) noexcept; /** * Index operator * * @param i index into this Point * @return a reference to the element at index i */ constexpr auto operator[](std::size_t i) noexcept -> T &; /** * Index operator * * @param i index into this Point * @return a reference to the element at index i */ constexpr auto operator[](std::size_t i) const noexcept -> T const &; /** * Return an iterator to the first element of this Point * * @return an iterator pointing to the begining of this Point */ constexpr auto begin() noexcept -> T *; /** * Return an iterator to the first element of this Point * * @return an iterator pointing to the begining of this Point */ constexpr auto begin() const noexcept -> T *; /** * Return an iterator to the end of this Point. * * @return an iterator pointing to the end of this Point */ constexpr auto end() noexcept -> T *; /** * Return an iterator to the end of this Point. * * @return an iterator pointing to the end of this Point */ constexpr auto end() const noexcept -> T *; public: /** * Anonymous union to allow access to members using different names */ union { /// Data represented as a std::array std::array<T, 2> data; struct { T x; ///< The first element T y; ///<The second element }; struct { T w; ///< Width T h; ///< Height }; }; }; /** * Point three element specialization */ template <template <typename, std::size_t> class D, typename T> class BasePoint<D, T, 3> { /** @cond doxygen has issues with static_assert */ static_assert(std::is_arithmetic<T>::value, "Underlying type must be a number"); /** @endcond */ public: /// The underlying type of this Point using Type = T; /// The number of elements in this Point const static std::size_t Size = 3; /** * Construct a Point with all elements initialized to Zero */ constexpr BasePoint() noexcept; /** * Construct a Point with all elements initialized to the given value * * @param v the value to assign to all elements of this Point */ constexpr explicit BasePoint(T const v) noexcept; /** * Construct a Vector with the given elements a,b,c -> x, y, z * @param a value to assign to x * @param b value to assign to y * @param c value to assign to z */ constexpr BasePoint(T const a, T const b, T const c) noexcept; /** * Construct a Point using the given pointer. Note: It assumed the given * pointer contains two values; */ explicit BasePoint(T *const v) noexcept; /** * Construct a Point using the values from the given std::array * * @param vals vals[0] is assigned to data[0] etc. etc. */ constexpr explicit BasePoint(std::array<T, Size> const &vals) noexcept; /** * Conversion Copy Constructor. Construct a Point using a Point with a * different * underlying type. Only simple type conversion is performed */ template <typename U> constexpr explicit BasePoint(BasePoint<D, U, Size> const &other) noexcept; /** * Index operator * * @param i index into this Point * @return a reference to the element at index i */ constexpr auto operator[](std::size_t i) noexcept -> T &; /** * Index operator * * @param i index into this Point * @return a reference to the element at index i */ constexpr auto operator[](std::size_t i) const noexcept -> T const &; /** * Return an iterator to the first element of this Point * * @return an iterator pointing to the begining of this Point */ constexpr auto begin() noexcept -> T *; /** * Return an iterator to the first element of this Point * * @return an iterator pointing to the begining of this Point */ constexpr auto begin() const noexcept -> T *; /** * Return an iterator to the end of this Point. * * @return an iterator pointing to the end of this Point */ constexpr auto end() noexcept -> T *; /** * Return an iterator to the end of this Point. * * @return an iterator pointing to the end of this Point */ constexpr auto end() const noexcept -> T *; public: /** * Anonymous union to allow access to members using different names */ union { /// Data represented as a std::array std::array<T, Size> data; struct { T x; ///< The first element T y; ///<The second element T z; ///<The third element }; struct { T r; ///< First element T g; ///< Second element T b; ///< Third element }; }; }; /** * Point four element specialization */ template <template <typename, std::size_t> class D, typename T> class BasePoint<D, T, 4> { /** @cond doxygen has issues with static_assert */ static_assert(std::is_arithmetic<T>::value, "Underlying type must be a number"); /** @endcond */ public: /// The underlying type of this Point using Type = T; /// The number of elements in this Point const static std::size_t Size = 4; /** * Construct a Point with all elements initialized to Zero */ constexpr BasePoint() noexcept; /** * Construct a Point with all elements initialized to the given value * * @param v the value to assign to all elements of this Point */ constexpr explicit BasePoint(T const v) noexcept; /** * Construct a BasePoint with the given elements a,b,c, d -> x, y, z, w * @param a value to assign to x * @param b value to assign to y * @param c value to assign to z * @param d value to assign to w */ constexpr BasePoint(T const a, T const b, T const c, T const d) noexcept; /** * Construct a Point using the given pointer. Note: It assumed the given * pointer contains two values; */ explicit BasePoint(T *const v) noexcept; /** * Construct a Point using the values from the given std::array * * @param vals vals[0] is assigned to data[0] etc. etc. */ constexpr explicit BasePoint(std::array<T, Size> const &vals) noexcept; /** * Conversion Copy Constructor. Construct a Point using a Point with a * different * underlying type. Only simple type conversion is performed */ template <typename U> constexpr explicit BasePoint(BasePoint<D, U, Size> const &other) noexcept; /** * Index operator * * @param i index into this Point * @return a reference to the element at index i */ constexpr auto operator[](std::size_t i) noexcept -> T &; /** * Index operator * * @param i index into this Point * @return a reference to the element at index i */ constexpr auto operator[](std::size_t i) const noexcept -> T const &; /** * Return an iterator to the first element of this Point * * @return an iterator pointing to the begining of this Point */ constexpr auto begin() noexcept -> T *; /** * Return an iterator to the first element of this Point * * @return an iterator pointing to the begining of this Point */ constexpr auto begin() const noexcept -> T *; /** * Return an iterator to the end of this Point. * * @return an iterator pointing to the end of this Point */ constexpr auto end() noexcept -> T *; /** * Return an iterator to the end of this Point. * * @return an iterator pointing to the end of this Point */ constexpr auto end() const noexcept -> T *; public: /** * Anonymous union to allow access to members using different names */ union { /// Data represented as a std::array std::array<T, Size> data; struct { T x; ///< The first element T y; ///<The second element T z; ///<The third element T w; ///<The fourth element }; // Allow access to elements with a different name struct { T r; ///< First Element T g; ///< Second Element T b; ///< Third Element T a; ///< Fourth Element }; }; }; /** * Swap the contents of the two BasePoints */ template <template <typename, std::size_t> class D, typename T, std::size_t S> auto swap(BasePoint<D, T, S> & rhs, BasePoint<D, T, S> & lhs)->void { std::swap(rhs.data, lhs.data); } /** * Returns the smallest element in the given BasePoint * * @param vec the BasePoint to search for a small element * @return the smallest element of the given BasePoint */ template <template <typename, std::size_t> class D, typename T, std::size_t S> inline auto min(BasePoint<D, T, S> const &vec)->T { return *std::min_element(std::begin(vec), std::end(vec)); } /** * Returns the largest element in the given BasePoint * * @param vec the BasePoint to search for a large element * @return the largest element in the given BasePoint */ template <template <typename, std::size_t> class D, typename T, std::size_t S> inline auto max(BasePoint<D, T, S> const &vec)->T { return *std::max_element(std::begin(vec), std::end(vec)); } /** * Returns the sum of all the elements in the given BasePoint * * @param vec the BasePoint to search for a large element * @return the num of all of the elements of the given BasePoint */ template <template <typename, std::size_t> class D, typename T, std::size_t S> inline auto sum(BasePoint<D, T, S> const &vec)->T { return std::accumulate(std::begin(vec), std::end(vec), T(0)); } //////////////////////////////////////////////////////////////////////////////// //// BasePoint() Impl //////////////////////////////////////////////////////////////////////////////// // template<template<typename,std::size_t> class D,typename T, std::size_t S> // inline constexpr BasePoint<D,T,S>::BasePoint() noexcept : data() {}; // // template<template<typename,std::size_t> class D,typename T> // inline constexpr BasePoint<D,T,2>::BasePoint() noexcept : data() {}; ////////////////////////////////////////////////////////////////////////////// // BasePoint() Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline constexpr BasePoint<D, T, S>::BasePoint() noexcept : data(){}; template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 2>::BasePoint() noexcept : data(){}; template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 3>::BasePoint() noexcept : data(){}; template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 4>::BasePoint() noexcept : data(){}; ////////////////////////////////////////////////////////////////////////////// // BasePoint(T) Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline BasePoint<D, T, S>::BasePoint(T const v) noexcept { data.fill(v); } template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 2>::BasePoint(T const v) noexcept : data{{v, v}} {} template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 3>::BasePoint(T const v) noexcept : data{{v, v, v}} {} template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 4>::BasePoint(T const v) noexcept : data{{v, v, v, v}} {} ////////////////////////////////////////////////////////////////////////////// // BasePoint() Component Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 2>::BasePoint(T const a, T const b) noexcept : x{a}, y{b} {} template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 3>::BasePoint(T const a, T const b, T const c) noexcept : x{a}, y{b}, z{c} {} template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 4>::BasePoint( T const a, T const b, T const c, T const d) noexcept : x{a}, y{b}, z{c}, w{d} {} ////////////////////////////////////////////////////////////////////////////// // BasePoint(T*) Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline BasePoint<D, T, S>::BasePoint(T * const v) noexcept { std::copy(std::begin(v), std::end(v), data.begin()); } template <template <typename, std::size_t> class D, typename T> inline BasePoint<D, T, 2>::BasePoint(T * const v) noexcept : x{v[0]}, y{v[1]} {} template <template <typename, std::size_t> class D, typename T> inline BasePoint<D, T, 3>::BasePoint(T * const v) noexcept : x{v[0]}, y{v[1]}, z{v[2]} {} template <template <typename, std::size_t> class D, typename T> inline BasePoint<D, T, 4>::BasePoint(T * const v) noexcept : x{v[0]}, y{v[1]}, z{v[2]}, w{v[3]} {} ////////////////////////////////////////////////////////////////////////////// // BasePoint(std::array) Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline constexpr BasePoint<D, T, S>::BasePoint( std::array<T, Size> const &vals) noexcept : data(vals) {} template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 2>::BasePoint( std::array<T, Size> const &vals) noexcept : data(vals) {} template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 3>::BasePoint( std::array<T, Size> const &vals) noexcept : data(vals) {} template <template <typename, std::size_t> class D, typename T> inline constexpr BasePoint<D, T, 4>::BasePoint( std::array<T, Size> const &vals) noexcept : data(vals) {} ////////////////////////////////////////////////////////////////////////////// // BasePoint(BasePoint<U>) Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, size_t S> template <typename U, typename I> inline constexpr BasePoint<D, T, S>::BasePoint( BasePoint<D, U, Size> const &other) noexcept : BasePoint(other, I()) {} template <template <typename, std::size_t> class D, typename T, size_t S> template <typename U, std::size_t... I> inline constexpr BasePoint<D, T, S>::BasePoint( BasePoint<D, U, Size> const &other, std::index_sequence<I...>)noexcept : data{{(T(other.data[I]))...}} {} template <template <typename, std::size_t> class D, typename T> template <typename U> inline constexpr BasePoint<D, T, 2>::BasePoint( BasePoint<D, U, Size> const &p) noexcept : data{{T(p.x), T(p.y)}} {} template <template <typename, std::size_t> class D, typename T> template <typename U> inline constexpr BasePoint<D, T, 3>::BasePoint( BasePoint<D, U, Size> const &other) noexcept : data{{T(other[0]), T(other[1]), T(other[2])}} {} template <template <typename, std::size_t> class D, typename T> template <typename U> inline constexpr BasePoint<D, T, 4>::BasePoint( BasePoint<D, U, Size> const &other) noexcept : data{{T(other[0]), T(other[1]), T(other[2]), T(other[3])}} {} ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator[] Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline constexpr auto BasePoint<D, T, S>::operator[]( std::size_t i) noexcept->T & { return this->data[i]; } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 2>::operator[]( std::size_t i) noexcept->T & { return this->data[i]; } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 3>::operator[]( std::size_t i) noexcept->T & { return this->data[i]; } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 4>::operator[]( std::size_t i) noexcept->T & { return this->data[i]; } template <template <typename, std::size_t> class D, typename T, std::size_t S> inline constexpr auto BasePoint<D, T, S>::operator[](std::size_t i) const noexcept->T const & { return data[i]; } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 2>::operator[](std::size_t i) const noexcept->T const & { return this->data[i]; } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 3>::operator[](std::size_t i) const noexcept->T const & { return this->data[i]; } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 4>::operator[](std::size_t i) const noexcept->T const & { return this->data[i]; } ////////////////////////////////////////////////////////////////////////////// // BasePoint::begin() Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline constexpr auto BasePoint<D, T, S>::begin() noexcept->T * { return data.begin(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 2>::begin() noexcept->T * { return data.begin(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 3>::begin() noexcept->T * { return data.begin(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 4>::begin() noexcept->T * { return data.begin(); } template <template <typename, std::size_t> class D, typename T, std::size_t S> inline constexpr auto BasePoint<D, T, S>::begin() const noexcept->T * { return data.begin(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 2>::begin() const noexcept->T * { return data.begin(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 3>::begin() const noexcept->T * { return data.begin(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 4>::begin() const noexcept->T * { return data.begin(); } ////////////////////////////////////////////////////////////////////////////// // BasePoint::end() Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline constexpr auto BasePoint<D, T, S>::end() noexcept->T * { return data.end(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 2>::end() noexcept->T * { return data.end(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 3>::end() noexcept->T * { return data.end(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 4>::end() noexcept->T * { return data.end(); } template <template <typename, std::size_t> class D, typename T, std::size_t S> inline constexpr auto BasePoint<D, T, S>::end() const noexcept->T * { return data.end(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 2>::end() const noexcept->T * { return data.end(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 3>::end() const noexcept->T * { return data.end(); } template <template <typename, std::size_t> class D, typename T> inline constexpr auto BasePoint<D, T, 4>::end() const noexcept->T * { return data.end(); } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator+= Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline auto operator+=(BasePoint<D, T, S> & lhs, BasePoint<D, T, S> & rhs) ->void { std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(), [](T l, T r) -> T { return l + r; }); } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator-= Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline auto operator-=(BasePoint<D, T, S> & lhs, BasePoint<D, T, S> & rhs) ->void { std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(), [](T l, T r) -> T { return l - r; }); } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator*= Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline auto operator*=(BasePoint<D, T, S> & lhs, T value)->void { std::for_each(lhs.begin(), lhs.end(), [value](T &t) { t *= value; }); } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator/= Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> inline auto operator/=(BasePoint<D, T, S> & lhs, T value)->void { std::for_each(lhs.begin(), lhs.end(), [value](T &t) { t /= value; }); } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator== Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> auto operator==(BasePoint<D, T, S> const &rhs, BasePoint<D, T, S> const &lhs) ->BasePoint<D, T, S> { return rhs.data == rhs.data; } template <template <typename, std::size_t> class D, typename T, std::size_t S> auto operator!=(BasePoint<D, T, S> const &rhs, BasePoint<D, T, S> const &lhs) ->BasePoint<D, T, S> { return !(rhs.data == rhs.data); } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator+ Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> auto operator+(BasePoint<D, T, S> rhs, BasePoint<D, T, S> const &lhs) ->BasePoint<D, T, S> { rhs += lhs; return rhs; } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator- Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> auto operator-(BasePoint<D, T, S> vec)->BasePoint<D, T, S> { std::transform(vec.begin(), vec.end(), vec.begin(), std::negate<T>()); return vec; } template <template <typename, std::size_t> class D, typename T, std::size_t S> auto operator-(BasePoint<D, T, S> rhs, BasePoint<D, T, S> const &lhs) ->BasePoint<D, T, S> { rhs -= lhs; return rhs; } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator* Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> auto operator*(BasePoint<D, T, S> rhs, T lhs)->BasePoint<D, T, S> { rhs *= lhs; return rhs; } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator/ Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> auto operator/(BasePoint<D, T, S> rhs, T lhs)->BasePoint<D, T, S> { rhs /= lhs; return rhs; } ////////////////////////////////////////////////////////////////////////////// // BasePoint::operator<< Impl ////////////////////////////////////////////////////////////////////////////// template <template <typename, std::size_t> class D, typename T, std::size_t S> std::ostream &operator<<(std::ostream & sink, BasePoint<D, T, S> const &vec) { sink << "( "; std::for_each(vec.begin(), vec.end() - 1, [&sink](T &v) { sink << v << ", "; }); sink << vec[S - 1] << " )"; return sink; } } // namespace cagey::math
34.750266
82
0.55208
theycallmecoach
9603020de6c69df040ff3512875e9dc04a7adb7b
70,508
cpp
C++
piLibs/src/libRender/opengl4x/piGL4X_Renderer.cpp
Livictor213/testing2
4121cbb23ec6cb55d8aad3524d1dc029165c8532
[ "MIT" ]
6
2021-03-27T01:54:55.000Z
2021-12-15T22:50:28.000Z
piLibs/src/libRender/opengl4x/piGL4X_Renderer.cpp
Livictor213/testing2
4121cbb23ec6cb55d8aad3524d1dc029165c8532
[ "MIT" ]
null
null
null
piLibs/src/libRender/opengl4x/piGL4X_Renderer.cpp
Livictor213/testing2
4121cbb23ec6cb55d8aad3524d1dc029165c8532
[ "MIT" ]
null
null
null
#define USETEXTURECACHE #include <malloc.h> #include <stdio.h> #define GLCOREARB_PROTOTYPES #include "glcorearb.h" #include "piGL4X_Renderer.h" #include "piGL4X_Ext.h" #include "piGL4X_RenderContext.h" #include "../../libSystem/piStr.h" namespace piLibs { typedef struct { unsigned int mProgID; }piIShader; typedef struct { GLuint64 mHandle; piTextureInfo mInfo; piTextureFilter mFilter; piTextureWrap mWrap; unsigned int mObjectID; bool mIsResident; }piITexture; typedef struct { wchar_t *mKey; piITexture *mTexture; int mReference; }TextureSlot; typedef struct { unsigned int mObjectID; // int mNumStreams; // piRArrayLayout mStreams[2]; }piIVertexArray; typedef struct { unsigned int mObjectID; //void *mPtr; unsigned int mSize; //GLsync mSync; }piIBuffer; typedef struct { unsigned int mObjectID; }piISampler; typedef struct { unsigned int mObjectID; unsigned int mSamples; unsigned int mXres; unsigned int mYres; }piIRTarget; static int unidades[32] = { GL_TEXTURE0, GL_TEXTURE1, GL_TEXTURE2, GL_TEXTURE3, GL_TEXTURE4, GL_TEXTURE5, GL_TEXTURE6, GL_TEXTURE7, GL_TEXTURE8, GL_TEXTURE9, GL_TEXTURE10, GL_TEXTURE11, GL_TEXTURE12, GL_TEXTURE13, GL_TEXTURE14, GL_TEXTURE15, GL_TEXTURE16, GL_TEXTURE17, GL_TEXTURE18, GL_TEXTURE19, GL_TEXTURE20, GL_TEXTURE21, GL_TEXTURE22, GL_TEXTURE23, GL_TEXTURE24, GL_TEXTURE25, GL_TEXTURE26, GL_TEXTURE27, GL_TEXTURE28, GL_TEXTURE29, GL_TEXTURE30, GL_TEXTURE31 }; static int format2gl( int format, int *bpp, int *mode, int *moInternal, int *mode3, int compressed ) { switch( format ) { case piFORMAT_C1I8: *bpp = 1; *mode = GL_RED; *moInternal = GL_R8; *mode3 = GL_UNSIGNED_BYTE; if (compressed) *moInternal = GL_COMPRESSED_RED; break; case piFORMAT_C2I8: *bpp = 2; *mode = GL_RG; *moInternal = GL_RG8; *mode3 = GL_UNSIGNED_BYTE; if (compressed) *moInternal = GL_COMPRESSED_RGB; break; case piFORMAT_C3I8: *bpp = 3; *mode = GL_RGB; *moInternal = GL_RGB8; *mode3 = GL_UNSIGNED_BYTE; if (compressed) *moInternal = GL_COMPRESSED_RGB; break; case piFORMAT_C4I8: *bpp = 4; *mode = GL_BGRA; *moInternal = GL_RGBA8; *mode3 = GL_UNSIGNED_BYTE; if (compressed) *moInternal = GL_COMPRESSED_RGBA; break; case piFORMAT_D24: *bpp = 4; *mode = GL_DEPTH_COMPONENT; *moInternal = GL_DEPTH_COMPONENT24; *mode3 = GL_UNSIGNED_BYTE; break; case piFORMAT_D32F: *bpp = 4; *mode = GL_DEPTH_COMPONENT; *moInternal = GL_DEPTH_COMPONENT32F; *mode3 = GL_FLOAT; break; case piFORMAT_C1F16: *bpp = 2; *mode = GL_RED; *moInternal = GL_R16F; *mode3 = GL_FLOAT; break; case piFORMAT_C2F16: *bpp = 4; *mode = GL_RG; *moInternal = GL_RG16F; *mode3 = GL_FLOAT; break; case piFORMAT_C3F16: *bpp = 6; *mode = GL_RGB; *moInternal = GL_RGB16F; *mode3 = GL_FLOAT; break; case piFORMAT_C4F16: *bpp = 8; *mode = GL_RGBA; *moInternal = GL_RGBA16F; *mode3 = GL_FLOAT; break; case piFORMAT_C1F32: *bpp = 4; *mode = GL_RED; *moInternal = GL_R32F; *mode3 = GL_FLOAT; break; case piFORMAT_C4F32: *bpp = 16; *mode = GL_RGBA; *moInternal = GL_RGBA32F; *mode3 = GL_FLOAT; break; case piFORMAT_C1I8I: *bpp = 1; *mode = GL_RED_INTEGER; *moInternal = GL_R8UI; *mode3 = GL_UNSIGNED_BYTE; break; case piFORMAT_C1I16I: *bpp = 2; *mode = GL_RED_INTEGER; *moInternal = GL_R16UI; *mode3 = GL_UNSIGNED_SHORT; break; case piFORMAT_C1I32I: *bpp = 4; *mode = GL_RED_INTEGER; *moInternal = GL_R32UI; *mode3 = GL_UNSIGNED_INT; break; case piFORMAT_C4I1010102: *bpp = 4; *mode = GL_BGRA; *moInternal = GL_RGB10_A2; *mode3 = GL_UNSIGNED_BYTE; break; case piFORMAT_C3I111110: *bpp = 4; *mode = GL_BGRA; *moInternal = GL_R11F_G11F_B10F; *mode3 = GL_UNSIGNED_BYTE; break; default: return( 0 ); } return( 1 ); } static uint64 piTexture_GetMem( const piITexture *me ) { int mode, fInternal, mode3, bpp; if( !format2gl( me->mInfo.mFormat, &bpp, &mode, &fInternal, &mode3, me->mInfo.mCompressed ) ) return 0; return me->mInfo.mXres * me->mInfo.mYres * me->mInfo.mZres * bpp; } //static const unsigned int filter2gl[] = { GL_NEAREST, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR }; static const unsigned int wrap2gl[] = { GL_CLAMP_TO_BORDER, GL_CLAMP_TO_EDGE, GL_REPEAT, GL_MIRROR_CLAMP_TO_EDGE, GL_MIRRORED_REPEAT }; static const unsigned int glType[] = { GL_UNSIGNED_BYTE, GL_FLOAT, GL_INT, GL_DOUBLE, GL_HALF_FLOAT }; static const unsigned int glSizeof[] = { 1, 4, 4, 8, 2}; //--------------------------------------------- piRendererGL4X::piRendererGL4X():piRenderer() { } piRendererGL4X::~piRendererGL4X() { } static const float verts2f[] = { -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f }; static const float verts3f[] = { -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f }; static const float verts3f3f[] = { -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f }; void CALLBACK piRendererGL4X::DebugLog( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *vme ) { piRendererGL4X *me = (piRendererGL4X*)vme; if( !me->mReporter ) return; const char *sources = "Unknown"; if( source==GL_DEBUG_SOURCE_API_ARB ) sources = "API"; if( source==GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB ) sources = "OS"; if( source==GL_DEBUG_SOURCE_SHADER_COMPILER_ARB ) sources = "Shader Compiler"; if( source==GL_DEBUG_SOURCE_THIRD_PARTY_ARB ) sources = "Third Party"; if( source==GL_DEBUG_SOURCE_APPLICATION_ARB ) sources = "Application"; const char *types = "Unknown"; if( type==GL_DEBUG_TYPE_ERROR_ARB ) types = "Error"; if( type==GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB ) types = "Deprecated Behavior"; if( type==GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB ) types = "Undefined Behavior"; if( type==GL_DEBUG_TYPE_PORTABILITY_ARB ) types = "Portability"; if( type==GL_DEBUG_TYPE_PERFORMANCE_ARB ) types = "Performance"; int severitiID = 0; const char *severities = "Unknown"; if( severity==GL_DEBUG_SEVERITY_HIGH_ARB ) { severitiID = 2; severities = "High"; } if( severity==GL_DEBUG_SEVERITY_MEDIUM_ARB ) { severitiID = 1; severities = "Medium"; } if( severity==GL_DEBUG_SEVERITY_LOW_ARB ) { severitiID = 0; severities = "Low"; } if( severity!=GL_DEBUG_SEVERITY_HIGH_ARB ) return; char tmp[2048]; pisprintf( tmp, sizeof(tmp), "Renderer Error, source = \"%s\", type = \"%s\", severity = \"%s\", description = \"%s\"", sources, types, severities, message ); me->mReporter->Error( tmp, severitiID ); } void piRendererGL4X::PrintInfo( void ) { if( !mReporter ) return; char *str = (char*)malloc( 65536 ); if( !str ) return; int nume = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &nume); sprintf( str, "OpenGL %s\nGLSL %s\n%s by %s\n%d extensions\n", (const char*)glGetString( GL_VERSION ), (const char*)glGetString( GL_SHADING_LANGUAGE_VERSION ), (const char*)glGetString( GL_RENDERER ), (const char*)glGetString( GL_VENDOR ), nume ); #if 1 for( int i=0; i<nume; i++ ) { strcat( str, (char const*)oglGetStringi(GL_EXTENSIONS, i) ); strcat( str, "\n" ); } #endif mReporter->Info( str ); free( str ); } bool piRendererGL4X::Initialize(int id, const void **hwnd, int num, bool disableVSync, piRenderReporter *reporter) { mID = id; mBindedTarget = nullptr; mReporter = reporter; mMngTexSlots = nullptr; mRC = new piGL4X_RenderContext(); if( !mRC ) return false; if (!mRC->Create(hwnd, num, disableVSync, true, true)) { mRC->Delete(); return false; } mRC->Enable(); mExt = piGL4X_Ext_Init(reporter); if( !mExt ) return false; int maxZMultisample, maxCMultisample, maxGSInvocations, maxTextureUnits, maxVerticesPerPatch; glGetIntegerv( GL_MAX_DEPTH_TEXTURE_SAMPLES, &maxZMultisample ); glGetIntegerv( GL_MAX_COLOR_TEXTURE_SAMPLES, &maxCMultisample ); glGetIntegerv( GL_MAX_GEOMETRY_SHADER_INVOCATIONS, &maxGSInvocations ); glGetIntegerv( GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits ); glGetIntegerv(GL_MAX_PATCH_VERTICES, &maxVerticesPerPatch ); if( reporter ) { char str[256]; sprintf( str, "Num Texture Units: %d", maxTextureUnits ); reporter->Info( str ); sprintf( str, "Max Vertex per Patch: %d", maxVerticesPerPatch); reporter->Info(str); sprintf( str, "Max GS invocations: %d", maxGSInvocations); reporter->Info(str); } //--- texture management --- mMngTexMax = 512; mMngTexMemCurrent = 0; mMngTexMemPeak = 0; mMngTexNumCurrent = 0; mMngTexNumPeak = 0; mMngTexSlots = (TextureSlot*)malloc( mMngTexMax*sizeof(TextureSlot) ); if( !mMngTexSlots ) return false; memset( mMngTexSlots, 0, mMngTexMax*sizeof(TextureSlot) ); ////////////// mVBO[0] = this->CreateBuffer(verts2f, sizeof(verts2f), piBufferType_Static); mVBO[1] = this->CreateBuffer(verts3f3f, sizeof(verts3f3f), piBufferType_Static); mVBO[2] = this->CreateBuffer(verts3f, sizeof(verts3f), piBufferType_Static); const piRArrayLayout lay0 = { 2 * sizeof(float), 1, 0, { { 2, piRArrayType_Float, false } } }; const piRArrayLayout lay1 = { 6 * sizeof(float), 2, 0, { { 3, piRArrayType_Float, false }, { 3, piRArrayType_Float, false } } }; const piRArrayLayout lay2 = { 3 * sizeof(float), 1, 0, { { 3, piRArrayType_Float, false } } }; const piRArrayLayout lay3 = { 2 * sizeof(float), 1, 0, { { 2, piRArrayType_Float, false } } }; const piRArrayLayout lay4 = { 4 * sizeof(float), 2, 0, { { 2, piRArrayType_Float, false }, { 2, piRArrayType_Float, false } } }; mVA[0] = this->CreateVertexArray(1, mVBO[0], &lay0, nullptr, nullptr, nullptr); mVA[1] = this->CreateVertexArray(1, mVBO[1], &lay1, nullptr, nullptr, nullptr); mVA[2] = this->CreateVertexArray(1, mVBO[2], &lay2, nullptr, nullptr, nullptr); // set log if( reporter ) { oglDebugMessageCallback( DebugLog, this ); oglDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE,GL_DONT_CARE, 0, 0, GL_TRUE ); glEnable( GL_DEBUG_OUTPUT ); glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS ); } glDisable(GL_DITHER); glDepthFunc(GL_LEQUAL); glHint( GL_FRAGMENT_SHADER_DERIVATIVE_HINT, GL_NICEST ); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST ); PrintInfo(); return true; } void piRendererGL4X::SetActiveWindow( int id ) { mRC->SetActiveWindow( id ); } void piRendererGL4X::Enable(void) { mRC->Enable(); } void piRendererGL4X::Disable(void) { mRC->Disable(false); } void piRendererGL4X::Report( void ) { if( !mReporter ) return; mReporter->Begin( mMngTexMemCurrent, mMngTexMemPeak, mMngTexNumCurrent, mMngTexNumPeak ); if( mMngTexNumCurrent!=0 ) { TextureSlot *slots = (TextureSlot*)mMngTexSlots; for( int i=0; i<mMngTexNumCurrent; i++ ) { mReporter->Texture( slots[i].mKey, piTexture_GetMem( slots[i].mTexture ) >> 10L, slots[i].mTexture->mInfo.mFormat, slots[i].mTexture->mInfo.mCompressed, slots[i].mTexture->mInfo.mXres, slots[i].mTexture->mInfo.mYres, slots[i].mTexture->mInfo.mZres ); } } mReporter->End(); } void piRendererGL4X::Deinitialize( void ) { //--- texture management --- if( mMngTexSlots!=nullptr) free( mMngTexSlots ); this->DestroyVertexArray(mVA[0]); this->DestroyVertexArray(mVA[1]); this->DestroyVertexArray(mVA[2]); this->DestroyBuffer(mVBO[0]); this->DestroyBuffer(mVBO[1]); this->DestroyBuffer(mVBO[2]); piGL4X_Ext_Free( (NGLEXTINFO*)mExt ); mRC->Disable( false ); mRC->Destroy(); mRC->Delete(); delete mRC; } void piRendererGL4X::SwapBuffers( void ) { //glFlush(); mRC->SwapBuffers(); } static int check_framebuffer( NGLEXTINFO *mExt ) { GLenum status; status = oglCheckFramebufferStatus(GL_FRAMEBUFFER); switch( status ) { case GL_FRAMEBUFFER_COMPLETE: break; case GL_FRAMEBUFFER_UNSUPPORTED: break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: return 0; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: return 0; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: return 0; default: return 0; } if( status!=GL_FRAMEBUFFER_COMPLETE ) return 0; return 1; } void piRendererGL4X::SetShadingSamples( int shadingSamples ) { piIRTarget *rt = (piIRTarget*)mBindedTarget; if( shadingSamples>1 && rt!=NULL ) { glEnable( GL_SAMPLE_SHADING ); oglMinSampleShading( (float)shadingSamples/(float)rt->mSamples ); } else { glDisable( GL_SAMPLE_SHADING ); } } piRTarget piRendererGL4X::CreateRenderTarget( piTexture vtex0, piTexture vtex1, piTexture vtex2, piTexture vtex3, piTexture zbuf ) { const piITexture *tex[4] = { (piITexture*)vtex0, (piITexture*)vtex1, (piITexture*)vtex2, (piITexture*)vtex3 }; const piITexture *zbu = (piITexture*)zbuf; piIRTarget *me = (piIRTarget*)malloc( sizeof(piIRTarget) ); if( !me ) return nullptr; me->mObjectID = 0; bool hasLayers = false; bool found = false; for( int i=0; i<4; i++ ) { if( !tex[i] ) continue; me->mSamples = tex[i]->mInfo.mMultisample; me->mXres = tex[i]->mInfo.mXres; me->mYres = tex[i]->mInfo.mYres; //hasLayers = (tex[i]->mInfo.mType == piTEXTURE_CUBE); //hasLayers = (tex[i]->mInfo.mType == piTEXTURE_2D_ARRAY); found = true; break; } if( !found ) { if( zbu ) { me->mSamples = zbu->mInfo.mMultisample; me->mXres = zbu->mInfo.mXres; me->mYres = zbu->mInfo.mYres; found = true; } } if (!found) { free(me); return nullptr; } oglCreateFramebuffers(1, (GLuint*)&me->mObjectID); if( zbu ) { if (hasLayers ) oglNamedFramebufferTextureLayer(me->mObjectID, GL_DEPTH_ATTACHMENT, zbu->mObjectID, 0, 0); else oglNamedFramebufferTexture(me->mObjectID, GL_DEPTH_ATTACHMENT, zbu->mObjectID, 0); } else { if (hasLayers) oglNamedFramebufferTextureLayer(me->mObjectID, GL_DEPTH_ATTACHMENT, 0, 0, 0); else oglNamedFramebufferTexture(me->mObjectID, GL_DEPTH_ATTACHMENT, 0, 0); } GLenum mMRT[4]; int mNumMRT = 0; for( int i=0; i<4; i++ ) { if( tex[i] ) { if (hasLayers) oglNamedFramebufferTextureLayer(me->mObjectID, GL_COLOR_ATTACHMENT0 + i, tex[i]->mObjectID, 0, 0); else oglNamedFramebufferTexture(me->mObjectID, GL_COLOR_ATTACHMENT0 + i, tex[i]->mObjectID, 0); mMRT[i] = GL_COLOR_ATTACHMENT0 + i; mNumMRT++; } else { if (hasLayers) oglNamedFramebufferTextureLayer(me->mObjectID, GL_COLOR_ATTACHMENT0 + i, 0, 0, 0); else oglNamedFramebufferTexture(me->mObjectID, GL_COLOR_ATTACHMENT0 + i, 0, 0); mMRT[i] = 0; } } oglNamedFramebufferDrawBuffers(me->mObjectID, mNumMRT, mMRT); GLenum st = oglCheckNamedFramebufferStatus(me->mObjectID, GL_FRAMEBUFFER); if (st != GL_FRAMEBUFFER_COMPLETE) return nullptr; return me; } void piRendererGL4X::DestroyRenderTarget( piRTarget obj ) { piIRTarget *me = (piIRTarget*)obj; oglDeleteFramebuffers( 1, (GLuint*)&me->mObjectID ); } void piRendererGL4X::RenderTargetSampleLocations(piRTarget vdst, const float *locations ) { /* const piIRTarget *dst = (piIRTarget*)vdst; if( locations==nullptr ) { oglNamedFramebufferParameteri(dst->mObjectID, GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB, 0); } else { oglNamedFramebufferParameteri(dst->mObjectID, GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB, 1); oglNamedFramebufferSampleLocationsfv(dst->mObjectID, 0, dst->mSamples, locations); } */ } void piRendererGL4X::RenderTargetGetDefaultSampleLocation(piRTarget vdst, const int id, float *location) { const piIRTarget *dst = (piIRTarget*)vdst; oglGetMultisamplefv( GL_SAMPLE_LOCATION_ARB, id, location); } void piRendererGL4X::BlitRenderTarget( piRTarget vdst, piRTarget vsrc, bool color, bool depth ) { const piIRTarget *src = (piIRTarget*)vsrc; const piIRTarget *dst = (piIRTarget*)vdst; int flag = 0; if( color ) flag += GL_COLOR_BUFFER_BIT; if( depth ) flag += GL_DEPTH_BUFFER_BIT; const GLenum mMRT[1] = { GL_COLOR_ATTACHMENT0 }; oglNamedFramebufferDrawBuffers(dst->mObjectID, 1, mMRT); oglBlitNamedFramebuffer( src->mObjectID, dst->mObjectID, 0, 0, dst->mXres, dst->mYres, 0, 0, dst->mXres, dst->mYres, flag, GL_NEAREST ); } bool piRendererGL4X::SetRenderTarget( piRTarget obj ) { if( obj==NULL ) { mBindedTarget = NULL; oglBindFramebuffer( GL_FRAMEBUFFER, 0 ); const GLenum zeros[4] = { 0, 0, 0, 0 };// { GL_NONE, GL_NONE, GL_NONE, GL_NONE };// segun la especificacion... oglDrawBuffers(4, zeros); glDrawBuffer(GL_BACK); //glReadBuffer(GL_BACK); //glDisable(GL_MULTISAMPLE); } else { piIRTarget *me = (piIRTarget*)obj; mBindedTarget = obj; oglBindFramebuffer( GL_FRAMEBUFFER, me->mObjectID ); //glEnable(GL_FRAMEBUFFER_SRGB); if( me->mSamples>1 ) { glEnable(GL_MULTISAMPLE); } else { glDisable(GL_MULTISAMPLE); } } return true; } void piRendererGL4X::SetViewport( int id, const int *vp ) { //glViewport( vp[0], vp[1], vp[2], vp[3] ); oglViewportIndexedf(id, float(vp[0]), float(vp[1]), float(vp[2]), float(vp[3]) ); } //=========================================================================================================================================== static int ilog2i(int x) { int r = 0; while (x >>= 1) r++; return r; } static piITexture *piITexture_Create( const piTextureInfo *info, piTextureFilter rfilter, piTextureWrap rwrap, float aniso, void *buffer, void *mExt ) { int mode, moInternal, mode3, bpp; if (!format2gl(info->mFormat, &bpp, &mode, &moInternal, &mode3, info->mCompressed)) return nullptr; piITexture *me = (piITexture*)malloc( sizeof(piITexture) ); if( !me ) return nullptr; me->mHandle = 0; me->mIsResident = false; me->mInfo = *info; me->mFilter = rfilter; me->mWrap = rwrap; //const int filter = filter2gl[ rfilter ]; const int wrap = wrap2gl[ rwrap ]; if( info->mType==piTEXTURE_2D ) { if (info->mMultisample>1) { oglCreateTextures(GL_TEXTURE_2D_MULTISAMPLE, 1, &me->mObjectID); oglTextureStorage2DMultisample(me->mObjectID, info->mMultisample, moInternal, info->mXres, info->mYres, GL_FALSE); } else { oglCreateTextures(GL_TEXTURE_2D, 1, &me->mObjectID); switch (rfilter) { case piFILTER_NONE: if (moInternal == GL_DEPTH_COMPONENT24) { oglTextureStorage2D(me->mObjectID, 1, GL_DEPTH_COMPONENT24, info->mXres, info->mYres); oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE); } else { oglTextureStorage2D(me->mObjectID, 1, moInternal, info->mXres, info->mYres); if (buffer) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer); } oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_NEAREST); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_NEAREST); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap); break; case piFILTER_LINEAR: if (moInternal == GL_DEPTH_COMPONENT24) { oglTextureStorage2D(me->mObjectID, 1, GL_DEPTH_COMPONENT24, info->mXres, info->mYres); oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE); } else { oglTextureStorage2D(me->mObjectID, 1, moInternal, info->mXres, info->mYres); if( buffer ) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer); } oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap); break; case piFILTER_PCF: if (moInternal == GL_DEPTH_COMPONENT24) { oglTextureStorage2D(me->mObjectID, 1, GL_DEPTH_COMPONENT24, info->mXres, info->mYres); oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); } else { return nullptr; //oglTextureStorage2D(me->mObjectID, 1, moInternal, info->mXres, info->mYres); //if (buffer) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer); } oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap); break; case piFILTER_MIPMAP: { const int numMipmaps = ilog2i(info->mXres ); oglTextureStorage2D(me->mObjectID, numMipmaps, moInternal, info->mXres, info->mYres); if (buffer) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer); oglGenerateTextureMipmap(me->mObjectID); oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, numMipmaps); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap); if( aniso>1.0001f ) oglTextureParameterf(me->mObjectID, 0x84FE, aniso); // GL_TEXTURE_MAX_ANISOTROPY_EXT break; } case piFILTER_NONE_MIPMAP: { const int numMipmaps = ilog2i(info->mXres ); oglTextureStorage2D(me->mObjectID, numMipmaps, moInternal, info->mXres, info->mYres); if (buffer) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer); oglGenerateTextureMipmap(me->mObjectID); oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, numMipmaps); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR ); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap); if( aniso>1.0001f ) oglTextureParameterf(me->mObjectID, 0x84FE, aniso); // GL_TEXTURE_MAX_ANISOTROPY_EXT break; } } } } else if( info->mType==piTEXTURE_3D ) { oglCreateTextures(GL_TEXTURE_3D, 1, &me->mObjectID); oglTextureStorage3D(me->mObjectID, 1, moInternal, info->mXres, info->mYres, info->mZres); if (buffer) oglTextureSubImage3D(me->mObjectID, 0, 0, 0, 0, info->mXres, info->mYres, info->mZres, mode, mode3, buffer); oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_R, wrap); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap); } else if( info->mType==piTEXTURE_CUBE ) { if (rfilter == piFILTER_MIPMAP) { const int numMipmaps = ilog2i(info->mXres); oglCreateTextures(GL_TEXTURE_CUBE_MAP_ARRAY, 1, &me->mObjectID); oglTextureStorage3D(me->mObjectID, numMipmaps, moInternal, info->mXres, info->mYres, 6); if (buffer) { oglTextureSubImage3D(me->mObjectID, 0, 0, 0, 0, info->mXres, info->mYres, 6, mode, mode3, buffer); oglGenerateTextureMipmap(me->mObjectID); } oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, numMipmaps); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { oglCreateTextures(GL_TEXTURE_CUBE_MAP_ARRAY, 1, &me->mObjectID); oglTextureStorage3D(me->mObjectID, 1, moInternal, info->mXres, info->mYres, 6); if (buffer) oglTextureSubImage3D(me->mObjectID, 0, 0, 0, 0, info->mXres, info->mYres, 6, mode, mode3, buffer); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); oglTextureParameteri(me->mObjectID, GL_TEXTURE_CUBE_MAP_SEAMLESS, GL_TRUE); oglTextureParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f); oglTextureParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f); oglTextureParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f); oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE); oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); oglTextureParameterf(me->mObjectID, 0x84FE, aniso); } else if( info->mType==piTEXTURE_2D_ARRAY ) { oglCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &me->mObjectID); oglTextureStorage3D(me->mObjectID, 1, moInternal, info->mXres, info->mYres, info->mZres); //if (buffer) oglTextureSubImage3D(me->mObjectID, 0, 0, 0, 0, info->mXres, info->mYres, info->mZres, mode, mode3, buffer); if( rfilter==piFILTER_PCF ) { oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } else { oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_R, wrap); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap); oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap); } me->mHandle = oglGetTextureHandle( me->mObjectID ); return me; } piTexture piRendererGL4X::CreateTextureFromID(unsigned int id, piTextureFilter filter ) { piITexture *me = (piITexture*)malloc(sizeof(piITexture)); if (!me) return nullptr; me->mObjectID = id; //me->mInfo = *info; me->mFilter = filter; //me->mWrap = rwrap; return me; } piTexture piRendererGL4X::CreateTexture( const wchar_t *key, const piTextureInfo *info, piTextureFilter filter, piTextureWrap wrap1, float aniso, void *buffer ) { #ifdef USETEXTURECACHE // look for an existing copy (linear) TextureSlot *slots = (TextureSlot*)mMngTexSlots; if( key ) { for( int i=0; i<mMngTexNumCurrent; i++ ) { TextureSlot *ts = slots + i; piITexture *tex = (piITexture*)ts->mTexture; if( tex->mInfo.mType == info->mType && tex->mFilter == filter && tex->mInfo.mFormat == info->mFormat && tex->mInfo.mCompressed == info->mCompressed && tex->mInfo.mXres == info->mXres && tex->mInfo.mYres == info->mYres && tex->mInfo.mZres == info->mZres && piwstrequ(ts->mKey,key) ) { ts->mReference++; return (piTexture)tex; } } } // mp free slots? make room if( mMngTexNumCurrent>=mMngTexMax ) { const int newmax = 4*mMngTexMax/3; mMngTexSlots = (TextureSlot*)realloc( mMngTexSlots, newmax*sizeof(TextureSlot) ); if (!mMngTexSlots) return nullptr; slots = (TextureSlot*)mMngTexSlots; mMngTexMax = newmax; } // ok, create the texture piITexture *tex = piITexture_Create( info, filter, wrap1, aniso, buffer, mExt ); if (!tex) return nullptr; TextureSlot *ts = slots + mMngTexNumCurrent; ts->mTexture = tex; int err = 0; ts->mKey = piwstrdup( key, &err ); if (err) return nullptr; ts->mReference = 1; #else piITexture *tex = piITexture_Create( type, format, compressed, filter, wrap1, wrap2, buffer, xres, yres, zres, ext ); #endif mMngTexMemCurrent += piTexture_GetMem( tex ); mMngTexNumCurrent += 1; if( mMngTexNumCurrent>mMngTexNumPeak ) mMngTexNumPeak = mMngTexNumCurrent; if( mMngTexMemCurrent>mMngTexMemPeak ) mMngTexMemPeak = mMngTexMemCurrent; return tex; } void piRendererGL4X::ComputeMipmaps( piTexture vme ) { piITexture *me = (piITexture*)vme; if( me->mFilter!=piFILTER_MIPMAP ) return; oglGenerateTextureMipmap(me->mObjectID); } void piRendererGL4X::DestroyTexture( piTexture me ) { #ifdef USETEXTURECACHE TextureSlot *slots = (TextureSlot*)mMngTexSlots; // find (linear...) int id = -1; for( int i=0; i<mMngTexNumCurrent; i++ ) { if( slots[i].mTexture == (piITexture*)me ) { id = i; break; } } if( id==-1 ) { return; } slots[id].mReference--; if( slots[id].mReference==0 ) { mMngTexMemCurrent -= piTexture_GetMem( slots[id].mTexture ); //piITexture_Destroy( slots[id].mTexture, ext ); glDeleteTextures( 1, &slots[id].mTexture->mObjectID ); free( me ); free( slots[id].mKey ); // shrink list slots[id] = slots[mMngTexNumCurrent-1]; mMngTexNumCurrent--; } else if( slots[id].mReference<0 ) { // megaerror int i = 0; } else { int i = 0; } #else mMngTexMemCurrent -= piITexture_GetMem( (piITexture*)me ); //piITexture_Destroy( (piITexture*)me, ext ); glDeleteTextures( 1, &me->mObjectID ); free( me ); mMngTexNumCurrent--; #endif } void piRendererGL4X::AttachTextures( int num, piTexture vt0, piTexture vt1, piTexture vt2, piTexture vt3, piTexture vt4, piTexture vt5, piTexture vt6, piTexture vt7, piTexture vt8, piTexture vt9, piTexture vt10, piTexture vt11, piTexture vt12, piTexture vt13, piTexture vt14, piTexture vt15 ) { piITexture *t[16] = { (piITexture*)vt0, (piITexture*)vt1, (piITexture*)vt2, (piITexture*)vt3, (piITexture*)vt4, (piITexture*)vt5, (piITexture*)vt6, (piITexture*)vt7, (piITexture*)vt8, (piITexture*)vt9, (piITexture*)vt10, (piITexture*)vt11, (piITexture*)vt12, (piITexture*)vt13, (piITexture*)vt14, (piITexture*)vt15 }; GLuint texIDs[16]; for (int i = 0; i<num; i++) texIDs[i] = (t[i]) ? t[i]->mObjectID : 0; oglBindTextures( 0, num, texIDs ); } void piRendererGL4X::DettachTextures( void ) { #if 0 GLuint texIDs[6] = { 0, 0, 0, 0, 0, 0 }; oglBindTextures( 0, 6, texIDs ); #endif } void piRendererGL4X::AttachImage(int unit, piTexture texture, int level, bool layered, int layer, piTextureFormat format) { int mode, moInternal, mode3, bpp; if (!format2gl(format, &bpp, &mode, &moInternal, &mode3, 0)) return; oglBindImageTexture(unit, ((piITexture*)texture)->mObjectID, level, layered, layer, GL_READ_WRITE, moInternal); } void piRendererGL4X::ClearTexture( piTexture vme, int level, const void *data ) { piITexture *me = (piITexture*)vme; int mode, mode2, mode3, bpp; if( !format2gl( me->mInfo.mFormat, &bpp, &mode, &mode2, &mode3, me->mInfo.mCompressed ) ) return; oglActiveTexture( unidades[0] ); if( me->mInfo.mType==piTEXTURE_2D ) { oglClearTexImage( me->mObjectID, level, mode, mode3, data ); } else if( me->mInfo.mType==piTEXTURE_2D_ARRAY ) { oglClearTexSubImage( me->mObjectID, level, 0, 0, 0, me->mInfo.mXres, me->mInfo.mYres, me->mInfo.mZres, mode, mode3, data ); } } void piRendererGL4X::UpdateTexture( piTexture vme, int x0, int y0, int z0, int xres, int yres, int zres, const void *buffer ) { piITexture *me = (piITexture*)vme; int fFormat, fInternal, fType, bpp; if( !format2gl( me->mInfo.mFormat, &bpp, &fFormat, &fInternal, &fType, me->mInfo.mCompressed ) ) return; if( me->mInfo.mType==piTEXTURE_2D ) { oglTextureSubImage2D( me->mObjectID, 0, x0, y0, xres, yres, fFormat, fType, buffer); if (me->mFilter == piFILTER_MIPMAP) oglGenerateTextureMipmap(me->mObjectID); } else if( me->mInfo.mType==piTEXTURE_2D_ARRAY ) { oglTextureSubImage3D( me->mObjectID, 0, x0, y0, z0, xres, yres, zres, fFormat, fType, buffer); } } void piRendererGL4X::MakeResident( piTexture vme ) { piITexture *me = (piITexture*)vme; if( me->mIsResident ) return; oglMakeTextureHandleResident( me->mHandle ); me->mIsResident = true; } void piRendererGL4X::MakeNonResident( piTexture vme ) { piITexture *me = (piITexture*)vme; if( !me->mIsResident ) return; oglMakeTextureHandleNonResident( me->mHandle ); me->mIsResident = false; } uint64 piRendererGL4X::GetTextureHandle( piTexture vme ) { piITexture *me = (piITexture*)vme; return me->mHandle; } //================================================== piSampler piRendererGL4X::CreateSampler(piTextureFilter filter, piTextureWrap wrap, float maxAnisotrop) { piISampler *me = (piISampler*)malloc( sizeof(piISampler) ); if( !me ) return nullptr; oglGenSamplers( 1, &me->mObjectID ); //oglCreateSamplers( 1, &me->mObjectID ); int glwrap = wrap2gl[ wrap ]; if (filter == piFILTER_NONE) { oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_NEAREST); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_NEAREST); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f); oglSamplerParameterf(me->mObjectID, 0x84FE, maxAnisotrop); } else if (filter == piFILTER_LINEAR) { oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE); oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f); oglSamplerParameterf(me->mObjectID, 0x84FE, maxAnisotrop); } else if (filter == piFILTER_MIPMAP) { oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f); oglSamplerParameterf(me->mObjectID, 0x84FE, maxAnisotrop); } else // if (filter == piFILTER_PCF) { oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f); oglSamplerParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f); oglSamplerParameterf(me->mObjectID, 0x84FE, maxAnisotrop); } oglSamplerParameteri( me->mObjectID, GL_TEXTURE_WRAP_R, glwrap ); oglSamplerParameteri( me->mObjectID, GL_TEXTURE_WRAP_S, glwrap ); oglSamplerParameteri( me->mObjectID, GL_TEXTURE_WRAP_T, glwrap ); return me; } void piRendererGL4X::DestroySampler( piSampler obj ) { piISampler *me = (piISampler*)obj; oglDeleteSamplers( 1, &me->mObjectID ); } void piRendererGL4X::AttachSamplers(int num, piSampler vt0, piSampler vt1, piSampler vt2, piSampler vt3, piSampler vt4, piSampler vt5, piSampler vt6, piSampler vt7) { piISampler *t[8] = { (piISampler*)vt0, (piISampler*)vt1, (piISampler*)vt2, (piISampler*)vt3, (piISampler*)vt4, (piISampler*)vt5, (piISampler*)vt6, (piISampler*)vt7 }; GLuint texIDs[8]; for( int i=0; i<num; i++ ) { texIDs[i] = ( t[i] ) ? t[i]->mObjectID : 0; } oglBindSamplers( 0, num, texIDs ); } void piRendererGL4X::DettachSamplers( void ) { GLuint texIDs[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; oglBindSamplers( 0, 8, texIDs ); } //=========================================================================================================================================== static const char *versionStr = "#version 440 core\n"; static bool createOptionsString(char *buffer, const int bufferLength, const piShaderOptions *options ) { const int num = options->mNum; if (num>64) return false; int ptr = 0; for (int i = 0; i<num; i++) { int offset = pisprintf(buffer + ptr, bufferLength - ptr, "#define %s %d\n", options->mOption[i].mName, options->mOption[i].mValue); ptr += offset; } buffer[ptr] = 0; return true; } piShader piRendererGL4X::CreateShader( const piShaderOptions *options, const char *vs, const char *cs, const char *es, const char *gs, const char *fs, char *error) { piIShader *me = (piIShader*)malloc( sizeof(piIShader) ); if( !me ) return nullptr; //glEnable( GL_DEPTH_TEST ); const char *vtext = vs; const char *ctext = cs; const char *etext = es; const char *gtext = gs; const char *ftext = fs; me->mProgID = oglCreateProgram(); const int mVertShaderID = vs?oglCreateShader( GL_VERTEX_SHADER ):-1; const int mCtrlShaderID = cs?oglCreateShader( GL_TESS_CONTROL_SHADER ):-1; const int mEvalShaderID = es?oglCreateShader( GL_TESS_EVALUATION_SHADER ):-1; const int mGeomShaderID = gs?oglCreateShader( GL_GEOMETRY_SHADER ):-1; const int mFragShaderID = fs?oglCreateShader( GL_FRAGMENT_SHADER ):-1; char optionsStr[80*64] = { 0 }; if (options != nullptr) { if (!createOptionsString(optionsStr, 80 * 64, options)) { free(me); return nullptr; } } const GLchar *vstrings[3] = { versionStr, optionsStr, vtext }; const GLchar *cstrings[3] = { versionStr, optionsStr, ctext }; const GLchar *estrings[3] = { versionStr, optionsStr, etext }; const GLchar *gstrings[3] = { versionStr, optionsStr, gtext }; const GLchar *fstrings[3] = { versionStr, optionsStr, ftext }; if( vs ) oglShaderSource(mVertShaderID, 3, vstrings, 0); if( cs ) oglShaderSource(mCtrlShaderID, 3, cstrings, 0); if( es ) oglShaderSource(mEvalShaderID, 3, estrings, 0); if( gs ) oglShaderSource(mGeomShaderID, 3, gstrings, 0); if( fs ) oglShaderSource(mFragShaderID, 3, fstrings, 0); int result = 0; //-------- if( vs ) { oglCompileShader( mVertShaderID ); oglGetShaderiv( mVertShaderID, GL_COMPILE_STATUS, &result ); if( !result ) { if (error) { error[0] = 'V'; error[1] = 'S'; error[2] = ':'; oglGetShaderInfoLog(mVertShaderID, 1024, NULL, (char *)(error + 3)); } free(me); return nullptr; } } //-------- if( cs ) { oglCompileShader( mCtrlShaderID ); oglGetShaderiv( mCtrlShaderID, GL_COMPILE_STATUS, &result ); if( !result ) { if( error ) { error[0]='C'; error[1]='S'; error[2]=':'; oglGetShaderInfoLog( mCtrlShaderID, 1024, NULL, (char *)(error+3) ); } free(me); return nullptr; } } //-------- if( es ) { oglCompileShader( mEvalShaderID ); oglGetShaderiv( mEvalShaderID, GL_COMPILE_STATUS, &result ); if( !result ) { if( error ) { error[0]='E'; error[1]='S'; error[2]=':'; oglGetShaderInfoLog( mEvalShaderID, 1024, NULL, (char *)(error+3) ); } return nullptr; } } //-------- if( gs ) { oglCompileShader( mGeomShaderID ); oglGetShaderiv( mGeomShaderID, GL_COMPILE_STATUS, &result ); if( !result ) { if( error ) { error[0]='G'; error[1]='S'; error[2]=':'; oglGetShaderInfoLog( mGeomShaderID, 1024, NULL, (char *)(error+3) ); } return nullptr; } } //-------- if( fs ) { oglCompileShader( mFragShaderID ); oglGetShaderiv( mFragShaderID, GL_COMPILE_STATUS, &result ); if( !result ) { if( error ) { error[0]='F'; error[1]='S'; error[2]=':'; oglGetShaderInfoLog( mFragShaderID, 1024, NULL, (char *)(error+3) ); } return nullptr; } } //-------- if( vs ) oglAttachShader( me->mProgID, mVertShaderID ); if( cs ) oglAttachShader( me->mProgID, mCtrlShaderID ); if( es ) oglAttachShader( me->mProgID, mEvalShaderID ); if( gs ) oglAttachShader( me->mProgID, mGeomShaderID ); if( fs ) oglAttachShader( me->mProgID, mFragShaderID ); //-------- oglLinkProgram( me->mProgID ); oglGetProgramiv( me->mProgID, GL_LINK_STATUS, &result ); if( !result ) { if( error ) { error[0]='L'; error[1]='I'; error[2]=':'; oglGetProgramInfoLog( me->mProgID, 1024, NULL, (char *)(error+3) ); } return nullptr; } if( vs ) oglDeleteShader( mVertShaderID ); if( cs ) oglDeleteShader( mCtrlShaderID ); if( es ) oglDeleteShader( mEvalShaderID ); if( gs ) oglDeleteShader( mGeomShaderID ); if( fs ) oglDeleteShader( mFragShaderID ); return (piShader)me; } piShader piRendererGL4X::CreateCompute(const piShaderOptions *options, const char *cs, char *error) { if (!cs) return nullptr; piIShader *me = (piIShader*)malloc(sizeof(piIShader)); if (!me) return nullptr; const char *ctext = cs; char optionsStr[80 * 64] = { 0 }; if (options != nullptr) createOptionsString(optionsStr, 80*64, options); me->mProgID = oglCreateProgram(); const int mShaderID = oglCreateShader(GL_COMPUTE_SHADER); const GLchar *vstrings[3] = { versionStr, optionsStr, ctext }; oglShaderSource(mShaderID, 3, vstrings, 0); int result = 0; //-------- oglCompileShader(mShaderID); oglGetShaderiv(mShaderID, GL_COMPILE_STATUS, &result); if (!result) { if (error) { error[0] = 'C'; error[1] = 'S'; error[2] = ':'; oglGetShaderInfoLog(mShaderID, 1024, NULL, (char *)(error + 3)); } free(me); return(0); } //-------- oglAttachShader(me->mProgID, mShaderID); //-------- oglLinkProgram(me->mProgID); oglGetProgramiv(me->mProgID, GL_LINK_STATUS, &result); if (!result) { if (error) { error[0] = 'L'; error[1] = 'I'; error[2] = ':'; oglGetProgramInfoLog(me->mProgID, 1024, NULL, (char *)(error + 3)); } free(me); return(0); } oglDeleteShader(mShaderID); return (piShader)me; } void piRendererGL4X::DestroyShader( piShader vme ) { piIShader *me = (piIShader *)vme; oglDeleteProgram( me->mProgID ); } void piRendererGL4X::AttachShader( piShader vme ) { piIShader *me = (piIShader *)vme; //if (me->mProgID==this->mB oglUseProgram( me->mProgID ); //glEnable( GL_VERTEX_PROGRAM_POINT_SIZE ); } void piRendererGL4X::DettachShader( void ) { //glDisable(GL_VERTEX_PROGRAM_POINT_SIZE); oglUseProgram( 0 ); } void piRendererGL4X::AttachShaderConstants(piBuffer obj, int unit) { piIBuffer *me = (piIBuffer *)obj; oglBindBufferRange(GL_UNIFORM_BUFFER, unit, me->mObjectID, 0, me->mSize); } void piRendererGL4X::AttachShaderBuffer(piBuffer obj, int unit) { piIBuffer *me = (piIBuffer *)obj; oglBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, me->mObjectID ); } void piRendererGL4X::DettachShaderBuffer(int unit) { oglBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, 0); } void piRendererGL4X::AttachAtomicsBuffer(piBuffer obj, int unit) { piIBuffer *me = (piIBuffer *)obj; oglBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, unit, me->mObjectID); } void piRendererGL4X::DettachAtomicsBuffer(int unit) { oglBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, unit, 0); } void piRendererGL4X::SetShaderConstant4F(const unsigned int pos, const float *value, int num) { oglUniform4fv(pos,num,value); } void piRendererGL4X::SetShaderConstant3F(const unsigned int pos, const float *value, int num) { oglUniform3fv(pos,num,value); } void piRendererGL4X::SetShaderConstant2F(const unsigned int pos, const float *value, int num) { oglUniform2fv(pos,num,value); } void piRendererGL4X::SetShaderConstant1F(const unsigned int pos, const float *value, int num) { oglUniform1fv(pos,num,value); } void piRendererGL4X::SetShaderConstant1I(const unsigned int pos, const int *value, int num) { oglUniform1iv(pos,num,value); } void piRendererGL4X::SetShaderConstant1UI(const unsigned int pos, const unsigned int *value, int num) { oglUniform1uiv(pos,num,value); } void piRendererGL4X::SetShaderConstantMat4F(const unsigned int pos, const float *value, int num, bool transpose) { oglUniformMatrix4fv(pos,num,transpose,value); //oglProgramUniformMatrix4fv( ((piIShader *)mBindedShader)->mProgID, pos, num, transpose, value ); // can do without binding! } void piRendererGL4X::SetShaderConstantSampler(const unsigned int pos, int unit) { oglUniform1i(pos,unit); } static const int r2gl_blendMode[] = { GL_ONE, GL_SRC_ALPHA, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA_SATURATE, GL_ZERO }; static const int r2gl_blendEqua[] = { GL_FUNC_ADD, GL_FUNC_SUBTRACT, GL_FUNC_REVERSE_SUBTRACT, GL_MIN, GL_MAX }; void piRendererGL4X::SetBlending( int buf, piBlendEquation equRGB, piBlendOperations srcRGB, piBlendOperations dstRGB, piBlendEquation equALP, piBlendOperations srcALP, piBlendOperations dstALP ) { oglBlendEquationSeparatei(buf, r2gl_blendEqua[equRGB], r2gl_blendEqua[equALP]); oglBlendFuncSeparatei( buf, r2gl_blendMode[srcRGB], r2gl_blendMode[dstRGB], r2gl_blendMode[srcALP], r2gl_blendMode[dstALP]); } void piRendererGL4X::SetWriteMask( bool c0, bool c1, bool c2, bool c3, bool z ) { glDepthMask( z?GL_TRUE:GL_FALSE ); oglColorMaski( 0, c0, c0, c0, c0 ); oglColorMaski( 1, c0, c0, c0, c0 ); oglColorMaski( 2, c0, c0, c0, c0 ); oglColorMaski( 3, c0, c0, c0, c0 ); } void piRendererGL4X::SetState( piState state, bool value ) { if( state==piSTATE_WIREFRAME ) { if( value ) glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); else glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } else if( state==piSTATE_FRONT_FACE ) { if( !value ) glFrontFace( GL_CW ); else glFrontFace( GL_CCW ); } else if (state == piSTATE_DEPTH_TEST) { if (value) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); } else if( state== piSTATE_CULL_FACE ) { if( value ) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); } else if( state == piSTATE_ALPHA_TO_COVERAGE ) { if (value) { glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); glEnable(GL_SAMPLE_ALPHA_TO_ONE); glDisable(GL_SAMPLE_COVERAGE ); } else { glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); glDisable(GL_SAMPLE_ALPHA_TO_ONE); glDisable(GL_SAMPLE_COVERAGE); } } else if( state == piSTATE_DEPTH_CLAMP ) { if( value ) glEnable( GL_DEPTH_CLAMP); else glDisable( GL_DEPTH_CLAMP); } else if( state == piSTATE_VIEWPORT_FLIPY ) { if( value ) oglClipControl(GL_UPPER_LEFT, GL_ZERO_TO_ONE); else oglClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE); } else if( state == piSTATE_BLEND ) { if (value) glEnable(GL_BLEND); else glDisable(GL_BLEND); } } void piRendererGL4X::Clear( const float *color0, const float *color1, const float *color2, const float *color3, const bool depth0 ) { if( mBindedTarget == NULL ) { int mode = 0; if( color0 ) { mode |= GL_COLOR_BUFFER_BIT; glClearColor( color0[0], color0[1], color0[2], color0[3] ); } if( depth0 ) { mode |= GL_DEPTH_BUFFER_BIT; glClearDepth( 1.0f ); } glClear( mode ); } else { float z = 1.0f; if( color0 ) oglClearBufferfv( GL_COLOR, 0, color0 ); if( color1 ) oglClearBufferfv( GL_COLOR, 1, color1 ); if( color2 ) oglClearBufferfv( GL_COLOR, 2, color2 ); if( color3 ) oglClearBufferfv( GL_COLOR, 3, color3 ); if( depth0 ) oglClearBufferfv( GL_DEPTH, 0, &z ); } // glClearBufferfi( GL_DEPTH_STENCIL, 0, z, s ); } //----------------------- piBuffer piRendererGL4X::CreateBuffer(const void *data, unsigned int amount, piBufferType mode) { piIBuffer *me = (piIBuffer*)malloc(sizeof(piIBuffer)); if (!me) return nullptr; oglCreateBuffers(1, &me->mObjectID); if (mode == piBufferType_Dynamic) { oglNamedBufferStorage(me->mObjectID, amount, data, GL_DYNAMIC_STORAGE_BIT); //oglNamedBufferStorage(me->mObjectID, amount, data, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT ); //me->mPtr = oglMapNamedBufferRange(me->mObjectID, 0, amount, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT ); //if (me->mPtr == nullptr ) // return 0; //me->mSync = oglFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); } else { oglNamedBufferStorage(me->mObjectID, amount, data, 0); //me->mPtr = nullptr; } me->mSize = amount; return (piBuffer)me; } //glGenBuffers(1, &me->mObjectID); //glBindBuffer(GL_SHADER_STORAGE_BUFFER, me->mObjectID); //glBufferData(GL_SHADER_STORAGE_BUFFER, amount, nullptr, GL_DYNAMIC_COPY); void piRendererGL4X::DestroyBuffer(piBuffer vme) { piIBuffer *me = (piIBuffer*)vme; oglDeleteBuffers(1, &me->mObjectID ); } void piRendererGL4X::UpdateBuffer(piBuffer obj, const void *data, int offset, int len) { piIBuffer *me = (piIBuffer *)obj; oglNamedBufferSubData(me->mObjectID, offset, len, data); /* while(1) { GLenum waitReturn = oglClientWaitSync(me->mSync, GL_SYNC_FLUSH_COMMANDS_BIT, 1); if (waitReturn == GL_ALREADY_SIGNALED || waitReturn == GL_CONDITION_SATISFIED) break; } memcpy(me->mPtr, data, len); */ //void *ptr = oglMapNamedBufferRange(me->mObjectID, 0, len, GL_MAP_WRITE_BIT | GL_MAP_COHERENT_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); //memcpy(ptr, data, len); //oglUnmapNamedBuffer( me->mObjectID ); } piVertexArray piRendererGL4X::CreateVertexArray( int numStreams, piBuffer vb0, const piRArrayLayout *streamLayout0, piBuffer vb1, const piRArrayLayout *streamLayout1, piBuffer eb ) { piIVertexArray *me = (piIVertexArray*)malloc(sizeof(piIVertexArray)); if( !me ) return nullptr; oglCreateVertexArrays(1, &me->mObjectID); if (!me->mObjectID) return nullptr; unsigned int aid = 0; for( int j=0; j<numStreams; j++ ) { unsigned int sid = j; //me->mStreams[j] = (j == 0) *streamLayout0 : *streamLayout1; const piRArrayLayout * st = (j == 0) ? streamLayout0 : streamLayout1; piBuffer vb = (j==0 ) ? vb0 : vb1; int offset = 0; const int num = st->mNumElements; for( int i=0; i<num; i++ ) { oglEnableVertexArrayAttrib(me->mObjectID, aid); oglVertexArrayAttribFormat(me->mObjectID, aid, st->mEntry[i].mNumComponents, glType[st->mEntry[i].mType], st->mEntry[i].mNormalize, offset); oglVertexArrayAttribBinding(me->mObjectID, aid, sid); offset += st->mEntry[i].mNumComponents*glSizeof[st->mEntry[i].mType]; aid++; } oglVertexArrayVertexBuffer(me->mObjectID, sid, ((piIBuffer*)vb)->mObjectID, 0, st->mStride); //oglVertexArrayBindingDivisor(me->mObjectID, bid, (streamLayout->mDivisor>0) ? streamLayout->mDivisor : 1 ); } if (eb != nullptr ) oglVertexArrayElementBuffer(me->mObjectID, ((piIBuffer*)eb)->mObjectID); return (piVertexArray)me; } void piRendererGL4X::DestroyVertexArray(piVertexArray vme) { piIVertexArray *me = (piIVertexArray*)vme; oglDeleteVertexArrays(1, &me->mObjectID); } void piRendererGL4X::AttachVertexArray(piVertexArray vme) { piIVertexArray *me = (piIVertexArray*)vme; oglBindVertexArray(me->mObjectID); } void piRendererGL4X::DettachVertexArray( void ) { oglBindVertexArray( 0 ); } void piRendererGL4X::DrawPrimitiveIndexed(piPrimitiveType pt, int num, int numInstances, int baseVertex, int baseInstance) { GLenum glpt = GL_TRIANGLES; if (pt == piPT_Triangle) glpt = GL_TRIANGLES; else if (pt == piPT_Point) glpt = GL_POINTS; else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP; else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP; else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); } else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); } else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY; else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY; else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); } else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); } else if (pt == piPT_Lines) glpt = GL_LINES; /* unsigned int cmd[5] = { num, // num elements 1, // num instances 0, // first index 0, // base vertex 0 };// base instance subdata( GL_DRAW_INDIRECT_BUFFER​, cmd ) oglDrawElementsIndirect(glpt[pt], GL_UNSIGNED_INT, 0); */ oglDrawElementsInstancedBaseVertexBaseInstance( glpt, num, GL_UNSIGNED_INT, NULL, // indices numInstances, // prim count baseVertex, // base vertex baseInstance); // base instance } void piRendererGL4X::DrawPrimitiveNotIndexed(piPrimitiveType pt, int first, int num, int numInstanced) { GLenum glpt = GL_TRIANGLES; if (pt == piPT_Triangle) glpt = GL_TRIANGLES; else if (pt == piPT_Point) glpt = GL_POINTS; else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP; else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP; else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); } else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); } else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY; else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY; else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); } else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); } else if (pt == piPT_Lines) glpt = GL_LINES; oglDrawArraysInstanced(glpt, first, num, numInstanced); } void piRendererGL4X::DrawPrimitiveNotIndexedMultiple(piPrimitiveType pt, const int *firsts, const int *counts, int num) { GLenum glpt = GL_TRIANGLES; if (pt == piPT_Triangle) glpt = GL_TRIANGLES; else if (pt == piPT_Point) glpt = GL_POINTS; else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP; else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP; else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); } else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); } else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY; else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY; else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); } else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); } else if (pt == piPT_Lines) glpt = GL_LINES; oglMultiDrawArrays(glpt,firsts,counts,num); } void piRendererGL4X::DrawPrimitiveNotIndexedIndirect(piPrimitiveType pt, piBuffer cmds, int num) { piIBuffer *buf = (piIBuffer *)cmds; oglBindBuffer(GL_DRAW_INDIRECT_BUFFER, buf->mObjectID); GLenum glpt = GL_TRIANGLES; if (pt == piPT_Triangle) glpt = GL_TRIANGLES; else if (pt == piPT_Point) glpt = GL_POINTS; else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP; else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP; else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); } else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); } else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY; else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY; else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); } else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); } else if (pt == piPT_Lines) glpt = GL_LINES; oglMultiDrawArraysIndirect(glpt, 0, num, sizeof(piDrawArraysIndirectCommand)); oglBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0); } void piRendererGL4X::DrawPrimitiveIndirect(piPrimitiveType pt, piBuffer cmds, int num) { piIBuffer *buf = (piIBuffer *)cmds; oglBindBuffer(GL_DRAW_INDIRECT_BUFFER, buf->mObjectID); GLenum glpt = GL_TRIANGLES; if (pt == piPT_Triangle) glpt = GL_TRIANGLES; else if (pt == piPT_Point) glpt = GL_POINTS; else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP; else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP; else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); } else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); } else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY; else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY; else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); } else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); } else if (pt == piPT_Lines) glpt = GL_LINES; oglMultiDrawElementsIndirect(glpt, GL_UNSIGNED_INT, 0, num, sizeof(piDrawElementsIndirectCommand)); oglBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0); } void piRendererGL4X::DrawUnitQuad_XY( int numInstanced ) { this->AttachVertexArray( mVA[0] ); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, numInstanced); this->DettachVertexArray(); } void piRendererGL4X::DrawUnitCube_XYZ_NOR(int numInstanced) { this->AttachVertexArray(mVA[1]); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 4, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 8, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 12, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 16, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 20, 4, numInstanced); this->DettachVertexArray(); } void piRendererGL4X::DrawUnitCube_XYZ(int numInstanced) { this->AttachVertexArray(mVA[2]); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 4, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 8, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 12, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 16, 4, numInstanced); oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 20, 4, numInstanced); this->DettachVertexArray(); } void piRendererGL4X::ExecuteCompute(int tx, int ty, int tz, int gsx, int gsy, int gsz) { int ngx = tx / gsx; if( (ngx*gsx) < tx ) ngx++; int ngy = ty / gsy; if( (ngy*gsy) < ty ) ngy++; int ngz = tz / gsz; if( (ngz*gsz) < tz ) ngz++; oglDispatchCompute( ngx, ngy, ngz ); } void piRendererGL4X::SetLineWidth( float size ) { glLineWidth( size ); } void piRendererGL4X::SetPointSize( bool mode, float size ) { if( mode ) { glEnable( GL_PROGRAM_POINT_SIZE ); glPointSize( size ); } else glDisable( GL_PROGRAM_POINT_SIZE ); } void piRendererGL4X::GetTextureRes( piTexture vme, int *res ) { piITexture *me = (piITexture*)vme; res[0] = me->mInfo.mXres; res[1] = me->mInfo.mYres; res[2] = me->mInfo.mZres; } void piRendererGL4X::GetTextureFormat( piTexture vme, piTextureFormat *format ) { piITexture *me = (piITexture*)vme; format[0] = me->mInfo.mFormat; } void piRendererGL4X::GetTextureInfo( piTexture vme, piTextureInfo *info ) { piITexture *me = (piITexture*)vme; info[0] = me->mInfo; info->mDeleteMe = me->mObjectID; } void piRendererGL4X::GetTextureSampling(piTexture vme, piTextureFilter *rfilter, piTextureWrap *rwrap) { piITexture *me = (piITexture*)vme; rfilter[0] = me->mFilter; rwrap[0] = me->mWrap; } void piRendererGL4X::GetTextureContent( piTexture vme, void *data, const piTextureFormat fmt ) { piITexture *me = (piITexture*)vme; int mode, mode2, mode3, bpp; //if( !format2gl( me->mInfo.mFormat, &bpp, &mode, &mode2, &mode3, me->mInfo.mCompressed ) ) if( !format2gl( fmt, &bpp, &mode, &mode2, &mode3, me->mInfo.mCompressed ) ) return; oglGetTextureImage(me->mObjectID, 0, mode, mode3, me->mInfo.mXres*me->mInfo.mYres*me->mInfo.mZres * bpp, data); } void piRendererGL4X::GetTextureContent(piTexture vme, void *data, int x, int y, int z, int xres, int yres, int zres) { piITexture *me = (piITexture*)vme; int exteriorFormat, internalFormat, ftype, bpp; if (!format2gl(me->mInfo.mFormat, &bpp, &exteriorFormat, &internalFormat, &ftype, me->mInfo.mCompressed)) return; oglGetTextureSubImage( me->mObjectID, 0, x, y, z, xres, yres, zres, exteriorFormat, ftype, xres*yres*zres*bpp, data ); } //------------ /* void piRendererGL4X::SetAttribute1F( int pos, const float data ) { oglVertexAttrib1f( pos, data ); } void piRendererGL4X::SetAttribute2F( int pos, const float *data ) { oglVertexAttrib2fv( pos, data ); } void piRendererGL4X::SetAttribute3F( int pos, const float *data ) { oglVertexAttrib3fv( pos, data ); } void piRendererGL4X::SetAttribute4F( int pos, const float *data ) { oglVertexAttrib4fv( pos, data ); } */ void piRendererGL4X::PolygonOffset( bool mode, bool wireframe, float a, float b ) { if( mode ) { glEnable( wireframe?GL_POLYGON_OFFSET_LINE:GL_POLYGON_OFFSET_FILL ); glPolygonOffset( a, b ); } else { glDisable( wireframe?GL_POLYGON_OFFSET_LINE:GL_POLYGON_OFFSET_FILL ); } } void piRendererGL4X::RenderMemoryBarrier(piBarrierType type) { GLbitfield bf = 0; if( type & piBARRIER_SHADER_STORAGE ) bf |= GL_SHADER_STORAGE_BARRIER_BIT; if( type & piBARRIER_UNIFORM ) bf |= GL_UNIFORM_BARRIER_BIT; if( type & piBARRIER_ATOMICS ) bf |= GL_ATOMIC_COUNTER_BARRIER_BIT; if( type & piBARRIER_IMAGE ) bf |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; if (type & piBARRIER_COMMAND ) bf |= GL_COMMAND_BARRIER_BIT; if (type & piBARRIER_TEXTURE ) bf |= GL_TEXTURE_UPDATE_BARRIER_BIT; if( type == piBARRIER_ALL) bf = GL_ALL_BARRIER_BITS; oglMemoryBarrier(bf); } }
35.628095
188
0.632552
Livictor213
96046ebd4f9e5693425634fe9e481cdb497f2936
9,122
cpp
C++
src/tgcreator/tgStructure.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
148
2015-01-08T22:44:00.000Z
2022-03-19T18:42:48.000Z
src/tgcreator/tgStructure.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
107
2015-01-02T16:41:42.000Z
2021-06-14T22:09:19.000Z
src/tgcreator/tgStructure.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
86
2015-01-06T07:02:36.000Z
2022-02-28T17:36:14.000Z
/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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 tgStructure.cpp * @brief Implementation of class tgStructure * @author Ryan Adams * @date March 2014 * $Id$ */ // This module #include "tgStructure.h" // This library #include "tgNode.h" #include "tgPair.h" // The Bullet Physics library #include <LinearMath/btQuaternion.h> #include <LinearMath/btVector3.h> tgStructure::tgStructure() : tgTaggable() { } /** * Copy constructor */ tgStructure::tgStructure(const tgStructure& orig) : tgTaggable(orig.getTags()), m_children(orig.m_children.size()), m_nodes(orig.m_nodes), m_pairs(orig.m_pairs) { // Copy children for (std::size_t i = 0; i < orig.m_children.size(); ++i) { m_children[i] = new tgStructure(*orig.m_children[i]); } } tgStructure::tgStructure(const tgTags& tags) : tgTaggable(tags) { } tgStructure::tgStructure(const std::string& space_separated_tags) : tgTaggable(space_separated_tags) { } tgStructure::~tgStructure() { for (std::size_t i = 0; i < m_children.size(); ++i) { delete m_children[i]; } } void tgStructure::addNode(double x, double y, double z, std::string tags) { m_nodes.addNode(x, y, z, tags); } void tgStructure::addNode(tgNode& newNode) { m_nodes.addNode(newNode); } void tgStructure::addPair(int fromNodeIdx, int toNodeIdx, std::string tags) { addPair(m_nodes[fromNodeIdx], m_nodes[toNodeIdx], tags); } void tgStructure::addPair(const btVector3& from, const btVector3& to, std::string tags) { // @todo: do we need to pass in tags here? might be able to save some proc time if not... tgPair p = tgPair(from, to); if (!m_pairs.contains(p)) { m_pairs.addPair(tgPair(from, to, tags)); } else { std::ostringstream os; os << "A pair matching " << p << " already exists in this structure."; throw tgException(os.str()); } } void tgStructure::removePair(const tgPair& pair) { m_pairs.removePair(pair); for (unsigned int i = 0; i < m_children.size(); i++) { m_children[i]->removePair(pair); } } void tgStructure::move(const btVector3& offset) { m_nodes.move(offset); m_pairs.move(offset); for (size_t i = 0; i < m_children.size(); ++i) { tgStructure * const pStructure = m_children[i]; assert(pStructure != NULL); pStructure->move(offset); } } void tgStructure::addRotation(const btVector3& fixedPoint, const btVector3& axis, double angle) { const btQuaternion rotation(axis, angle); addRotation(fixedPoint, rotation); } void tgStructure::addRotation(const btVector3& fixedPoint, const btVector3& fromOrientation, const btVector3& toOrientation) { addRotation(fixedPoint, tgUtil::getQuaternionBetween(fromOrientation, toOrientation)); } void tgStructure::addRotation(const btVector3& fixedPoint, const btQuaternion& rotation) { m_nodes.addRotation(fixedPoint, rotation); m_pairs.addRotation(fixedPoint, rotation); for (std::size_t i = 0; i < m_children.size(); ++i) { tgStructure * const pStructure = m_children[i]; assert(pStructure != NULL); pStructure->addRotation(fixedPoint, rotation); } } void tgStructure::scale(double scaleFactor) { btVector3 structureCentroid = getCentroid(); scale(structureCentroid, scaleFactor); } void tgStructure::scale(const btVector3& referencePoint, double scaleFactor) { m_nodes.scale(referencePoint, scaleFactor); m_pairs.scale(referencePoint, scaleFactor); for (int i = 0; i < m_children.size(); i++) { tgStructure* const childStructure = m_children[i]; assert(childStructure != NULL); childStructure->scale(referencePoint, scaleFactor); } } void tgStructure::addChild(tgStructure* pChild) { /// @todo: check to make sure we don't already have one of these structures /// (what does that mean?) /// @note: We only want to check that pairs are the same at build time, since one /// structure may build the pairs, while another may not depending on its tags. if (pChild != NULL) { m_children.push_back(pChild); } } void tgStructure::addChild(const tgStructure& child) { m_children.push_back(new tgStructure(child)); } btVector3 tgStructure::getCentroid() const { btVector3 centroid = btVector3(0, 0, 0); int numNodes = 0; std::queue< const tgStructure*> q; q.push(this); while (!q.empty()) { const tgStructure* structure = q.front(); q.pop(); for (int i = 0; i < structure->m_nodes.size(); i++) { centroid += structure->m_nodes[i]; numNodes++; } for (int i = 0; i < structure->m_children.size(); i++) { q.push(structure->m_children[i]); } } return centroid/numNodes; } tgNode& tgStructure::findNode(const std::string& tags) { std::queue<tgStructure*> q; q.push(this); while (!q.empty()) { tgStructure* structure = q.front(); q.pop(); for (int i = 0; i < structure->m_nodes.size(); i++) { if (structure->m_nodes[i].hasAllTags(tags)) { return structure->m_nodes[i]; } } for (int i = 0; i < structure->m_children.size(); i++) { q.push(structure->m_children[i]); } } throw std::invalid_argument("Node not found: " + tags); } tgPair& tgStructure::findPair(const btVector3& from, const btVector3& to) { std::queue<tgStructure*> q; q.push(this); while (!q.empty()) { tgStructure* structure = q.front(); q.pop(); for (int i = 0; i < structure->m_pairs.size(); i++) { if ((structure->m_pairs[i].getFrom() == from && structure->m_pairs[i].getTo() == to) || (structure->m_pairs[i].getFrom() == to && structure->m_pairs[i].getTo() == from)) { return structure->m_pairs[i]; } } for (int i = 0; i < structure->m_children.size(); i++) { q.push(structure->m_children[i]); } } std::ostringstream pairString; pairString << from << ", " << to; throw std::invalid_argument("Pair not found: " + pairString.str()); } tgStructure& tgStructure::findChild(const std::string& tags) { std::queue<tgStructure*> q; for (int i = 0; i < m_children.size(); i++) { q.push(m_children[i]); } while (!q.empty()) { tgStructure* structure = q.front(); q.pop(); if (structure->hasAllTags(tags)) { return *structure; } for (int i = 0; i < structure->m_children.size(); i++) { q.push(structure->m_children[i]); } } throw std::invalid_argument("Child structure not found: " + tags); } /* Standalone functions */ std::string asYamlElement(const tgStructure& structure, int indentLevel) { std::stringstream os; std::string indent = std::string(2 * (indentLevel), ' '); os << indent << "structure:" << std::endl; os << indent << " tags: " << asYamlList(structure.getTags()) << std::endl; os << asYamlItems(structure.getNodes(), indentLevel + 1); os << asYamlItems(structure.getPairs(), indentLevel + 1); os << asYamlItems(structure.getChildren(), indentLevel + 1); return os.str(); } std::string asYamlItem(const tgStructure& structure, int indentLevel) { std::stringstream os; std::string indent = std::string(2 * (indentLevel), ' '); os << indent << "- tags: " << asYamlList(structure.getTags()) << std::endl; os << asYamlItems(structure.getNodes(), indentLevel + 1); os << asYamlItems(structure.getPairs(), indentLevel + 1); os << asYamlItems(structure.getChildren(), indentLevel + 1); return os.str(); } std::string asYamlItems(const std::vector<tgStructure*> structures, int indentLevel) { std::stringstream os; std::string indent = std::string(2 * (indentLevel), ' '); if (structures.size() == 0) { os << indent << "structures: []" << std::endl; return os.str(); } os << indent << "structures:" << std::endl; for(size_t i = 0; i < structures.size(); i++) { os << asYamlItem(*structures[i], indentLevel+1); } return os.str(); }
29.521036
100
0.62267
wvat
96093b609c018eb3ef7b6d80a160f60ad79f433f
1,488
cpp
C++
LightOJ/LightOJ - 1298/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
LightOJ/LightOJ - 1298/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
LightOJ/LightOJ - 1298/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 2019-05-15 00:42:06 * solution_verdict: Accepted language: C++ * run_time (ms): 783 memory_used (MB): 4.1 * problem: https://vjudge.net/problem/LightOJ-1298 ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=2e6; const long mod=1000000007; long dp[502][502]; bool isPrime(int x) { int sq=sqrt(x+1); for(int i=2;i<=sq;i++) if(x%i==0)return false; return true; } vector<int>prime; long dfs(int pi,int mt) { if(pi<0)return mt?0:1; if(dp[pi][mt]!=-1)return dp[pi][mt]; long now=0,ml=1; for(int i=1;i<=mt;i++) { now=(now+((ml*(prime[pi]-1))%mod)*dfs(pi-1,mt-i))%mod; ml=(ml*prime[pi])%mod; } return dp[pi][mt]=now; } int main() { //freopen("inp.txt","r",stdin); //freopen("out.txt","w",stdout); //ios_base::sync_with_stdio(0);cin.tie(0); int t,tc=0;cin>>t; for(int i=2; ;i++) { if(prime.size()>500)break; if(isPrime(i)) prime.push_back(i); } memset(dp,-1,sizeof(dp)); while(t--) { long ans=0; int n,p;cin>>n>>p; cout<<"Case "<<++tc<<": "<<dfs(p-1,n)<<"\n"; } return 0; }
28.075472
111
0.438172
kzvd4729
9609ceda16c8c790a443ac654cb6aab25e3aa4e6
821
cc
C++
Matura/rozwiazania/62/zadanie 4.cc
Kwandes/highschool-code
ffaf7aea78236cec709ec7c70886df5427005332
[ "MIT" ]
null
null
null
Matura/rozwiazania/62/zadanie 4.cc
Kwandes/highschool-code
ffaf7aea78236cec709ec7c70886df5427005332
[ "MIT" ]
null
null
null
Matura/rozwiazania/62/zadanie 4.cc
Kwandes/highschool-code
ffaf7aea78236cec709ec7c70886df5427005332
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> using namespace std; int main() { int i; int liczba; int temp; int cyfr6d = 0; int cyfr6o = 0; ifstream plik; plik.open("liczby2.txt"); for(i=0; i<1000; i++) { plik >> liczba; temp = liczba; while (temp) { if (temp%10 == 6) { cyfr6d++; } temp /= 10; } temp = liczba; while (temp) { if (temp%8 == 6) { cyfr6o++; } temp /= 8; } } plik.close(); cout << "Zadanie 4:\n"; cout << "w podanych liczbach znalazlem " << cyfr6o << " szostek w zapisie osemkowym\n"; cout << "w podanych liczbach znalazlem " << cyfr6d << " szostek w zapisie dziesietnym\n\n"; return 0; }
19.093023
95
0.457978
Kwandes
960b7f307e1c724850a03d98fa118c010730dd67
4,427
cxx
C++
Modules/Loadable/SceneViews/qSlicerSceneViewsModule.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Modules/Loadable/SceneViews/qSlicerSceneViewsModule.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Modules/Loadable/SceneViews/qSlicerSceneViewsModule.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
// Qt includes #include <QtPlugin> // QTGUI includes #include "qSlicerApplication.h" #include "qSlicerCoreIOManager.h" #include <qSlicerNodeWriter.h> // SceneViewsModule includes #include "qSlicerSceneViewsModule.h" #include <qSlicerSceneViewsModuleWidget.h> #include <vtkSlicerSceneViewsModuleLogic.h> // SubjectHierarchy Plugins includes #include "qSlicerSubjectHierarchyPluginHandler.h" #include "qSlicerSubjectHierarchySceneViewsPlugin.h" //----------------------------------------------------------------------------- Q_EXPORT_PLUGIN2(qSlicerSceneViewsModule, qSlicerSceneViewsModule); //----------------------------------------------------------------------------- /// \ingroup Slicer_QtModules_SceneViews class qSlicerSceneViewsModulePrivate { public: }; //----------------------------------------------------------------------------- qSlicerSceneViewsModule::qSlicerSceneViewsModule(QObject* _parent) : Superclass(_parent) , d_ptr(new qSlicerSceneViewsModulePrivate) { } //----------------------------------------------------------------------------- qSlicerSceneViewsModule::~qSlicerSceneViewsModule() { } //----------------------------------------------------------------------------- void qSlicerSceneViewsModule::setup() { qSlicerCoreIOManager* ioManager = qSlicerApplication::application()->coreIOManager(); ioManager->registerIO(new qSlicerNodeWriter( "SceneViews", QString("SceneViewFile"), QStringList() << "vtkMRMLSceneViewNode", true, this)); // Register Subject Hierarchy core plugins qSlicerSubjectHierarchyPluginHandler::instance()->registerPlugin( new qSlicerSubjectHierarchySceneViewsPlugin()); } //----------------------------------------------------------------------------- qSlicerAbstractModuleRepresentation* qSlicerSceneViewsModule::createWidgetRepresentation() { return new qSlicerSceneViewsModuleWidget; } //----------------------------------------------------------------------------- vtkMRMLAbstractLogic* qSlicerSceneViewsModule::createLogic() { return vtkSlicerSceneViewsModuleLogic::New(); } //----------------------------------------------------------------------------- QString qSlicerSceneViewsModule::helpText() const { QString help = "The SceneViews module. Create, edit, restore, delete scene views. Scene " "views capture the state of the MRML scene at a given point. The " "recommended way to use them is to load all of your data and then adjust " "visibility of the elements and capture interesting scene views. " "Unexpected behavior may occur if you add or delete data from the scene " "while saving and restoring scene views.\n" "<a href=\"%1/Documentation/%2.%3/Modules/SceneViews\">" "%1/Documentation/%2.%3/Modules/SceneViews</a>\n"; return help.arg(this->slicerWikiUrl()).arg(Slicer_VERSION_MAJOR).arg(Slicer_VERSION_MINOR); } //----------------------------------------------------------------------------- QString qSlicerSceneViewsModule::acknowledgementText() const { return "This module was developed by Daniel Haehn and Kilian Pohl. The research was funded by an ARRA supplement to NIH NCRR (P41 RR13218)."; } //----------------------------------------------------------------------------- QStringList qSlicerSceneViewsModule::contributors() const { QStringList moduleContributors; moduleContributors << QString("Nicole Aucoin (SPL, BWH)"); moduleContributors << QString("Wendy Plesniak (SPL, BWH)"); moduleContributors << QString("Daniel Haehn (UPenn)"); moduleContributors << QString("Kilian Pohl (UPenn)"); return moduleContributors; } //----------------------------------------------------------------------------- QIcon qSlicerSceneViewsModule::icon() const { return QIcon(":/Icons/SelectCameras.png"); } //----------------------------------------------------------------------------- QStringList qSlicerSceneViewsModule::categories() const { return QStringList() << ""; } //----------------------------------------------------------------------------- void qSlicerSceneViewsModule::showSceneViewDialog() { Q_ASSERT(this->widgetRepresentation()); dynamic_cast<qSlicerSceneViewsModuleWidget*>(this->widgetRepresentation()) ->showSceneViewDialog(); } //----------------------------------------------------------------------------- QStringList qSlicerSceneViewsModule::associatedNodeTypes() const { return QStringList() << "vtkMRMLSceneViewNode"; }
34.858268
143
0.580529
TheInterventionCentre
960bcbc38b50b7fee00c52e57087d6ad10fb6fee
7,316
hxx
C++
include/idocp/contact_complementarity/contact_normal_force.hxx
KY-Lin22/idocp
8cacfea7bb2184023eb15316aea07154a62d59bb
[ "BSD-3-Clause" ]
1
2021-09-04T07:43:04.000Z
2021-09-04T07:43:04.000Z
include/idocp/contact_complementarity/contact_normal_force.hxx
KY-Lin22/idocp
8cacfea7bb2184023eb15316aea07154a62d59bb
[ "BSD-3-Clause" ]
null
null
null
include/idocp/contact_complementarity/contact_normal_force.hxx
KY-Lin22/idocp
8cacfea7bb2184023eb15316aea07154a62d59bb
[ "BSD-3-Clause" ]
null
null
null
#ifndef IDOCP_CONTACT_NORMAL_FORCE_HXX_ #define IDOCP_CONTACT_NORMAL_FORCE_HXX_ #include "idocp/contact_complementarity/contact_normal_force.hpp" #include <exception> #include <iostream> #include <assert.h> namespace idocp { inline ContactNormalForce::ContactNormalForce( const Robot& robot, const double barrier, const double fraction_to_boundary_rate) : ContactComplementarityComponentBase(barrier, fraction_to_boundary_rate), dimc_(robot.max_point_contacts()) { } inline ContactNormalForce::ContactNormalForce() : ContactComplementarityComponentBase(), dimc_(0) { } inline ContactNormalForce::~ContactNormalForce() { } inline bool ContactNormalForce::isFeasible_impl(Robot& robot, ConstraintComponentData& data, const SplitSolution& s) const { for (int i=0; i<robot.max_point_contacts(); ++i) { if (robot.is_contact_active(i)) { if (s.f[i].coeff(2) < 0) { return false; } } } return true; } inline void ContactNormalForce::setSlackAndDual_impl( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s) const { assert(dtau > 0); for (int i=0; i<robot.max_point_contacts(); ++i) { data.slack.coeffRef(i) = dtau * s.f[i].coeff(2); } setSlackAndDualPositive(data.slack, data.dual); } inline void ContactNormalForce::augmentDualResidual_impl( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s, KKTResidual& kkt_residual) const { assert(dtau > 0); int dimf_stack = 0; for (int i=0; i<robot.max_point_contacts(); ++i) { if (robot.is_contact_active(i)) { kkt_residual.lf().coeffRef(dimf_stack+2) -= dtau * data.dual.coeff(i); dimf_stack += 3; } } } inline void ContactNormalForce::condenseSlackAndDual_impl( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s, KKTMatrix& kkt_matrix, KKTResidual& kkt_residual) const { assert(dtau > 0); int dimf_stack = 0; for (int i=0; i<robot.max_point_contacts(); ++i) { if (robot.is_contact_active(i)) { kkt_matrix.Qff().coeffRef(dimf_stack+2, dimf_stack+2) += dtau * dtau * data.dual.coeff(i) / data.slack.coeff(i); data.residual.coeffRef(i) = - dtau * s.f[i].coeff(2) + data.slack.coeff(i); data.duality.coeffRef(i) = computeDuality(data.slack.coeff(i), data.dual.coeff(i)); kkt_residual.lf().coeffRef(dimf_stack+2) -= dtau * (data.dual.coeff(i)*data.residual.coeff(i)-data.duality.coeff(i)) / data.slack.coeff(i); dimf_stack += 3; } } } inline void ContactNormalForce::computeSlackAndDualDirection_impl( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s, const SplitDirection& d) const { int dimf_stack = 0; for (int i=0; i<robot.max_point_contacts(); ++i) { if (robot.is_contact_active(i)) { data.dslack.coeffRef(i) = dtau * d.df().coeff(dimf_stack+2) - data.residual.coeff(i); data.ddual.coeffRef(i) = computeDualDirection(data.slack.coeff(i), data.dual.coeff(i), data.dslack.coeff(i), data.duality.coeff(i)); dimf_stack += 3; } } } inline double ContactNormalForce::residualL1Nrom_impl( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s) const { double norm = 0; for (int i=0; i<robot.max_point_contacts(); ++i) { if (robot.is_contact_active(i)) { norm += std::abs(data.slack.coeff(i) - dtau * s.f[i].coeff(2)); norm += std::abs(computeDuality(data.slack.coeff(i), data.dual.coeff(i))); } } return norm; } inline double ContactNormalForce::squaredKKTErrorNorm_impl( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s) const { double norm = 0; for (int i=0; i<robot.max_point_contacts(); ++i) { if (robot.is_contact_active(i)) { const double residual = data.slack.coeff(i) - dtau * s.f[i].coeff(2); const double duality = computeDuality(data.slack.coeff(i), data.dual.coeff(i)); norm += residual * residual + duality * duality; } } return norm; } inline int ContactNormalForce::dimc_impl() const { return dimc_; } inline double ContactNormalForce::maxSlackStepSize_impl( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active) const { double min_step_size = 1; for (int i=0; i<dimc_; ++i) { if (is_contact_active[i]) { const double fraction_to_boundary = fractionToBoundary(data.slack.coeff(i), data.dslack.coeff(i)); if (fraction_to_boundary > 0 && fraction_to_boundary < 1) { if (fraction_to_boundary < min_step_size) { min_step_size = fraction_to_boundary; } } } } assert(min_step_size > 0); assert(min_step_size <= 1); return min_step_size; } inline double ContactNormalForce::maxDualStepSize_impl( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active) const { double min_step_size = 1; for (int i=0; i<dimc_; ++i) { if (is_contact_active[i]) { const double fraction_to_boundary = fractionToBoundary(data.dual.coeff(i), data.ddual.coeff(i)); if (fraction_to_boundary > 0 && fraction_to_boundary < 1) { if (fraction_to_boundary < min_step_size) { min_step_size = fraction_to_boundary; } } } } assert(min_step_size > 0); assert(min_step_size <= 1); return min_step_size; } inline void ContactNormalForce::updateSlack_impl( ConstraintComponentData& data, const std::vector<bool>& is_contact_active, const double step_size) const { for (int i=0; i<dimc_; ++i) { if (is_contact_active[i]) { data.slack.coeffRef(i) += step_size * data.dslack.coeff(i); } } } inline void ContactNormalForce::updateDual_impl( ConstraintComponentData& data, const std::vector<bool>& is_contact_active, const double step_size) const { for (int i=0; i<dimc_; ++i) { if (is_contact_active[i]) { data.dual.coeffRef(i) += step_size * data.ddual.coeff(i); } } } inline double ContactNormalForce::costSlackBarrier_impl( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active) const { double cost = 0; for (int i=0; i<dimc_; ++i) { if (is_contact_active[i]) { cost += costSlackBarrier(data.slack.coeff(i)); } } return cost; } inline double ContactNormalForce::costSlackBarrier_impl( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active, const double step_size) const { double cost = 0; for (int i=0; i<dimc_; ++i) { if (is_contact_active[i]) { cost += costSlackBarrier(data.slack.coeff(i), data.dslack.coeff(i), step_size); } } return cost; } } // namespace idocp #endif // IDOCP_CONTACT_NORMAL_FORCE_HXX_
30.739496
86
0.642564
KY-Lin22
960d8ac353f53dd95e742ad5cc52fcc2f6226b6d
4,905
hpp
C++
src/config/gc.hpp
Gwenio/synafis
37176e965318ae555fdc542fc87ffb79866f770f
[ "ISC" ]
1
2019-01-27T14:44:50.000Z
2019-01-27T14:44:50.000Z
src/config/gc.hpp
Gwenio/synafis
37176e965318ae555fdc542fc87ffb79866f770f
[ "ISC" ]
null
null
null
src/config/gc.hpp
Gwenio/synafis
37176e965318ae555fdc542fc87ffb79866f770f
[ "ISC" ]
null
null
null
/* ISC License (ISC) Copyright 2018-2019 Adam Armstrong Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "general.hpp" #ifndef SYNAFIS_CONFIG_GC_HPP #define SYNAFIS_CONFIG_GC_HPP #pragma once #include <cstddef> /** \file src/config/gc.hpp * \brief Configures the garbage collector. */ // Set default configurations for those not specified. /** \def SYNAFIS_CONFIG_GUARD_PAGES * \brief The value for config::guard_pages. * \note Define this value in the compiler commandline. * \see config::guard_pages */ #ifndef SYNAFIS_CONFIG_GUARD_PAGES #define SYNAFIS_CONFIG_GUARD_PAGES (config::debug) #endif /** \def SYNAFIS_CONFIG_MIN_POOL * \brief The value for config::min_pool. * \note Define this value in the compiler commandline. * \see config::min_pool */ #ifndef SYNAFIS_CONFIG_MIN_POOL #define SYNAFIS_CONFIG_MIN_POOL (sizeof(std::size_t) * 8) #endif /** \def SYNAFIS_CONFIG_MAX_POOL * \brief The value for config::max_pool. * \note Define this value in the compiler commandline. * \see config::max_pool */ #ifndef SYNAFIS_CONFIG_MAX_POOL #define SYNAFIS_CONFIG_MAX_POOL (sizeof(std::size_t) * 8) #endif /** \def SYNAFIS_CONFIG_GC_PERIOD * \brief The value for config::gc_period. * \note Define this value in the compiler commandline. * \see config::gc_period */ #ifndef SYNAFIS_CONFIG_GC_PERIOD #define SYNAFIS_CONFIG_GC_PERIOD 1000 #endif /** \def SYNAFIS_CONFIG_GC_DEBUG_MUTEX * \brief The value for config::gc_debug_mutex. * \note Define this value in the compiler commandline. * \see config::gc_debug_mutex */ #ifndef SYNAFIS_CONFIG_GC_DEBUG_MUTEX #define SYNAFIS_CONFIG_GC_DEBUG_MUTEX config::debug #endif /** \def SYNAFIS_CONFIG_INIT_TRACKING * \brief The value for config::init_tracking. * \note Define this value in the compiler commandline. * \see config::gc_debug_mutex */ #ifndef SYNAFIS_CONFIG_INIT_TRACKING #define SYNAFIS_CONFIG_INIT_TRACKING config::debug #endif namespace config { /** \var guard_pages * \brief Controls the presence and number of guard pages for blocks of virtual memory. * \details Set to the preprocessor definition SYNAFIS_CONFIG_GUARD_PAGE. * \details * \details Guard pages are page(s) of inaccessible memory separating * \details accessible regions. * \details * \details This detects some memory issues as an error will occur * \details if the program touches a guard page. * \details Due to how virtual memory is used in the collector, the detection * \details provided by this alone is limited. */ inline constexpr bool const guard_pages = SYNAFIS_CONFIG_GUARD_PAGES; /** \var min_pool * \brief The minimum number of objects a pool can hold. * \details Set to the preprocessor definition SYNAFIS_CONFIG_MIN_POOL. */ inline constexpr std::size_t const min_pool = SYNAFIS_CONFIG_MIN_POOL; /** \var max_pool * \brief The maximum number of pages to use for objects in a pool. * \details Set to the preprocessor definition SYNAFIS_CONFIG_MAX_PAGE. * \details * \details The variable min_pool takes priority if min_pool objects * \details need more space than max_pool pages. */ inline constexpr std::size_t const max_pool = SYNAFIS_CONFIG_MAX_POOL; /** \var gc_period * \brief The default time to wait between unforced GC cycles. * \details The value is the number of miliseconds between cycles. * \details If zero, then collection cycles will only run when forced. * \see gc::set_period() */ inline constexpr std::size_t const gc_period = SYNAFIS_CONFIG_GC_PERIOD; /** \var gc_debug_mutex * \brief When true gc::debug_mutex will be used; otherwise, gc::basic_mutex will be used. * \see gc::mutex */ inline constexpr bool const gc_debug_mutex = SYNAFIS_CONFIG_GC_DEBUG_MUTEX; /** \var init_tracking * \brief When true allocators will always track if allocated memory is initialized. */ inline constexpr bool const init_tracking = SYNAFIS_CONFIG_INIT_TRACKING; //! TODO At this time config::init_tracking does nothing, as initialization is always tracked. } // Remove preprocessor definitions that are no longer needed. #undef SYNAFIS_CONFIG_GUARD_PAGES #undef SYNAFIS_CONFIG_MIN_POOL #undef SYNAFIS_CONFIG_MAX_POOL #undef SYNAFIS_CONFIG_GC_PERIOD #undef SYNAFIS_CONFIG_GC_DEBUG_MUTEX #undef SYNAFIS_CONFIG_INIT_TRACKING #endif
32.7
94
0.782671
Gwenio
960f083afdc553cd111f7655aaefb683c6361e00
2,138
cpp
C++
libkram/etc2comp/EtcBlock4x4Encoding_RG11.cpp
yanivams/kramUMK
04d841720cf45b1e7005112643c23177b34ebb84
[ "MIT" ]
53
2020-11-12T03:29:10.000Z
2022-03-13T19:00:52.000Z
libkram/etc2comp/EtcBlock4x4Encoding_RG11.cpp
yanivams/kramUMK
04d841720cf45b1e7005112643c23177b34ebb84
[ "MIT" ]
10
2020-11-11T16:45:46.000Z
2022-03-19T18:45:30.000Z
libkram/etc2comp/EtcBlock4x4Encoding_RG11.cpp
yanivams/kramUMK
04d841720cf45b1e7005112643c23177b34ebb84
[ "MIT" ]
3
2021-09-29T05:44:18.000Z
2022-02-28T11:26:34.000Z
/* * Copyright 2015 The Etc2Comp Authors. * * 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. */ /* EtcBlock4x4Encoding_RG11.cpp Block4x4Encoding_RG11 is the encoder to use when targetting file format RG11 and SRG11 (signed RG11). */ #include "EtcConfig.h" #include "EtcBlock4x4Encoding_RG11.h" namespace Etc { Block4x4Encoding_RG11::Block4x4Encoding_RG11(void) { } Block4x4Encoding_RG11::~Block4x4Encoding_RG11(void) {} void Block4x4Encoding_RG11::Encode( const float *sourcePixels, uint8_t *encodingBits, bool isSnorm) { m_red.Encode(sourcePixels + 0, encodingBits, isSnorm); m_green.Encode(sourcePixels + 1, encodingBits + 8, isSnorm); } void Block4x4Encoding_RG11::Decode( unsigned char *encodingBits, const float *sourcePixels, bool isSnorm, uint16_t lastIteration) { m_red.Decode(encodingBits, sourcePixels, isSnorm, (lastIteration >> 0) & 0xFF); m_green.Decode(encodingBits + 8, sourcePixels + 1, isSnorm, (lastIteration >> 8) & 0xFF); } void Block4x4Encoding_RG11::DecodeOnly( const uint8_t *encodingBits, float *decodedPixels, bool isSnorm) { m_red.DecodeOnly(encodingBits, decodedPixels, isSnorm); m_green.DecodeOnly(encodingBits + 8, decodedPixels + 1, isSnorm); } void Block4x4Encoding_RG11::PerformIteration(float a_fEffort) { m_red.PerformIteration(a_fEffort); m_green.PerformIteration(a_fEffort); } void Block4x4Encoding_RG11::SetEncodingBits(void) { m_red.SetEncodingBits(); m_green.SetEncodingBits(); } }
30.985507
102
0.703929
yanivams
9610efcb7670d5d9dbca7608d56125c8e98920ce
26,809
cpp
C++
src/tests/system/kernel/file_corruption/driver/checksum_device.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/tests/system/kernel/file_corruption/driver/checksum_device.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/tests/system/kernel/file_corruption/driver/checksum_device.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2010, Ingo Weinhold, ingo_weinhold@gmx.de. * Distributed under the terms of the MIT License. */ #include "checksum_device.h" #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <algorithm> #include <device_manager.h> #include <AutoDeleter.h> #include <util/AutoLock.h> #include <util/DoublyLinkedList.h> #include <fs/KPath.h> #include <lock.h> #include <vm/vm.h> #include "dma_resources.h" #include "io_requests.h" #include "IOSchedulerSimple.h" #include "CheckSum.h" //#define TRACE_CHECK_SUM_DEVICE #ifdef TRACE_CHECK_SUM_DEVICE # define TRACE(x...) dprintf(x) #else # define TRACE(x) do {} while (false) #endif // parameters for the DMA resource static const uint32 kDMAResourceBufferCount = 16; static const uint32 kDMAResourceBounceBufferCount = 16; static const size_t kCheckSumLength = sizeof(CheckSum); static const uint32 kCheckSumsPerBlock = B_PAGE_SIZE / sizeof(CheckSum); static const char* const kDriverModuleName = "drivers/disk/virtual/checksum_device/driver_v1"; static const char* const kControlDeviceModuleName = "drivers/disk/virtual/checksum_device/control/device_v1"; static const char* const kRawDeviceModuleName = "drivers/disk/virtual/checksum_device/raw/device_v1"; static const char* const kControlDeviceName = "disk/virtual/checksum_device/control"; static const char* const kRawDeviceBaseName = "disk/virtual/checksum_device"; static const char* const kFilePathItem = "checksum_device/file_path"; struct RawDevice; typedef DoublyLinkedList<RawDevice> RawDeviceList; struct device_manager_info* sDeviceManager; static RawDeviceList sDeviceList; static mutex sDeviceListLock = MUTEX_INITIALIZER("checksum device list"); struct CheckSumBlock : public DoublyLinkedListLinkImpl<CheckSumBlock> { uint64 blockIndex; bool used; bool dirty; CheckSum checkSums[kCheckSumsPerBlock]; CheckSumBlock() : used(false) { } }; struct CheckSumCache { CheckSumCache() { mutex_init(&fLock, "check sum cache"); } ~CheckSumCache() { while (CheckSumBlock* block = fBlocks.RemoveHead()) delete block; mutex_destroy(&fLock); } status_t Init(int fd, uint64 blockCount, uint32 cachedBlockCount) { fBlockCount = blockCount; fFD = fd; for (uint32 i = 0; i < cachedBlockCount; i++) { CheckSumBlock* block = new(std::nothrow) CheckSumBlock; if (block == NULL) return B_NO_MEMORY; fBlocks.Add(block); } return B_OK; } status_t GetCheckSum(uint64 blockIndex, CheckSum& checkSum) { ASSERT(blockIndex < fBlockCount); MutexLocker locker(fLock); CheckSumBlock* block; status_t error = _GetBlock( fBlockCount + blockIndex / kCheckSumsPerBlock, block); if (error != B_OK) return error; checkSum = block->checkSums[blockIndex % kCheckSumsPerBlock]; return B_OK; } status_t SetCheckSum(uint64 blockIndex, const CheckSum& checkSum) { ASSERT(blockIndex < fBlockCount); MutexLocker locker(fLock); CheckSumBlock* block; status_t error = _GetBlock( fBlockCount + blockIndex / kCheckSumsPerBlock, block); if (error != B_OK) return error; block->checkSums[blockIndex % kCheckSumsPerBlock] = checkSum; block->dirty = true; #ifdef TRACE_CHECK_SUM_DEVICE TRACE("checksum_device: setting check sum of block %" B_PRIu64 " to: ", blockIndex); for (size_t i = 0; i < kCheckSumLength; i++) TRACE("%02x", checkSum.Data()[i]); TRACE("\n"); #endif return B_OK; } private: typedef DoublyLinkedList<CheckSumBlock> BlockList; private: status_t _GetBlock(uint64 blockIndex, CheckSumBlock*& _block) { // check whether we have already cached the block for (BlockList::Iterator it = fBlocks.GetIterator(); CheckSumBlock* block = it.Next();) { if (block->used && blockIndex == block->blockIndex) { // we know it -- requeue and return it.Remove(); fBlocks.Add(block); _block = block; return B_OK; } } // flush the least recently used block and recycle it CheckSumBlock* block = fBlocks.Head(); status_t error = _FlushBlock(block); if (error != B_OK) return error; error = _ReadBlock(block, blockIndex); if (error != B_OK) return error; // requeue fBlocks.Remove(block); fBlocks.Add(block); _block = block; return B_OK; } status_t _FlushBlock(CheckSumBlock* block) { if (!block->used || !block->dirty) return B_OK; ssize_t written = pwrite(fFD, block->checkSums, B_PAGE_SIZE, block->blockIndex * B_PAGE_SIZE); if (written < 0) return errno; if (written != B_PAGE_SIZE) return B_ERROR; block->dirty = false; return B_OK; } status_t _ReadBlock(CheckSumBlock* block, uint64 blockIndex) { // mark unused for the failure cases -- reset later block->used = false; ssize_t bytesRead = pread(fFD, block->checkSums, B_PAGE_SIZE, blockIndex * B_PAGE_SIZE); if (bytesRead < 0) return errno; if (bytesRead != B_PAGE_SIZE) return B_ERROR; block->blockIndex = blockIndex; block->used = true; block->dirty = false; return B_OK; } private: mutex fLock; uint64 fBlockCount; int fFD; BlockList fBlocks; // LRU first }; struct Device { Device(device_node* node) : fNode(node) { mutex_init(&fLock, "checksum device"); } virtual ~Device() { mutex_destroy(&fLock); } bool Lock() { mutex_lock(&fLock); return true; } void Unlock() { mutex_unlock(&fLock); } device_node* Node() const { return fNode; } virtual status_t PublishDevice() = 0; protected: mutex fLock; device_node* fNode; }; struct ControlDevice : Device { ControlDevice(device_node* node) : Device(node) { } status_t Register(const char* fileName) { device_attr attrs[] = { {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "Checksum Raw Device"}}, {kFilePathItem, B_STRING_TYPE, {string: fileName}}, {NULL} }; return sDeviceManager->register_node( sDeviceManager->get_parent_node(Node()), kDriverModuleName, attrs, NULL, NULL); } virtual status_t PublishDevice() { return sDeviceManager->publish_device(Node(), kControlDeviceName, kControlDeviceModuleName); } }; struct RawDevice : Device, DoublyLinkedListLinkImpl<RawDevice> { RawDevice(device_node* node) : Device(node), fIndex(-1), fFD(-1), fFileSize(0), fDeviceSize(0), fDeviceName(NULL), fDMAResource(NULL), fIOScheduler(NULL), fTransferBuffer(NULL), fCheckSumCache(NULL) { } virtual ~RawDevice() { if (fIndex >= 0) { MutexLocker locker(sDeviceListLock); sDeviceList.Remove(this); } if (fFD >= 0) close(fFD); free(fDeviceName); } int32 Index() const { return fIndex; } off_t DeviceSize() const { return fDeviceSize; } const char* DeviceName() const { return fDeviceName; } status_t Init(const char* fileName) { // open file/device fFD = open(fileName, O_RDWR | O_NOCACHE); // TODO: The O_NOCACHE is a work-around for a page writer problem. // Since it collects pages for writing back without regard for // which caches and file systems they belong to, a deadlock can // result when pages from both the underlying file system and the // one using the checksum device are collected in one run. if (fFD < 0) return errno; // get the size struct stat st; if (fstat(fFD, &st) < 0) return errno; switch (st.st_mode & S_IFMT) { case S_IFREG: fFileSize = st.st_size; break; case S_IFCHR: case S_IFBLK: { device_geometry geometry; if (ioctl(fFD, B_GET_GEOMETRY, &geometry, sizeof(geometry)) < 0) return errno; fFileSize = (off_t)geometry.bytes_per_sector * geometry.sectors_per_track * geometry.cylinder_count * geometry.head_count; break; } default: return B_BAD_VALUE; } fFileSize = fFileSize / B_PAGE_SIZE * B_PAGE_SIZE; fDeviceSize = fFileSize / (B_PAGE_SIZE + kCheckSumLength) * B_PAGE_SIZE; // find a free slot fIndex = 0; RawDevice* nextDevice = NULL; MutexLocker locker(sDeviceListLock); for (RawDeviceList::Iterator it = sDeviceList.GetIterator(); (nextDevice = it.Next()) != NULL;) { if (nextDevice->Index() > fIndex) break; fIndex = nextDevice->Index() + 1; } sDeviceList.InsertBefore(nextDevice, this); // construct our device path KPath path(kRawDeviceBaseName); char buffer[32]; snprintf(buffer, sizeof(buffer), "%" B_PRId32 "/raw", fIndex); status_t error = path.Append(buffer); if (error != B_OK) return error; fDeviceName = path.DetachBuffer(); return B_OK; } status_t Prepare() { fCheckSumCache = new(std::nothrow) CheckSumCache; if (fCheckSumCache == NULL) { Unprepare(); return B_NO_MEMORY; } status_t error = fCheckSumCache->Init(fFD, fDeviceSize / B_PAGE_SIZE, 16); if (error != B_OK) { Unprepare(); return error; } // no DMA restrictions const dma_restrictions restrictions = {}; fDMAResource = new(std::nothrow) DMAResource; if (fDMAResource == NULL) { Unprepare(); return B_NO_MEMORY; } error = fDMAResource->Init(restrictions, B_PAGE_SIZE, kDMAResourceBufferCount, kDMAResourceBounceBufferCount); if (error != B_OK) { Unprepare(); return error; } fIOScheduler = new(std::nothrow) IOSchedulerSimple(fDMAResource); if (fIOScheduler == NULL) { Unprepare(); return B_NO_MEMORY; } error = fIOScheduler->Init("checksum device scheduler"); if (error != B_OK) { Unprepare(); return error; } fIOScheduler->SetCallback(&_DoIOEntry, this); fTransferBuffer = malloc(B_PAGE_SIZE); if (fTransferBuffer == NULL) { Unprepare(); return B_NO_MEMORY; } return B_OK; } void Unprepare() { free(fTransferBuffer); fTransferBuffer = NULL; delete fIOScheduler; fIOScheduler = NULL; delete fDMAResource; fDMAResource = NULL; delete fCheckSumCache; fCheckSumCache = NULL; } status_t DoIO(IORequest* request) { return fIOScheduler->ScheduleRequest(request); } virtual status_t PublishDevice() { return sDeviceManager->publish_device(Node(), fDeviceName, kRawDeviceModuleName); } status_t GetBlockCheckSum(uint64 blockIndex, CheckSum& checkSum) { return fCheckSumCache->GetCheckSum(blockIndex, checkSum); } status_t SetBlockCheckSum(uint64 blockIndex, const CheckSum& checkSum) { return fCheckSumCache->SetCheckSum(blockIndex, checkSum); } private: static status_t _DoIOEntry(void* data, IOOperation* operation) { return ((RawDevice*)data)->_DoIO(operation); } status_t _DoIO(IOOperation* operation) { off_t offset = operation->Offset(); generic_size_t length = operation->Length(); ASSERT(offset % B_PAGE_SIZE == 0); ASSERT(length % B_PAGE_SIZE == 0); const generic_io_vec* vecs = operation->Vecs(); generic_size_t vecOffset = 0; bool isWrite = operation->IsWrite(); while (length > 0) { status_t error = _TransferBlock(vecs, vecOffset, offset, isWrite); if (error != B_OK) { fIOScheduler->OperationCompleted(operation, error, 0); return error; } offset += B_PAGE_SIZE; length -= B_PAGE_SIZE; } fIOScheduler->OperationCompleted(operation, B_OK, operation->Length()); return B_OK; } status_t _TransferBlock(const generic_io_vec*& vecs, generic_size_t& vecOffset, off_t offset, bool isWrite) { if (isWrite) { // write -- copy data to transfer buffer status_t error = _CopyData(vecs, vecOffset, true); if (error != B_OK) return error; _CheckCheckSum(offset / B_PAGE_SIZE); } ssize_t transferred = isWrite ? pwrite(fFD, fTransferBuffer, B_PAGE_SIZE, offset) : pread(fFD, fTransferBuffer, B_PAGE_SIZE, offset); if (transferred < 0) return errno; if (transferred != B_PAGE_SIZE) return B_ERROR; if (!isWrite) { // read -- copy data from transfer buffer status_t error =_CopyData(vecs, vecOffset, false); if (error != B_OK) return error; } return B_OK; } status_t _CopyData(const generic_io_vec*& vecs, generic_size_t& vecOffset, bool toBuffer) { uint8* buffer = (uint8*)fTransferBuffer; size_t length = B_PAGE_SIZE; while (length > 0) { size_t toCopy = std::min((generic_size_t)length, vecs->length - vecOffset); if (toCopy == 0) { vecs++; vecOffset = 0; continue; } phys_addr_t vecAddress = vecs->base + vecOffset; status_t error = toBuffer ? vm_memcpy_from_physical(buffer, vecAddress, toCopy, false) : vm_memcpy_to_physical(vecAddress, buffer, toCopy, false); if (error != B_OK) return error; buffer += toCopy; length -= toCopy; vecOffset += toCopy; } return B_OK; } void _CheckCheckSum(uint64 blockIndex) { // get the checksum the block should have CheckSum expectedCheckSum; if (fCheckSumCache->GetCheckSum(blockIndex, expectedCheckSum) != B_OK) return; // if the checksum is clear, we aren't supposed to check if (expectedCheckSum.IsZero()) { dprintf("checksum_device: skipping check sum check for block %" B_PRIu64 "\n", blockIndex); return; } // compute the transfer buffer check sum fSHA256.Init(); fSHA256.Update(fTransferBuffer, B_PAGE_SIZE); if (expectedCheckSum != fSHA256.Digest()) panic("Check sum mismatch for block %" B_PRIu64 " (exptected at %p" ", actual at %p)", blockIndex, &expectedCheckSum, fSHA256.Digest()); } private: int32 fIndex; int fFD; off_t fFileSize; off_t fDeviceSize; char* fDeviceName; DMAResource* fDMAResource; IOScheduler* fIOScheduler; void* fTransferBuffer; CheckSumCache* fCheckSumCache; SHA256 fSHA256; }; struct RawDeviceCookie { RawDeviceCookie(RawDevice* device, int openMode) : fDevice(device), fOpenMode(openMode) { } RawDevice* Device() const { return fDevice; } int OpenMode() const { return fOpenMode; } private: RawDevice* fDevice; int fOpenMode; }; // #pragma mark - static bool parse_command_line(char* buffer, char**& _argv, int& _argc) { // Process the argument string. We split at whitespace, heeding quotes and // escaped characters. The processed arguments are written to the given // buffer, separated by single null chars. char* start = buffer; char* out = buffer; bool pendingArgument = false; int argc = 0; while (*start != '\0') { // ignore whitespace if (isspace(*start)) { if (pendingArgument) { *out = '\0'; out++; argc++; pendingArgument = false; } start++; continue; } pendingArgument = true; if (*start == '"' || *start == '\'') { // quoted text -- continue until closing quote char quote = *start; start++; while (*start != '\0' && *start != quote) { if (*start == '\\' && quote == '"') { start++; if (*start == '\0') break; } *out = *start; start++; out++; } if (*start != '\0') start++; } else { // unquoted text if (*start == '\\') { // escaped char start++; if (start == '\0') break; } *out = *start; start++; out++; } } if (pendingArgument) { *out = '\0'; argc++; } // allocate argument vector char** argv = new(std::nothrow) char*[argc + 1]; if (argv == NULL) return false; // fill vector start = buffer; for (int i = 0; i < argc; i++) { argv[i] = start; start += strlen(start) + 1; } argv[argc] = NULL; _argv = argv; _argc = argc; return true; } // #pragma mark - driver static float checksum_driver_supports_device(device_node* parent) { const char* bus = NULL; if (sDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false) == B_OK && !strcmp(bus, "generic")) return 0.8; return -1; } static status_t checksum_driver_register_device(device_node* parent) { device_attr attrs[] = { {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "Checksum Control Device"}}, {NULL} }; return sDeviceManager->register_node(parent, kDriverModuleName, attrs, NULL, NULL); } static status_t checksum_driver_init_driver(device_node* node, void** _driverCookie) { const char* fileName; if (sDeviceManager->get_attr_string(node, kFilePathItem, &fileName, false) == B_OK) { RawDevice* device = new(std::nothrow) RawDevice(node); if (device == NULL) return B_NO_MEMORY; status_t error = device->Init(fileName); if (error != B_OK) { delete device; return error; } *_driverCookie = (Device*)device; } else { ControlDevice* device = new(std::nothrow) ControlDevice(node); if (device == NULL) return B_NO_MEMORY; *_driverCookie = (Device*)device; } return B_OK; } static void checksum_driver_uninit_driver(void* driverCookie) { Device* device = (Device*)driverCookie; delete device; } static status_t checksum_driver_register_child_devices(void* driverCookie) { Device* device = (Device*)driverCookie; return device->PublishDevice(); } // #pragma mark - control device static status_t checksum_control_device_init_device(void* driverCookie, void** _deviceCookie) { *_deviceCookie = driverCookie; return B_OK; } static void checksum_control_device_uninit_device(void* deviceCookie) { } static status_t checksum_control_device_open(void* deviceCookie, const char* path, int openMode, void** _cookie) { *_cookie = deviceCookie; return B_OK; } static status_t checksum_control_device_close(void* cookie) { return B_OK; } static status_t checksum_control_device_free(void* cookie) { return B_OK; } static status_t checksum_control_device_read(void* cookie, off_t position, void* buffer, size_t* _length) { *_length = 0; return B_OK; } static status_t checksum_control_device_write(void* cookie, off_t position, const void* data, size_t* _length) { ControlDevice* device = (ControlDevice*)cookie; if (position != 0) return B_BAD_VALUE; // copy data to stack buffer char* buffer = (char*)malloc(*_length + 1); if (buffer == NULL) return B_NO_MEMORY; MemoryDeleter bufferDeleter(buffer); if (IS_USER_ADDRESS(data)) { if (user_memcpy(buffer, data, *_length) != B_OK) return B_BAD_ADDRESS; } else memcpy(buffer, data, *_length); buffer[*_length] = '\0'; // parse arguments char** argv; int argc; if (!parse_command_line(buffer, argv, argc)) return B_NO_MEMORY; ArrayDeleter<char*> argvDeleter(argv); if (argc == 0) { dprintf("\"help\" for usage!\n"); return B_BAD_VALUE; } // execute command if (strcmp(argv[0], "help") == 0) { // help dprintf("register <path>\n"); dprintf(" Registers file <path> as a new checksum device.\n"); dprintf("unregister <device>\n"); dprintf(" Unregisters <device>.\n"); } else if (strcmp(argv[0], "register") == 0) { // register if (argc != 2) { dprintf("Usage: register <path>\n"); return B_BAD_VALUE; } return device->Register(argv[1]); } else if (strcmp(argv[0], "unregister") == 0) { // unregister if (argc != 2) { dprintf("Usage: unregister <device>\n"); return B_BAD_VALUE; } const char* deviceName = argv[1]; if (strncmp(deviceName, "/dev/", 5) == 0) deviceName += 5; // find the device in the list and unregister it MutexLocker locker(sDeviceListLock); for (RawDeviceList::Iterator it = sDeviceList.GetIterator(); RawDevice* device = it.Next();) { if (strcmp(device->DeviceName(), deviceName) == 0) { // TODO: Race condition: We should mark the device as going to // be unregistered, so no one else can try the same after we // unlock! locker.Unlock(); // TODO: The following doesn't work! unpublish_device(), as per implementation // (partially commented out) and unregister_node() returns B_BUSY. status_t error = sDeviceManager->unpublish_device( device->Node(), device->DeviceName()); if (error != B_OK) { dprintf("Failed to unpublish device \"%s\": %s\n", deviceName, strerror(error)); return error; } error = sDeviceManager->unregister_node(device->Node()); if (error != B_OK) { dprintf("Failed to unregister node \"%s\": %s\n", deviceName, strerror(error)); return error; } return B_OK; } } dprintf("Device \"%s\" not found!\n", deviceName); return B_BAD_VALUE; } else { dprintf("Invalid command \"%s\"!\n", argv[0]); return B_BAD_VALUE; } return B_OK; } static status_t checksum_control_device_control(void* cookie, uint32 op, void* buffer, size_t length) { return B_BAD_VALUE; } // #pragma mark - raw device static status_t checksum_raw_device_init_device(void* driverCookie, void** _deviceCookie) { RawDevice* device = static_cast<RawDevice*>((Device*)driverCookie); status_t error = device->Prepare(); if (error != B_OK) return error; *_deviceCookie = device; return B_OK; } static void checksum_raw_device_uninit_device(void* deviceCookie) { RawDevice* device = (RawDevice*)deviceCookie; device->Unprepare(); } static status_t checksum_raw_device_open(void* deviceCookie, const char* path, int openMode, void** _cookie) { RawDevice* device = (RawDevice*)deviceCookie; RawDeviceCookie* cookie = new(std::nothrow) RawDeviceCookie(device, openMode); if (cookie == NULL) return B_NO_MEMORY; *_cookie = cookie; return B_OK; } static status_t checksum_raw_device_close(void* cookie) { return B_OK; } static status_t checksum_raw_device_free(void* _cookie) { RawDeviceCookie* cookie = (RawDeviceCookie*)_cookie; delete cookie; return B_OK; } static status_t checksum_raw_device_read(void* _cookie, off_t pos, void* buffer, size_t* _length) { RawDeviceCookie* cookie = (RawDeviceCookie*)_cookie; RawDevice* device = cookie->Device(); size_t length = *_length; if (pos >= device->DeviceSize()) return B_BAD_VALUE; if (pos + length > device->DeviceSize()) length = device->DeviceSize() - pos; IORequest request; status_t status = request.Init(pos, (addr_t)buffer, length, false, 0); if (status != B_OK) return status; status = device->DoIO(&request); if (status != B_OK) return status; status = request.Wait(0, 0); if (status == B_OK) *_length = length; return status; } static status_t checksum_raw_device_write(void* _cookie, off_t pos, const void* buffer, size_t* _length) { RawDeviceCookie* cookie = (RawDeviceCookie*)_cookie; RawDevice* device = cookie->Device(); size_t length = *_length; if (pos >= device->DeviceSize()) return B_BAD_VALUE; if (pos + length > device->DeviceSize()) length = device->DeviceSize() - pos; IORequest request; status_t status = request.Init(pos, (addr_t)buffer, length, true, 0); if (status != B_OK) return status; status = device->DoIO(&request); if (status != B_OK) return status; status = request.Wait(0, 0); if (status == B_OK) *_length = length; return status; } static status_t checksum_raw_device_io(void* _cookie, io_request* request) { RawDeviceCookie* cookie = (RawDeviceCookie*)_cookie; RawDevice* device = cookie->Device(); return device->DoIO(request); } static status_t checksum_raw_device_control(void* _cookie, uint32 op, void* buffer, size_t length) { RawDeviceCookie* cookie = (RawDeviceCookie*)_cookie; RawDevice* device = cookie->Device(); switch (op) { case B_GET_DEVICE_SIZE: { size_t size = device->DeviceSize(); return user_memcpy(buffer, &size, sizeof(size_t)); } case B_SET_NONBLOCKING_IO: case B_SET_BLOCKING_IO: return B_OK; case B_GET_READ_STATUS: case B_GET_WRITE_STATUS: { bool value = true; return user_memcpy(buffer, &value, sizeof(bool)); } case B_GET_GEOMETRY: case B_GET_BIOS_GEOMETRY: { device_geometry geometry; geometry.bytes_per_sector = B_PAGE_SIZE; geometry.sectors_per_track = 1; geometry.cylinder_count = device->DeviceSize() / B_PAGE_SIZE; // TODO: We're limited to 2^32 * B_PAGE_SIZE, if we don't use // sectors_per_track and head_count. geometry.head_count = 1; geometry.device_type = B_DISK; geometry.removable = true; geometry.read_only = false; geometry.write_once = false; return user_memcpy(buffer, &geometry, sizeof(device_geometry)); } case B_GET_MEDIA_STATUS: { status_t status = B_OK; return user_memcpy(buffer, &status, sizeof(status_t)); } case B_SET_UNINTERRUPTABLE_IO: case B_SET_INTERRUPTABLE_IO: case B_FLUSH_DRIVE_CACHE: return B_OK; case CHECKSUM_DEVICE_IOCTL_GET_CHECK_SUM: { if (IS_USER_ADDRESS(buffer)) { checksum_device_ioctl_check_sum getCheckSum; if (user_memcpy(&getCheckSum, buffer, sizeof(getCheckSum)) != B_OK) { return B_BAD_ADDRESS; } status_t error = device->GetBlockCheckSum( getCheckSum.blockIndex, getCheckSum.checkSum); if (error != B_OK) return error; return user_memcpy(buffer, &getCheckSum, sizeof(getCheckSum)); } checksum_device_ioctl_check_sum* getCheckSum = (checksum_device_ioctl_check_sum*)buffer; return device->GetBlockCheckSum(getCheckSum->blockIndex, getCheckSum->checkSum); } case CHECKSUM_DEVICE_IOCTL_SET_CHECK_SUM: { if (IS_USER_ADDRESS(buffer)) { checksum_device_ioctl_check_sum setCheckSum; if (user_memcpy(&setCheckSum, buffer, sizeof(setCheckSum)) != B_OK) { return B_BAD_ADDRESS; } return device->SetBlockCheckSum(setCheckSum.blockIndex, setCheckSum.checkSum); } checksum_device_ioctl_check_sum* setCheckSum = (checksum_device_ioctl_check_sum*)buffer; return device->SetBlockCheckSum(setCheckSum->blockIndex, setCheckSum->checkSum); } } return B_BAD_VALUE; } // #pragma mark - module_dependency module_dependencies[] = { {B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&sDeviceManager}, {} }; static const struct driver_module_info sChecksumDeviceDriverModule = { { kDriverModuleName, 0, NULL }, checksum_driver_supports_device, checksum_driver_register_device, checksum_driver_init_driver, checksum_driver_uninit_driver, checksum_driver_register_child_devices }; static const struct device_module_info sChecksumControlDeviceModule = { { kControlDeviceModuleName, 0, NULL }, checksum_control_device_init_device, checksum_control_device_uninit_device, NULL, checksum_control_device_open, checksum_control_device_close, checksum_control_device_free, checksum_control_device_read, checksum_control_device_write, NULL, // io checksum_control_device_control, NULL, // select NULL // deselect }; static const struct device_module_info sChecksumRawDeviceModule = { { kRawDeviceModuleName, 0, NULL }, checksum_raw_device_init_device, checksum_raw_device_uninit_device, NULL, checksum_raw_device_open, checksum_raw_device_close, checksum_raw_device_free, checksum_raw_device_read, checksum_raw_device_write, checksum_raw_device_io, checksum_raw_device_control, NULL, // select NULL // deselect }; const module_info* modules[] = { (module_info*)&sChecksumDeviceDriverModule, (module_info*)&sChecksumControlDeviceModule, (module_info*)&sChecksumRawDeviceModule, NULL };
21.327765
80
0.699802
Kirishikesan
96137485aca19dee42154adb80eb2367a79b611a
3,481
cpp
C++
src/red4ext.loader/Main.cpp
ADawesomeguy/RED4ext
fec0e216b27c30fca66b31a38b850f814b5a48d6
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/red4ext.loader/Main.cpp
ADawesomeguy/RED4ext
fec0e216b27c30fca66b31a38b850f814b5a48d6
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/red4ext.loader/Main.cpp
ADawesomeguy/RED4ext
fec0e216b27c30fca66b31a38b850f814b5a48d6
[ "MIT", "BSD-3-Clause" ]
null
null
null
#include "stdafx.hpp" #include "pwrprof.hpp" BOOL APIENTRY DllMain(HMODULE aModule, DWORD aReason, LPVOID aReserved) { switch (aReason) { case DLL_PROCESS_ATTACH: { DisableThreadLibraryCalls(aModule); try { if (!LoadOriginal()) { return FALSE; } constexpr auto msgCaption = L"RED4ext"; constexpr auto dir = L"red4ext"; constexpr auto dll = L"RED4ext.dll"; std::wstring fileName; auto hr = wil::GetModuleFileNameW(nullptr, fileName); if (FAILED(hr)) { wil::unique_hlocal_ptr<wchar_t> buffer; auto errorCode = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, LANG_USER_DEFAULT, wil::out_param_ptr<LPWSTR>(buffer), 0, nullptr); auto caption = fmt::format(L"{} (error {})", msgCaption, errorCode); auto message = fmt::format(L"{}\nCould not get the file name.", buffer.get()); MessageBox(nullptr, message.c_str(), caption.c_str(), MB_ICONERROR | MB_OK); return TRUE; } std::error_code fsErr; std::filesystem::path exePath = fileName; auto rootPath = exePath .parent_path() // Resolve to "x64" directory. .parent_path() // Resolve to "bin" directory. .parent_path(); // Resolve to game root directory. auto modPath = rootPath / dir; if (std::filesystem::exists(modPath, fsErr)) { auto dllPath = modPath / dll; if (!LoadLibrary(dllPath.c_str())) { wil::unique_hlocal_ptr<wchar_t> buffer; auto errorCode = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, LANG_USER_DEFAULT, wil::out_param_ptr<LPWSTR>(buffer), 0, nullptr); auto caption = fmt::format(L"{} (error {})", msgCaption, errorCode); auto message = fmt::format(L"{}\n{}\n\nRED4ext could not be loaded.", buffer.get(), dllPath.c_str()); MessageBox(nullptr, message.c_str(), caption.c_str(), MB_ICONERROR | MB_OK); } } else if (fsErr) { auto message = fmt::format(L"RED4ext could not be loaded because of a filesystem error ({}).", fsErr.value()); MessageBox(nullptr, message.c_str(), msgCaption, MB_ICONERROR | MB_OK); } } catch (const std::exception& e) { auto message = fmt::format("An exception occured in RED4ext's loader.\n\n{}", e.what()); MessageBoxA(nullptr, message.c_str(), "RED4ext", MB_ICONERROR | MB_OK); } catch (...) { MessageBox(nullptr, L"An unknown exception occured in RED4ext's loader.", L"RED4ext", MB_ICONERROR | MB_OK); } break; } case DLL_PROCESS_DETACH: { break; } } return TRUE; }
37.031915
120
0.520827
ADawesomeguy
9615a0237f2635883c350f01e691db9eda49f79d
1,853
cpp
C++
masterui/main.cpp
rickfoosusa/dnp
ec17eb20817db32cc6356139afd2daaa1803576f
[ "BSD-2-Clause-FreeBSD" ]
1
2017-09-19T16:37:59.000Z
2017-09-19T16:37:59.000Z
masterui/main.cpp
rickfoosusa/dnp
ec17eb20817db32cc6356139afd2daaa1803576f
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
masterui/main.cpp
rickfoosusa/dnp
ec17eb20817db32cc6356139afd2daaa1803576f
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// // $Id$ // // Copyright (C) 2007 Turner Technolgoies Inc. http://www.turner.ca // // 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 <QtGui> #include <QThread> #include "main_window.hpp" #include "_test_lpdu.hpp" #include "_test_master.hpp" #include "_test_security.hpp" int main(int argc, char *argv[]) { QApplication app(argc, argv); // execute all unit tests TestLpdu* testLpdu = new TestLpdu(); QTest::qExec(testLpdu); delete testLpdu; TestMaster* testMaster = new TestMaster(); QTest::qExec(testMaster); delete testMaster; TestSecurity* testSecurity = new TestSecurity(); QTest::qExec(testSecurity); delete testSecurity; MainWindow mainWindow; mainWindow.show(); app.exec(); return 1; }
30.883333
68
0.706962
rickfoosusa
961866ed4c9d4b6fb23e3b643c36e39975d6154f
9,049
hh
C++
src/ast/detail/types.hh
evanacox/cascade
3b337c465bff91e4987fb6f738a03a82d07b97cc
[ "Apache-2.0" ]
null
null
null
src/ast/detail/types.hh
evanacox/cascade
3b337c465bff91e4987fb6f738a03a82d07b97cc
[ "Apache-2.0" ]
null
null
null
src/ast/detail/types.hh
evanacox/cascade
3b337c465bff91e4987fb6f738a03a82d07b97cc
[ "Apache-2.0" ]
null
null
null
/*---------------------------------------------------------------------------* * * Copyright 2020 Evan Cox * * 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. * *---------------------------------------------------------------------------* * * ast/detail/types.hh: * Outlines the declaration AST nodes * *---------------------------------------------------------------------------*/ #ifndef CASCADE_AST_DETAIL_TYPES_HH #define CASCADE_AST_DETAIL_TYPES_HH #include "ast/detail/nodes.hh" #include "core/lexer.hh" #include <cassert> #include <deque> #include <memory> namespace cascade::ast { /** * @brief Internal structure that encodes only the type, used in the typechecker * Makes it easy to modify type attributes (e.g remove/add pointer, reference, promotions, casts, * etc) */ class type_data { public: /** @brief Any modifiers on a base type */ enum class type_modifiers : char { ref, mut_ref, ptr, mut_ptr, array }; /** @brief */ enum class type_base { boolean, integer, unsigned_integer, floating_point, user_defined, implied, void_type, error_type, }; private: /** @brief The actual stream of modifiers on the type */ std::deque<type_modifiers> m_modifiers; /** @brief The actual "type" of a thing, e.g "bool" in "*mut bool" */ type_base m_base; /** * @brief Represents either the precision of the builtin (if m_type ends as a builtin) * or the name of a userdef */ std::variant<std::size_t, std::string> m_data; public: /** * @brief Creates a builtin type of @p precision * @param modifs The modifiers for the type * @param base The builtin type * @param precision The precision of the builtin */ type_data(std::deque<type_modifiers> modifs, type_base base, std::size_t precision) : m_modifiers(std::move(modifs)) , m_base(base) , m_data() { m_data.emplace<std::size_t>(precision); } type_data(std::deque<type_modifiers> modifs, type_base base, std::string name) : m_modifiers(std::move(modifs)) , m_base(base) , m_data() { m_data.emplace<std::string>(std::move(name)); } /** @brief Returns a mutable reference to the type modifiers */ [[nodiscard]] std::deque<type_modifiers> &modifiers() { return m_modifiers; } /** @brief Returns a mutable reference to the base type */ [[nodiscard]] type_base &base() { return m_base; } /** @brief Returns a mutable reference to the raw data variant */ [[nodiscard]] std::variant<std::size_t, std::string> &data() { return m_data; } /** @brief Returns a const reference to the type modifiers */ [[nodiscard]] const std::deque<type_modifiers> &modifiers() const { return m_modifiers; } /** @brief Returns a const reference to the base type */ [[nodiscard]] const type_base &base() const { return m_base; } /** @brief Returns a const reference to the raw data variant */ [[nodiscard]] const std::variant<std::size_t, std::string> &data() const { return m_data; } /** @brief Gets the data as a size_t */ [[nodiscard]] std::size_t precision() const { return std::get<std::size_t>(m_data); } /** @brief Gets the data as an std::string */ [[nodiscard]] std::string name() const { return std::get<std::string>(m_data); } /** * @brief Performs memberwise equality on two type_data objects * @param other The other type_data to compare against * @return True if they're equal */ bool operator==(const type_data &other) const { // <error-type> is only given when an error is reported, // it's used to prevent cascading errors if an expression with // an error type is used inside a larger thing if (is(type_base::error_type)) { return true; } if (other.is(type_base::error_type)) { return true; } return modifiers() == other.modifiers() && data() == other.data() && base() == other.base(); } /** * @brief Performs memberwise equality on two type_data objects * @param other The other type_data to compare against * @return True if they're not equal */ bool operator!=(const type_data &other) const { return !(*this == other); } /** * @brief Checks if a type is of @p type * @param type The type to check against * @return If the type is of @p type for a base */ [[nodiscard]] bool is(type_base type) const { return m_base == type; } /** * @brief Checks if a type is not of @p type * @param type The type to check against * @return If the base type is not @p type */ [[nodiscard]] bool is_not(type_base type) const { return !is(type); } /** * @brief Checks if a type is of @p type or one of @p rest is the base type * @param type The type to check against * @param rest The rest of the types to check against * @return If the base type is @p type or is included in @p rest */ template <class... Rest>[[nodiscard]] bool is_one_of(type_base first, Rest... rest) const { if (is(first)) { return true; } if constexpr (sizeof...(rest) > 0) { return is_one_of(std::forward<type_base>(rest...)); } return false; } /** * @brief Returns if the type is one of the builtin types * @return True if the type is one of the builtin types */ [[nodiscard]] bool is_builtin() const { return is_not(type_base::implied) && is_not(type_base::void_type) && is_not(type_base::user_defined); } /** * @brief Returns if the type is an error_type * @return True if the type is an error_type */ [[nodiscard]] bool is_error() const { return is(type_base::error_type); } }; /** @brief A simple class holding a type */ class type : public node, public visitable<type> { public: using type_modifiers = type_data::type_modifiers; using type_base = type_data::type_base; private: type_data m_type; protected: // ctor that the implied/void types can use explicit type(kind type, core::source_info info, type_base base) : node(type, std::move(info)) , m_type({}, base, 0) {} public: /** * @brief Creates a new **builtin** type * @param info The source info with the location of the type * @param mods Any modifiers on the type (e.g &mut, *, []) * @param base The "base" type (e.g bool, integer, float) * @param precision The precision of the builtin type */ explicit type(core::source_info info, std::deque<type_modifiers> mods, type_base base, std::size_t precision) : node(kind::type, std::move(info)) , m_type(std::move(mods), base, std::move(precision)) {} /** * @brief Creates a new **user defined** type * @param info The source info with the location of the type * @param mods Any modifiers on the type (e.g &mut, *, []) * @param name The name of the userdefined type */ explicit type(core::source_info info, std::deque<type_modifiers> mods, std::string name) : node(kind::type, std::move(info)) , m_type(std::move(mods), type_base::user_defined, std::move(name)) {} [[nodiscard]] virtual bool is_expression() const final { return false; } [[nodiscard]] virtual bool is_declaration() const final { return false; } [[nodiscard]] virtual bool is_statement() const final { return false; } /** @brief Returns the type's information */ [[nodiscard]] type_data &data() { return m_type; } [[nodiscard]] const type_data &data() const { return m_type; } }; /** @brief Serves as a marker for a type that the user left implied */ class implied : public type { public: /** * @brief Creates an implied instance * @param info The source info for the location where the type **would be**. */ explicit implied(core::source_info info) : type(kind::type_implied, std::move(info), type_base::implied) {} }; /** @brief Serves as a marker for something that doesn't really *have* a type */ class void_type : public type { public: /** * @brief Creates a void_type instance * @param info The source info for the location where the type **would be**. */ explicit void_type(core::source_info info) : type(kind::type_void, std::move(info), type_base::void_type) {} }; } // namespace cascade::ast #endif
34.14717
99
0.620953
evanacox
961a5ba39f21bad2bc0f5dcee3e6277d326988a3
2,460
cpp
C++
BlueBerry/Bundles/org.blueberry.ui/src/berryPlatformUI.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
1
2017-03-05T05:29:32.000Z
2017-03-05T05:29:32.000Z
BlueBerry/Bundles/org.blueberry.ui/src/berryPlatformUI.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
null
null
null
BlueBerry/Bundles/org.blueberry.ui/src/berryPlatformUI.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
2
2020-10-27T06:51:00.000Z
2020-10-27T06:51:01.000Z
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPlatformUI.h" #include "berryPlatform.h" #include "service/berryIConfigurationElement.h" #include "service/berryIExtensionPointService.h" #include "internal/berryWorkbench.h" #include "berryUIException.h" #include <vector> namespace berry { const std::string PlatformUI::PLUGIN_ID = "org.blueberry.ui"; const std::string PlatformUI::XP_WORKBENCH = PlatformUI::PLUGIN_ID + ".workbench"; const std::string PlatformUI::XP_VIEWS = PlatformUI::PLUGIN_ID + ".views"; const int PlatformUI::RETURN_OK = 0; const int PlatformUI::RETURN_RESTART = 1; const int PlatformUI::RETURN_UNSTARTABLE = 2; const int PlatformUI::RETURN_EMERGENCY_CLOSE = 3; int PlatformUI::CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor) { // std::vector<IConfigurationElement::Pointer> extensions( // Platform::GetExtensionPointService()->GetConfigurationElementsFor(PlatformUI::XP_WORKBENCH)); // // for (unsigned int i = 0; i < extensions.size(); ++i) // { // if (extensions[i]->GetName() == "workbench") // { // // m_Workbench = extensions[i]->CreateExecutableExtension<berry::Workbench>("berryWorkbench", "class"); // m_Workbench->InternalInit(advisor); // return m_Workbench->RunUI(); // } // } // // throw WorkbenchException("No registered workbench extension found"); return Workbench::CreateAndRunWorkbench(display, advisor); } Display* PlatformUI::CreateDisplay() { return Workbench::CreateDisplay(); } IWorkbench* PlatformUI::GetWorkbench() { if (Workbench::GetInstance() == 0) { // app forgot to call createAndRunWorkbench beforehand throw Poco::IllegalStateException("Workbench has not been created yet."); } return Workbench::GetInstance(); } bool PlatformUI::IsWorkbenchRunning() { return Workbench::GetInstance() != 0 && Workbench::GetInstance()->IsRunning(); } TestableObject::Pointer PlatformUI::GetTestableObject() { return Workbench::GetWorkbenchTestable(); } PlatformUI::PlatformUI() { } }
25.360825
108
0.698374
danielknorr
961a790274bac6b16f5fd35135542689ac090d23
1,170
cpp
C++
codechef/CHEFCOUN/Wrong Answer (3).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codechef/CHEFCOUN/Wrong Answer (3).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codechef/CHEFCOUN/Wrong Answer (3).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 06-10-2017 16:39:17 * solution_verdict: Wrong Answer language: C++14 * run_time: 0.00 sec memory_used: 0M * problem: https://www.codechef.com/OCT17/problems/CHEFCOUN ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; long t,n; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>t; while(t--) { cin>>n; for(long i=1;i<n;i++) { if(i==10)cout<<999<<" "; else if(i==45)cout<<991<<" "; else if(i==50)cout<<100000<<" "; else if(i==57)cout<<991<<" "; else if(i==100)cout<<999<<" "; else if(i==200)cout<<100000<<" "; else cout<<9999<<" "; } cout<<9999<<endl; } return 0; }
35.454545
111
0.347863
kzvd4729
961aa56c24a00f05dca64939859d74b637135eb8
2,150
cpp
C++
test/btunittest/Agent/EmployeeParTestAgent.cpp
pjkui/behaviac-1
426fbac954d7c1db00eb842d6e0b9390fda82dd3
[ "BSD-3-Clause" ]
2
2016-12-11T09:40:43.000Z
2021-07-09T22:55:38.000Z
test/btunittest/Agent/EmployeeParTestAgent.cpp
BantamJoe/behaviac-1
426fbac954d7c1db00eb842d6e0b9390fda82dd3
[ "BSD-3-Clause" ]
null
null
null
test/btunittest/Agent/EmployeeParTestAgent.cpp
BantamJoe/behaviac-1
426fbac954d7c1db00eb842d6e0b9390fda82dd3
[ "BSD-3-Clause" ]
10
2016-11-29T12:04:07.000Z
2018-09-04T06:13:30.000Z
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "EmployeeParTestAgent.h" float EmployeeParTestAgent::STV_F_0 = 0.0f; behaviac::string EmployeeParTestAgent::STV_STR_0 = ""; behaviac::Agent* EmployeeParTestAgent::STV_AGENT_0 = NULL; behaviac::vector<float> EmployeeParTestAgent::STV_LIST_F_0; behaviac::vector<behaviac::string> EmployeeParTestAgent::STV_LIST_STR_0; behaviac::vector<behaviac::Agent*> EmployeeParTestAgent::STV_LIST_AGENT_0; EmployeeParTestAgent::EmployeeParTestAgent() { TV_UINT_0 = 0; TV_ULONG_0 = 0L; TV_LL_0 = 0L; TV_ULL_0 = 0L; TV_F_0 = 0.0f; TV_D_0 = 0.0; TV_STR_0 = ""; TV_AGENT_0 = NULL; TV_CSZSTR_0 = 0; TV_SZSTR_0 = 0; } EmployeeParTestAgent::~EmployeeParTestAgent() { } void EmployeeParTestAgent::resetProperties() { super::resetProperties(); TV_UINT_0 = 0; TV_ULONG_0 = 0L; TV_F_0 = 0.0f; STV_F_0 = 0.0f; TV_D_0 = 0.0; TV_LL_0 = 0L; TV_ULL_0 = 0L; TV_STR_0 = ""; TV_SZSTR_0 = NULL; TV_CSZSTR_0 = "TV_CSZSTR_0"; STV_STR_0 = ""; TV_AGENT_0 = NULL; STV_AGENT_0 = NULL; TV_LIST_F_0.clear(); STV_LIST_F_0.clear(); TV_LIST_STR_0.clear(); STV_LIST_STR_0.clear(); TV_LIST_AGENT_0.clear(); STV_LIST_AGENT_0.clear(); }
32.089552
113
0.640465
pjkui
961bbf250f7721ddd5d8fba573dcef81b1436d73
304
cpp
C++
Point.cpp
argorain/dtw
f863bf38882a36accc6da80101b1201c43cd3261
[ "MIT" ]
null
null
null
Point.cpp
argorain/dtw
f863bf38882a36accc6da80101b1201c43cd3261
[ "MIT" ]
null
null
null
Point.cpp
argorain/dtw
f863bf38882a36accc6da80101b1201c43cd3261
[ "MIT" ]
null
null
null
// // Created by rain on 27.5.15. // #include "Point.h" Point::Point() { x=y=0; } Point::Point(int x, int y) { this->x=x; this->y=y; } int Point::getX() { return x; } int Point::getY() { return y; } void Point::setX(const int x) { this->x=x; } void Point::setY(const int y) { this->y=y; }
16
44
0.559211
argorain
961c21db07f1fef8cbce1c41e0c5c52f43f7908c
336
cpp
C++
cpp/env.cpp
simnalamburt/snippets
8ba4cfcb1305d2b82ea892e3305613eeb7ba382b
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
31
2016-01-27T07:03:25.000Z
2022-02-25T07:59:11.000Z
cpp/env.cpp
simnalamburt/snippets
8ba4cfcb1305d2b82ea892e3305613eeb7ba382b
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2015-01-26T01:27:21.000Z
2015-01-30T16:16:30.000Z
cpp/env.cpp
simnalamburt/snippets
8ba4cfcb1305d2b82ea892e3305613eeb7ba382b
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
3
2017-02-07T04:17:56.000Z
2020-06-12T05:01:31.000Z
#include <cstdlib> #include <iostream> using namespace std; int main() { const auto getenv_or = [](auto env_var, auto default_value) { const auto env = getenv(env_var); return env != nullptr ? env : default_value; }; cout << getenv_or("HOME", "Not found") << endl; cout << getenv_or("HOMEE", "Not found") << endl; }
21
63
0.639881
simnalamburt
961d918e340191e1f2f0761a5eb4cff9a96ecede
21,099
cpp
C++
src/storage/forkdb.cpp
metabasenet/metabasenet
e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1
[ "MIT" ]
null
null
null
src/storage/forkdb.cpp
metabasenet/metabasenet
e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1
[ "MIT" ]
null
null
null
src/storage/forkdb.cpp
metabasenet/metabasenet
e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1
[ "MIT" ]
null
null
null
// Copyright (c) 2021-2022 The MetabaseNet developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "forkdb.h" #include <boost/bind.hpp> #include "leveldbeng.h" using namespace std; using namespace hcode; namespace metabasenet { namespace storage { #define DB_FORK_KEY_NAME_CTXT string("ctxt") #define DB_FORK_KEY_NAME_TRIEROOT string("trieroot") #define DB_FORK_KEY_NAME_PREVROOT string("prevroot") #define DB_FORK_KEY_NAME_ACTIVE string("active") #define DB_FORK_KEY_NAME_FORKNAME string("forkname") #define DB_FORK_KEY_NAME_FORKSN string("forksn") ////////////////////////////// // CListForkTrieDBWalker bool CListForkTrieDBWalker::Walk(const bytes& btKey, const bytes& btValue, const uint32 nDepth, bool& fWalkOver) { if (btKey.size() == 0 || btValue.size() == 0) { hcode::StdError("CListForkTrieDBWalker", "btKey.size() = %ld, btValue.size() = %ld", btKey.size(), btValue.size()); return false; } try { hcode::CBufStream ssKey(btKey); string strName; ssKey >> strName; if (strName == DB_FORK_KEY_NAME_CTXT) { hcode::CBufStream ssValue(btValue); uint256 hashFork; CForkContext ctxtFork; ssKey >> hashFork; ssValue >> ctxtFork; mapForkCtxt.insert(std::make_pair(hashFork, ctxtFork)); } } catch (std::exception& e) { hcode::StdError(__PRETTY_FUNCTION__, e.what()); return false; } return true; } ////////////////////////////// // CCacheFork void CCacheFork::AddForkCtxt(const std::map<uint256, CForkContext>& mapForkCtxtIn) { for (const auto& kv : mapForkCtxtIn) { mapForkContext[kv.first] = kv.second; mapForkName[kv.second.strName] = kv.first; mapForkSn[CTransaction::GetForkSn(kv.first)] = kv.first; mapForkParent.insert(std::make_pair(kv.second.hashParent, kv.first)); mapForkJoint.insert(std::make_pair(kv.second.hashJoint, kv.first)); } } bool CCacheFork::ExistForkContext(const uint256& hashFork) const { return (mapForkContext.find(hashFork) != mapForkContext.end()); } uint256 CCacheFork::GetForkIdByName(const std::string& strName) const { auto it = mapForkName.find(strName); if (it != mapForkName.end()) { return it->second; } return 0; } uint256 CCacheFork::GetForkIdBySn(const uint16 nForkSn) const { auto it = mapForkSn.find(nForkSn); if (it != mapForkSn.end()) { return it->second; } return 0; } ////////////////////////////// // CForkDB bool CForkDB::Initialize(const boost::filesystem::path& pathData, const uint256& hashGenesisBlockIn) { hashGenesisBlock = hashGenesisBlockIn; if (!dbTrie.Initialize(pathData / "fork")) { StdLog("CForkDB", "Initialize trie fail"); return false; } return true; } void CForkDB::Deinitialize() { CWriteLock wlock(rwAccess); dbTrie.Deinitialize(); mapCacheFork.clear(); mapCacheLast.clear(); mapCacheRoot.clear(); } void CForkDB::Clear() { CWriteLock wlock(rwAccess); dbTrie.Clear(); mapCacheFork.clear(); mapCacheLast.clear(); mapCacheRoot.clear(); } bool CForkDB::AddForkContext(const uint256& hashPrevBlock, const uint256& hashBlock, const std::map<uint256, CForkContext>& mapForkCtxt, uint256& hashNewRoot) { CWriteLock wlock(rwAccess); uint256 hashPrevRoot; if (!ReadTrieRoot(hashPrevBlock, hashPrevRoot)) { StdLog("CForkDB", "Add fork context: Read trie root fail, pre block: %s", hashPrevBlock.GetHex().c_str()); return false; } const CCacheFork* pCacheFork = LoadCacheForkContext(hashPrevBlock); std::map<uint256, CForkContext> mapNewForkCtxt; bytesmap mapKv; for (const auto& kv : mapForkCtxt) { const uint16 nForkSn = CTransaction::GetForkSn(kv.first); if (pCacheFork) { if (pCacheFork->ExistForkContext(kv.first)) { StdLog("CForkDB", "Add fork context: Fork existed, fork: %s", kv.first.GetHex().c_str()); continue; } if (pCacheFork->GetForkIdByName(kv.second.strName) != 0) { StdLog("CForkDB", "Add fork context: Fork name existed, name: %s, fork: %s", kv.second.strName.c_str(), kv.first.GetHex().c_str()); continue; } if (pCacheFork->GetForkIdBySn(nForkSn) != 0) { StdLog("CForkDB", "Add fork context: Fork sn existed, sn: 0x%4.4x, fork: %s", nForkSn, kv.first.GetHex().c_str()); continue; } } { hcode::CBufStream ssKey, ssValue; bytes btKey, btValue; ssKey << DB_FORK_KEY_NAME_CTXT << kv.first; ssKey.GetData(btKey); ssValue << kv.second; ssValue.GetData(btValue); mapKv.insert(make_pair(btKey, btValue)); } { hcode::CBufStream ssKey, ssValue; bytes btKey, btValue; ssKey << DB_FORK_KEY_NAME_FORKNAME << kv.second.strName; ssKey.GetData(btKey); ssValue << kv.first; ssValue.GetData(btValue); mapKv.insert(make_pair(btKey, btValue)); } { hcode::CBufStream ssKey, ssValue; bytes btKey, btValue; ssKey << DB_FORK_KEY_NAME_FORKSN << nForkSn; ssKey.GetData(btKey); ssValue << kv.first; ssValue.GetData(btValue); mapKv.insert(make_pair(btKey, btValue)); } mapNewForkCtxt.insert(kv); } AddPrevRoot(hashPrevRoot, hashBlock, mapKv); if (!dbTrie.AddNewTrie(hashPrevRoot, mapKv, hashNewRoot)) { StdLog("CForkDB", "Add fork context: Add new trie fail, block: %s", hashBlock.GetHex().c_str()); return false; } if (!WriteTrieRoot(hashBlock, hashNewRoot)) { StdLog("CForkDB", "Add fork context: Write trie root fail, block: %s", hashBlock.GetHex().c_str()); return false; } if (!AddCacheForkContext(hashPrevBlock, hashBlock, mapNewForkCtxt)) { StdLog("CForkDB", "Add fork context: Add cache fail, block: %s", hashBlock.GetHex().c_str()); return false; } return true; } bool CForkDB::ListForkContext(std::map<uint256, CForkContext>& mapForkCtxt, const uint256& hashBlock) { CReadLock rlock(rwAccess); uint256 hashLastBlock; if (hashBlock == 0) { if (!GetForkLast(hashGenesisBlock, hashLastBlock)) { hashLastBlock = 0; } } else { hashLastBlock = hashBlock; } const CCacheFork* ptr = GetCacheForkContext(hashBlock); if (ptr) { mapForkCtxt = ptr->mapForkContext; return true; } if (!ListDbForkContext(hashLastBlock, mapForkCtxt)) { StdLog("CForkDB", "List Fork Context: List db fork fail, block: %s", hashLastBlock.GetHex().c_str()); return false; } return true; } bool CForkDB::RetrieveForkContext(const uint256& hashFork, CForkContext& ctxt, const uint256& hashBlock) { CReadLock rlock(rwAccess); uint256 hashLastBlock; if (hashBlock == 0) { if (!GetForkLast(hashGenesisBlock, hashLastBlock)) { hashLastBlock = 0; } } else { hashLastBlock = hashBlock; } const CCacheFork* ptr = GetCacheForkContext(hashBlock); if (ptr) { auto mt = ptr->mapForkContext.find(hashFork); if (mt != ptr->mapForkContext.end()) { ctxt = mt->second; return true; } } uint256 hashRoot; if (!ReadTrieRoot(hashLastBlock, hashRoot)) { return false; } hcode::CBufStream ssKey, ssValue; bytes btKey, btValue; ssKey << DB_FORK_KEY_NAME_CTXT << hashFork; ssKey.GetData(btKey); if (!dbTrie.Retrieve(hashRoot, btKey, btValue)) { return false; } try { ssValue.Write((char*)(btValue.data()), btValue.size()); ssValue >> ctxt; } catch (std::exception& e) { hcode::StdError(__PRETTY_FUNCTION__, e.what()); return false; } return true; } bool CForkDB::UpdateForkLast(const uint256& hashFork, const uint256& hashLastBlock) { CWriteLock wlock(rwAccess); CBufStream ss; ss << DB_FORK_KEY_NAME_ACTIVE << hashFork; uint256 hashKey = metabasenet::crypto::CryptoHash(ss.GetData(), ss.GetSize()); bytes btValue(hashLastBlock.begin(), hashLastBlock.end()); if (!dbTrie.SetValueNode(hashKey, btValue)) { StdLog("CForkDB", "Update fork last: Set value node fail, fork: %s", hashFork.GetHex().c_str()); return false; } if (hashLastBlock == 0) { mapCacheLast.erase(hashFork); } else { mapCacheLast[hashFork] = hashLastBlock; } return true; } bool CForkDB::RemoveFork(const uint256& hashFork) { return UpdateForkLast(hashFork, uint256()); } bool CForkDB::RetrieveForkLast(const uint256& hashFork, uint256& hashLastBlock) { CReadLock rlock(rwAccess); return GetForkLast(hashFork, hashLastBlock); } bool CForkDB::GetForkIdByForkName(const std::string& strForkName, uint256& hashFork, const uint256& hashBlock) { CReadLock rlock(rwAccess); uint256 hashLastBlock; if (hashBlock == 0) { if (!GetForkLast(hashGenesisBlock, hashLastBlock)) { hashLastBlock = 0; } } else { hashLastBlock = hashBlock; } const CCacheFork* ptr = GetCacheForkContext(hashBlock); if (ptr) { hashFork = ptr->GetForkIdByName(strForkName); if (hashFork != 0) { return true; } } uint256 hashRoot; if (!ReadTrieRoot(hashLastBlock, hashRoot)) { StdLog("CForkDB", "Get forkid by fork name: Read trie root fail, fork: %s", hashFork.GetHex().c_str()); return false; } hcode::CBufStream ssKey, ssValue; bytes btKey, btValue; ssKey << DB_FORK_KEY_NAME_FORKNAME << strForkName; ssKey.GetData(btKey); if (!dbTrie.Retrieve(hashRoot, btKey, btValue)) { return false; } try { ssValue.Write((char*)(btValue.data()), btValue.size()); ssValue >> hashFork; } catch (std::exception& e) { hcode::StdError(__PRETTY_FUNCTION__, e.what()); return false; } return true; } bool CForkDB::GetForkIdByForkSn(const uint16 nForkSn, uint256& hashFork, const uint256& hashBlock) { CReadLock rlock(rwAccess); uint256 hashLastBlock; if (hashBlock == 0) { if (!GetForkLast(hashGenesisBlock, hashLastBlock)) { hashLastBlock = 0; } } else { hashLastBlock = hashBlock; } const CCacheFork* ptr = GetCacheForkContext(hashBlock); if (ptr) { hashFork = ptr->GetForkIdBySn(nForkSn); if (hashFork != 0) { return true; } } uint256 hashRoot; if (!ReadTrieRoot(hashLastBlock, hashRoot)) { StdLog("CForkDB", "Get forkid by fork sn: Read trie root fail, fork: %s", hashFork.GetHex().c_str()); return false; } hcode::CBufStream ssKey, ssValue; bytes btKey, btValue; ssKey << DB_FORK_KEY_NAME_FORKSN << nForkSn; ssKey.GetData(btKey); if (!dbTrie.Retrieve(hashRoot, btKey, btValue)) { return false; } try { ssValue.Write((char*)(btValue.data()), btValue.size()); ssValue >> hashFork; } catch (std::exception& e) { hcode::StdError(__PRETTY_FUNCTION__, e.what()); return false; } return true; } bool CForkDB::VerifyForkContext(const uint256& hashPrevBlock, const uint256& hashBlock, uint256& hashRoot, const bool fVerifyAllNode) { CReadLock rlock(rwAccess); if (!ReadTrieRoot(hashBlock, hashRoot)) { StdLog("CForkDB", "Verify fork context: Read trie root fail, block: %s", hashBlock.GetHex().c_str()); return false; } if (fVerifyAllNode) { std::map<uint256, CTrieValue> mapCacheNode; if (!dbTrie.CheckTrieNode(hashRoot, mapCacheNode)) { StdLog("CForkDB", "Verify fork context: Check trie node fail, root: %s, block: %s", hashRoot.GetHex().c_str(), hashBlock.GetHex().c_str()); return false; } } uint256 hashPrevRoot; if (hashPrevBlock != 0) { if (!ReadTrieRoot(hashPrevBlock, hashPrevRoot)) { StdLog("CForkDB", "Verify fork context: Read prev trie root fail, prev block: %s", hashPrevBlock.GetHex().c_str()); return false; } } uint256 hashRootPrevDb; uint256 hashBlockLocalDb; if (!GetPrevRoot(hashRoot, hashRootPrevDb, hashBlockLocalDb)) { StdLog("CForkDB", "Verify fork context: Get prev root fail, root: %s, block: %s", hashRoot.GetHex().c_str(), hashBlock.GetHex().c_str()); return false; } if (hashRootPrevDb != hashPrevRoot || hashBlockLocalDb != hashBlock) { StdLog("CForkDB", "Verify fork context: Verify fail, hashRootPrevDb: %s, hashPrevRoot: %s, hashBlockLocalDb: %s, block: %s", hashRootPrevDb.GetHex().c_str(), hashPrevRoot.GetHex().c_str(), hashBlockLocalDb.GetHex().c_str(), hashBlock.GetHex().c_str()); return false; } return true; } /////////////////////////////////// bool CForkDB::WriteTrieRoot(const uint256& hashBlock, const uint256& hashTrieRoot) { CBufStream ss; ss << DB_FORK_KEY_NAME_TRIEROOT << hashBlock; uint256 hashKey = metabasenet::crypto::CryptoHash(ss.GetData(), ss.GetSize()); bytes btValue(hashTrieRoot.begin(), hashTrieRoot.end()); if (!dbTrie.SetValueNode(hashKey, btValue)) { return false; } while (mapCacheRoot.size() >= MAX_CACHE_ROOT_COUNT) { mapCacheRoot.erase(mapCacheRoot.begin()); } mapCacheRoot[hashBlock] = hashTrieRoot; return true; } bool CForkDB::ReadTrieRoot(const uint256& hashBlock, uint256& hashTrieRoot) { if (hashBlock == 0) { hashTrieRoot = 0; return true; } auto it = mapCacheRoot.find(hashBlock); if (it != mapCacheRoot.end()) { hashTrieRoot = it->second; return true; } CBufStream ss; ss << DB_FORK_KEY_NAME_TRIEROOT << hashBlock; uint256 hashKey = metabasenet::crypto::CryptoHash(ss.GetData(), ss.GetSize()); bytes btValue; if (!dbTrie.GetValueNode(hashKey, btValue)) { return false; } hashTrieRoot = uint256(btValue); while (mapCacheRoot.size() >= MAX_CACHE_ROOT_COUNT) { mapCacheRoot.erase(mapCacheRoot.begin()); } mapCacheRoot[hashBlock] = hashTrieRoot; return true; } void CForkDB::AddPrevRoot(const uint256& hashPrevRoot, const uint256& hashBlock, bytesmap& mapKv) { hcode::CBufStream ssKey, ssValue; bytes btKey, btValue; ssKey << DB_FORK_KEY_NAME_PREVROOT; ssKey.GetData(btKey); ssValue << hashPrevRoot << hashBlock; ssValue.GetData(btValue); mapKv.insert(make_pair(btKey, btValue)); } bool CForkDB::GetPrevRoot(const uint256& hashRoot, uint256& hashPrevRoot, uint256& hashBlock) { hcode::CBufStream ssKey, ssValue; bytes btKey, btValue; ssKey << DB_FORK_KEY_NAME_PREVROOT; ssKey.GetData(btKey); if (!dbTrie.Retrieve(hashRoot, btKey, btValue)) { return false; } try { ssValue.Write((char*)(btValue.data()), btValue.size()); ssValue >> hashPrevRoot >> hashBlock; } catch (std::exception& e) { hcode::StdError(__PRETTY_FUNCTION__, e.what()); return false; } return true; } bool CForkDB::GetForkLast(const uint256& hashFork, uint256& hashLastBlock) { auto it = mapCacheLast.find(hashFork); if (it != mapCacheLast.end()) { hashLastBlock = it->second; return true; } CBufStream ss; ss << DB_FORK_KEY_NAME_ACTIVE << hashFork; uint256 hashKey = metabasenet::crypto::CryptoHash(ss.GetData(), ss.GetSize()); bytes btValue; if (!dbTrie.GetValueNode(hashKey, btValue)) { return false; } hashLastBlock = uint256(btValue); mapCacheLast[hashFork] = hashLastBlock; return true; } bool CForkDB::AddCacheForkContext(const uint256& hashPrevBlock, const uint256& hashBlock, const std::map<uint256, CForkContext>& mapNewForkCtxt) { set<uint256> setRemoveFullFork; while (mapCacheFork.size() >= MAX_CACHE_CONTEXT_COUNT) { auto it = mapCacheFork.begin(); if (it == mapCacheFork.end()) { break; } if (it->second.hashRef == 0) { setRemoveFullFork.insert(it->first); } mapCacheFork.erase(it); } if (!setRemoveFullFork.empty()) { for (auto it = mapCacheFork.begin(); it != mapCacheFork.end();) { if (it->second.hashRef != 0 && setRemoveFullFork.count(it->second.hashRef) > 0) { mapCacheFork.erase(it++); } else { ++it; } } } bool fAddFull = false; if (CBlock::GetBlockHeightByHash(hashBlock) % (MAX_CACHE_CONTEXT_COUNT / 4) == 0) { fAddFull = true; } auto it = mapCacheFork.find(hashPrevBlock); if (fAddFull || it == mapCacheFork.end()) { std::map<uint256, CForkContext> mapForkCtxt; if (!ListDbForkContext(hashPrevBlock, mapForkCtxt)) { StdLog("CForkDB", "Add Cache Fork Context: List db fork context fail, prev block: %s", hashPrevBlock.GetHex().c_str()); return false; } if (!mapNewForkCtxt.empty()) { for (const auto& kv : mapNewForkCtxt) { mapForkCtxt[kv.first] = kv.second; } } mapCacheFork[hashBlock] = CCacheFork(mapForkCtxt); } else { if (!mapNewForkCtxt.empty()) { std::map<uint256, CForkContext> mapForkCtxt; mapForkCtxt = it->second.mapForkContext; for (const auto& kv : mapNewForkCtxt) { mapForkCtxt[kv.first] = kv.second; } mapCacheFork[hashBlock] = CCacheFork(mapForkCtxt); } else { if (it->second.hashRef == 0) { mapCacheFork[hashBlock] = CCacheFork(hashPrevBlock); } else { mapCacheFork[hashBlock] = CCacheFork(it->second.hashRef); } } } return true; } const CCacheFork* CForkDB::GetCacheForkContext(const uint256& hashBlock) { if (hashBlock == 0) { return nullptr; } auto it = mapCacheFork.find(hashBlock); if (it != mapCacheFork.end()) { if (it->second.hashRef != 0) { it = mapCacheFork.find(it->second.hashRef); if (it == mapCacheFork.end()) { StdLog("CForkDB", "Get Cache Fork Context: Get ref cache fail, block: %s", hashBlock.GetHex().c_str()); return nullptr; } } return &(it->second); } return nullptr; } const CCacheFork* CForkDB::LoadCacheForkContext(const uint256& hashBlock) { if (hashBlock == 0) { return nullptr; } const CCacheFork* ptr = GetCacheForkContext(hashBlock); if (ptr == nullptr) { std::map<uint256, CForkContext> mapForkCtxt; if (!ListDbForkContext(hashBlock, mapForkCtxt)) { StdLog("CForkDB", "Get Cache Fork Context: List db fork fail, block: %s", hashBlock.GetHex().c_str()); return nullptr; } if (mapCacheFork.find(hashBlock) != mapCacheFork.end()) { mapCacheFork.erase(hashBlock); } auto it = mapCacheFork.insert(make_pair(hashBlock, CCacheFork(mapForkCtxt))).first; return &(it->second); } return ptr; } bool CForkDB::ListDbForkContext(const uint256& hashBlock, std::map<uint256, CForkContext>& mapForkCtxt) { if (hashBlock == 0) { return true; } uint256 hashRoot; if (!ReadTrieRoot(hashBlock, hashRoot)) { StdLog("CForkDB", "List Db Fork Context: Read trie root fail, block: %s", hashBlock.GetHex().c_str()); return false; } hcode::CBufStream ssKeyPrefix; ssKeyPrefix << DB_FORK_KEY_NAME_CTXT; bytes btKeyPrefix; ssKeyPrefix.GetData(btKeyPrefix); CListForkTrieDBWalker walker(mapForkCtxt); if (!dbTrie.WalkThroughTrie(hashRoot, walker, btKeyPrefix)) { StdLog("CForkDB", "List Db Fork Context: Walk through trie fail, block: %s", hashBlock.GetHex().c_str()); return false; } return true; } } // namespace storage } // namespace metabasenet
26.741445
158
0.600834
metabasenet
9625f66ca0c7cb91db28f3cd9ede5ad43d0d4080
4,359
cpp
C++
Engine/Source/Editor/BlueprintGraph/Private/K2Node_MakeArray.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Editor/BlueprintGraph/Private/K2Node_MakeArray.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Editor/BlueprintGraph/Private/K2Node_MakeArray.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "K2Node_MakeArray.h" #include "EdGraph/EdGraphPin.h" #include "Engine/Blueprint.h" #include "Framework/Commands/UIAction.h" #include "Framework/MultiBox/MultiBoxBuilder.h" #include "EdGraphSchema_K2.h" #include "EdGraph/EdGraphNodeUtils.h" #include "Kismet2/BlueprintEditorUtils.h" #include "ScopedTransaction.h" #include "EdGraphUtilities.h" #include "KismetCompiledFunctionContext.h" #include "KismetCompilerMisc.h" #include "BlueprintNodeSpawner.h" #include "EditorCategoryUtils.h" #include "BlueprintActionDatabaseRegistrar.h" namespace MakeArrayLiterals { static const FString OutputPinName = FString(TEXT("Array")); }; #define LOCTEXT_NAMESPACE "MakeArrayNode" ///////////////////////////////////////////////////// // FKCHandler_MakeArray class FKCHandler_MakeArray : public FKCHandler_MakeContainer { public: FKCHandler_MakeArray(FKismetCompilerContext& InCompilerContext) : FKCHandler_MakeContainer(InCompilerContext) { CompiledStatementType = KCST_CreateArray; } }; ///////////////////////////////////////////////////// // UK2Node_MakeArray UK2Node_MakeArray::UK2Node_MakeArray(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { ContainerType = EPinContainerType::Array; } FNodeHandlingFunctor* UK2Node_MakeArray::CreateNodeHandler(FKismetCompilerContext& CompilerContext) const { return new FKCHandler_MakeArray(CompilerContext); } FText UK2Node_MakeArray::GetNodeTitle(ENodeTitleType::Type TitleType) const { return LOCTEXT("NodeTitle", "Make Array"); } FString UK2Node_MakeArray::GetOutputPinName() const { return MakeArrayLiterals::OutputPinName; } FText UK2Node_MakeArray::GetTooltipText() const { return LOCTEXT("MakeArrayTooltip", "Create an array from a series of items."); } FSlateIcon UK2Node_MakeArray::GetIconAndTint(FLinearColor& OutColor) const { static FSlateIcon Icon("EditorStyle", "GraphEditor.MakeArray_16x"); return Icon; } void UK2Node_MakeArray::GetContextMenuActions(const FGraphNodeContextMenuBuilder& Context) const { Super::GetContextMenuActions(Context); if (!Context.bIsDebugging) { Context.MenuBuilder->BeginSection("K2NodeMakeArray", NSLOCTEXT("K2Nodes", "MakeArrayHeader", "MakeArray")); if (Context.Pin != NULL) { if (Context.Pin->Direction == EGPD_Input && Context.Pin->ParentPin == nullptr) { Context.MenuBuilder->AddMenuEntry( LOCTEXT("RemovePin", "Remove array element pin"), LOCTEXT("RemovePinTooltip", "Remove this array element pin"), FSlateIcon(), FUIAction( FExecuteAction::CreateUObject(this, &UK2Node_MakeArray::RemoveInputPin, const_cast<UEdGraphPin*>(Context.Pin)) ) ); } } else { Context.MenuBuilder->AddMenuEntry( LOCTEXT("AddPin", "Add array element pin"), LOCTEXT("AddPinTooltip", "Add another array element pin"), FSlateIcon(), FUIAction( FExecuteAction::CreateUObject(this, &UK2Node_MakeArray::InteractiveAddInputPin) ) ); } Context.MenuBuilder->AddMenuEntry( LOCTEXT("ResetToWildcard", "Reset to wildcard"), LOCTEXT("ResetToWildcardTooltip", "Reset the node to have wildcard input/outputs. Requires no pins are connected."), FSlateIcon(), FUIAction( FExecuteAction::CreateUObject(this, &UK2Node_MakeArray::ClearPinTypeToWildcard), FCanExecuteAction::CreateUObject(this, &UK2Node_MakeArray::CanResetToWildcard) ) ); Context.MenuBuilder->EndSection(); } } void UK2Node_MakeArray::ValidateNodeDuringCompilation(class FCompilerResultsLog& MessageLog) const { Super::ValidateNodeDuringCompilation(MessageLog); const UEdGraphSchema_K2* Schema = Cast<const UEdGraphSchema_K2>(GetSchema()); UEdGraphPin* OutputPin = GetOutputPin(); if (!ensure(Schema) || !ensure(OutputPin) || Schema->IsExecPin(*OutputPin)) { MessageLog.Error(*NSLOCTEXT("K2Node", "MakeArray_OutputIsExec", "Unacceptable array type in @@").ToString(), this); } } FText UK2Node_MakeArray::GetMenuCategory() const { static FNodeTextCache CachedCategory; if (CachedCategory.IsOutOfDate(this)) { // FText::Format() is slow, so we cache this to save on performance CachedCategory.SetCachedText(FEditorCategoryUtils::BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("ActionMenuCategory", "Array")), this); } return CachedCategory; } #undef LOCTEXT_NAMESPACE
29.653061
154
0.752466
windystrife
96295caa4d4dba082d76d8e089c8c823aef7a1b4
15,828
cpp
C++
libraries/spncci/explicit_construction.cpp
nd-nuclear-theory/spncci
18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4
[ "MIT" ]
1
2021-10-17T22:58:31.000Z
2021-10-17T22:58:31.000Z
libraries/spncci/explicit_construction.cpp
nd-nuclear-theory/spncci
18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4
[ "MIT" ]
1
2021-02-16T03:16:31.000Z
2021-02-16T19:46:18.000Z
libraries/spncci/explicit_construction.cpp
nd-nuclear-theory/spncci
18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4
[ "MIT" ]
2
2019-04-27T17:26:59.000Z
2021-04-28T17:04:07.000Z
/**************************************************************** explicit_construction.cpp Anna E. McCoy and Mark A. Caprio University of Notre Dame ****************************************************************/ #include "spncci/explicit_construction.h" #include <omp.h> #include "cppformat/format.h" #include "mcutils/eigen.h" namespace spncci { typedef std::vector<basis::MatrixVector> PolynomialMatrices; void GenerateSpRaisingPolynomials( const spncci::SpNCCIIrrepFamily& sp_irrep_family, const u3shell::SpaceU3SPN& lsu3shell_space, const u3shell::SectorsU3SPN& Arel_sectors, const basis::MatrixVector& Arel_matrices, PolynomialMatrices& polynomial_matrices ) { const sp3r::Sp3RSpace& u3_subspaces=sp_irrep_family.Sp3RSpace(); u3shell::U3SPN sigmaSPN(sp_irrep_family); int lgi_lsu3shell_subspace_index=lsu3shell_space.LookUpSubspaceIndex(sigmaSPN); // index starts with 1 because we don't care about lgi nex=0 subspace (i=0 subspace) polynomial_matrices.resize(u3_subspaces.size()); for(int w=1; w<u3_subspaces.size(); ++w) { const sp3r::U3Subspace& omega_subspace=u3_subspaces.GetSubspace(w); u3::U3 omega(omega_subspace.labels()); MultiplicityTagged<u3::SU3>::vector omegapp_list=KroneckerProduct(omega.SU3(), u3::SU3(0,2)); // get index for omega in lsu3shell basis int omega_lsu3shell_subspace_index =lsu3shell_space.LookUpSubspaceIndex(u3shell::U3SPN(omega,sigmaSPN.Sp(),sigmaSPN.Sn(),sigmaSPN.S())); // resize matrix vector for omega polynomials polynomial_matrices[w].resize(omega_subspace.size()); // iterate over n_rho "states" in u3 subspace for(int i=0; i<omega_subspace.size(); ++i) { MultiplicityTagged<u3::U3> n_rho(omega_subspace.GetStateLabels(i)); const u3::U3& n=n_rho.irrep; bool init=true; for(int w_bar=0; w_bar<omegapp_list.size(); ++w_bar) { u3::U3 omega_bar(omega.N()-2,omegapp_list[w_bar].irrep); // check if omega_bar is a valid U3 state and in irrep if(not omega_bar.Valid()) continue; int omega_bar_index=u3_subspaces.LookUpSubspaceIndex(omega_bar); if(omega_bar_index==basis::kNone) continue; // get index for omega in lsu3shell basis int omega_bar_lsu3shell_subspace_index =lsu3shell_space.LookUpSubspaceIndex(u3shell::U3SPN(omega_bar,sigmaSPN.Sp(),sigmaSPN.Sn(),sigmaSPN.S())); // get Aintr matrix int Arel_sector_index =Arel_sectors.LookUpSectorIndex(omega_lsu3shell_subspace_index,omega_bar_lsu3shell_subspace_index); const Eigen::MatrixXd& A=Arel_matrices[Arel_sector_index]; // special case: if Nn=2, then polynomial is A if((omega.N()-sigmaSPN.N())==2) { polynomial_matrices[w][i]=A; continue; } const sp3r::U3Subspace& omega_bar_subspace=u3_subspaces.GetSubspace(omega_bar_index); // initial polynomial matrix if(init) { int rows=A.rows(); int cols=polynomial_matrices[omega_bar_index][0].cols(); polynomial_matrices[w][i]=Eigen::MatrixXd::Zero(rows,cols); init=false; } // sum over n_bar,rho_bar for(int j=0; j<omega_bar_subspace.size(); ++j) { u3::U3 n_bar(omega_bar_subspace.GetStateLabels(j).irrep); int rho_bar=omega_bar_subspace.GetStateLabels(j).tag; double coef=2./int(n.N())*vcs::BosonCreationRME(n,n_bar) *u3::U(sigmaSPN.U3().SU3(),n_bar.SU3(), omega.SU3(),u3::SU3(2,0), omega_bar.SU3(),rho_bar,1,n.SU3(),1,1); // std::cout<<polynomial_matrices[omega_bar_index][j].rows()<<std::endl<<std::endl; // std::cout<<"A "<<A.rows()<<" "<<A.cols()<<std::endl<<A<<std::endl; // std::cout<<polynomial_matrices[w][i].rows()<<std::endl<<std::endl; polynomial_matrices[w][i]+=coef*A*polynomial_matrices[omega_bar_index][j]; } } } } } void ConstructSpNCCIBasisExplicit( const u3shell::SpaceU3SPN& lsu3shell_space, const spncci::SpNCCISpace& sp_irrep_families, const basis::MatrixVector& lgi_expansions, const spncci::BabySpNCCISpace& baby_spncci_space, const spncci::KMatrixCache& k_matrix_cache, const spncci::KMatrixCache& kinv_matrix_cache, const u3shell::SectorsU3SPN& Arel_sectors, const basis::MatrixVector& Arel_matrices, basis::MatrixVector& spncci_expansions, bool restrict_sp3r_u3_branching ) { u3::UCoefCache u_coef_cache; // Generate raising polynomials // std::cout<<"generate polynomial matrices"<<std::endl; std::vector<PolynomialMatrices> polynomial_matrices_by_lgi_family(sp_irrep_families.size()); for(int p=0; p<sp_irrep_families.size(); ++p) { const spncci::SpNCCIIrrepFamily& sp_irrep_family=sp_irrep_families[p]; spncci::GenerateSpRaisingPolynomials( sp_irrep_family,lsu3shell_space, Arel_sectors,Arel_matrices, polynomial_matrices_by_lgi_family[p] ); } // std::cout<<"get spncci expansions "<<std::endl; spncci_expansions.resize(baby_spncci_space.size()); for (int subspace_index=0; subspace_index<baby_spncci_space.size(); ++subspace_index) { // extract subspace properties const BabySpNCCISubspace& subspace = baby_spncci_space.GetSubspace(subspace_index); int irrep_family_index = subspace.irrep_family_index(); int Nex = int(subspace.omega().N()-subspace.sigma().N()); // extract sp3r properties const sp3r::Sp3RSpace& u3_subspaces=sp_irrep_families[irrep_family_index].Sp3RSpace(); int omega_index=u3_subspaces.LookUpSubspaceIndex(subspace.omega()); const auto& u3_subspace=u3_subspaces.GetSubspace(omega_index); basis::MatrixVector& raising_polynomials=polynomial_matrices_by_lgi_family[irrep_family_index][omega_index]; // define aliases to the relevant lsu3shell subspaces int lgi_lsu3shell_subspace_index = lsu3shell_space.LookUpSubspaceIndex(subspace.sigmaSPN()); int spncci_lsu3shell_subspace_index = lsu3shell_space.LookUpSubspaceIndex(subspace.omegaSPN()); // diagnostics const u3shell::SubspaceU3SPN& lgi_lsu3shell_subspace = lsu3shell_space.GetSubspace(lgi_lsu3shell_subspace_index); const u3shell::SubspaceU3SPN& spncci_lsu3shell_subspace = lsu3shell_space.GetSubspace(spncci_lsu3shell_subspace_index); // std::cout // << fmt::format( // "Constructing subspace: LGI sigmaSPN {} family index {} => omegaSPN {} (Nex {})", // subspace.sigmaSPN().Str(),irrep_family_index, // subspace.omegaSPN().Str(),spncci_lsu3shell_subspace.size(),Nex // ) // << std::endl // << fmt::format( // " lsu3shell subspace sigmaSPN: U3SPN {} subspace index {} dim {}", // lgi_lsu3shell_subspace.U3SPN().Str(), // lgi_lsu3shell_subspace_index, // lgi_lsu3shell_subspace.size() // ) // << std::endl // << fmt::format( // " lsu3shell subspace omegaSPN: U3SPN {} subspace index {} dim {}", // spncci_lsu3shell_subspace.U3SPN().Str(), // spncci_lsu3shell_subspace_index, // spncci_lsu3shell_subspace.size() // ) // << std::endl; // define aliases to expansion matrices // std::cout<<"get lgi expansion "<<std::endl; // const Eigen::MatrixXd& lgi_expansion = lgi_expansions[irrep_family_index]; const Eigen::MatrixXd& lgi_expansion = lgi_expansions[lgi_lsu3shell_subspace_index]; Eigen::MatrixXd& spncci_expansion = spncci_expansions[subspace_index]; // diagnostics // std::cout << fmt::format(" lgi_expansion ({},{})",lgi_expansion.rows(),lgi_expansion.cols()) << std::endl; // calculate expansion of baby SpNCCI subspace // assert((Nex==0)||(Nex==2)); if (Nex==0) // Nex=0 -- trivial expansion { spncci_expansion = lgi_expansion; } else { int upsilon_max=subspace.upsilon_max(); int u3_subspace_dim=u3_subspace.size(); int gamma_max=subspace.gamma_max(); int rows=raising_polynomials[0].rows(); int cols=lgi_expansion.cols(); spncci_expansion=Eigen::MatrixXd::Zero(rows,upsilon_max*gamma_max); Eigen::MatrixXd k_matrix_inverse = kinv_matrix_cache.at(subspace.sigma()).at(subspace.omega()); int phase = ParitySign( u3::ConjugationGrade(subspace.sigma().SU3()) +u3::ConjugationGrade(subspace.omega().SU3()) ); assert(raising_polynomials.size()==u3_subspace_dim); for(int u=0; u<upsilon_max; ++u) { Eigen::MatrixXd omega_expansion_temp=Eigen::MatrixXd::Zero(rows,cols); for(int u_bar=0; u_bar<u3_subspace_dim; ++u_bar) { // std::cout<<u<<" "<<u_bar<<" "<<k_matrix_inverse.rows()<<" "<<k_matrix_inverse.cols() // <<" "<<raising_polynomials[u_bar].rows()<<" "<<raising_polynomials[u_bar].rows()<<std::endl; omega_expansion_temp+=phase*k_matrix_inverse(u_bar,u)*raising_polynomials[u_bar]*lgi_expansion; } // Populating spncci_expansion with omega expansions. // omega_expansion_temp // u=upsilon-1 // g=gamma-1 // index in expansion is upsilon_max(gamma-1)+(upsilon-1) for(int g=0; g<gamma_max; ++g) { int column_index=g*upsilon_max+u; spncci_expansion.block(0,column_index,rows,1)=omega_expansion_temp.block(0,g,rows,1); } } } } } void ComputeUnitTensorSectorsExplicit( const u3::U3& sigmap, const u3::U3& sigma, const u3shell::RelativeUnitTensorLabelsU3ST& unit_tensor, const u3shell::RelativeUnitTensorSpaceU3S& unit_tensor_space, const u3shell::SpaceU3SPN& lsu3shell_space, const u3shell::SectorsU3SPN& lsu3shell_operator_sectors, basis::MatrixVector& lsu3shell_operator_matrices, const spncci::BabySpNCCISpace& baby_spncci_space, const basis::MatrixVector& spncci_expansions, const spncci::BabySpNCCIHypersectors& baby_spncci_hypersectors, basis::OperatorHyperblocks<double>& unit_tensor_hyperblocks ) { // #pragma omp parallel // #pragma omp for schedule(runtime) // for each of the unit tensors in lsu3shell basis for(int s=0; s<lsu3shell_operator_sectors.size(); ++s) { // std::cout<<"sector "<<s<<std::endl; // extract U3SPN labels auto& lsu3shell_sector=lsu3shell_operator_sectors.GetSector(s); int lsu3shell_bra_index=lsu3shell_sector.bra_subspace_index(); int lsu3shell_ket_index=lsu3shell_sector.ket_subspace_index(); int rho0=lsu3shell_sector.multiplicity_index(); u3shell::U3SPN lsu3shell_ket_subspace_labels=lsu3shell_space.GetSubspace(lsu3shell_ket_index).labels(); u3shell::U3SPN lsu3shell_bra_subspace_labels=lsu3shell_space.GetSubspace(lsu3shell_bra_index).labels(); // look up unit tensor subspace index u3shell::UnitTensorSubspaceLabels unit_tensor_labels(unit_tensor.x0(),unit_tensor.S0(),unit_tensor.bra().eta(),unit_tensor.ket().eta()); int unit_tensor_subspace_index=unit_tensor_space.LookUpSubspaceIndex(unit_tensor_labels); // look up unit tensor index std::tuple<int,int,int,int,int> unit_tensor_state_labels( int(unit_tensor.T0()), int(unit_tensor.bra().S()), int(unit_tensor.bra().T()),int(unit_tensor.ket().S()),int(unit_tensor.ket().T()) ); int unit_tensor_index=unit_tensor_space.GetSubspace(unit_tensor_subspace_index).LookUpStateIndex(unit_tensor_state_labels); // Look up baby spncci index spncci::BabySpNCCISubspaceLabels baby_spncci_labels_bra( sigmap, lsu3shell_bra_subspace_labels.Sp(), lsu3shell_bra_subspace_labels.Sn(), lsu3shell_bra_subspace_labels.S(), lsu3shell_bra_subspace_labels.U3() ); int baby_spncci_subspace_index_bra=baby_spncci_space.LookUpSubspaceIndex(baby_spncci_labels_bra); // If baby spncci index=-1, then omega is not in sigma irrep // so go to next omega. if(baby_spncci_subspace_index_bra==-1) continue; spncci::BabySpNCCISubspaceLabels baby_spncci_labels_ket( sigma, lsu3shell_ket_subspace_labels.Sp(), lsu3shell_ket_subspace_labels.Sn(), lsu3shell_ket_subspace_labels.S(), lsu3shell_ket_subspace_labels.U3() ); int baby_spncci_subspace_index_ket=baby_spncci_space.LookUpSubspaceIndex(baby_spncci_labels_ket); if(baby_spncci_subspace_index_ket==-1) continue; // look up hyper sector index int hypersector_index =baby_spncci_hypersectors.LookUpHypersectorIndex( baby_spncci_subspace_index_bra,baby_spncci_subspace_index_ket, unit_tensor_subspace_index, rho0 ); // If not in hypersector set, continue. if(hypersector_index==-1) continue; // std::cout<<fmt::format("unit tensor subspace {}, unit tensor {}, baby spncci bra {} ket{} hypersector{}", // unit_tensor_subspace_index,unit_tensor_index,baby_spncci_subspace_index_bra, baby_spncci_subspace_index_ket,hypersector_index)<<std::endl; // Get bra and ket lsu3shell expansion and compute unit tensor block const Eigen::MatrixXd& bra_expansion=spncci_expansions[baby_spncci_subspace_index_bra]; const Eigen::MatrixXd& ket_expansion=spncci_expansions[baby_spncci_subspace_index_ket]; Eigen::MatrixXd temp=bra_expansion.transpose()*lsu3shell_operator_matrices[s]*ket_expansion; // std::cout<<temp<<std::endl; // std::cout<<fmt::format(" bra : {} x {} operator : {} x {} ket : {} x {}", // bra_expansion.rows(), bra_expansion.cols(), // lsu3shell_operator_matrices[s].rows(), lsu3shell_operator_matrices[s].cols(), // ket_expansion.rows(), ket_expansion.cols() // )<<std::endl; // Store unit tensor block in hypersector structure unit_tensor_hyperblocks[hypersector_index][unit_tensor_index]+=temp; // std::cout<<"hypersector "<<hypersector_index<<" tensor "<<unit_tensor_index<<std::endl; // std::cout<<"temp "<<temp<<" in hypersectors "<<unit_tensor_hyperblocks[hypersector_index][unit_tensor_index]<<std::endl<<std::endl; } } } // namespace
45.222857
155
0.616376
nd-nuclear-theory
962da2035184e223c3aabb2569c6565c254aa433
1,948
cpp
C++
Parse/PFManager.cpp
sourada/Parse-Qt-SDK
32bb10a37ddebc71bae4e648438efb3bd9fdd48b
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
Parse/PFManager.cpp
sourada/Parse-Qt-SDK
32bb10a37ddebc71bae4e648438efb3bd9fdd48b
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
Parse/PFManager.cpp
sourada/Parse-Qt-SDK
32bb10a37ddebc71bae4e648438efb3bd9fdd48b
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// // PFManager.cpp // Parse // // Created by Christian Noon on 11/5/13. // Copyright (c) 2013 Christian Noon. All rights reserved. // // Parse headers #include "PFManager.h" // Qt headers #include <QMutex> #include <QMutexLocker> namespace parse { // Static Globals static QMutex gPFManagerMutex; #ifdef __APPLE__ #pragma mark - Memory Management Methods #endif PFManager::PFManager() : _applicationId(""), _restApiKey(""), _masterKey(""), _cacheDirectory(""), _networkAccessManager() { // Define the default cache directory as $$TMPDIR/Parse _cacheDirectory = QDir::temp(); _cacheDirectory.mkdir("Parse"); _cacheDirectory.cd("Parse"); qDebug() << "Cache directory:" << _cacheDirectory.absolutePath(); } PFManager::~PFManager() { // No-op } #ifdef __APPLE__ #pragma mark - Creation Methods #endif PFManager* PFManager::sharedManager() { QMutexLocker lock(&gPFManagerMutex); static PFManager manager; return &manager; } #ifdef __APPLE__ #pragma mark - User API #endif void PFManager::setApplicationIdAndRestApiKey(const QString& applicationId, const QString& restApiKey) { _applicationId = applicationId; _restApiKey = restApiKey; } void PFManager::setMasterKey(const QString& masterKey) { _masterKey = masterKey; } const QString& PFManager::applicationId() { return _applicationId; } const QString& PFManager::restApiKey() { return _restApiKey; } const QString& PFManager::masterKey() { return _masterKey; } #ifdef __APPLE__ #pragma mark - Backend API - Caching and Network Methods #endif QNetworkAccessManager* PFManager::networkAccessManager() { return &_networkAccessManager; } void PFManager::setCacheDirectory(const QDir& cacheDirectory) { _cacheDirectory = cacheDirectory; } QDir& PFManager::cacheDirectory() { return _cacheDirectory; } void PFManager::clearCache() { _cacheDirectory.removeRecursively(); _cacheDirectory.mkpath(_cacheDirectory.absolutePath()); } } // End of parse namespace
17.54955
102
0.747433
sourada
962ffee954876d8999083f3bffc80ce4602a7c70
1,441
cpp
C++
greedy/Huffman_coding.cpp
verma-tanishq/placement-essentials
515135f417f002db5e59317cce7660f29b8e902a
[ "MIT" ]
1
2021-04-04T16:23:15.000Z
2021-04-04T16:23:15.000Z
greedy/Huffman_coding.cpp
verma-tanishq/placement-essentials
515135f417f002db5e59317cce7660f29b8e902a
[ "MIT" ]
null
null
null
greedy/Huffman_coding.cpp
verma-tanishq/placement-essentials
515135f417f002db5e59317cce7660f29b8e902a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct MinHeapNode{ char data; unsigned frq; MinHeapNode *left; MinHeapNode *right; MinHeapNode(char data, unsigned frq){ left=right=NULL; this->data = data; this->frq = frq; } }; struct comp{ bool operator()(MinHeapNode *l, MinHeapNode *r){ return l->frq > r->frq; } }; void printHuff(struct MinHeapNode* root, string str){ if(!root){ return; } if(root->data!='$'){ cout<<root->data<<": "<<str<<"\n"; } printHuff(root->left, str+"0"); printHuff(root->right, str+"1"); } void huffmanCode(char data[], int frq[], int n){ struct MinHeapNode *left, *right, *top; priority_queue<MinHeapNode*, vector<MinHeapNode*>, comp> minHeap; for(int i=0; i<n; ++i){ minHeap.push(new MinHeapNode(data[i], frq[i])); } while(minHeap.size()!=1){ left = minHeap.top(); minHeap.pop(); right = minHeap.top(); minHeap.pop(); top = new MinHeapNode('$', left->frq + right->frq); top->left=left; top->right=right; minHeap.push(top); } printHuff(minHeap.top(),""); } int main(){ char arr[] = {'a','b','c','d','e','f'}; int frq[] = {5,9,12,13,16,45}; int n = sizeof(arr)/sizeof(arr[0]); huffmanCode(arr,frq,n); return 0; }
22.169231
70
0.519084
verma-tanishq
9635570a8c1ba2dbdfc1faf6a8ff56b8ffbd5222
1,367
cpp
C++
Chapter13/TextQuery.cpp
FrogLu/CPPP
0ee4632c12b287957739e2061fd6b02234465346
[ "MIT" ]
null
null
null
Chapter13/TextQuery.cpp
FrogLu/CPPP
0ee4632c12b287957739e2061fd6b02234465346
[ "MIT" ]
null
null
null
Chapter13/TextQuery.cpp
FrogLu/CPPP
0ee4632c12b287957739e2061fd6b02234465346
[ "MIT" ]
null
null
null
#include "pch.h" #include "StrVec.h" #include "myfunction.h" #include "TextQuery.h" std::set<TextQuery::line_no>::iterator QueryResult::begin() { auto ret=lines->begin(); return ret; } const std::set<TextQuery::line_no>::iterator QueryResult::begin() const { auto ret = lines->cbegin(); return ret; } std::set<TextQuery::line_no>::iterator QueryResult::end() { auto ret = lines->end(); return ret; } const std::set<TextQuery::line_no>::iterator QueryResult::end() const { auto ret = lines->cend(); return ret; } void TextQuery::display_map() { auto iter = wm.cbegin(), iter_end = wm.cend(); for (; iter != iter_end; ++iter) { std::cout << "word: " << iter->first << " {"; auto text_locs = iter->second; auto loc_iter = text_locs->cbegin(); auto loc_iter_end = text_locs->cend(); while (loc_iter != loc_iter_end) { std::cout << *loc_iter; if (++loc_iter != loc_iter_end) { std::cout << ", "; } } std::cout << "}" << std::endl; } std::cout << std::endl; } std::string TextQuery::cleanup_str(const std::string& word) { std::string ret; for (auto iter = word.begin(); iter != word.end(); ++iter) { if (!ispunct(*iter)) { ret += tolower(*iter); } } return ret; }
22.783333
71
0.556693
FrogLu
963c7efd265515d3a06622501dd8338d5263c25b
3,601
cpp
C++
pc/attr_id.cpp
rtilder/pyth-client
aaf33e1dd13c7c945f1545dd5b207646cba034d3
[ "Apache-2.0" ]
89
2021-05-13T15:05:45.000Z
2022-03-17T16:42:21.000Z
pc/attr_id.cpp
rtilder/pyth-client
aaf33e1dd13c7c945f1545dd5b207646cba034d3
[ "Apache-2.0" ]
46
2021-05-14T15:26:14.000Z
2022-03-31T11:33:48.000Z
pc/attr_id.cpp
rtilder/pyth-client
aaf33e1dd13c7c945f1545dd5b207646cba034d3
[ "Apache-2.0" ]
50
2021-05-18T05:10:38.000Z
2022-03-31T22:26:28.000Z
#include "attr_id.hpp" using namespace pc; /////////////////////////////////////////////////////////////////////////// // attr_dict attr_dict::pos::pos() : idx_( 0 ), len_ ( 0 ) { } void attr_dict::clear() { num_ = 0; abuf_.clear(); avec_.clear(); } unsigned attr_dict::get_num_attr() const { return num_; } bool attr_dict::get_attr( attr_id aid, str& val ) const { if ( aid.get_id() >= avec_.size() ) return false; const pos& p = avec_[aid.get_id()]; val.str_ = &abuf_[p.idx_]; val.len_ = p.len_; return val.len_ != 0; } bool attr_dict::get_next_attr( attr_id&id, str& val ) const { for(unsigned i=1+id.get_id(); i<avec_.size(); ++i ) { id = attr_id( i ); if ( get_attr( id, val ) ) { return true; } } return false; } void attr_dict::add_ref( attr_id aid, str val ) { if ( aid.get_id() >= avec_.size() ) { avec_.resize( 1 + aid.get_id() ); } pos& p = avec_[aid.get_id()]; p.idx_ = abuf_.size(); p.len_ = val.len_; abuf_.resize( abuf_.size() + p.len_ ); __builtin_memcpy( &abuf_[p.idx_], val.str_, p.len_ ); ++num_; } bool attr_dict::init_from_account( pc_prod_t *aptr ) { clear(); str key, val; char *ptr = (char*)aptr + sizeof( pc_prod_t ); char *end = (char*)aptr + aptr->size_; while( ptr != end ) { key.str_ = &ptr[1]; key.len_ = (size_t)ptr[0]; ptr += 1 + key.len_; if ( ptr > end ) return false; val.str_ = &ptr[1]; val.len_ = (size_t)ptr[0]; ptr += 1 + val.len_; if ( ptr > end ) return false; attr_id aid = attr_id_set::inst().add_attr_id( key ); add_ref( aid, val ); } return true; } bool attr_dict::init_from_json( jtree& pt, uint32_t hd ) { if ( hd == 0 || pt.get_type( hd ) != jtree::e_obj ) { return false; } clear(); for( uint32_t it=pt.get_first(hd); it; it = pt.get_next(it) ) { uint32_t kt = pt.get_key( it ); if ( !kt ) return false; attr_id aid = attr_id::add( pt.get_str( kt ) ); str val = pt.get_str( pt.get_val( it ) ); add_ref( aid, val ); } return true; } void attr_dict::write_account( net_wtr& wtr ) { str vstr, kstr; for( unsigned id=1; id < avec_.size(); ++id ) { attr_id aid( id ); if ( !get_attr( aid, vstr ) ) { continue; } kstr = aid.get_str(); wtr.add( (char)kstr.len_ ); wtr.add( kstr ); wtr.add( (char)vstr.len_ ); wtr.add( vstr ); } } void attr_dict::write_json( json_wtr& wtr ) const { str vstr, kstr; for( unsigned id=1; id < avec_.size(); ++id ) { attr_id aid( id ); if ( !get_attr( aid, vstr ) ) { continue; } kstr = aid.get_str(); wtr.add_key( kstr, vstr ); } } /////////////////////////////////////////////////////////////////////////// // attr_id_set attr_id_set::attr_id_set() : aid_( 0 ) { } str attr_id_set::attr_wtr::add_attr( str v ) { char *tgt = reserve( v.len_ ); __builtin_memcpy( tgt, v.str_, v.len_ ); advance( v.len_ ); return str( tgt, v.len_ ); } attr_id attr_id_set::add_attr_id( str v ) { attr_map_t::iter_t it = amap_.find( v ); if ( it ) { return amap_.obj( it ); } else { str k = abuf_.add_attr( v ); it = amap_.add( k ); attr_id aid( ++aid_ ); avec_.resize( 1 + aid_ ); avec_[aid_] = k; amap_.ref( it ) = aid; return aid; } } attr_id attr_id_set::get_attr_id( str v ) { attr_map_t::iter_t it = amap_.find( v ); if ( it ) { return amap_.obj( it ); } else { return attr_id(); } } str attr_id_set::get_str( attr_id aid ) { if ( aid.get_id() < avec_.size() ) { return avec_[aid.get_id()]; } else { return str(); } }
20.815029
75
0.550958
rtilder
9640b4ab153b76bf5f6ac5aca006d12f618598b4
3,907
cpp
C++
src/Host.cpp
dgu123/enet-pp
19559db6201d5b5d679185731bbb0bc623241576
[ "MIT" ]
null
null
null
src/Host.cpp
dgu123/enet-pp
19559db6201d5b5d679185731bbb0bc623241576
[ "MIT" ]
null
null
null
src/Host.cpp
dgu123/enet-pp
19559db6201d5b5d679185731bbb0bc623241576
[ "MIT" ]
null
null
null
// Copyright (c) 2010 Johann Duscher (alias Jonny Dee) // // 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 "enetpp/ENet.h" #include <stdexcept> namespace enetpp { Host::Host(ENet* parent, const Address& address, size_t maxClients, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) : _parent(parent), _host(enet_host_create(&address._address, maxClients, incomingBandwidth, outgoingBandwidth)) { if (NULL == _host) throw std::runtime_error("An error occurred while trying to create an ENet server host"); } Host::Host(ENet* parent, size_t maxClients, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) : _parent(parent), _host(enet_host_create(NULL, maxClients, incomingBandwidth, outgoingBandwidth)) { if (NULL == _host) throw std::runtime_error("An error occurred while trying to create an ENet client host"); } Host::~Host() { destroy(); } void Host::destroy() { enet_host_destroy(_host); } int Host::service(Event& event, enet_uint32 timeoutMillis) { int result = enet_host_service(_host, &event._event, timeoutMillis); handleEvent(event); return result; } void Host::handleEvent(Event& event) { switch (event.type()) { case ENET_EVENT_TYPE_CONNECT: // Remember the new peer. _allPeers.push_back(event.peer()._peer); break; case ENET_EVENT_TYPE_DISCONNECT: // This is where you are informed about disconnects. // Simply remove the peer from the list of all peers. _allPeers.erase(std::find(_allPeers.begin(), _allPeers.end(), event.peer()._peer)); break; default: break; } } Peer Host::connect(const Address& address, size_t channelCount) { ENetPeer* peer = enet_host_connect(_host, &address._address, channelCount); if (NULL == peer) throw std::runtime_error("Creating connection failed"); return Peer(peer); } void Host::broadcast(enet_uint8 channelID, Packet& packet) { // Once the packet is handed over to ENet with broadcast(), // ENet will handle its deallocation. enet_host_broadcast(_host, channelID, packet._packet); } void Host::flush() { enet_host_flush(_host); } void Host::bandwidthThrottle() { enet_host_bandwidth_throttle(_host); } void Host::bandwidthLimit(enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) { enet_host_bandwidth_limit(_host, incomingBandwidth, outgoingBandwidth); } int Host::checkEvents(Event& event) const { return enet_host_check_events(_host, &event._event); } }
32.02459
135
0.668032
dgu123
96444558a1df67b443e3e3b51efad318659be8e0
17,885
cpp
C++
system/test/preprocessor_tools_test.cpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
[ "MIT" ]
2
2020-11-19T03:23:35.000Z
2021-02-25T03:34:40.000Z
system/test/preprocessor_tools_test.cpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
[ "MIT" ]
null
null
null
system/test/preprocessor_tools_test.cpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
[ "MIT" ]
null
null
null
/******************************************************************************* MIT License Copyright (c) 2021 Romain Vinders 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 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. *******************************************************************************/ #ifdef _MSC_VER # define _CRT_SECURE_NO_WARNINGS #endif #if !defined(_MSC_VER) && !defined(__clang__) && defined(__GNUG__) && __GNUC__ > 7 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wstringop-truncation" #endif #include <cstdint> #include <string> #include <vector> #include <gtest/gtest.h> #include <system/force_inline.h> // include to force compiler check #include <system/preprocessor_tools.h> class PreprocessorToolsTest : public testing::Test { public: protected: //static void SetUpTestCase() {} //static void TearDownTestCase() {} void SetUp() override {} void TearDown() override {} __forceinline int forceInlineTest() const { return 42; } }; // -- expand/stringify macros -- TEST_F(PreprocessorToolsTest, expand) { int abc = 2; EXPECT_EQ(999, _P_EXPAND(999)); EXPECT_EQ(2.5, _P_EXPAND(2.5)); EXPECT_STREQ("abc", _P_EXPAND("abc")); EXPECT_EQ(abc, _P_EXPAND(abc)); } TEST_F(PreprocessorToolsTest, stringify) { EXPECT_STREQ("999", _P_STRINGIFY(999)); EXPECT_STREQ("2.5", _P_STRINGIFY(2.5)); EXPECT_STREQ("abc", _P_STRINGIFY(abc)); } // -- variadic macros -- TEST_F(PreprocessorToolsTest, getFirstArg) { int abc = 2, def = 4; EXPECT_EQ(5, _P_GET_FIRST_ARG(5, 7, 9, 11)); EXPECT_EQ(5, _P_GET_FIRST_ARG(5)); EXPECT_EQ(2.5, _P_GET_FIRST_ARG(2.5, 2.7, 2.9, 2.11)); EXPECT_EQ(2.5, _P_GET_FIRST_ARG(2.5)); EXPECT_STREQ("abc", _P_GET_FIRST_ARG("abc", "def")); EXPECT_STREQ("abc", _P_GET_FIRST_ARG("abc")); EXPECT_EQ(abc, _P_GET_FIRST_ARG(abc, def)); EXPECT_EQ(def, _P_GET_FIRST_ARG(def)); EXPECT_EQ(5, _P_GET_FIRST_ARG(5, 7.5, "abc", def)); } TEST_F(PreprocessorToolsTest, dropFirstArg) { std::vector<int> arrayInt { _P_DROP_FIRST_ARG(5, 7, 9, 11) }; ASSERT_EQ(size_t{ 3u }, arrayInt.size()); EXPECT_EQ(7, arrayInt[0]); EXPECT_EQ(9, arrayInt[1]); EXPECT_EQ(11, arrayInt[2]); std::vector<double> arrayDec { _P_DROP_FIRST_ARG(2.5, 2.7, 2.9, 2.11) }; ASSERT_EQ(size_t{ 3u }, arrayDec.size()); EXPECT_EQ(2.7, arrayDec[0]); EXPECT_EQ(2.9, arrayDec[1]); EXPECT_EQ(2.11, arrayDec[2]); std::vector<std::string> arrayStr { _P_DROP_FIRST_ARG("abc", "def", "ghi") }; ASSERT_EQ(size_t{ 2u }, arrayStr.size()); EXPECT_EQ(std::string("def"), arrayStr[0]); EXPECT_EQ(std::string("ghi"), arrayStr[1]); std::vector<int> arrayEmpty { _P_DROP_FIRST_ARG(5) }; EXPECT_EQ(size_t{ 0 }, arrayEmpty.size()); } TEST_F(PreprocessorToolsTest, getArgCount) { EXPECT_EQ(4, _P_GET_ARG_COUNT(5, 7, 9, 11)); EXPECT_EQ(4, _P_GET_ARG_COUNT(2.5, 2.7, 2.9, 2.11)); EXPECT_EQ(3, _P_GET_ARG_COUNT("abc", "def", "ghi")); EXPECT_EQ(4, _P_GET_ARG_COUNT(5, 2.7, "def", "ghi")); } #define _FOREACH_TEST(x) |x TEST_F(PreprocessorToolsTest, foreach) { int abc = 5 _P_FOREACH(_FOREACH_TEST, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); EXPECT_EQ((5|0|1|2|3|4|5|6|7|8|9), abc); } #undef _FOREACH_TEST #define _FOREACH_TEST(x) +x TEST_F(PreprocessorToolsTest, foreachString) { std::string abc = std::string("a") _P_FOREACH(_FOREACH_TEST, "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"); ASSERT_EQ(size_t{ 101u }, abc.size()); EXPECT_EQ(std::string("abcdefghijkbcdefghijkbcdefghijkbcdefghijkbcdefghijkbcdefghijkbcdefghijkbcdefghijkbcdefghijkbcdefghijk"), abc); } #undef _FOREACH_TEST TEST_F(PreprocessorToolsTest, foreachComma) { std::vector<int> array{ _P_FOREACH_COMMA(_P_EXPAND, 1, 2, 3, 4, 5, 6, 7, 8) }; ASSERT_EQ(size_t{ 8u }, array.size()); for (int i = 0; static_cast<size_t>(i) < array.size(); ++i) EXPECT_EQ(i+1, array[i]); } TEST_F(PreprocessorToolsTest, foreachCommaString) { std::vector<std::string> array{ _P_FOREACH_COMMA(_P_EXPAND, "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k") }; ASSERT_EQ(size_t{ 100u }, array.size()); EXPECT_EQ("b", array[0]); EXPECT_EQ("c", array[1]); EXPECT_EQ("k", array[99]); } #define _FOREACH_TEST(x) counter+=x TEST_F(PreprocessorToolsTest, foreachSemicolon) { int counter = 0; _P_FOREACH_SEMICOLON(_FOREACH_TEST, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); EXPECT_EQ(100, counter); } #undef _FOREACH_TEST #define _FOREACH_TEST(val, x) +(val << x) TEST_F(PreprocessorToolsTest, paramForeach) { int abc = 5 _P_PARAM_FOREACH(_FOREACH_TEST, 1, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4); EXPECT_EQ(5+20*0x1F, abc); } #undef _FOREACH_TEST // -- enumerations -- enum class DummyEnum: uint32_t { a, b, c, d, e, f, ghi }; _P_LIST_ENUM_VALUES(DummyEnum, all, a, b, c, d, e, f, ghi); _P_LIST_ENUM_VALUES(DummyEnum, repeat, a, a, b, b, a, b); _P_LIST_ENUM_VALUES(DummyEnum, odd, ghi, e, c, a); _P_SERIALIZABLE_ENUM(DummyEnum, a, b, c, d, e, f, ghi); _P_SERIALIZABLE_ENUM_BUFFER(DummyEnum, a, b, c, d, e, f, ghi); TEST_F(PreprocessorToolsTest, listEnumValues) { ASSERT_EQ(size_t{ 7u }, DummyEnum_all().size()); EXPECT_EQ(DummyEnum::a, DummyEnum_all()[0]); EXPECT_EQ(DummyEnum::b, DummyEnum_all()[1]); EXPECT_EQ(DummyEnum::c, DummyEnum_all()[2]); EXPECT_EQ(DummyEnum::d, DummyEnum_all()[3]); EXPECT_EQ(DummyEnum::e, DummyEnum_all()[4]); EXPECT_EQ(DummyEnum::f, DummyEnum_all()[5]); EXPECT_EQ(DummyEnum::ghi, DummyEnum_all()[6]); ASSERT_EQ(size_t{ 6u }, DummyEnum_repeat().size()); EXPECT_EQ(DummyEnum::a, DummyEnum_repeat()[0]); EXPECT_EQ(DummyEnum::a, DummyEnum_repeat()[1]); EXPECT_EQ(DummyEnum::b, DummyEnum_repeat()[2]); EXPECT_EQ(DummyEnum::b, DummyEnum_repeat()[3]); EXPECT_EQ(DummyEnum::a, DummyEnum_repeat()[4]); EXPECT_EQ(DummyEnum::b, DummyEnum_repeat()[5]); ASSERT_EQ(size_t{ 4u }, DummyEnum_odd().size()); EXPECT_EQ(DummyEnum::ghi, DummyEnum_odd()[0]); EXPECT_EQ(DummyEnum::e, DummyEnum_odd()[1]); EXPECT_EQ(DummyEnum::c, DummyEnum_odd()[2]); EXPECT_EQ(DummyEnum::a, DummyEnum_odd()[3]); } TEST_F(PreprocessorToolsTest, fromSerializableEnum) { EXPECT_EQ(std::string("a"), toString(DummyEnum::a)); EXPECT_EQ(std::string("b"), toString(DummyEnum::b)); EXPECT_EQ(std::string("c"), toString(DummyEnum::c)); EXPECT_EQ(std::string("d"), toString(DummyEnum::d)); EXPECT_EQ(std::string("e"), toString(DummyEnum::e)); EXPECT_EQ(std::string("f"), toString(DummyEnum::f)); EXPECT_EQ(std::string("ghi"), toString(DummyEnum::ghi)); EXPECT_EQ(std::string(""), toString((DummyEnum)123456)); bool result = false; result = (memcmp("a", toString<DummyEnum::a>(), size_t{ 2u }) == 0); EXPECT_TRUE(result); result = (memcmp("b", toString<DummyEnum::b>(), size_t{ 2u }) == 0); EXPECT_TRUE(result); result = (memcmp("c", toString<DummyEnum::c>(), size_t{ 2u }) == 0); EXPECT_TRUE(result); result = (memcmp("d", toString<DummyEnum::d>(), size_t{ 2u }) == 0); EXPECT_TRUE(result); result = (memcmp("e", toString<DummyEnum::e>(), size_t{ 2u }) == 0); EXPECT_TRUE(result); result = (memcmp("f", toString<DummyEnum::f>(), size_t{ 2u }) == 0); EXPECT_TRUE(result); result = (memcmp("ghi", toString<DummyEnum::ghi>(), size_t{ 4u }) == 0); EXPECT_TRUE(result); result = (memcmp("", toString<(DummyEnum)123456>(), size_t{ 1u }) == 0); EXPECT_TRUE(result); } TEST_F(PreprocessorToolsTest, fromSerializableEnumBuffered) { char buffer[256]{ 0 }; EXPECT_EQ(std::string("a"), std::string(toString(buffer, size_t{ 256u }, DummyEnum::a))); EXPECT_EQ(std::string("b"), std::string(toString(buffer, size_t{ 256u }, DummyEnum::b))); EXPECT_EQ(std::string("c"), std::string(toString(buffer, size_t{ 256u }, DummyEnum::c))); EXPECT_EQ(std::string("d"), std::string(toString(buffer, size_t{ 256u }, DummyEnum::d))); EXPECT_EQ(std::string("e"), std::string(toString(buffer, size_t{ 256u }, DummyEnum::e))); EXPECT_EQ(std::string("f"), std::string(toString(buffer, size_t{ 256u }, DummyEnum::f))); EXPECT_EQ(std::string("ghi"), std::string(toString(buffer, size_t{ 256u }, DummyEnum::ghi))); EXPECT_EQ(std::string("g"), std::string(toString(buffer, size_t{ 2u }, DummyEnum::ghi))); EXPECT_EQ(std::string(""), std::string(toString(buffer, size_t{ 256u }, (DummyEnum)123456))); } TEST_F(PreprocessorToolsTest, toSerializableEnum) { DummyEnum result = DummyEnum::a; EXPECT_TRUE(fromString("a", result)); EXPECT_EQ(DummyEnum::a, result); EXPECT_TRUE(fromString("b", result)); EXPECT_EQ(DummyEnum::b, result); EXPECT_TRUE(fromString("c", result)); EXPECT_EQ(DummyEnum::c, result); EXPECT_TRUE(fromString("d", result)); EXPECT_EQ(DummyEnum::d, result); EXPECT_TRUE(fromString("e", result)); EXPECT_EQ(DummyEnum::e, result); EXPECT_TRUE(fromString("f", result)); EXPECT_EQ(DummyEnum::f, result); EXPECT_TRUE(fromString("ghi", result)); EXPECT_EQ(DummyEnum::ghi, result); EXPECT_FALSE(fromString("azerty", result)); EXPECT_EQ(DummyEnum::ghi, result); } TEST_F(PreprocessorToolsTest, toSerializableEnumBuffered) { DummyEnum result = DummyEnum::a; EXPECT_TRUE(fromString("a", size_t{ 1u }, result)); EXPECT_EQ(DummyEnum::a, result); EXPECT_TRUE(fromString("b", size_t{ 1u }, result)); EXPECT_EQ(DummyEnum::b, result); EXPECT_TRUE(fromString("c", size_t{ 1u }, result)); EXPECT_EQ(DummyEnum::c, result); EXPECT_TRUE(fromString("d", size_t{ 1u }, result)); EXPECT_EQ(DummyEnum::d, result); EXPECT_TRUE(fromString("e", size_t{ 1u }, result)); EXPECT_EQ(DummyEnum::e, result); EXPECT_TRUE(fromString("f", size_t{ 1u }, result)); EXPECT_EQ(DummyEnum::f, result); EXPECT_TRUE(fromString("ghi", size_t{ 3u }, result)); EXPECT_EQ(DummyEnum::ghi, result); EXPECT_FALSE(fromString("azerty", size_t{ 6u }, result)); EXPECT_EQ(DummyEnum::ghi, result); } TEST_F(PreprocessorToolsTest, toFromSerializableListedEnum) { DummyEnum result = DummyEnum::a; for (auto it : DummyEnum_all()) { EXPECT_TRUE(fromString(toString(it), result)); EXPECT_EQ(it, result); } } TEST_F(PreprocessorToolsTest, toFromSerializableListedEnumBuffered) { char buffer[256]{ 0 }; DummyEnum result = DummyEnum::a; for (auto it : DummyEnum_all()) { EXPECT_TRUE(fromString(toString(buffer, size_t{ 256u }, it), (it == DummyEnum::ghi) ? size_t{ 3u } : size_t{ 1u }, result)); EXPECT_EQ(it, result); } } // -- flags -- enum class FlagEnum: uint32_t { none = 0, b = 1, c = 2, d = 4, e = 8 }; _P_FLAGS_OPERATORS(FlagEnum, uint32_t); TEST_F(PreprocessorToolsTest, flagCompare) { EXPECT_TRUE(FlagEnum::none != true); EXPECT_TRUE(FlagEnum::b == true); EXPECT_TRUE(FlagEnum::c == true); EXPECT_TRUE(FlagEnum::d == true); EXPECT_TRUE(FlagEnum::none == false); EXPECT_TRUE(FlagEnum::b != false); EXPECT_TRUE(FlagEnum::c != false); EXPECT_TRUE(FlagEnum::d != false); EXPECT_FALSE(FlagEnum::none < FlagEnum::none); EXPECT_TRUE(FlagEnum::none <= FlagEnum::none); EXPECT_FALSE(FlagEnum::none > FlagEnum::none); EXPECT_TRUE(FlagEnum::none >= FlagEnum::none); EXPECT_TRUE(FlagEnum::none < FlagEnum::b); EXPECT_TRUE(FlagEnum::none <= FlagEnum::b); EXPECT_FALSE(FlagEnum::none > FlagEnum::b); EXPECT_FALSE(FlagEnum::none >= FlagEnum::b); EXPECT_TRUE(FlagEnum::b < FlagEnum::d); EXPECT_TRUE(FlagEnum::b <= FlagEnum::d); EXPECT_FALSE(FlagEnum::b > FlagEnum::d); EXPECT_FALSE(FlagEnum::b >= FlagEnum::d); } TEST_F(PreprocessorToolsTest, flagOperation) { EXPECT_EQ(FlagEnum::none, FlagEnum::none&FlagEnum::b); EXPECT_EQ(FlagEnum::b, FlagEnum::none|FlagEnum::b); EXPECT_EQ(FlagEnum::b, FlagEnum::none^FlagEnum::b); EXPECT_EQ(((uint32_t)-1) ^ 1, (uint32_t)~FlagEnum::b); EXPECT_EQ(FlagEnum::none, FlagEnum::b&FlagEnum::c); EXPECT_EQ(3, (int)(FlagEnum::b|FlagEnum::c)); EXPECT_EQ(3, (int)(FlagEnum::b^FlagEnum::c)); EXPECT_EQ(FlagEnum::c, (FlagEnum)(3)&FlagEnum::c); EXPECT_EQ(3, (int)((FlagEnum)3|FlagEnum::c)); EXPECT_EQ(FlagEnum::b, (FlagEnum)(3)^FlagEnum::c); FlagEnum abc = FlagEnum::b; abc &= FlagEnum::b; EXPECT_EQ(FlagEnum::b, abc); abc |= FlagEnum::c; EXPECT_EQ(3, (int)abc); abc ^= FlagEnum::c; EXPECT_EQ(FlagEnum::b, abc); abc &= FlagEnum::d; EXPECT_EQ(FlagEnum::none, abc); } TEST_F(PreprocessorToolsTest, flagAddRemove) { FlagEnum abc = FlagEnum::none; addFlag(abc, FlagEnum::b); EXPECT_EQ(FlagEnum::b, abc); addFlag(abc, FlagEnum::c); EXPECT_EQ(3, (int)abc); removeFlag(abc, FlagEnum::c); EXPECT_EQ(FlagEnum::b, abc); } // -- duplication -- TEST_F(PreprocessorToolsTest, duplicate) { int abc = 0 _P_DUPLICATE_64X(+1); EXPECT_EQ(64, abc); abc = 0 _P_DUPLICATE_48X(+1); EXPECT_EQ(48, abc); abc = 0 _P_DUPLICATE_24X(+1); EXPECT_EQ(24, abc); abc = 0 _P_DUPLICATE_12X(+1); EXPECT_EQ(12, abc); abc = 0 _P_DUPLICATE_10X(+1); EXPECT_EQ(10, abc); abc = 0 _P_DUPLICATE_9X(+1); EXPECT_EQ(9, abc); abc = 0 _P_DUPLICATE_7X(+1); EXPECT_EQ(7, abc); } TEST_F(PreprocessorToolsTest, duplicateComma) { std::vector<int> array{ _P_DUPLICATE_64X_COMMA(42) }; EXPECT_EQ(size_t{ 64u }, array.size()); for (auto it : array) { EXPECT_EQ(42, it); } array = { _P_DUPLICATE_48X_COMMA(42) }; EXPECT_EQ(size_t{ 48u }, array.size()); array = { _P_DUPLICATE_24X_COMMA(42) }; EXPECT_EQ(size_t{ 24u }, array.size()); array = { _P_DUPLICATE_12X_COMMA(42) }; EXPECT_EQ(size_t{ 12u }, array.size()); array = { _P_DUPLICATE_10X_COMMA(42) }; EXPECT_EQ(size_t{ 10u }, array.size()); array = { _P_DUPLICATE_9X_COMMA(42) }; EXPECT_EQ(size_t{ 9u }, array.size()); array = { _P_DUPLICATE_7X_COMMA(42) }; EXPECT_EQ(size_t{ 7u }, array.size()); } TEST_F(PreprocessorToolsTest, duplicateSemicolon) { int counter = 0; _P_DUPLICATE_64X_SEMICOLON(++counter); EXPECT_EQ(64, counter); counter = 0; _P_DUPLICATE_48X_SEMICOLON(++counter); EXPECT_EQ(48, counter); counter = 0; _P_DUPLICATE_24X_SEMICOLON(++counter); EXPECT_EQ(24, counter); counter = 0; _P_DUPLICATE_12X_SEMICOLON(++counter); EXPECT_EQ(12, counter); counter = 0; _P_DUPLICATE_10X_SEMICOLON(++counter); EXPECT_EQ(10, counter); counter = 0; _P_DUPLICATE_9X_SEMICOLON(++counter); EXPECT_EQ(9, counter); counter = 0; _P_DUPLICATE_7X_SEMICOLON(++counter); EXPECT_EQ(7, counter); } // -- force inline -- TEST_F(PreprocessorToolsTest, forceInlineMethod) { EXPECT_EQ(42, forceInlineTest()); } #if !defined(_MSC_VER) && !defined(__clang__) && defined(__GNUG__) && __GNUC__ > 5 # pragma GCC diagnostic pop #endif
38.462366
135
0.601342
vinders
9645aa2ab6dbd5e765fff8cc431bc20f5a56dfb0
6,234
cpp
C++
src/sigspm/spmtest.cpp
Hexlord/sig
50be810f3f56e79e56110165972b7911d7519281
[ "Apache-2.0" ]
null
null
null
src/sigspm/spmtest.cpp
Hexlord/sig
50be810f3f56e79e56110165972b7911d7519281
[ "Apache-2.0" ]
null
null
null
src/sigspm/spmtest.cpp
Hexlord/sig
50be810f3f56e79e56110165972b7911d7519281
[ "Apache-2.0" ]
null
null
null
# pragma once # include <sig/gs_vars.h> # include <sig/sn_poly_editor.h> # include <sig/sn_lines.h> # include <sigogl/gl_texture.h> # include <sigogl/gl_resources.h> # include <sigogl/ui_radio_button.h> # include <sigogl/ws_viewer.h> # include <sigogl/ws_run.h> # include "spm_manager.h" class SpmViewer : public WsViewer { public: // ui: enum MenuEv { EvBuild, EvAutoBuild, EvMode, EvExit }; UiRadioButton *_obstbut, *_sinkbut; UiCheckButton *_abbut; public: // scene: SnPolygons *_domain; SnPolyEditor *_sinks; SnPolyEditor *_obstacles; SnPlanarObjects* SpmPlane; SnLines *_path; public: // spm data: GlTexture SpmTexture; ShortestPathMap* Spm; ShortestPathMapManager SpmManager; std::vector<GsVec> SpmPath; public: SpmViewer ( int x, int y, int w, int h, const char* l ); void refresh () { render(); ws_fast_check(); } void build (); void get_path ( float x, float y ); virtual int uievent ( int e ) override; virtual int handle_scene_event ( const GsEvent& e ) override; }; static void polyeditor_callback ( SnPolyEditor* pe, SnPolyEditor::Event e, int pid ) { SpmViewer* v = (SpmViewer*)pe->userdata(); if ( !v->_abbut->value() ) return; if ( e==SnPolyEditor::PostMovement || e==SnPolyEditor::PostEdition || e==SnPolyEditor::PostInsertion || e==SnPolyEditor::PostRemoval ) { v->build(); if ( !v->_path->empty() ) v->get_path( v->SpmPath[0].x, v->SpmPath[0].y ); } } SpmViewer::SpmViewer ( int x, int y, int w, int h, const char* l ) : WsViewer( x, y, w, h, l ) { // Define domain boundaries: const float minx=-12, miny=-12, maxx=12, maxy=12; // Define a plane to display the spm as a texture: SnGroup* g = rootg(); g->add ( SpmPlane = new SnPlanarObjects ); // will initialize plane after 1st spm is built GsRect rect ( minx, miny, maxx-minx, maxy-miny ); SpmPlane->zcoordinate = -0.01f; SpmPlane->start_group ( SnPlanarObjects::Textured, 0 ); // texture id will be set after ogl is initialized SpmPlane->push_rect ( rect, GsColor::gray ); SpmPlane->setT ( 0, GsPnt2( 0, 0 ), GsPnt2( 1, 0 ), GsPnt2( 1, 1 ), GsPnt2( 0, 1 ) ); // Define the non-editable domain polygon: g->add ( _domain = new SnPolygons ); _domain->push().rectangle ( minx, miny, maxx, maxy ); _domain->draw_mode ( 0, 0 ); _domain->ecolor ( GsColor::black ); // Define an editable initial sink segment: g->add ( _sinks = new SnPolyEditor ); _sinks->polygons()->push().setpoly ( "5 -5 5 5", true ); // the SPM sink _sinks->solid_drawing ( 0 ); _sinks->polyline_mode ( true ); _sinks->min_polygons ( 1 ); // need to always have a source _sinks->set_limits ( minx, maxx, miny, maxy ); _sinks->mode ( SnPolyEditor::ModeNoEdition ); _sinks->callback ( polyeditor_callback, this ); // Define an editable obstacle: g->add ( _obstacles = new SnPolyEditor ); _obstacles->solid_drawing ( 0 ); _obstacles->set_limits ( minx, maxx, miny, maxy ); _obstacles->callback ( polyeditor_callback, this ); _obstacles->polygons()->push().setpoly ( "-2 -5 0 0 -2 5" ); // define one obstacle // Define scene node to show a path: g->add ( _path = new SnLines ); // Initiaze Spm objects: Spm = 0; SpmManager.SetDomain ( _domain->cget(0) ); SpmManager.SetEnv ( _obstacles->polygons(), _sinks->polygons() ); GlResources::configuration()->add("oglfuncs",500); // need to load more OpenGL functions then the default number const char* shadersfolder = 0;//"../src/sigspm/shaders/"; // Use this to load external shaders if ( shadersfolder ) { SpmManager.SetShadersFolder ( shadersfolder ); // to load shaders instead of using the pre-defined ones if ( !SpmManager.CanLoadShaders() ) gsout.fatal("Cannot find spm shaders in: %s",shadersfolder); } // Build ui: UiPanel *p, *sp; p = uim()->add_panel ( 0, UiPanel::HorizLeft, UiPanel::Top ); p->add ( new UiButton ( "build", EvBuild ) ); p->add ( new UiButton ( "mode", sp=new UiPanel(0,UiPanel::Vertical) ) ); { UiPanel* p=sp; p->add( _obstbut=new UiRadioButton( "obstacles", EvMode, true ) ); p->add( _sinkbut=new UiRadioButton( "sink", EvMode, false ) ); p->add ( _abbut=new UiCheckButton ( "auto build", EvAutoBuild, true ) ); p->top()->separate(); } p->add ( new UiButton ( "exit", EvExit ) ); p->top()->separate(); } void SpmViewer::build () { activate_ogl_context(); Spm = SpmManager.Compute ( glrenderer()->glcontext(), Spm ); //xxx: computation is not correct when there are no obstacles? SpmTexture.data ( Spm->GetMapBuffer(), Spm->Width(), Spm->Height(), GlTexture::Linear ); SpmPlane->G[0].texid = SpmTexture.id; // only needed for first time the id is created } void SpmViewer::get_path ( float x, float y ) { if ( !Spm ) return; Spm->GetShortestPath ( x, y, SpmPath ); _path->init (); _path->line_width ( 2.0f ); _path->color ( GsColor::red ); _path->begin_polyline(); for ( int i=0, s=SpmPath.size(); i<s; i++ ) _path->push(SpmPath[i]); _path->end_polyline(); } int SpmViewer::uievent ( int e ) { switch ( e ) { case EvMode: _obstacles->mode ( _obstbut->value()? SnPolyEditor::ModeEdit : SnPolyEditor::ModeNoEdition ); _sinks->mode ( _sinkbut->value()? SnPolyEditor::ModeEdit : SnPolyEditor::ModeNoEdition ); break; case EvAutoBuild: if ( _abbut->value() ) { build(); refresh(); } break; case EvBuild: build(); refresh(); break; case EvExit: gs_exit(); } return WsViewer::uievent(e); } int SpmViewer::handle_scene_event ( const GsEvent& e ) { if ( Spm && e.alt && e.button1 && (e.type==GsEvent::Push||e.type==GsEvent::Drag) ) { get_path ( e.mousep.x, e.mousep.y ); render(); return 1; } return WsViewer::handle_scene_event(e); } int main ( int argc, char** argv ) { SpmViewer* v = new SpmViewer( -1, -1, 800, 600, "SIG SPM!" ); v->cmd ( WsViewer::VCmdPlanar ); GsCamera cam; v->camera().eye.z = 25.0f; v->root()->visible(false); // do not show unitialized texture that will contain the spm v->show (); // request window to show v->refresh (); // forces window to show and OpenGL to initialize now v->root()->visible(true); // after initialization we can draw the scene v->build (); // now we can use OpenGL to draw the first spm v->message ( "Press Esc to switch between polygon creation and edition mode. Alt-left click to query path." ); ws_run (); return 1; }
34.441989
113
0.675008
Hexlord
9646cd98ebe3115856182d1ed9135977190899a2
22,222
cc
C++
components/favicon/core/large_icon_service_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/favicon/core/large_icon_service_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/favicon/core/large_icon_service_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/favicon/core/large_icon_service.h" #include <deque> #include <memory> #include "base/bind.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted_memory.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/task/cancelable_task_tracker.h" #include "base/test/histogram_tester.h" #include "base/test/mock_callback.h" #include "base/threading/thread_task_runner_handle.h" #include "components/favicon/core/favicon_client.h" #include "components/favicon/core/test/mock_favicon_service.h" #include "components/favicon_base/fallback_icon_style.h" #include "components/favicon_base/favicon_types.h" #include "components/image_fetcher/core/image_fetcher.h" #include "components/image_fetcher/core/request_metadata.h" #include "components/variations/variations_params_manager.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" #include "url/gurl.h" namespace favicon { namespace { using testing::IsEmpty; using testing::IsNull; using testing::Eq; using testing::HasSubstr; using testing::NiceMock; using testing::Not; using testing::Property; using testing::Return; using testing::SaveArg; using testing::_; const char kDummyUrl[] = "http://www.example.com"; const char kDummyIconUrl[] = "http://www.example.com/touch_icon.png"; const SkColor kTestColor = SK_ColorRED; ACTION_P(PostFetchReply, p0) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(arg2, arg0, p0, image_fetcher::RequestMetadata())); } ACTION_P2(PostFetchReplyWithMetadata, p0, p1) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(arg2, arg0, p0, p1)); } ACTION_P(PostBoolReply, p0) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(arg4, p0)); } SkBitmap CreateTestSkBitmap(int w, int h, SkColor color) { SkBitmap bitmap; bitmap.allocN32Pixels(w, h); bitmap.eraseColor(color); return bitmap; } favicon_base::FaviconRawBitmapResult CreateTestBitmapResult(int w, int h, SkColor color) { favicon_base::FaviconRawBitmapResult result; result.expired = false; // Create bitmap and fill with |color|. scoped_refptr<base::RefCountedBytes> data(new base::RefCountedBytes()); SkBitmap bitmap; bitmap.allocN32Pixels(w, h); bitmap.eraseColor(color); gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &data->data()); result.bitmap_data = data; result.pixel_size = gfx::Size(w, h); result.icon_url = GURL(kDummyIconUrl); result.icon_type = favicon_base::TOUCH_ICON; CHECK(result.is_valid()); return result; } bool HasBackgroundColor( const favicon_base::FallbackIconStyle& fallback_icon_style, SkColor color) { return !fallback_icon_style.is_default_background_color && fallback_icon_style.background_color == color; } class MockImageFetcher : public image_fetcher::ImageFetcher { public: MOCK_METHOD1(SetImageFetcherDelegate, void(image_fetcher::ImageFetcherDelegate* delegate)); MOCK_METHOD1(SetDataUseServiceName, void(image_fetcher::ImageFetcher::DataUseServiceName name)); MOCK_METHOD1(SetImageDownloadLimit, void(base::Optional<int64_t> max_download_bytes)); MOCK_METHOD1(SetDesiredImageFrameSize, void(const gfx::Size& size)); MOCK_METHOD4(StartOrQueueNetworkRequest, void(const std::string&, const GURL&, const ImageFetcherCallback&, const net::NetworkTrafficAnnotationTag&)); MOCK_METHOD0(GetImageDecoder, image_fetcher::ImageDecoder*()); }; // TODO(jkrcal): Make the tests a bit crisper, see crbug.com/725822. class LargeIconServiceTest : public testing::Test { public: LargeIconServiceTest() : mock_image_fetcher_(new NiceMock<MockImageFetcher>()), large_icon_service_(&mock_favicon_service_, base::ThreadTaskRunnerHandle::Get(), base::WrapUnique(mock_image_fetcher_)) {} ~LargeIconServiceTest() override {} protected: base::MessageLoopForIO loop_; NiceMock<MockImageFetcher>* mock_image_fetcher_; testing::NiceMock<MockFaviconService> mock_favicon_service_; LargeIconService large_icon_service_; base::HistogramTester histogram_tester_; private: DISALLOW_COPY_AND_ASSIGN(LargeIconServiceTest); }; TEST_F(LargeIconServiceTest, ShouldGetFromGoogleServer) { const GURL kExpectedServerUrl( "https://t0.gstatic.com/faviconV2?client=chrome&drop_404_icon=true" "&check_seen=true&size=61&min_size=42&max_size=122" "&fallback_opts=TYPE,SIZE,URL&url=http://www.example.com/"); EXPECT_CALL(mock_favicon_service_, UnableToDownloadFavicon(_)).Times(0); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; EXPECT_CALL(*mock_image_fetcher_, StartOrQueueNetworkRequest(_, kExpectedServerUrl, _, _)) .WillOnce(PostFetchReply(gfx::Image::CreateFrom1xBitmap( CreateTestSkBitmap(64, 64, kTestColor)))); EXPECT_CALL(mock_favicon_service_, SetOnDemandFavicons(GURL(kDummyUrl), kExpectedServerUrl, favicon_base::IconType::TOUCH_ICON, _, _)) .WillOnce(PostBoolReply(true)); large_icon_service_ .GetLargeIconOrFallbackStyleFromGoogleServerSkippingLocalCache( GURL(kDummyUrl), /*min_source_size_in_pixel=*/42, /*desired_size_in_pixel=*/61, /*may_page_url_be_private=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, callback.Get()); EXPECT_CALL(callback, Run(favicon_base::GoogleFaviconServerRequestStatus::SUCCESS)); base::RunLoop().RunUntilIdle(); histogram_tester_.ExpectUniqueSample( "Favicons.LargeIconService.DownloadedSize", 64, /*expected_count=*/1); } TEST_F(LargeIconServiceTest, ShouldGetFromGoogleServerWithCustomUrl) { variations::testing::VariationParamsManager variation_params( "LargeIconServiceFetching", {{"request_format", "https://t0.gstatic.com/" "faviconV2?%ssize=%d&min_size=%d&max_size=%d&url=%s"}, {"enforced_min_size_in_pixel", "43"}, {"desired_to_max_size_factor", "1.5"}}, {"LargeIconServiceFetching"}); const GURL kExpectedServerUrl( "https://t0.gstatic.com/faviconV2?check_seen=true&" "size=61&min_size=43&max_size=91&url=http://www.example.com/"); EXPECT_CALL(mock_favicon_service_, UnableToDownloadFavicon(_)).Times(0); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; EXPECT_CALL(*mock_image_fetcher_, StartOrQueueNetworkRequest(_, kExpectedServerUrl, _, _)) .WillOnce(PostFetchReply(gfx::Image::CreateFrom1xBitmap( CreateTestSkBitmap(64, 64, kTestColor)))); EXPECT_CALL(mock_favicon_service_, SetOnDemandFavicons(GURL(kDummyUrl), kExpectedServerUrl, favicon_base::IconType::TOUCH_ICON, _, _)) .WillOnce(PostBoolReply(true)); large_icon_service_ .GetLargeIconOrFallbackStyleFromGoogleServerSkippingLocalCache( GURL(kDummyUrl), /*min_source_size_in_pixel=*/42, /*desired_size_in_pixel=*/61, /*may_page_url_be_private=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, callback.Get()); EXPECT_CALL(callback, Run(favicon_base::GoogleFaviconServerRequestStatus::SUCCESS)); base::RunLoop().RunUntilIdle(); } TEST_F(LargeIconServiceTest, ShouldGetFromGoogleServerWithOriginalUrl) { const GURL kExpectedServerUrl( "https://t0.gstatic.com/faviconV2?client=chrome&drop_404_icon=true" "&check_seen=true&size=61&min_size=42&max_size=122" "&fallback_opts=TYPE,SIZE,URL&url=http://www.example.com/"); const GURL kExpectedOriginalUrl("http://www.example.com/favicon.png"); image_fetcher::RequestMetadata expected_metadata; expected_metadata.content_location_header = kExpectedOriginalUrl.spec(); EXPECT_CALL(*mock_image_fetcher_, StartOrQueueNetworkRequest(_, kExpectedServerUrl, _, _)) .WillOnce(PostFetchReplyWithMetadata( gfx::Image::CreateFrom1xBitmap( CreateTestSkBitmap(64, 64, kTestColor)), expected_metadata)); EXPECT_CALL(mock_favicon_service_, SetOnDemandFavicons(GURL(kDummyUrl), kExpectedOriginalUrl, favicon_base::IconType::TOUCH_ICON, _, _)) .WillOnce(PostBoolReply(true)); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; large_icon_service_ .GetLargeIconOrFallbackStyleFromGoogleServerSkippingLocalCache( GURL(kDummyUrl), /*min_source_size_in_pixel=*/42, /*desired_size_in_pixel=*/61, /*may_page_url_be_private=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, callback.Get()); EXPECT_CALL(callback, Run(favicon_base::GoogleFaviconServerRequestStatus::SUCCESS)); base::RunLoop().RunUntilIdle(); } TEST_F(LargeIconServiceTest, ShouldTrimQueryParametersForGoogleServer) { const GURL kDummyUrlWithQuery("http://www.example.com?foo=1"); const GURL kExpectedServerUrl( "https://t0.gstatic.com/faviconV2?client=chrome&drop_404_icon=true" "&check_seen=true&size=61&min_size=42&max_size=122" "&fallback_opts=TYPE,SIZE,URL&url=http://www.example.com/"); EXPECT_CALL(*mock_image_fetcher_, StartOrQueueNetworkRequest(_, kExpectedServerUrl, _, _)) .WillOnce(PostFetchReply(gfx::Image::CreateFrom1xBitmap( CreateTestSkBitmap(64, 64, kTestColor)))); // Verify that the non-trimmed page URL is used when writing to the database. EXPECT_CALL(mock_favicon_service_, SetOnDemandFavicons(_, kExpectedServerUrl, _, _, _)); large_icon_service_ .GetLargeIconOrFallbackStyleFromGoogleServerSkippingLocalCache( GURL(kDummyUrlWithQuery), /*min_source_size_in_pixel=*/42, /*desired_size_in_pixel=*/61, /*may_page_url_be_private=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, favicon_base::GoogleFaviconServerCallback()); base::RunLoop().RunUntilIdle(); } TEST_F(LargeIconServiceTest, ShouldNotCheckOnPublicUrls) { // The request has no "check_seen=true"; full URL is tested elsewhere. EXPECT_CALL( *mock_image_fetcher_, StartOrQueueNetworkRequest( _, Property(&GURL::query, Not(HasSubstr("check_seen=true"))), _, _)) .WillOnce(PostFetchReply(gfx::Image())); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; large_icon_service_ .GetLargeIconOrFallbackStyleFromGoogleServerSkippingLocalCache( GURL(kDummyUrl), /*min_source_size_in_pixel=*/42, /*desired_size_in_pixel=*/61, /*may_page_url_be_private=*/false, TRAFFIC_ANNOTATION_FOR_TESTS, callback.Get()); EXPECT_CALL(callback, Run(favicon_base::GoogleFaviconServerRequestStatus:: FAILURE_CONNECTION_ERROR)); base::RunLoop().RunUntilIdle(); } TEST_F(LargeIconServiceTest, ShouldNotQueryGoogleServerIfInvalidScheme) { const GURL kDummyFtpUrl("ftp://www.example.com"); EXPECT_CALL(*mock_image_fetcher_, StartOrQueueNetworkRequest(_, _, _, _)) .Times(0); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; large_icon_service_ .GetLargeIconOrFallbackStyleFromGoogleServerSkippingLocalCache( GURL(kDummyFtpUrl), /*min_source_size_in_pixel=*/42, /*desired_size_in_pixel=*/61, /*may_page_url_be_private=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, callback.Get()); EXPECT_CALL( callback, Run(favicon_base::GoogleFaviconServerRequestStatus::FAILURE_INVALID)); base::RunLoop().RunUntilIdle(); EXPECT_THAT(histogram_tester_.GetAllSamples( "Favicons.LargeIconService.DownloadedSize"), IsEmpty()); } TEST_F(LargeIconServiceTest, ShouldReportUnavailableIfFetchFromServerFails) { const GURL kDummyUrlWithQuery("http://www.example.com?foo=1"); const GURL kExpectedServerUrl( "https://t0.gstatic.com/faviconV2?client=chrome&drop_404_icon=true" "&check_seen=true&size=61&min_size=42&max_size=122" "&fallback_opts=TYPE,SIZE,URL&url=http://www.example.com/"); EXPECT_CALL(mock_favicon_service_, SetOnDemandFavicons(_, _, _, _, _)) .Times(0); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; EXPECT_CALL(*mock_image_fetcher_, StartOrQueueNetworkRequest(_, kExpectedServerUrl, _, _)) .WillOnce(PostFetchReply(gfx::Image())); EXPECT_CALL(mock_favicon_service_, UnableToDownloadFavicon(kExpectedServerUrl)); large_icon_service_ .GetLargeIconOrFallbackStyleFromGoogleServerSkippingLocalCache( kDummyUrlWithQuery, /*min_source_size_in_pixel=*/42, /*desired_size_in_pixel=*/61, /*may_page_url_be_private=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, callback.Get()); EXPECT_CALL(callback, Run(favicon_base::GoogleFaviconServerRequestStatus:: FAILURE_CONNECTION_ERROR)); base::RunLoop().RunUntilIdle(); // Verify that download failure gets recorded. histogram_tester_.ExpectUniqueSample( "Favicons.LargeIconService.DownloadedSize", 0, /*expected_count=*/1); } TEST_F(LargeIconServiceTest, ShouldNotGetFromGoogleServerIfUnavailable) { ON_CALL( mock_favicon_service_, WasUnableToDownloadFavicon(GURL( "https://t0.gstatic.com/faviconV2?client=chrome&drop_404_icon=true" "&check_seen=true&size=61&min_size=42&max_size=122" "&fallback_opts=TYPE,SIZE,URL&url=http://www.example.com/"))) .WillByDefault(Return(true)); EXPECT_CALL(mock_favicon_service_, UnableToDownloadFavicon(_)).Times(0); EXPECT_CALL(*mock_image_fetcher_, StartOrQueueNetworkRequest(_, _, _, _)) .Times(0); EXPECT_CALL(mock_favicon_service_, SetOnDemandFavicons(_, _, _, _, _)) .Times(0); base::MockCallback<favicon_base::GoogleFaviconServerCallback> callback; large_icon_service_ .GetLargeIconOrFallbackStyleFromGoogleServerSkippingLocalCache( GURL(kDummyUrl), /*min_source_size_in_pixel=*/42, /*desired_size_in_pixel=*/61, /*may_page_url_be_private=*/true, TRAFFIC_ANNOTATION_FOR_TESTS, callback.Get()); EXPECT_CALL(callback, Run(favicon_base::GoogleFaviconServerRequestStatus:: FAILURE_HTTP_ERROR_CACHED)); base::RunLoop().RunUntilIdle(); EXPECT_THAT(histogram_tester_.GetAllSamples( "Favicons.LargeIconService.DownloadedSize"), IsEmpty()); } class LargeIconServiceGetterTest : public LargeIconServiceTest, public ::testing::WithParamInterface<bool> { public: LargeIconServiceGetterTest() : LargeIconServiceTest() {} ~LargeIconServiceGetterTest() override {} void GetLargeIconOrFallbackStyleAndWaitForCallback( const GURL& page_url, int min_source_size_in_pixel, int desired_size_in_pixel) { // Switch over testing two analogous functions based on the bool param. if (GetParam()) { large_icon_service_.GetLargeIconOrFallbackStyle( page_url, min_source_size_in_pixel, desired_size_in_pixel, base::Bind(&LargeIconServiceGetterTest::RawBitmapResultCallback, base::Unretained(this)), &cancelable_task_tracker_); } else { large_icon_service_.GetLargeIconImageOrFallbackStyle( page_url, min_source_size_in_pixel, desired_size_in_pixel, base::Bind(&LargeIconServiceGetterTest::ImageResultCallback, base::Unretained(this)), &cancelable_task_tracker_); } base::RunLoop().RunUntilIdle(); } void RawBitmapResultCallback(const favicon_base::LargeIconResult& result) { if (result.bitmap.is_valid()) { returned_bitmap_size_ = base::MakeUnique<gfx::Size>(result.bitmap.pixel_size); } StoreFallbackStyle(result.fallback_icon_style.get()); } void ImageResultCallback(const favicon_base::LargeIconImageResult& result) { if (!result.image.IsEmpty()) { returned_bitmap_size_ = base::MakeUnique<gfx::Size>(result.image.ToImageSkia()->size()); ASSERT_TRUE(result.icon_url.is_valid()); } StoreFallbackStyle(result.fallback_icon_style.get()); } void StoreFallbackStyle( const favicon_base::FallbackIconStyle* fallback_style) { if (fallback_style) { returned_fallback_style_ = base::MakeUnique<favicon_base::FallbackIconStyle>(*fallback_style); } } void InjectMockResult( const GURL& page_url, const favicon_base::FaviconRawBitmapResult& mock_result) { ON_CALL(mock_favicon_service_, GetLargestRawFaviconForPageURL(page_url, _, _, _, _)) .WillByDefault(PostReply<5>(mock_result)); } protected: base::CancelableTaskTracker cancelable_task_tracker_; std::unique_ptr<favicon_base::FallbackIconStyle> returned_fallback_style_; std::unique_ptr<gfx::Size> returned_bitmap_size_; private: DISALLOW_COPY_AND_ASSIGN(LargeIconServiceGetterTest); }; TEST_P(LargeIconServiceGetterTest, SameSize) { InjectMockResult(GURL(kDummyUrl), CreateTestBitmapResult(24, 24, kTestColor)); GetLargeIconOrFallbackStyleAndWaitForCallback( GURL(kDummyUrl), 24, // |min_source_size_in_pixel| 24); // |desired_size_in_pixel| EXPECT_EQ(gfx::Size(24, 24), *returned_bitmap_size_); EXPECT_EQ(nullptr, returned_fallback_style_); } TEST_P(LargeIconServiceGetterTest, ScaleDown) { InjectMockResult(GURL(kDummyUrl), CreateTestBitmapResult(32, 32, kTestColor)); GetLargeIconOrFallbackStyleAndWaitForCallback(GURL(kDummyUrl), 24, 24); EXPECT_EQ(gfx::Size(24, 24), *returned_bitmap_size_); EXPECT_EQ(nullptr, returned_fallback_style_); } TEST_P(LargeIconServiceGetterTest, ScaleUp) { InjectMockResult(GURL(kDummyUrl), CreateTestBitmapResult(16, 16, kTestColor)); GetLargeIconOrFallbackStyleAndWaitForCallback( GURL(kDummyUrl), 14, // Lowered requirement so stored bitmap is admitted. 24); EXPECT_EQ(gfx::Size(24, 24), *returned_bitmap_size_); EXPECT_EQ(nullptr, returned_fallback_style_); } // |desired_size_in_pixel| == 0 means retrieve original image without scaling. TEST_P(LargeIconServiceGetterTest, NoScale) { InjectMockResult(GURL(kDummyUrl), CreateTestBitmapResult(24, 24, kTestColor)); GetLargeIconOrFallbackStyleAndWaitForCallback(GURL(kDummyUrl), 16, 0); EXPECT_EQ(gfx::Size(24, 24), *returned_bitmap_size_); EXPECT_EQ(nullptr, returned_fallback_style_); } TEST_P(LargeIconServiceGetterTest, FallbackSinceIconTooSmall) { InjectMockResult(GURL(kDummyUrl), CreateTestBitmapResult(16, 16, kTestColor)); GetLargeIconOrFallbackStyleAndWaitForCallback(GURL(kDummyUrl), 24, 24); EXPECT_EQ(nullptr, returned_bitmap_size_); EXPECT_TRUE(HasBackgroundColor(*returned_fallback_style_, kTestColor)); histogram_tester_.ExpectUniqueSample("Favicons.LargeIconService.FallbackSize", 16, /*expected_count=*/1); } TEST_P(LargeIconServiceGetterTest, FallbackSinceIconNotSquare) { InjectMockResult(GURL(kDummyUrl), CreateTestBitmapResult(24, 32, kTestColor)); GetLargeIconOrFallbackStyleAndWaitForCallback(GURL(kDummyUrl), 24, 24); EXPECT_EQ(nullptr, returned_bitmap_size_); EXPECT_TRUE(HasBackgroundColor(*returned_fallback_style_, kTestColor)); histogram_tester_.ExpectUniqueSample("Favicons.LargeIconService.FallbackSize", 24, /*expected_count=*/1); } TEST_P(LargeIconServiceGetterTest, FallbackSinceIconMissing) { InjectMockResult(GURL(kDummyUrl), favicon_base::FaviconRawBitmapResult()); GetLargeIconOrFallbackStyleAndWaitForCallback(GURL(kDummyUrl), 24, 24); EXPECT_EQ(nullptr, returned_bitmap_size_); EXPECT_TRUE(returned_fallback_style_->is_default_background_color); histogram_tester_.ExpectUniqueSample("Favicons.LargeIconService.FallbackSize", 0, /*expected_count=*/1); } TEST_P(LargeIconServiceGetterTest, FallbackSinceIconMissingNoScale) { InjectMockResult(GURL(kDummyUrl), favicon_base::FaviconRawBitmapResult()); GetLargeIconOrFallbackStyleAndWaitForCallback(GURL(kDummyUrl), 24, 0); EXPECT_EQ(nullptr, returned_bitmap_size_); EXPECT_TRUE(returned_fallback_style_->is_default_background_color); histogram_tester_.ExpectUniqueSample("Favicons.LargeIconService.FallbackSize", 0, /*expected_count=*/1); } // Oddball case where we demand a high resolution icon to scale down. Generates // fallback even though an icon with the final size is available. TEST_P(LargeIconServiceGetterTest, FallbackSinceTooPicky) { InjectMockResult(GURL(kDummyUrl), CreateTestBitmapResult(24, 24, kTestColor)); GetLargeIconOrFallbackStyleAndWaitForCallback(GURL(kDummyUrl), 32, 24); EXPECT_EQ(nullptr, returned_bitmap_size_); EXPECT_TRUE(HasBackgroundColor(*returned_fallback_style_, kTestColor)); histogram_tester_.ExpectUniqueSample("Favicons.LargeIconService.FallbackSize", 24, /*expected_count=*/1); } // Every test will appear with suffix /0 (param false) and /1 (param true), e.g. // LargeIconServiceGetterTest.FallbackSinceTooPicky/0: get image. // LargeIconServiceGetterTest.FallbackSinceTooPicky/1: get raw bitmap. INSTANTIATE_TEST_CASE_P(, // Empty instatiation name. LargeIconServiceGetterTest, ::testing::Values(false, true)); } // namespace } // namespace favicon
41.458955
80
0.727837
metux
96471df8a208257b172268172b40cd98a5fd3e76
2,953
hpp
C++
products/PurePhone/services/db/include/db/ServiceDB.hpp
SP2FET/MuditaOS-1
2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd
[ "BSL-1.0" ]
1
2021-11-11T22:56:43.000Z
2021-11-11T22:56:43.000Z
products/PurePhone/services/db/include/db/ServiceDB.hpp
SP2FET/MuditaOS-1
2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd
[ "BSL-1.0" ]
null
null
null
products/PurePhone/services/db/include/db/ServiceDB.hpp
SP2FET/MuditaOS-1
2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include <service-db/DBServiceName.hpp> #include <service-db/ServiceDBCommon.hpp> class AlarmEventRecordInterface; class AlarmsRecordInterface; class CalllogDB; class CalllogRecordInterface; class ContactRecordInterface; class ContactsDB; class CountryCodeRecordInterface; class CountryCodesDB; class DatabaseAgent; class EventsDB; class NotesDB; class NotesRecordInterface; class NotificationsDB; class NotificationsRecordInterface; class SMSRecordInterface; class SMSTemplateRecordInterface; class SettingsDB; class SmsDB; class ThreadRecordInterface; namespace Quotes { class QuotesAgent; } namespace db::multimedia_files { class MultimediaFilesDB; class MultimediaFilesRecordInterface; } // namespace db::multimedia_files class ServiceDB : public ServiceDBCommon { public: ~ServiceDB() override; bool StoreIntoBackup(const std::filesystem::path &backupPath); private: std::unique_ptr<EventsDB> eventsDB; std::unique_ptr<SmsDB> smsDB; std::unique_ptr<ContactsDB> contactsDB; std::unique_ptr<NotesDB> notesDB; std::unique_ptr<CalllogDB> calllogDB; std::unique_ptr<CountryCodesDB> countryCodesDB; std::unique_ptr<NotificationsDB> notificationsDB; std::unique_ptr<Database> quotesDB; std::unique_ptr<db::multimedia_files::MultimediaFilesDB> multimediaFilesDB; std::unique_ptr<AlarmEventRecordInterface> alarmEventRecordInterface; std::unique_ptr<SMSRecordInterface> smsRecordInterface; std::unique_ptr<ThreadRecordInterface> threadRecordInterface; std::unique_ptr<SMSTemplateRecordInterface> smsTemplateRecordInterface; std::unique_ptr<ContactRecordInterface> contactRecordInterface; std::unique_ptr<NotesRecordInterface> notesRecordInterface; std::unique_ptr<CalllogRecordInterface> calllogRecordInterface; std::unique_ptr<CountryCodeRecordInterface> countryCodeRecordInterface; std::unique_ptr<NotificationsRecordInterface> notificationsRecordInterface; std::unique_ptr<Quotes::QuotesAgent> quotesRecordInterface; std::unique_ptr<db::multimedia_files::MultimediaFilesRecordInterface> multimediaFilesRecordInterface; db::Interface *getInterface(db::Interface::Name interface) override; sys::MessagePointer DataReceivedHandler(sys::DataMessage *msgl, sys::ResponseMessage *resp) override; sys::ReturnCodes InitHandler() override; }; namespace sys { template <> struct ManifestTraits<ServiceDB> { static auto GetManifest() -> ServiceManifest { ServiceManifest manifest; manifest.name = service::name::db; #if ENABLE_FILEINDEXER_SERVICE manifest.dependencies = {service::name::file_indexer}; #endif manifest.timeout = std::chrono::minutes{1}; return manifest; } }; } // namespace sys
32.450549
105
0.772773
SP2FET
9649ef28c41a5d2316e8dbc02492efc189ff18b7
389
cpp
C++
Logistics/2-D Transformations/Translate.cpp
amrii1/Computer-Graphics
597b4ab061b57d222e54c01a7adf2799cb889f3a
[ "MIT" ]
27
2020-01-18T02:30:40.000Z
2022-03-13T17:15:38.000Z
Logistics/2-D Transformations/Translate.cpp
KINGRANDOLPH/Computer-Graphics
509d2b06a34d9988e6c866eb6f900a56167f78ac
[ "MIT" ]
5
2019-12-13T14:08:05.000Z
2020-08-11T15:31:54.000Z
Logistics/2-D Transformations/Translate.cpp
KINGRANDOLPH/Computer-Graphics
509d2b06a34d9988e6c866eb6f900a56167f78ac
[ "MIT" ]
16
2019-12-17T08:28:42.000Z
2021-10-31T03:47:54.000Z
#include<iostream> using namespace std; int main() { int x,y,tx,ty; cout<<"Translation"; cout<<"Enter point to be translated\n"; cout<<"x: "; cin>>x; cout<<"y: "; cin>>y; cout<<"Enter the translation factors\n"; cout<<"tx: "; cin>>tx; cout<<"ty: "; cin>>ty; //Translate x=x+tx; y=y+ty; // cout<<"Point after translation\n"; cout<<"x: "<<x<<endl; cout<<"y: "<<y<<endl; }
15.56
41
0.580977
amrii1
964c616723335f4c83822526c277ffb11d238bd9
455
hpp
C++
include/xvega/grammar/marks/mark_rule.hpp
domoritz/xvega
3754dee3e7e38e79282ba267cd86c3885807a4cd
[ "BSD-3-Clause" ]
34
2020-08-14T14:32:51.000Z
2022-02-16T23:20:02.000Z
include/xvega/grammar/marks/mark_rule.hpp
domoritz/xvega
3754dee3e7e38e79282ba267cd86c3885807a4cd
[ "BSD-3-Clause" ]
19
2020-08-20T20:04:39.000Z
2022-02-28T14:34:37.000Z
include/xvega/grammar/marks/mark_rule.hpp
domoritz/xvega
3754dee3e7e38e79282ba267cd86c3885807a4cd
[ "BSD-3-Clause" ]
7
2020-08-14T14:18:17.000Z
2022-02-01T10:59:24.000Z
// Copyright (c) 2020, QuantStack and XVega Contributors // // Distributed under the terms of the BSD 3-Clause License. // // The full license is in the file LICENSE, distributed with this software. #ifndef XVEGA_MARK_RULE_HPP #define XVEGA_MARK_RULE_HPP #include "../marks.hpp" namespace xv { struct mark_rule : public mark<mark_rule> { XVEGA_API mark_rule(); }; XVEGA_API void to_json(nl::json&, const mark_rule&); } #endif
19.782609
75
0.707692
domoritz
9654c62959de7600e8de907ad5a6839bd3b48315
585
hpp
C++
ClassicProblem/reFibonacci.hpp
shaneliu-zf/CodeBook
0c30e46f5661051d523c621eac9740d6dcbab440
[ "MIT" ]
3
2020-12-15T12:34:29.000Z
2020-12-15T21:21:33.000Z
ClassicProblem/reFibonacci.hpp
shane-liu-1010/CodeBook
0c30e46f5661051d523c621eac9740d6dcbab440
[ "MIT" ]
null
null
null
ClassicProblem/reFibonacci.hpp
shane-liu-1010/CodeBook
0c30e46f5661051d523c621eac9740d6dcbab440
[ "MIT" ]
null
null
null
int reFibonacci(int n){ union{ double d; long long lld; }log2={0x23C6EF372FE951P-52*n}; int result=((log2.lld>>52)-0x3FF)/0xB1B9D68A8E5338P-56; double power=0x727C9716FFB764P-56; int i=(result+3)/4; switch(result%4){ case 0:do{ power*=0x19E3779B97F4A8P-52; case 3: power*=0x19E3779B97F4A8P-52; case 2: power*=0x19E3779B97F4A8P-52; case 1: power*=0x19E3779B97F4A8P-52; }while(--i>0); } int ans=power+0x1P-1<n?power*0x19E3779B97F4A8P-52+0x1P-1<n?result+2:result+1:result; return ans; }
30.789474
88
0.620513
shaneliu-zf
9657b0ece15c4e4552b441526a981b1f5613f3fe
6,270
cpp
C++
wxGUI/ctrl_partition_list.cpp
Null665/partmod
11f2b90c745e27bdb47b105e0bf45834c62d3527
[ "BSD-3-Clause" ]
1
2017-02-12T15:10:38.000Z
2017-02-12T15:10:38.000Z
wxGUI/ctrl_partition_list.cpp
Null665/partmod
11f2b90c745e27bdb47b105e0bf45834c62d3527
[ "BSD-3-Clause" ]
1
2016-06-03T18:20:16.000Z
2016-10-10T22:22:41.000Z
wxGUI/ctrl_partition_list.cpp
Null665/partmod
11f2b90c745e27bdb47b105e0bf45834c62d3527
[ "BSD-3-Clause" ]
null
null
null
#include "ctrl_partition_list.h" #include "../Partmod/numstr.h" #include <algorithm> using std::sort; bool cmp_lv(lvlist a,lvlist b) { return strtoull((char*)a.begin_sect.c_str(),0,10) < strtoull((char*)b.begin_sect.c_str(),0,10); } wxPartitionList::wxPartitionList(wxWindow *parent, wxWindowID winid, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString &name) : wxListView(parent,winid,pos,size,style,validator,name) { InsertColumn(0,_("Partition #"),0,70); InsertColumn(1,_("Type"),0,100); InsertColumn(2,_("FS type"),0,90); InsertColumn(3,_("Size"),0,70); //InsertColumn(4,_("Free"),0,70); InsertColumn(5,_("First sect."),0,80); InsertColumn(6,_("Last sect."),0,80); InsertColumn(7,_("Mount point"),0,100); disk=NULL; } wxPartitionList::~wxPartitionList() { //dtor } void wxPartitionList::AssignDisk(Disk *disk) { this->disk=disk; } int wxPartitionList::GetSelectedPartition() { if(disk==NULL) return -1; if(disk_structure[this->GetFocusedItem()].selection_type==S_PARTITION) return disk_structure[this->GetFocusedItem()].num; else return -1; } int wxPartitionList::GetSelectedFreeSpace() { if(disk==NULL) return -1; if(disk_structure[this->GetFocusedItem()].selection_type==S_FREE_SPACE) return disk_structure[this->GetFocusedItem()].num; else return -1; } void wxPartitionList::Refresh() { this->DeleteAllItems(); disk_structure.clear(); if(disk==NULL) return; if(disk->IsOpen()==false) return; for(int i=0;i<disk->CountPartitions();i++) { GEN_PART gpart=disk->GetPartition(i); lvlist tmp; if(gpart.flags&PART_PRIMARY && gpart.flags&PART_ACTIVE) tmp.type="Primary (Active)"; else if(gpart.flags&PART_PRIMARY) tmp.type="Primary"; else if(gpart.flags&PART_EXTENDED) tmp.type="Extended MBR"; else if(gpart.flags&PART_LOGICAL) tmp.type="Logical"; else if(gpart.flags&PART_MBR_GPT) tmp.type="GUID part. table"; else if(gpart.flags&PART_GPT) tmp.type="GPT partition"; if(gpart.flags&PART_EXTENDED || gpart.flags&PART_MBR_GPT) tmp.mountpoint=""; else tmp.mountpoint=get_mount_point(gpart,disk->GetDiskSignature()); tmp.partition=to_string(i+1); tmp.begin_sect=to_string(gpart.begin_sector); tmp.last_sect=to_string(gpart.begin_sector+gpart.length); tmp.free="N/A"; if(gpart.flags&PART_PRIMARY || gpart.flags&PART_EXTENDED || gpart.flags&PART_MBR_GPT || gpart.flags&PART_LOGICAL) { try{ tmp.fs_type=disk->fsid_man->GetByFsid(disk->GetMBRSpecific(i).fsid).description; }catch(DiskException &de) { if(de.error_code==ERR_UNKNOWN_FSID) { std::string new_type= "[unknown 0x"+to_string(disk->GetMBRSpecific(i).fsid,STR_HEX)+"]"; disk->fsid_man->Add(disk->GetMBRSpecific(i).fsid,new_type,0,0,0/*OR MSDOS FSID?*/); tmp.fs_type=new_type; } else throw de; } } else if(gpart.flags&PART_GPT) { try{ tmp.fs_type=disk->guid_man->GetDescription(disk->GetGPTSpecific(i).type_guid); }catch(...) { tmp.fs_type="[unknown guid]"; } } else tmp.fs_type="[unknown]"; tmp.num=i; tmp.selection_type=S_PARTITION; tmp.flags=gpart.flags; tmp.size=size_str(gpart.length,disk->GetDiskGeometry().bps).c_str(); disk_structure.push_back(tmp); } for(int i=0;i<disk->CountFreeSpaces();i++) { FREE_SPACE frs=disk->GetFreeSpace(i); lvlist tmp; tmp.partition="-"; tmp.type="Free space"; tmp.fs_type=""; tmp.mountpoint=""; tmp.begin_sect=to_string(frs.begin_sector); tmp.last_sect=to_string(frs.begin_sector+frs.length); tmp.flags=frs.type; tmp.selection_type=S_FREE_SPACE; tmp.num=i; tmp.size=size_str(frs.length,disk->GetDiskGeometry().bps).c_str(); disk_structure.push_back(tmp); } sort(disk_structure.begin(),disk_structure.end(),cmp_lv); for(int i=0;i<disk_structure.size();i++) { lvlist tmp=disk_structure[i]; this->InsertItem(i,tmp.partition.c_str(),-1); this->SetItem(i,1,tmp.type.c_str(),-1); this->SetItem(i,2,tmp.fs_type.c_str(),-1); this->SetItem(i,3,tmp.size.c_str(),-1); // this->SetItem(i,4,tmp.free.c_str(),-1); this->SetItem(i,4,tmp.begin_sect.c_str(),-1); this->SetItem(i,5,tmp.last_sect.c_str(),-1); this->SetItem(i,6,tmp.mountpoint.c_str(),-1); if(tmp.selection_type==S_FREE_SPACE) { if(tmp.flags!=FREE_UNALLOCATED) this->SetItemTextColour(i,wxColor(50,130,50)); else this->SetItemTextColour(i,wxColor(50,50,50)); } else { if(tmp.flags&PART_PRIMARY) this->SetItemTextColour(i,wxColor(1,6,203)); else if(tmp.flags&PART_EXTENDED || tmp.flags&PART_MBR_GPT) this->SetItemTextColour(i,wxColor(240,0,0)); else if(tmp.flags&PART_LOGICAL || tmp.flags&PART_GPT) this->SetItemTextColour(i,wxColor(140,90,140)); } } } void wxPartitionList::HideMountPoint(bool hide) { static bool col_hidden=false; if(hide && col_hidden==false) { this->DeleteColumn(this->GetColumnCount()-1); col_hidden=true; } else if( !hide && col_hidden==true) { InsertColumn(7,_("Mount point"),0,100); col_hidden=false; } }
31.039604
123
0.560447
Null665
96585ee31292329c09c58f971397bc2e0b07b37e
6,026
cc
C++
src/ui/filters/tabbareventfilter.cc
pombredanne/veles
e65de5a7c268129acffcdb03034efd8d256d025c
[ "Apache-2.0" ]
918
2017-01-16T17:31:25.000Z
2022-03-27T07:10:31.000Z
src/ui/filters/tabbareventfilter.cc
pombredanne/veles
e65de5a7c268129acffcdb03034efd8d256d025c
[ "Apache-2.0" ]
193
2017-01-17T13:56:10.000Z
2020-09-01T08:29:48.000Z
src/ui/filters/tabbareventfilter.cc
pombredanne/veles
e65de5a7c268129acffcdb03034efd8d256d025c
[ "Apache-2.0" ]
112
2017-02-01T01:05:57.000Z
2022-03-29T07:21:12.000Z
/* * Copyright 2018 CodiLime * * 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 "ui/filters/tabbareventfilter.h" #include <QApplication> #include "ui/dockwidget_native.h" #include "ui/mainwindowwithdetachabledockwidgets.h" namespace veles { namespace ui { TabBarEventFilter::TabBarEventFilter(QObject* parent) : QObject(parent), drag_init_pos_(0, 0) {} void TabBarEventFilter::tabMoved(int /*from*/, int /*to*/) { if (dragged_tab_bar_ != nullptr) { dragged_tab_index_ = dragged_tab_bar_->currentIndex(); } } void TabBarEventFilter::currentChanged(int index) { auto main_window = MainWindowWithDetachableDockWidgets::getParentMainWindow(sender()); if (main_window != nullptr) { auto dock_widget = dynamic_cast<DockWidget*>( main_window->tabToDockWidget(dynamic_cast<QTabBar*>(sender()), index)); if (dock_widget != nullptr) { MainWindowWithDetachableDockWidgets::setActiveDockWidget(dock_widget); } } } bool TabBarEventFilter::eventFilter(QObject* watched, QEvent* event) { auto* tab_bar = dynamic_cast<QTabBar*>(watched); if (tab_bar == nullptr) { return false; } connect(tab_bar, &QTabBar::currentChanged, this, &TabBarEventFilter::currentChanged, Qt::UniqueConnection); auto main_window = MainWindowWithDetachableDockWidgets::getParentMainWindow(watched); if (main_window != nullptr && !main_window->dockWidgetsWithNoTitleBars()) { return false; } connect(tab_bar, &QTabBar::tabMoved, this, &TabBarEventFilter::tabMoved, Qt::UniqueConnection); if (event->type() != QEvent::MouseMove && event->type() != QEvent::MouseButtonPress && event->type() != QEvent::MouseButtonRelease && event->type() != QEvent::MouseButtonDblClick) { return false; } auto* mouse_event = static_cast<QMouseEvent*>(event); if (mouse_event->type() == QEvent::MouseMove) { return mouseMove(tab_bar, mouse_event); } if (mouse_event->type() == QEvent::MouseButtonPress) { return mouseButtonPress(tab_bar, mouse_event); } if (mouse_event->type() == QEvent::MouseButtonRelease) { return mouseButtonRelease(tab_bar, mouse_event); } if (mouse_event->type() == QEvent::MouseButtonDblClick) { return mouseButtonDblClick(tab_bar, mouse_event); } return false; } bool TabBarEventFilter::mouseMove(QTabBar* tab_bar, QMouseEvent* event) { if (dragged_tab_bar_ != nullptr) { bool horizontal_tabs = dragged_tab_bar_->shape() == QTabBar::RoundedNorth || dragged_tab_bar_->shape() == QTabBar::RoundedSouth || dragged_tab_bar_->shape() == QTabBar::TriangularNorth || dragged_tab_bar_->shape() == QTabBar::TriangularSouth; if ((horizontal_tabs ? (event->pos() - drag_init_pos_).y() : (event->pos() - drag_init_pos_).x()) > k_drag_treshold_ * QApplication::startDragDistance()) { auto window = dynamic_cast<MainWindowWithDetachableDockWidgets*>(tab_bar->window()); if (window != nullptr) { auto* dock_widget = dynamic_cast<DockWidget*>( window->tabToDockWidget(tab_bar, dragged_tab_index_)); if (dock_widget != nullptr) { stopTabBarDragging(dragged_tab_bar_); dragged_tab_bar_ = nullptr; dragged_tab_index_ = -1; dock_widget->switchTitleBar(true); dock_widget->setFloating(true); dock_widget->centerTitleBarOnPosition(event->globalPos()); QCursor::setPos(event->globalPos()); startDockDragging(dock_widget); return true; } } } } return false; } bool TabBarEventFilter::mouseButtonPress(QTabBar* tab_bar, QMouseEvent* event) { if (event->button() == Qt::LeftButton) { dragged_tab_index_ = tab_bar->tabAt(event->pos()); if (dragged_tab_index_ > -1) { dragged_tab_bar_ = tab_bar; drag_init_pos_ = event->pos(); } else { dragged_tab_bar_ = nullptr; } } return false; } bool TabBarEventFilter::mouseButtonRelease(QTabBar* tab_bar, QMouseEvent* event) { if (event->button() == Qt::LeftButton) { dragged_tab_bar_ = nullptr; dragged_tab_index_ = -1; } else if (event->button() == Qt::RightButton) { int tab_index = tab_bar->tabAt(event->pos()); if (tab_index > -1) { auto window = dynamic_cast<MainWindowWithDetachableDockWidgets*>(tab_bar->window()); if (window != nullptr) { auto* dock_widget = dynamic_cast<DockWidget*>( window->tabToDockWidget(tab_bar, tab_index)); if (dock_widget != nullptr) { dock_widget->displayContextMenu( dock_widget->mapFromGlobal(event->globalPos())); } } } } return false; } bool TabBarEventFilter::mouseButtonDblClick(QTabBar* tab_bar, QMouseEvent* event) { if (event->button() == Qt::LeftButton) { int tab_index = tab_bar->tabAt(event->pos()); if (tab_index > -1) { auto window = dynamic_cast<MainWindowWithDetachableDockWidgets*>(tab_bar->window()); if (window != nullptr) { auto* dock_widget = dynamic_cast<DockWidget*>( window->tabToDockWidget(tab_bar, tab_index)); if (dock_widget != nullptr) { dock_widget->setFloating(true); dock_widget->centerTitleBarOnPosition(event->globalPos()); } } } } return false; } } // namespace ui } // namespace veles
31.715789
80
0.659144
pombredanne
965a24213b0e0cce210c5eefd6c24f5e1b0ef002
2,730
hpp
C++
DT3Core/Scripting/ScriptingParticleColorRandomizer.hpp
9heart/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2018-10-05T15:03:27.000Z
2019-03-19T11:01:56.000Z
DT3Core/Scripting/ScriptingParticleColorRandomizer.hpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
null
null
null
DT3Core/Scripting/ScriptingParticleColorRandomizer.hpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2016-01-14T07:51:52.000Z
2021-08-21T08:02:51.000Z
#ifndef DT3_SCRIPTINGPARTICLECOLORRANDOMIZER #define DT3_SCRIPTINGPARTICLECOLORRANDOMIZER //============================================================================== /// /// File: ScriptingParticleColorRandomizer.hpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== #include "DT3Core/Scripting/ScriptingBase.hpp" //============================================================================== //============================================================================== namespace DT3 { //============================================================================== /// Forward declarations //============================================================================== class Particles; //============================================================================== /// Color Randomizer for Particle System. //============================================================================== class ScriptingParticleColorRandomizer: public ScriptingBase { public: DEFINE_TYPE(ScriptingParticleColorRandomizer,ScriptingBase) DEFINE_CREATE_AND_CLONE DEFINE_PLUG_NODE ScriptingParticleColorRandomizer (void); ScriptingParticleColorRandomizer (const ScriptingParticleColorRandomizer &rhs); ScriptingParticleColorRandomizer& operator = (const ScriptingParticleColorRandomizer &rhs); virtual ~ScriptingParticleColorRandomizer (void); virtual void archive (const std::shared_ptr<Archive> &archive); public: /// Called to initialize the object virtual void initialize (void); /// Computes the value of the node /// \param plug plug to compute DTboolean compute (const PlugBase *plug); DEFINE_ACCESSORS(r_mag, set_r_mag, DTfloat, _r_mag); DEFINE_ACCESSORS(g_mag, set_g_mag, DTfloat, _g_mag); DEFINE_ACCESSORS(b_mag, set_b_mag, DTfloat, _b_mag); DEFINE_ACCESSORS(a_mag, set_a_mag, DTfloat, _a_mag); private: static const DTint NUM_ENTRIES = 8; DTfloat _r_mag; DTfloat _g_mag; DTfloat _b_mag; DTfloat _a_mag; Plug<std::shared_ptr<Particles>> _in; Plug<std::shared_ptr<Particles>> _out; }; //============================================================================== //============================================================================== } // DT3 #endif
35.454545
107
0.476923
9heart
965acb9105b85009cae75d76f715acec39a19fe4
6,485
cpp
C++
sdl1/kiloblaster/src/2b_editr.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/kiloblaster/src/2b_editr.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/kiloblaster/src/2b_editr.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
// 2B_EDITR.C // // Kiloblaster v.2 Editor // // Written by Allen W. Pilgrim #include <stdlib.h> #include <ctype.h> #include <string.h> #include <fcntl.h> #include "include/gr.h" #include "include/keyboard.h" #include "include/windows.h" #include "include/gamectrl.h" #include "include/kconfig.h" #include "include/2blaster.h" int16_t x, y, cell; extern char cfgfname[]; extern char ext[]; void fill_brd (void); void infname (char *msg, char *fname, int16_t num) { fontcolor (&statvp, 10, 0); clearvp (&statvp); wprint (&statvp, 2, 2, 1, msg); fontcolor (&statvp, 13, 0); if (num) wprint (&statvp, 4, 26, 2, "NO EXT."); winput (&statvp, 0, 14, 2, fname, 8); }; void edit_brd (void) { int16_t tempint; int16_t lastcell = b_blank; // last placed item on the board char tempstr[12]; // temporary string, used for input char tempfname[12]; tempstr[0] = '\0'; tempfname[0] = '\0'; init_brd (); clrvp (&cmdvp, 0); clrvp (&statvp, 0); x = 0, y = 0, cell = 0; if (pcx_sh==0) loadboard ("menu"); drawboard (); fontcolor (&cmdvp, 14, 0); wprint (&cmdvp, 2, 4, 1, "L"); wprint (&cmdvp, 2, 16, 1, "S"); wprint (&cmdvp, 2, 28, 1, "A"); wprint (&cmdvp, 2, 40, 1, "C"); wprint (&cmdvp, 2, 52, 1, "F"); wprint (&cmdvp, 4, 76, 2, "<space>"); wprint (&cmdvp, 4, 98, 2, "<enter>"); fontcolor (&cmdvp, 13, 0); wprint (&cmdvp, 10, 4, 1, "OAD"); wprint (&cmdvp, 10, 16, 1, "AVE"); wprint (&cmdvp, 10, 28, 1, "DD"); wprint (&cmdvp, 10, 40, 1, "LEAR"); wprint (&cmdvp, 10, 52, 1, "ILL"); fontcolor (&cmdvp, 11, 0); wprint (&cmdvp, 0, 64, 1, "REPEAT"); wprint (&cmdvp, 8, 86, 1, "COPY"); do { drawshape (&gamevp, 0x4400 + 16, x * 16, y * 16); // cursor checkctrl0 (0); drawcell (x, y); // draw board cell (erases cursor!) x += dx1; y += dy1; if (x < 0) x = 0; // bounds checking routine if (x >= end_x) x = end_x - 1; if (y < 0) y = 0; if (y >= end_y) y = end_y - 1; switch (toupper(key)) { case 'A' : // A = add new background clearvp (&statvp); wprint (&statvp, 2, 2, 1, "NAME:"); winput (&statvp, 2, 14, 1, tempstr, 5); _strupr (tempstr); for (tempint = 0; tempint < b_maxbkgnd; tempint++) { if (strcmp (tempstr, info[tempint].na) == 0) { board[x][y] = tempint; lastcell = tempint; }; }; break; case ' ' : // SPACE = put down last background again board[x][y] = lastcell; break; case 13 : // RETURN = 'pick up' whatever is under cursor lastcell = board[x][y]; break; case 'F' : // Fills entire screen with selected pattern fill_brd (); for (x = 0; x < end_x; x++) { for (y = 0; y < end_y; y++) { board[x][y] = cell; }; }; drawboard (); break; case 'C' : // clears screen and sets everything to "0" init_brd (); x = 0, y = 0, cell = 0; break; case 'Z': infname ("LOAD:", tempfname, 0); if (tempfname[0] != '\0') { loadbrd (tempfname); drawboard (); }; break; case 'L': infname ("LOAD:", tempfname, 1); if (tempfname[0] != '\0') { loadboard (tempfname); drawboard (); }; break; case 'S': infname ("SAVE:", tempfname, 1); if (tempfname[0] != '\0') saveboard (tempfname); break; }; key = (toupper(key)); } while (key != escape); } /* void init_brd (void) { int16_t x, y; clrvp (&gamevp, 0); for (x = 0; x < end_x; x++) { for (y = 0; y < end_y; y++) { board[x][y] = 0; modflg[x][y] = 0; }; }; }; */ /* void drawboard (void) { int16_t x, y; statmodflg = 0; refresh (0); }; void drawcell (int16_t x, int16_t y) { if (board[x][y]==0) { drawshape (&gamevp, pcx_sh + x + y * 16, x * 16, y * 16); } else { drawshape (&gamevp, info[board[x][y]].sh, x * 16, y * 16); }; } */ void fill_brd () { cell = getch(); switch (cell) { case '0': cell = 0; break; // blank case '1': cell = 1; break; // wall1 case '2': cell = 2; break; // wall2 case '3': cell = 3; break; // wall3 case '4': cell = 4; break; // wall4 case '5': cell = 5; break; // wall5 case '6': cell = 6; break; // wall6 case '7': cell = 7; break; // wall7 case '8': cell = 8; break; // wall8 case '9': cell = 9; break; // wall9 case 'a': cell = 10; break; // walla case 'b': cell = 11; break; // wallb case 'c': cell = 12; break; // wallc case 'd': cell = 13; break; // walld case 'e': cell = 14; break; // walle case 'f': cell = 15; break; // wallf default : cell = 0; break; // default }; }; void loadbrd (char *fname) { // loads a board with .BAK extension FILE* boardfile; char dest[12]; char *src1 = ".bak"; strcpy(dest, fname); strcat(dest, src1); boardfile = fopen (dest, O_BINARY); if (!fread (&board, 1, sizeof(board), boardfile)) ; // rexit(1); fclose (boardfile); }; /* void loadboard (char *fname) { // loads a board with .BRD extension int16_t boardfile; char dest[12]; char *src1 = ext; strcpy(dest, fname); strcat(dest, src1); boardfile = _open (dest, O_BINARY); if (!read (boardfile, &board, sizeof(board))); // rexit(1); _close (boardfile); }; void saveboard (char *fname) { // saves a board with .BRD extension int16_t boardfile; char dest[12]; char dest2[12]; char *src1 = ext; char *src2 = ".bak"; strcpy(dest, fname); strcat(dest, src1); strcpy(dest2, fname); strcat(dest2, src2); boardfile = creatnew (dest, 0); if (boardfile== -1) { rename (dest, dest2); boardfile = _creat (dest, 0); if (!write (boardfile, &board, sizeof(board))) rexit(5); } else { if (!write (boardfile, &board, sizeof(board))) rexit(5); }; _close (boardfile); }; void loadcfg (void) { int16_t cfgfile, c; char ourname[64]; // strcpy (ourname, path); strcpy (ourname, cfgfname); cfgfile = _open (ourname, O_BINARY); if ((cfgfile < 0) || (filelength(cfgfile) <= 0)) { for (c = 0; c < numhighs; c++) {hiname[c][0]='\0'; hiscore[c]=0;}; for (c = 0; c < numsaves; c++) {savename[c][0]='\0';}; cf.firstthru = 1; } else { read (cfgfile, &hiname, sizeof(hiname)); read (cfgfile, &hiscore, sizeof(hiscore)); read (cfgfile, &savename, sizeof(savename)); if (read (cfgfile, &cf, sizeof (cf)) < 0) cf.firstthru = 1; }; close (cfgfile); }; void savecfg (void) { int16_t cfgfile; char ourname[64]; // strcpy (ourname, path); strcpy (ourname, cfgfname); cfgfile = _creat (ourname, 0); if (cfgfile >= 0) { write (cfgfile, &hiname, sizeof(hiname)); write (cfgfile, &hiscore, sizeof(hiscore)); write (cfgfile, &savename, sizeof(savename)); write (cfgfile, &cf, sizeof (cf)); }; close (cfgfile); }; */
24.846743
68
0.578412
pdpdds
965ca6279cac1e760ea9faafa930f71c56e5d994
9,743
cpp
C++
src/resource/resource_manager.cpp
sndrz/glen
398fbc146c92a2fa36433e9a9865344bc4c23c6e
[ "MIT" ]
null
null
null
src/resource/resource_manager.cpp
sndrz/glen
398fbc146c92a2fa36433e9a9865344bc4c23c6e
[ "MIT" ]
null
null
null
src/resource/resource_manager.cpp
sndrz/glen
398fbc146c92a2fa36433e9a9865344bc4c23c6e
[ "MIT" ]
null
null
null
#include "../../includes/resource/resource_manager.hpp" #include "../../includes/render/shader_program.hpp" #include "../../includes/render/texture2d.hpp" #include "../../includes/render/sprite.hpp" #include "../includes/logger.hpp" #include <sstream> #include <fstream> #include <iostream> #include <vector> #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_PNG #include "../../external/stb_image.h" #include <rapidjson/document.h> #include <rapidjson/error/en.h> ResourceManager::ShaderProgramsMap ResourceManager::shaderPrograms; ResourceManager::TexturesMap ResourceManager::textures; ResourceManager::SpritesMap ResourceManager::m_sprites; std::string ResourceManager::path; void ResourceManager::SetExecutablePath(const std::string& executablePath) { size_t slashPosition = executablePath.find_last_of("/\\"); path = executablePath.substr(0, slashPosition); } // endof ResourceManager::SetExecutablePath() void ResourceManager::UnloadAllResources() { shaderPrograms.clear(); textures.clear(); m_sprites.clear(); } // endof ResourceManager::UnloadAllResources() std::string ResourceManager::GetFileString(const std::string& relativeFilePath) { std::ifstream f; f.open(path + "/" + relativeFilePath.c_str(), std::ios::in | std::ios::binary); if (!f.is_open()) { LOG_CRITICAL("Failed to open file: {}", relativeFilePath); return std::string{}; } std::stringstream buffer; buffer << f.rdbuf(); return buffer.str(); } // ResourceManager::GetFileString() std::shared_ptr<render::ShaderProgram> ResourceManager::LoadShaders(const std::string& shaderName, const std::string& vertexPath, const std::string& fragmentPath) { std::string vertexString = GetFileString(vertexPath); if (vertexString.empty()) { LOG_ERROR("No vertex shader"); return nullptr; } std::string fragmentString = GetFileString(fragmentPath); if (fragmentString.empty()) { LOG_ERROR("No fragment shader"); return nullptr; } std::shared_ptr<render::ShaderProgram>& newShader = shaderPrograms.emplace(shaderName, std::make_shared<render::ShaderProgram>(vertexString, fragmentString)).first->second; if (newShader->IsCompiled()) { return newShader; } LOG_ERROR("Can't load shader program:\nVertex: {0}\nFragment: {1}", vertexPath, fragmentPath); return nullptr; } // ResourceManager::LoadShaders std::shared_ptr<render::ShaderProgram> ResourceManager::GetShaderProgram(const std::string& shaderName) { ShaderProgramsMap::const_iterator it = shaderPrograms.find(shaderName); if (it != shaderPrograms.end()) { return it->second; } LOG_ERROR("Can't find shader program: {}", shaderName); return nullptr; } // ResourceManager::GetShaderProgram std::shared_ptr<render::Texture2D> ResourceManager::LoadTexture(const std::string& textureName, const std::string& texturePath) { int channels = 0; int width = 0; int height = 0; stbi_set_flip_vertically_on_load(true); unsigned char* pixels = stbi_load(std::string(path + "/" + texturePath).c_str(), &width, &height, &channels, 0); if (!pixels) { LOG_ERROR("Can't load image: {}", texturePath); return nullptr; } std::shared_ptr<render::Texture2D> newTexture = textures.emplace(textureName, std::make_shared<render::Texture2D>(width, height, pixels, channels, GL_NEAREST, GL_CLAMP_TO_EDGE)).first->second; stbi_image_free(pixels); return newTexture; } // ResourceManager::LoadTexture std::shared_ptr<render::Texture2D> ResourceManager::GetTexture(const std::string& textureName) { TexturesMap::const_iterator it = textures.find(textureName); if (it != textures.end()) { return it->second; } LOG_ERROR("Can't find texture: {}", textureName); return nullptr; } // ResourceManager::GetTexture std::shared_ptr<render::Sprite> ResourceManager::LoadSprite(const std::string& spriteName, const std::string& textureName, const std::string& shaderName, const std::string& subTextureName) { auto pTexture = GetTexture(textureName); if (!pTexture) { std::cerr << "Can't find texture: " << textureName << " for sprite: " << spriteName << std::endl; } auto pShader = GetShaderProgram(shaderName); if (!pShader) { std::cerr << "Can't find shader: " << shaderName << " for sprite: " << spriteName << std::endl; } std::shared_ptr<render::Sprite> newSprite = m_sprites.emplace(spriteName, std::make_shared<render::Sprite>(pTexture, subTextureName, pShader)).first->second; return newSprite; } // ResourceManager::LoadSprite std::shared_ptr<render::Sprite> ResourceManager::GetSprite(const std::string& spriteName) { SpritesMap::const_iterator it = m_sprites.find(spriteName); if (it != m_sprites.end()) { return it->second; } std::cerr << "Can't find sprite: " << spriteName << std::endl; return nullptr; } // ResourceManager::GetSprite std::shared_ptr<render::Texture2D> ResourceManager::LoadTextureAtlas(const std::string& textureName, const std::string& texturePath, std::vector<std::string> subTextures, const unsigned int subTextureWidth, const unsigned int subTextureHeight) { auto pTexture = LoadTexture(std::move(textureName), std::move(texturePath)); if (pTexture) { const unsigned int textureWidth = pTexture->GetWidth(); const unsigned int textureHeight = pTexture->GetHeight(); unsigned int currentTextureOffsetX = 0; unsigned int currentTextureOffsetY = textureHeight; for (auto& currentSubTextureName : subTextures) { glm::vec2 leftBottomUV(static_cast<float>(currentTextureOffsetX + 0.01f) / textureWidth, static_cast<float>(currentTextureOffsetY - subTextureHeight + 0.01f) / textureHeight); glm::vec2 rightTopUV(static_cast<float>(currentTextureOffsetX + subTextureWidth - 0.01f) / textureWidth, static_cast<float>(currentTextureOffsetY - 0.01f) / textureHeight); pTexture->AddSubTexture(std::move(currentSubTextureName), leftBottomUV, rightTopUV); currentTextureOffsetX += subTextureWidth; if (currentTextureOffsetX >= textureWidth) { currentTextureOffsetX = 0; currentTextureOffsetY = subTextureHeight; } } // for } // if (pTexture) return pTexture; } // ResourceManager::LoadTextureAtlas bool ResourceManager::LoadJSONResources(const std::string& JSONPath) { const std::string JSONString = GetFileString(JSONPath); if (JSONString.empty()) { std::cerr << "No JSON resources file" << std::endl; return false; } rapidjson::Document document; rapidjson::ParseResult parseResult = document.Parse(JSONString.c_str()); if (!parseResult) { std::cerr << "JSON parce error: " << rapidjson::GetParseError_En(parseResult.Code()) << "(" << parseResult.Offset() << ")" << std::endl; std::cerr << "In JSON file: " << JSONPath << std::endl; return false; } auto shadersIt = document.FindMember("shaders"); if (shadersIt != document.MemberEnd()) { for (const auto& currentShader : shadersIt->value.GetArray()) { const std::string name = currentShader["name"].GetString(); const std::string filePath_v = currentShader["filePath_v"].GetString(); const std::string filePath_f = currentShader["filePath_f"].GetString(); LoadShaders(name, filePath_v, filePath_f); } } // endof if shadersIt auto textureAtlasesIt = document.FindMember("textureAtlases"); if (textureAtlasesIt != document.MemberEnd()) { for (const auto& currentTextureAtlas : textureAtlasesIt->value.GetArray()) { const std::string name = currentTextureAtlas["name"].GetString(); const std::string filePath = currentTextureAtlas["filePath"].GetString(); const unsigned int subTextureWidth = currentTextureAtlas["subTextureWidth"].GetUint(); const unsigned int subTextureHeight = currentTextureAtlas["subTextureHeight"].GetUint(); const auto subTexturesArray = currentTextureAtlas["subTextures"].GetArray(); std::vector<std::string> subTextures; subTextures.reserve(subTexturesArray.Size()); for (const auto & currentSubTexture : subTexturesArray) { subTextures.emplace_back(currentSubTexture.GetString()); } LoadTextureAtlas(name, filePath, std::move(subTextures), subTextureWidth, subTextureHeight); } // endof for currentTextureAtlas } // endof if textureAtlasesIt auto spritesIt = document.FindMember("sprites"); if (spritesIt != document.MemberEnd()) { for (const auto& currentSprite : spritesIt->value.GetArray()) { const std::string name = currentSprite["name"].GetString(); const std::string textureAtlas = currentSprite["textureAtlas"].GetString(); const std::string shader = currentSprite["shader"].GetString(); const std::string initialSubTexture = currentSprite["initialSubTexture"].GetString(); auto pSprite = LoadSprite(name, textureAtlas, shader, initialSubTexture); if (!pSprite) { continue; } auto framesIt = currentSprite.FindMember("frames"); if (framesIt != document.MemberEnd()) { const auto framesArray = framesIt->value.GetArray(); std::vector<render::Sprite::FrameDescription> framesDescription; framesDescription.reserve(framesArray.Size()); for (const auto& currentFrame : framesArray) { const std::string subTexture = currentFrame["subTexture"].GetString(); const uint64_t duration = currentFrame["duration"].GetUint64(); const auto pTextureAtlas = GetTexture(textureAtlas); const auto pSubTexture = pTextureAtlas->GetSubTexture(subTexture); framesDescription.emplace_back(pSubTexture.leftBottomUV, pSubTexture.rightTopUV, duration); } pSprite->InsertFrames(std::move(framesDescription)); } // endof if } // endof for currentAnimatedSprite } // endof if animatedSpritesIt return true; } // endof ResourceManager::LoadJSONResources()
41.815451
193
0.725136
sndrz
9660835c2012e72569a4a4f893a430e82ea2076b
2,939
cpp
C++
src/game/client/swarm/vgui/playerswaitingpanel.cpp
BlueNovember/alienswarm-reactivedrop
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
[ "CC0-1.0" ]
null
null
null
src/game/client/swarm/vgui/playerswaitingpanel.cpp
BlueNovember/alienswarm-reactivedrop
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
[ "CC0-1.0" ]
null
null
null
src/game/client/swarm/vgui/playerswaitingpanel.cpp
BlueNovember/alienswarm-reactivedrop
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
[ "CC0-1.0" ]
null
null
null
#include "cbase.h" #include "PlayersWaitingPanel.h" #include "vgui/isurface.h" #include <KeyValues.h> #include <vgui_controls/Label.h> #include "c_asw_game_resource.h" #include "c_playerresource.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> PlayersWaitingPanel::PlayersWaitingPanel(vgui::Panel *parent, const char *panelName) : vgui::Panel(parent, panelName) { m_pTitle = new vgui::Label(this, "Title", "#asw_commanders"); for (int i=0;i<ASW_MAX_READY_PLAYERS;i++) { m_pPlayerNameLabel[i] = new vgui::Label(this, "Ready", " "); m_pPlayerReadyLabel[i] = new vgui::Label(this, "Ready", " "); } } void PlayersWaitingPanel::PerformLayout() { int w, t; //w = ScreenWidth() * 0.3f; //t = ScreenHeight() * 0.3f; //SetSize(w, t); GetSize(w, t); int row_height = 0.035f * ScreenHeight(); float fScale = ScreenHeight() / 768.0f; int padding = fScale * 6.0f; int title_wide = w - padding * 2; m_pTitle->SetBounds(padding, padding, title_wide, row_height); int name_wide = title_wide * 0.6f; int ready_wide = title_wide * 0.4f; for (int i=0;i<ASW_MAX_READY_PLAYERS;i++) { m_pPlayerNameLabel[i]->SetBounds(padding, (i+1) * (row_height) + padding, name_wide, row_height); m_pPlayerReadyLabel[i]->SetBounds(padding + name_wide, (i+1) * (row_height) + padding, ready_wide, row_height); } } void PlayersWaitingPanel::ApplySchemeSettings(vgui::IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); SetPaintBackgroundEnabled(true); SetPaintBackgroundType(0); SetBgColor(Color(0,0,0,128)); vgui::HFont DefaultFont = pScheme->GetFont( "Default", IsProportional() ); m_pTitle->SetFont(DefaultFont); m_pTitle->SetFgColor(Color(255,255,255,255)); for (int i=0;i<ASW_MAX_READY_PLAYERS;i++) { m_pPlayerReadyLabel[i]->SetFont(DefaultFont); m_pPlayerReadyLabel[i]->SetFgColor(pScheme->GetColor("LightBlue", Color(128,128,128,255))); m_pPlayerNameLabel[i]->SetFont(DefaultFont); m_pPlayerNameLabel[i]->SetFgColor(pScheme->GetColor("LightBlue", Color(128,128,128,255))); } } void PlayersWaitingPanel::OnThink() { C_ASW_Game_Resource* pGameResource = ASWGameResource(); if (!pGameResource) return; // set labels and ready status from players int iNumPlayersInGame = 0; for ( int j = 1; j <= gpGlobals->maxClients; j++ ) { if ( g_PR->IsConnected( j ) ) { m_pPlayerNameLabel[iNumPlayersInGame]->SetText(g_PR->GetPlayerName(j)); bool bReady = pGameResource->IsPlayerReady(j); if (bReady) m_pPlayerReadyLabel[iNumPlayersInGame]->SetText("#asw_campaign_ready"); else m_pPlayerReadyLabel[iNumPlayersInGame]->SetText("#asw_campaign_waiting"); iNumPlayersInGame++; } } // hide further panels in for (int j=iNumPlayersInGame;j<ASW_MAX_READY_PLAYERS;j++) { m_pPlayerNameLabel[j]->SetText(""); m_pPlayerReadyLabel[j]->SetText(""); } }
31.602151
114
0.696155
BlueNovember
9663569663a266aae9657999178e5c9e5cbced75
12,841
cpp
C++
RenderCore/Techniques/CommonResources.cpp
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
3
2015-12-04T09:16:53.000Z
2021-05-28T23:22:49.000Z
RenderCore/Techniques/CommonResources.cpp
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
null
null
null
RenderCore/Techniques/CommonResources.cpp
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
2
2015-03-03T05:32:39.000Z
2015-12-04T09:16:54.000Z
// Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "CommonResources.h" #include "CommonBindings.h" #include "../IDevice.h" #include "../Metal/Metal.h" #include "../Metal/Resource.h" // for Metal::CompleteInitialization #include "../Metal/DeviceContext.h" // for Metal::CompleteInitialization #include "../../Utility/MemoryUtils.h" #if GFXAPI_TARGET == GFXAPI_DX11 #include "TechniqueUtils.h" // just for sizeof(LocalTransformConstants) #include "../Metal/ObjectFactory.h" #endif namespace RenderCore { namespace Techniques { DepthStencilDesc CommonResourceBox::s_dsReadWrite { CompareOp::GreaterEqual }; DepthStencilDesc CommonResourceBox::s_dsReadOnly { CompareOp::GreaterEqual, false }; DepthStencilDesc CommonResourceBox::s_dsDisable { CompareOp::Always, false }; DepthStencilDesc CommonResourceBox::s_dsReadWriteWriteStencil { CompareOp::GreaterEqual, true, true, 0xff, 0xff, StencilDesc::AlwaysWrite, StencilDesc::AlwaysWrite }; DepthStencilDesc CommonResourceBox::s_dsWriteOnly { CompareOp::Always, true }; DepthStencilDesc CommonResourceBox::s_dsReadWriteCloserThan { CompareOp::Greater }; // (ie, when reversed Z is the default, greater is closer) AttachmentBlendDesc CommonResourceBox::s_abStraightAlpha { true, Blend::SrcAlpha, Blend::InvSrcAlpha, BlendOp::Add }; AttachmentBlendDesc CommonResourceBox::s_abAlphaPremultiplied { true, Blend::One, Blend::InvSrcAlpha, BlendOp::Add }; AttachmentBlendDesc CommonResourceBox::s_abOneSrcAlpha { true, Blend::One, Blend::SrcAlpha, BlendOp::Add }; AttachmentBlendDesc CommonResourceBox::s_abAdditive { true, Blend::One, Blend::One, BlendOp::Add }; AttachmentBlendDesc CommonResourceBox::s_abOpaque { }; RasterizationDesc CommonResourceBox::s_rsDefault { CullMode::Back }; RasterizationDesc CommonResourceBox::s_rsCullDisable { CullMode::None }; RasterizationDesc CommonResourceBox::s_rsCullReverse { CullMode::Back, FaceWinding::CW }; static uint64_t s_nextCommonResourceBoxGuid = 1; static std::shared_ptr<IResource> CreateBlackResource(IDevice& device, const ResourceDesc& resDesc) { if (resDesc._type == ResourceDesc::Type::Texture) { return device.CreateResource(resDesc); } else { std::vector<uint8_t> blank(ByteCount(resDesc), 0); return device.CreateResource(resDesc, SubResourceInitData{MakeIteratorRange(blank)}); } } static std::shared_ptr<IResource> CreateWhiteResource(IDevice& device, const ResourceDesc& resDesc) { if (resDesc._type == ResourceDesc::Type::Texture) { return device.CreateResource(resDesc); } else { std::vector<uint8_t> blank(ByteCount(resDesc), 0xff); return device.CreateResource(resDesc, SubResourceInitData{MakeIteratorRange(blank)}); } } CommonResourceBox::CommonResourceBox(IDevice& device) : _samplerPool(device) , _guid(s_nextCommonResourceBoxGuid++) { using namespace RenderCore::Metal; #if GFXAPI_TARGET == GFXAPI_DX11 _dssReadWrite = DepthStencilState(); _dssReadOnly = DepthStencilState(true, false); _dssDisable = DepthStencilState(false, false); _dssReadWriteWriteStencil = DepthStencilState(true, true, 0xff, 0xff, StencilMode::AlwaysWrite, StencilMode::AlwaysWrite); _dssWriteOnly = DepthStencilState(true, true, CompareOp::Always); _blendStraightAlpha = BlendState(BlendOp::Add, Blend::SrcAlpha, Blend::InvSrcAlpha); _blendAlphaPremultiplied = BlendState(BlendOp::Add, Blend::One, Blend::InvSrcAlpha); _blendOneSrcAlpha = BlendState(BlendOp::Add, Blend::One, Blend::SrcAlpha); _blendAdditive = BlendState(BlendOp::Add, Blend::One, Blend::One); _blendOpaque = BlendOp::NoBlending; _defaultRasterizer = CullMode::Back; _cullDisable = CullMode::None; _cullReverse = RasterizerState(CullMode::Back, false); _localTransformBuffer = MakeConstantBuffer(GetObjectFactory(), sizeof(LocalTransformConstants)); #endif _linearClampSampler = device.CreateSampler(SamplerDesc{FilterMode::Trilinear, AddressMode::Clamp, AddressMode::Clamp}); _linearWrapSampler = device.CreateSampler(SamplerDesc{FilterMode::Trilinear, AddressMode::Wrap, AddressMode::Wrap}); _pointClampSampler = device.CreateSampler(SamplerDesc{FilterMode::Point, AddressMode::Clamp, AddressMode::Clamp}); _anisotropicWrapSampler = device.CreateSampler(SamplerDesc{FilterMode::Anisotropic, AddressMode::Wrap, AddressMode::Wrap}); _unnormalizedBilinearClampSampler = device.CreateSampler(SamplerDesc{FilterMode::Bilinear, AddressMode::Clamp, AddressMode::Clamp, AddressMode::Clamp, CompareOp::Never, SamplerDescFlags::UnnormalizedCoordinates}); _defaultSampler = _linearWrapSampler; _black2DSRV = CreateBlackResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::Plain2D(32, 32, Format::R8_UNORM), "black2d"))->CreateTextureView(); _black2DArraySRV = CreateBlackResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::Plain2D(32, 32, Format::R8_UNORM, 1, 1), "black2darray"))->CreateTextureView(); _black3DSRV = CreateBlackResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::Plain3D(8, 8, 8, Format::R8_UNORM), "black3d"))->CreateTextureView(); _blackCubeSRV = CreateBlackResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::PlainCube(32, 32, Format::R8_UNORM), "blackCube"))->CreateTextureView(); _blackCubeArraySRV = CreateBlackResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::PlainCube(32, 32, Format::R8_UNORM, 1, 6), "blackCubeArray"))->CreateTextureView(); _blackCB = CreateBlackResource(device, CreateDesc(BindFlag::ConstantBuffer, 0, GPUAccess::Read, LinearBufferDesc{256}, "blackbuffer")); _blackBufferUAV = CreateBlackResource(device, CreateDesc(BindFlag::UnorderedAccess, 0, GPUAccess::Read, LinearBufferDesc{256, 16}, "blackbufferuav"))->CreateBufferView(BindFlag::UnorderedAccess); _white2DSRV = CreateWhiteResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::Plain2D(32, 32, Format::R8_UNORM), "white2d"))->CreateTextureView(); _white2DArraySRV = CreateWhiteResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::Plain2D(32, 32, Format::R8_UNORM, 1, 1), "white2darray"))->CreateTextureView(); _white3DSRV = CreateWhiteResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::Plain3D(8, 8, 8, Format::R8_UNORM), "white3d"))->CreateTextureView(); _whiteCubeSRV = CreateWhiteResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::PlainCube(32, 32, Format::R8_UNORM), "whiteCube"))->CreateTextureView(); _whiteCubeArraySRV = CreateWhiteResource(device, CreateDesc(BindFlag::ShaderResource|BindFlag::TransferDst, 0, GPUAccess::Read, TextureDesc::PlainCube(32, 32, Format::R8_UNORM, 1, 6), "whiteCubeArray"))->CreateTextureView(); _pendingCompleteInitialization = true; } CommonResourceBox::~CommonResourceBox() {} void CommonResourceBox::CompleteInitialization(IThreadContext& threadContext) { if (!_pendingCompleteInitialization) return; IResource* blackTextures[] { _black2DSRV->GetResource().get(), _black2DArraySRV->GetResource().get(), _black3DSRV->GetResource().get(), _blackCubeSRV->GetResource().get(), _blackCubeArraySRV->GetResource().get() }; IResource* whiteTextures[] { _white2DSRV->GetResource().get(), _white2DArraySRV->GetResource().get(), _white3DSRV->GetResource().get(), _whiteCubeSRV->GetResource().get(), _whiteCubeArraySRV->GetResource().get() }; auto& metalContext = *Metal::DeviceContext::Get(threadContext); Metal::CompleteInitialization(metalContext, MakeIteratorRange(blackTextures)); Metal::CompleteInitialization(metalContext, MakeIteratorRange(whiteTextures)); // We also have to clear out data for the textures (since these can't be initialized // in the construction operation) // We might be able to do this with just a clear call on some APIs; but let's do it // it hard way, anyway size_t largest = 0; for (const auto& res:blackTextures) largest = std::max(largest, (size_t)ByteCount(res->GetDesc())); for (const auto& res:whiteTextures) largest = std::max(largest, (size_t)ByteCount(res->GetDesc())); { auto staging = CreateBlackResource(*threadContext.GetDevice(), CreateDesc(BindFlag::TransferSrc, 0, 0, LinearBufferDesc{(unsigned)largest}, "staging")); auto encoder = metalContext.BeginBlitEncoder(); for (const auto& res:blackTextures) encoder.Copy(*res, *staging); } { auto staging = CreateWhiteResource(*threadContext.GetDevice(), CreateDesc(BindFlag::TransferSrc, 0, 0, LinearBufferDesc{(unsigned)largest}, "staging")); auto encoder = metalContext.BeginBlitEncoder(); for (const auto& res:whiteTextures) encoder.Copy(*res, *staging); } _pendingCompleteInitialization = false; } namespace AttachmentSemantics { const char* TryDehash(uint64_t hashValue) { switch (hashValue) { case MultisampleDepth: return "MultisampleDepth"; case GBufferDiffuse: return "GBufferDiffuse"; case GBufferNormal: return "GBufferNormal"; case GBufferNormalPrev: return "GBufferNormalPrev"; case GBufferParameter: return "GBufferParameter"; case GBufferMotion: return "GBufferMotion"; case ColorLDR: return "ColorLDR"; case ColorHDR: return "ColorHDR"; case Depth: return "Depth"; case ShadowDepthMap: return "ShadowDepthMap"; case HierarchicalDepths: return "HierarchicalDepths"; case TiledLightBitField: return "TiledLightBitField"; case ConstHash64<'SSRe', 'flec', 'tion'>::Value: return "SSReflection"; case ConstHash64<'SSRe', 'flec', 'tion'>::Value+1: return "SSReflectionPrev"; case ConstHash64<'SSRC', 'onfi', 'denc', 'e'>::Value: return "SSRConfidence"; case ConstHash64<'SSRC', 'onfi', 'denc', 'e'>::Value+1: return "SSRConfidencePrev"; case ConstHash64<'SSRC', 'onfi', 'denc', 'eInt'>::Value: return "SSRConfidenceInt"; case ConstHash64<'SSRI', 'nt'>::Value: return "SSRInt"; case ConstHash64<'SSRD', 'ebug'>::Value: return "SSRDebug"; default: return nullptr; } } } namespace CommonSemantics { std::pair<const char*, unsigned> TryDehash(uint64_t hashValue) { if ((hashValue - POSITION) < 16) return std::make_pair("POSITION", unsigned(hashValue - POSITION)); if ((hashValue - PIXELPOSITION) < 16) return std::make_pair("PIXELPOSITION", unsigned(hashValue - PIXELPOSITION)); else if ((hashValue - TEXCOORD) < 16) return std::make_pair("TEXCOORD", unsigned(hashValue - TEXCOORD)); else if ((hashValue - COLOR) < 16) return std::make_pair("COLOR", unsigned(hashValue - COLOR)); else if ((hashValue - NORMAL) < 16) return std::make_pair("NORMAL", unsigned(hashValue - NORMAL)); else if ((hashValue - TEXTANGENT) < 16) return std::make_pair("TEXTANGENT", unsigned(hashValue - TEXTANGENT)); else if ((hashValue - TEXBITANGENT) < 16) return std::make_pair("TEXBITANGENT", unsigned(hashValue - TEXBITANGENT)); else if ((hashValue - BONEINDICES) < 16) return std::make_pair("BONEINDICES", unsigned(hashValue - BONEINDICES)); else if ((hashValue - BONEWEIGHTS) < 16) return std::make_pair("BONEWEIGHTS", unsigned(hashValue - BONEWEIGHTS)); else if ((hashValue - PER_VERTEX_AO) < 16) return std::make_pair("PER_VERTEX_AO", unsigned(hashValue - PER_VERTEX_AO)); else if ((hashValue - RADIUS) < 16) return std::make_pair("RADIUS", unsigned(hashValue - RADIUS)); else return std::make_pair(nullptr, ~0u); } } }}
62.639024
232
0.696052
djewsbury
966417aa7ffa9a07a97bc85a1348824217b9e726
5,067
cpp
C++
OpenSHMEM/buffon.cpp
aljo242/nn_training
ce583cbf5a03ec10dbece768961863720f83093b
[ "Apache-2.0" ]
null
null
null
OpenSHMEM/buffon.cpp
aljo242/nn_training
ce583cbf5a03ec10dbece768961863720f83093b
[ "Apache-2.0" ]
null
null
null
OpenSHMEM/buffon.cpp
aljo242/nn_training
ce583cbf5a03ec10dbece768961863720f83093b
[ "Apache-2.0" ]
null
null
null
#include <cstdlib> #include <iostream> #include <iomanip> #include <cmath> #include <shmem.h> static const double PI = 3.141592653589793238462643; int buffon_laplace_simulate(double a, double b, double l, int trial_num) { double angle; int hits; int trial; double x1; double x2; double y1; double y2; hits = 0; for (trial = 1; trial <= trial_num; ++trial) { // // Randomly choose the location of the eye of the needle in // [0,0]x[A,B], // and the angle the needle makes. // x1 = a * (double) rand() / (double) RAND_MAX; y1 = b * (double) rand() / (double) RAND_MAX; angle = 2.0 * PI * (double) rand() / (double) RAND_MAX; // // Compute the location of the point of the needle. // x2 = x1 + l * cos(angle); y2 = y1 + l * sin(angle); // // Count the end locations that lie outside the cell. // if (x2 <= 0.0 || a <= x2 || y2 <= 0.0 || b <= y2) { ++hits; } } return hits; } double r8_abs(double x) { return (0.0 <= x) ? x : (-x); } double r8_huge() { return 1.0E+30; } // // symmetric variables for reduction // int pWrk[SHMEM_REDUCE_SYNC_SIZE]; long pSync[SHMEM_BCAST_SYNC_SIZE]; int hit_total; int hit_num; int main() { const double a = 1.0; const double b = 1.0; const double l = 1.0; const int master = 0; double pdf_estimate; double pi_error; double pi_estimate; int process_num; int process_rank; double random_value; int seed; int trial_num = 100000; int trial_total; // // Initialize SHMEM. // shmem_init(); // // Get the number of processes. // process_num = shmem_n_pes(); // // Get the rank of this process. // process_rank = shmem_my_pe(); // // The master process prints a message. // if (process_rank == master) { std::cout << "\n"; std::cout << "BUFFON_LAPLACE - Master process:\n"; std::cout << " C++ version\n"; std::cout << "\n"; std::cout << " A SHMEM example program to estimate PI\n"; std::cout << " using the Buffon-Laplace needle experiment.\n"; std::cout << " On a grid of cells of width A and height B,\n"; std::cout << " a needle of length L is dropped at random.\n"; std::cout << " We count the number of times it crosses\n"; std::cout << " at least one grid line, and use this to estimate \n"; std::cout << " the value of PI.\n"; std::cout << "\n"; std::cout << " The number of processes is " << process_num << "\n"; std::cout << "\n"; std::cout << " Cell width A = " << a << "\n"; std::cout << " Cell height B = " << b << "\n"; std::cout << " Needle length L = " << l << "\n"; } // // added barrier here to force output sequence // shmem_barrier_all(); // // Each process sets a random number seed. // seed = 123456789 + process_rank * 100; srand(seed); // // Just to make sure that we're all doing different things, have each // process print out its rank, seed value, and a first test random value. // random_value = (double) rand() / (double) RAND_MAX; std::cout << " " << std::setw(8) << process_rank << " " << std::setw(12) << seed << " " << std::setw(14) << random_value << "\n"; // // Each process now carries out TRIAL_NUM trials, and then // sends the value back to the master process. // hit_num = buffon_laplace_simulate(a, b, l, trial_num); // // initialize sync buffer for reduction // for (int i = 0; i < SHMEM_BCAST_SYNC_SIZE; ++i) { pSync[i] = SHMEM_SYNC_VALUE; } shmem_barrier_all(); shmem_int_sum_to_all(&hit_total, &hit_num, 1, 0, 0, process_num, pWrk, pSync); // // The master process can now estimate PI. // if (process_rank == master) { trial_total = trial_num * process_num; pdf_estimate = (double) hit_total / (double) trial_total; if (hit_total == 0) { pi_estimate = r8_huge(); } else { pi_estimate = l * (2.0 * (a + b) - l) / (a * b * pdf_estimate); } pi_error = r8_abs(PI - pi_estimate); std::cout << "\n"; std::cout << " Trials Hits Estimated PDF Estimated Pi Error\n"; std::cout << "\n"; std::cout << " " << std::setw(8) << trial_total << " " << std::setw(8) << hit_total << " " << std::setw(16) << pdf_estimate << " " << std::setw(16) << pi_estimate << " " << std::setw(16) << pi_error << "\n"; } // // Shut down // if (process_rank == master) { std::cout << "\n"; std::cout << "BUFFON_LAPLACE - Master process:\n"; std::cout << " Normal end of execution.\n"; } shmem_finalize(); return 0; }
26.253886
86
0.525755
aljo242
966c21903180632e01bb45310a389af5a4677467
8,719
cpp
C++
src/wrapper/lua_qevent.cpp
nddvn2008/bullet-physics-playground
2895af190054b6a38525b679cf3f241c7147ee6f
[ "Zlib" ]
1
2015-10-05T01:25:18.000Z
2015-10-05T01:25:18.000Z
src/wrapper/lua_qevent.cpp
nddvn2008/bullet-physics-playground
2895af190054b6a38525b679cf3f241c7147ee6f
[ "Zlib" ]
null
null
null
src/wrapper/lua_qevent.cpp
nddvn2008/bullet-physics-playground
2895af190054b6a38525b679cf3f241c7147ee6f
[ "Zlib" ]
2
2015-01-02T20:02:13.000Z
2018-02-26T03:08:43.000Z
#include "lua_qevent.h" #include "luabind/dependency_policy.hpp" namespace luabind{ QT_ENUM_CONVERTER(Qt::KeyboardModifiers) QT_ENUM_CONVERTER(Qt::MouseButtons) QT_ENUM_CONVERTER(Qt::MouseButton) QT_ENUM_CONVERTER(Qt::DropAction) QT_ENUM_CONVERTER(Qt::DropActions) } template<typename T> bool isEvent(QEvent::Type type); template<typename T> struct myEventFilter : public QObject { myEventFilter(const object& obj):m_obj(obj){} virtual bool eventFilter(QObject * obj, QEvent * event) { try{ if(isEvent<T>(event->type())){ T* evt = static_cast<T *>(event); if(evt){ bool res = false; if(type(m_obj) == LUA_TFUNCTION){ res = call_function<bool>(m_obj,obj,evt); }else if(type(m_obj) == LUA_TTABLE){ object c,f; for(iterator i(m_obj),e;i!=e;++i){ if(type(*i) == LUA_TUSERDATA){ c = *i; }else if(type(*i) == LUA_TFUNCTION){ f = *i; }else if(type(*i) == LUA_TSTRING){ f = *i; } } if(f && c){ if(type(f) == LUA_TFUNCTION){ res = call_function<bool>(f,c,obj,evt); }else if(type(f) == LUA_TSTRING){ res = call_member<bool>(c,object_cast<const char*>(f),obj,evt); } } } if(res) return res; } } }catch(...){} return QObject::eventFilter(obj,event); } private: object m_obj; }; template<>bool isEvent<QEvent>(QEvent::Type){ return true; } template<>bool isEvent<QInputEvent>(QEvent::Type){ return true; } template<>bool isEvent<QCloseEvent>(QEvent::Type type){ return type == QEvent::Close; } template<>bool isEvent<QContextMenuEvent>(QEvent::Type type){ return type == QEvent::ContextMenu; } template<>bool isEvent<QKeyEvent>(QEvent::Type type){ return type == QEvent::KeyPress || type == QEvent::KeyRelease; } template<>bool isEvent<QMouseEvent>(QEvent::Type type){ switch(type){ case QEvent::MouseButtonDblClick: case QEvent::MouseMove: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: return true; default: return false; } return false; } template<>bool isEvent<QWheelEvent>(QEvent::Type type){ return type == QEvent::Wheel; } template<>bool isEvent<QPaintEvent>(QEvent::Type type){ return type == QEvent::Paint; } template<>bool isEvent<QTimerEvent>(QEvent::Type type){ return type == QEvent::Timer; } template<>bool isEvent<QResizeEvent>(QEvent::Type type){ return type == QEvent::Resize; } template<>bool isEvent<QShowEvent>(QEvent::Type type){ return type == QEvent::Show; } template<>bool isEvent<QHideEvent>(QEvent::Type type){ return type == QEvent::Hide; } template<>bool isEvent<QDropEvent>(QEvent::Type type){ return type == QEvent::Drop; } template<>bool isEvent<QDragEnterEvent>(QEvent::Type type){ return type == QEvent::DragEnter; } template<>bool isEvent<QDragMoveEvent>(QEvent::Type type){ return type == QEvent::DragMove; } template<>bool isEvent<QDragLeaveEvent>(QEvent::Type type){ return type == QEvent::DragLeave; } template<typename T> QObject* event_filter(const object& obj) { return new myEventFilter<T>(obj); } void lqevent_init_general(const luabind::argument & arg) { construct<QEvent>(arg,QEvent::Type(0)); } LQEvent lqevent() { return class_<QEvent>("QEvent") .def("__init",lqevent_init_general) .def(constructor<QEvent::Type>()) .def("accept", &QEvent::accept) .def("ignore", &QEvent::ignore) .property("type" , &QEvent::type) .property("accepted" , &QEvent::isAccepted, &QEvent::setAccepted) .scope[ def("filter", event_filter<QEvent>)] ; } LQInputEvent lqinputevent() { return LQInputEvent("QInputEvent") .property("modifiers", &QInputEvent::modifiers, &QInputEvent::setModifiers) .scope[ def("filter", event_filter<QInputEvent>)] ; } LQCloseEvent lqcloseevent() { return LQCloseEvent("QCloseEvent") .scope[ def("filter", event_filter<QCloseEvent>)] ; } LQContextMenuEvent lqcontextmenuevent() { return LQContextMenuEvent("QContextMenuEvent") .property("globalPos", &QContextMenuEvent::globalPos) .property("globalX", &QContextMenuEvent::globalX) .property("globalY", &QContextMenuEvent::globalY) .property("pos", &QContextMenuEvent::pos) .property("x", &QContextMenuEvent::x) .property("y", &QContextMenuEvent::y) .property("reason", &QContextMenuEvent::reason) .scope[ def("filter", event_filter<QContextMenuEvent>)] ; } LQKeyEvent lqkeyevent() { return LQKeyEvent("QKeyEvent") .def("matches", &QKeyEvent::matches) .property("count", &QKeyEvent::count) .property("autoRepeat", &QKeyEvent::isAutoRepeat) .property("key", &QKeyEvent::key) .property("text", &QKeyEvent::text) .property("modifiers", &QKeyEvent::modifiers) .scope[ def("filter", event_filter<QKeyEvent>)] ; } LQMouseEvent lqmouseevent() { return LQMouseEvent("QMouseEvent") .property("button", &QMouseEvent::button) .property("buttons", &QMouseEvent::buttons) .property("globalPos", &QMouseEvent::globalPos) .property("globalX", &QMouseEvent::globalX) .property("globalY", &QMouseEvent::globalY) .property("pos", &QMouseEvent::pos) .property("x", &QMouseEvent::x) .property("y", &QMouseEvent::y) .scope[ def("filter", event_filter<QMouseEvent>)] ; } LQWheelEvent lqwheelevent() { return LQWheelEvent("QWheelEvent") .property("buttons", &QWheelEvent::buttons) .property("globalPos", &QWheelEvent::globalPos) .property("globalX", &QWheelEvent::globalX) .property("globalY", &QWheelEvent::globalY) .property("pos", &QWheelEvent::pos) .property("x", &QWheelEvent::x) .property("y", &QWheelEvent::y) .property("orientation", &QWheelEvent::orientation) .scope[ def("filter", event_filter<QWheelEvent>)] ; } LQPaintEvent lqpaintevent() { return LQPaintEvent("QPaintEvent") .property("rect", &QPaintEvent::rect) .scope[ def("filter", event_filter<QPaintEvent>)] ; } LQTimerEvent lqtimerevent() { return LQTimerEvent("QTimerEvent") .property("timerId", &QTimerEvent::timerId) .scope[ def("filter", event_filter<QTimerEvent>)] ; } LQResizeEvent lqresizeevent() { return LQResizeEvent("QResizeEvent") .property("oldSize", &QResizeEvent::oldSize) .property("size", &QResizeEvent::size) .scope[ def("filter", event_filter<QResizeEvent>)] ; } LQShowEvent lqshowevent() { return LQShowEvent("QShowEvent") .scope[ def("filter", event_filter<QShowEvent>)] ; } LQHideEvent lqhideevent() { return LQHideEvent("QHideEvent") .scope[ def("filter", event_filter<QHideEvent>)] ; } LQDropEvent lqdropevent() { return LQDropEvent("QDropEvent") .def("acceptProposedAction", &QDropEvent::acceptProposedAction) .property("dropAction", &QDropEvent::dropAction, &QDropEvent::setDropAction) .property("keyboardModifiers", &QDropEvent::keyboardModifiers) .property("mimeData", &QDropEvent::mimeData) .property("mouseButtons", &QDropEvent::mouseButtons) .property("possibleActions", &QDropEvent::possibleActions) .property("proposedAction", &QDropEvent::proposedAction) .property("source", &QDropEvent::source) .property("pos", &QDropEvent::pos) .scope[ def("filter", event_filter<QDropEvent>)] ; } LQDragMoveEvent lqdragmoveevent() { return LQDragMoveEvent("QDragMoveEvent") .def("accept", ( void (QDragMoveEvent::*)())&QDragMoveEvent::accept) .def("accept", ( void (QDragMoveEvent::*)(const QRect&))&QDragMoveEvent::accept) .def("ignore", ( void (QDragMoveEvent::*)())&QDragMoveEvent::ignore) .def("ignore", ( void (QDragMoveEvent::*)(const QRect&))&QDragMoveEvent::ignore) .property("answerRect", &QDragMoveEvent::answerRect) .scope[ def("filter", event_filter<QDragMoveEvent>)] ; } LQDragEnterEvent lqdragenterevent() { return LQDragEnterEvent("QDragEnterEvent") .scope[ def("filter", event_filter<QDragEnterEvent>)] ; } LQDragLeaveEvent lqdragleaveevent() { return LQDragLeaveEvent("QDragLeaveEvent") .scope[ def("filter", event_filter<QDragLeaveEvent>)] ; }
31.59058
118
0.634247
nddvn2008
966f066b660428f453e76ff4f9310ab3f7219133
23,540
cc
C++
usd/src/usd_parser/USDLinks.cc
robotics-upo/sdformat
30f01b38b5284db2160a566fe8957a00ea707700
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
usd/src/usd_parser/USDLinks.cc
robotics-upo/sdformat
30f01b38b5284db2160a566fe8957a00ea707700
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
usd/src/usd_parser/USDLinks.cc
robotics-upo/sdformat
30f01b38b5284db2160a566fe8957a00ea707700
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "USDLinks.hh" #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #pragma push_macro ("__DEPRECATED") #undef __DEPRECATED #include <pxr/usd/kind/registry.h> #include <pxr/usd/usd/modelAPI.h> #include <pxr/usd/usdGeom/cube.h> #include <pxr/usd/usdGeom/cylinder.h> #include <pxr/usd/usdGeom/gprim.h> #include <pxr/usd/usdGeom/mesh.h> #include <pxr/usd/usdGeom/sphere.h> #include <pxr/usd/usdGeom/subset.h> #include "pxr/usd/usdPhysics/collisionAPI.h" #include "pxr/usd/usdPhysics/massAPI.h" #include <pxr/usd/usdPhysics/rigidBodyAPI.h> #include <pxr/usd/usdShade/materialBindingAPI.h> #pragma pop_macro ("__DEPRECATED") #include <ignition/common/ColladaExporter.hh> #include <ignition/common/Filesystem.hh> #include <ignition/common/Material.hh> #include <ignition/common/Mesh.hh> #include <ignition/common/SubMesh.hh> #include <ignition/common/Util.hh> #include <ignition/math/Inertial.hh> #include "sdf/Box.hh" #include "sdf/Collision.hh" #include "sdf/Cylinder.hh" #include "sdf/Geometry.hh" #include "sdf/Link.hh" #include "sdf/Mesh.hh" #include "sdf/Sphere.hh" #include "sdf/Visual.hh" #include "polygon_helper.hh" #include "sdf/usd/usd_parser/USDTransforms.hh" #include "sdf/usd/UsdError.hh" #include "../Conversions.hh" namespace sdf { // Inline bracket to help doxygen filtering. inline namespace SDF_VERSION_NAMESPACE { // namespace usd { ////////////////////////////////////////////////// void GetInertial( const pxr::UsdPrim &_prim, ignition::math::Inertiald &_inertial) { float mass; pxr::GfVec3f centerOfMass; pxr::GfVec3f diagonalInertia; pxr::GfQuatf principalAxes; ignition::math::MassMatrix3d massMatrix; if (_prim.HasAPI<pxr::UsdPhysicsRigidBodyAPI>()) { if (pxr::UsdAttribute massAttribute = _prim.GetAttribute(pxr::TfToken("physics:mass"))) { massAttribute.Get(&mass); if (pxr::UsdAttribute centerOfMassAttribute = _prim.GetAttribute(pxr::TfToken("physics:centerOfMass"))) { centerOfMassAttribute.Get(&centerOfMass); } if (pxr::UsdAttribute diagonalInertiaAttribute = _prim.GetAttribute(pxr::TfToken("physics:diagonalInertia"))) { diagonalInertiaAttribute.Get(&diagonalInertia); } if (pxr::UsdAttribute principalAxesAttribute = _prim.GetAttribute(pxr::TfToken("physics:principalAxes"))) { principalAxesAttribute.Get(&principalAxes); } // Added a diagonal inertia to avoid crash with the physics engine if (diagonalInertia == pxr::GfVec3f(0, 0, 0)) { diagonalInertia = pxr::GfVec3f(0.0001, 0.0001, 0.0001); } // Added a mass to avoid crash with the physics engine if (mass < 0.0001) { mass = 0.1; } massMatrix.SetMass(mass); // TODO(ahcorde) Figure out how to use PrincipalMoments and // PrincipalAxesOffset: see // https://github.com/ignitionrobotics/sdformat/pull/902#discussion_r840905534 massMatrix.SetDiagonalMoments( ignition::math::Vector3d( diagonalInertia[0], diagonalInertia[1], diagonalInertia[2])); _inertial.SetPose(ignition::math::Pose3d( ignition::math::Vector3d( centerOfMass[0], centerOfMass[1], centerOfMass[2]), ignition::math::Quaterniond(1.0, 0, 0, 0))); _inertial.SetMassMatrix(massMatrix); } } else { auto parent = _prim.GetParent(); if (parent) { GetInertial(parent, _inertial); } } } ////////////////////////////////////////////////// /// \brief Create the directory based on the USD path /// \param[in] _primPath Reference to the USD prim /// \return A string with the path std::string directoryFromUSDPath(const std::string &_primPath) { std::vector<std::string> tokensChild = ignition::common::split(_primPath, "/"); std::string directoryMesh; if (tokensChild.size() > 1) { directoryMesh = tokensChild[0]; for (unsigned int i = 1; i < tokensChild.size() - 1; ++i) { directoryMesh = ignition::common::joinPaths( directoryMesh, tokensChild[i+1]); } } return directoryMesh; } ////////////////////////////////////////////////// /// \brief Get the material name of the prim /// \param[in] _prim Reference to the USD prim /// \return A string with the material name std::string ParseMaterialName(const pxr::UsdPrim &_prim) { // Materials std::string nameMaterial; auto bindMaterial = pxr::UsdShadeMaterialBindingAPI(_prim); pxr::UsdRelationship directBindingRel = bindMaterial.GetDirectBindingRel(); pxr::SdfPathVector paths; directBindingRel.GetTargets(&paths); for (const auto & p : paths) { std::vector<std::string> tokensMaterial = ignition::common::split(pxr::TfStringify(p), "/"); if(tokensMaterial.size() > 0) { nameMaterial = tokensMaterial[tokensMaterial.size() - 1]; } } return nameMaterial; } ////////////////////////////////////////////////// /// \brief Parse USD mesh subsets /// \param[in] _prim Reference to the USD prim /// \param[in] _link Current link /// \param[in] _subMesh submesh to add the subsets /// \param[in] _meshGeom Mesh geom /// \param[inout] _scale scale mesh /// \param[in] _usdData metadata of the USD file /// \return Number of mesh subsets int ParseMeshSubGeom(const pxr::UsdPrim &_prim, sdf::Link *_link, ignition::common::SubMesh &_subMesh, sdf::Mesh &_meshGeom, ignition::math::Vector3d &_scale, const USDData &_usdData) { int numSubMeshes = 0; for (const auto & child : _prim.GetChildren()) { if (child.IsA<pxr::UsdGeomSubset>()) { sdf::Visual visSubset; std::string nameMaterial = ParseMaterialName(child); auto it = _usdData.Materials().find(nameMaterial); if (it != _usdData.Materials().end()) { visSubset.SetMaterial(it->second); } ignition::common::Mesh meshSubset; numSubMeshes++; ignition::common::SubMesh subMeshSubset; subMeshSubset.SetPrimitiveType(ignition::common::SubMesh::TRISTRIPS); subMeshSubset.SetName("subgeommesh_" + std::to_string(numSubMeshes)); if (it != _usdData.Materials().end()) { std::shared_ptr<ignition::common::Material> matCommon = std::make_shared<ignition::common::Material>(); convert(it->second, *matCommon.get()); meshSubset.AddMaterial(matCommon); subMeshSubset.SetMaterialIndex(meshSubset.MaterialCount() - 1); } pxr::VtIntArray faceVertexIndices; child.GetAttribute(pxr::TfToken("indices")).Get(&faceVertexIndices); for (unsigned int i = 0; i < faceVertexIndices.size(); ++i) { subMeshSubset.AddIndex(_subMesh.Index(faceVertexIndices[i] * 3)); subMeshSubset.AddIndex(_subMesh.Index(faceVertexIndices[i] * 3 + 1)); subMeshSubset.AddIndex(_subMesh.Index(faceVertexIndices[i] * 3 + 2)); } for (unsigned int i = 0; i < _subMesh.VertexCount(); ++i) { subMeshSubset.AddVertex(_subMesh.Vertex(i)); } for (unsigned int i = 0; i < _subMesh.NormalCount(); ++i) { subMeshSubset.AddNormal(_subMesh.Normal(i)); } for (unsigned int i = 0; i < _subMesh.TexCoordCount(); ++i) { subMeshSubset.AddTexCoord(_subMesh.TexCoord(i)); } meshSubset.AddSubMesh(subMeshSubset); sdf::Mesh meshGeomSubset; sdf::Geometry geomSubset; geomSubset.SetType(sdf::GeometryType::MESH); std::string childPathName = pxr::TfStringify(child.GetPath()); std::string directoryMesh = directoryFromUSDPath(childPathName) + childPathName; if (ignition::common::createDirectories(directoryMesh)) { directoryMesh = ignition::common::joinPaths(directoryMesh, ignition::common::basename(directoryMesh)); // Export with extension ignition::common::ColladaExporter exporter; exporter.Export(&meshSubset, directoryMesh, false); } _meshGeom.SetFilePath(directoryMesh + ".dae"); _meshGeom.SetUri(directoryMesh + ".dae"); geomSubset.SetMeshShape(_meshGeom); visSubset.SetName("mesh_subset_" + std::to_string(numSubMeshes)); visSubset.SetGeom(geomSubset); ignition::math::Pose3d pose; ignition::math::Vector3d scale(1, 1, 1); std::string linkName = pxr::TfStringify(_prim.GetPath()); auto found = linkName.find(_link->Name()); if (found != std::string::npos) { linkName = linkName.substr(0, found + _link->Name().size()); } GetTransform(child, _usdData, pose, scale, linkName); _scale *= scale; visSubset.SetRawPose(pose); _link->AddVisual(visSubset); } } return numSubMeshes; } ////////////////////////////////////////////////// /// \brief Parse USD mesh /// \param[in] _prim Reference to the USD prim /// \param[in] _link Current link /// \param[in] _vis sdf visual /// \param[in] _geom sdf geom /// \param[in] _scale scale mesh /// \param[in] _usdData metadata of the USD file /// \param[out] _pose The pose of the parsed mesh /// \return UsdErrors, which is a list of UsdError objects. An empty list means /// that no errors occurred when parsing the USD mesh UsdErrors ParseMesh( const pxr::UsdPrim &_prim, sdf::Link *_link, sdf::Visual &_vis, sdf::Geometry &_geom, ignition::math::Vector3d &_scale, const USDData &_usdData, ignition::math::Pose3d &_pose) { UsdErrors errors; const std::pair<std::string, std::shared_ptr<USDStage>> data = _usdData.FindStage(_prim.GetPath().GetName()); double metersPerUnit = data.second->MetersPerUnit(); ignition::common::Mesh mesh; ignition::common::SubMesh subMesh; subMesh.SetPrimitiveType(ignition::common::SubMesh::TRISTRIPS); pxr::VtIntArray faceVertexIndices; pxr::VtIntArray faceVertexCounts; pxr::VtArray<pxr::GfVec3f> normals; pxr::VtArray<pxr::GfVec3f> points; pxr::VtArray<pxr::GfVec2f> textCoords; _prim.GetAttribute(pxr::TfToken("faceVertexCounts")).Get(&faceVertexCounts); _prim.GetAttribute(pxr::TfToken("faceVertexIndices")).Get(&faceVertexIndices); _prim.GetAttribute(pxr::TfToken("normals")).Get(&normals); _prim.GetAttribute(pxr::TfToken("points")).Get(&points); _prim.GetAttribute(pxr::TfToken("primvars:st")).Get(&textCoords); if (textCoords.size() == 0) { _prim.GetAttribute(pxr::TfToken("primvars:st_0")).Get(&textCoords); } std::vector<unsigned int> indexes; errors = PolygonToTriangles( faceVertexIndices, faceVertexCounts, indexes); if (!errors.empty()) { errors.emplace_back(UsdErrorCode::USD_TO_SDF_POLYGON_PARSING_ERROR, "Unable to parse polygon in path [" + pxr::TfStringify(_prim.GetPath()) + "]"); return errors; } for (unsigned int i = 0; i < indexes.size(); ++i) { subMesh.AddIndex(indexes[i]); } for (const auto & textCoord : textCoords) { subMesh.AddTexCoord(textCoord[0], (1 - textCoord[1])); } for (const auto & point : points) { ignition::math::Vector3d v = ignition::math::Vector3d(point[0], point[1], point[2]) * metersPerUnit; subMesh.AddVertex(v); } for (const auto & normal : normals) { subMesh.AddNormal(normal[0], normal[1], normal[2]); } sdf::Mesh meshGeom; _geom.SetType(sdf::GeometryType::MESH); ignition::math::Pose3d pose; ignition::math::Vector3d scale(1, 1, 1); std::string linkName = pxr::TfStringify(_prim.GetPath()); auto found = linkName.find(_link->Name()); if (found != std::string::npos) { linkName = linkName.substr(0, found + _link->Name().size()); } size_t nSlash = std::count(linkName.begin(), linkName.end(), '/'); if (nSlash == 1) { GetTransform(_prim, _usdData, pose, scale, "/"); } else { GetTransform(_prim, _usdData, pose, scale, linkName); } _pose = pose; meshGeom.SetScale(scale * _scale); std::string primName = pxr::TfStringify(_prim.GetPath()); std::string directoryMesh = directoryFromUSDPath(primName) + primName; meshGeom.SetFilePath( ignition::common::joinPaths( directoryMesh, ignition::common::basename(directoryMesh)) + ".dae"); meshGeom.SetUri(meshGeom.FilePath()); int numSubMeshes = ParseMeshSubGeom( _prim, _link, subMesh, meshGeom, _scale, _usdData); _geom.SetMeshShape(meshGeom); if (numSubMeshes == 0) { std::string nameMaterial = ParseMaterialName(_prim); auto it = _usdData.Materials().find(nameMaterial); if (it != _usdData.Materials().end()) { _vis.SetMaterial(it->second); std::shared_ptr<ignition::common::Material> matCommon = std::make_shared<ignition::common::Material>(); convert(it->second, *matCommon.get()); mesh.AddMaterial(matCommon); subMesh.SetMaterialIndex(mesh.MaterialCount() - 1); } std::string primNameStr = _prim.GetPath().GetName(); _vis.SetName(primNameStr + "_visual"); _vis.SetRawPose(pose); _vis.SetGeom(_geom); _link->AddVisual(_vis); mesh.AddSubMesh(subMesh); if (ignition::common::createDirectories(directoryMesh)) { directoryMesh = ignition::common::joinPaths( directoryMesh, ignition::common::basename(directoryMesh)); // Export with extension ignition::common::ColladaExporter exporter; exporter.Export(&mesh, directoryMesh, false); } } return errors; } ////////////////////////////////////////////////// /// \brief Parse USD cube /// \param[in] _prim Reference to the USD prim /// \param[in] _geom sdf geom /// \param[in] _scale scale mesh /// \param[in] _metersPerUnit meter per unit of the stage void ParseCube(const pxr::UsdPrim &_prim, sdf::Geometry &_geom, const ignition::math::Vector3d &_scale, double _metersPerUnit) { double size; auto variant_cube = pxr::UsdGeomCube(_prim); variant_cube.GetSizeAttr().Get(&size); size = size * _metersPerUnit; sdf::Box box; _geom.SetType(sdf::GeometryType::BOX); box.SetSize(ignition::math::Vector3d( size * _scale.X(), size * _scale.Y(), size * _scale.Z())); _geom.SetBoxShape(box); } ////////////////////////////////////////////////// /// \brief Parse USD sphere /// \param[in] _prim Reference to the USD prim /// \param[in] _geom sdf geom /// \param[in] _scale scale mesh /// \param[in] _metersPerUnit meter per unit of the stage void ParseSphere(const pxr::UsdPrim &_prim, sdf::Geometry &_geom, const ignition::math::Vector3d &_scale, double _metersPerUnit) { double radius; auto variant_sphere = pxr::UsdGeomSphere(_prim); variant_sphere.GetRadiusAttr().Get(&radius); sdf::Sphere s; _geom.SetType(sdf::GeometryType::SPHERE); s.SetRadius(radius * _metersPerUnit * _scale.X()); _geom.SetSphereShape(s); } ////////////////////////////////////////////////// /// \brief Parse USD cylinder /// \param[in] _prim Reference to the USD prim /// \param[in] _geom sdf geom /// \param[in] _scale scale mesh /// \param[in] _metersPerUnit meter per unit of the stage void ParseCylinder( const pxr::UsdPrim &_prim, sdf::Geometry &_geom, const ignition::math::Vector3d &_scale, double _metersPerUnit) { auto variant_cylinder = pxr::UsdGeomCylinder(_prim); double radius; double height; variant_cylinder.GetRadiusAttr().Get(&radius); variant_cylinder.GetHeightAttr().Get(&height); sdf::Cylinder c; _geom.SetType(sdf::GeometryType::CYLINDER); c.SetRadius(radius * _metersPerUnit * _scale.X()); c.SetLength(height * _metersPerUnit * _scale.Z()); _geom.SetCylinderShape(c); } ////////////////////////////////////////////////// UsdErrors ParseUSDLinks( const pxr::UsdPrim &_prim, const std::string &_nameLink, std::optional<sdf::Link> &_link, const USDData &_usdData, ignition::math::Vector3d &_scale) { UsdErrors errors; const std::string primNameStr = _prim.GetPath().GetName(); const std::string primPathStr = pxr::TfStringify(_prim.GetPath()); const std::string primType = _prim.GetPrimTypeInfo().GetTypeName().GetText(); const std::pair<std::string, std::shared_ptr<USDStage>> data = _usdData.FindStage(primNameStr); // Is this a new link ? if (!_link) { _link = sdf::Link(); _link->SetName(ignition::common::basename(_nameLink)); // USD define visual inside other visuals or links // This loop allow to find the link for a specific visual // For example // This visual /ur10_long_suction/shoulder_link/cylinder // correponds to the link /ur10_long_suction/wrist_3_link // Then we can find the right transformations std::string originalPrimName = pxr::TfStringify(_prim.GetPath()); size_t pos = std::string::npos; std::string nameOfLink; if ((pos = originalPrimName.find(_link->Name()))!= std::string::npos) { nameOfLink = originalPrimName.erase( pos + _link->Name().length(), originalPrimName.length() - (pos + _link->Name().length())); } pxr::UsdPrim tmpPrim = _prim; if (!nameOfLink.empty()) { while (tmpPrim) { if (pxr::TfStringify(tmpPrim.GetPath()) == nameOfLink) { break; } tmpPrim = tmpPrim.GetParent(); } } ignition::math::Pose3d pose; ignition::math::Vector3d scale(1, 1, 1); GetTransform(tmpPrim, _usdData, pose, scale, ""); // This is a special case when a geometry is defined in the higher level // of the path. we should only set the position if the path at least has // more than 1 level. // TODO(ahcorde) Review this code and improve this logic size_t nSlash = std::count(_nameLink.begin(), _nameLink.end(), '/'); if (nSlash > 1) _link->SetRawPose(pose); _scale *= scale; } // If the schema is a rigid body use this name instead. if (_prim.HasAPI<pxr::UsdPhysicsRigidBodyAPI>()) { _link->SetName(ignition::common::basename(primPathStr)); } ignition::math::Inertiald noneInertial = {{1.0, ignition::math::Vector3d::One, ignition::math::Vector3d::Zero}, ignition::math::Pose3d::Zero}; const auto inertial = _link->Inertial(); if (inertial == noneInertial) { ignition::math::Inertiald newInertial; GetInertial(_prim, newInertial); _link->SetInertial(newInertial); } sdf::Geometry geom; if (_prim.IsA<pxr::UsdGeomSphere>() || _prim.IsA<pxr::UsdGeomCylinder>() || _prim.IsA<pxr::UsdGeomCube>() || _prim.IsA<pxr::UsdGeomMesh>() || primType == "Plane") { sdf::Visual vis; auto variant_geom = pxr::UsdGeomGprim(_prim); bool collisionEnabled = false; if (_prim.HasAPI<pxr::UsdPhysicsCollisionAPI>()) { _prim.GetAttribute( pxr::TfToken("physics:collisionEnabled")).Get(&collisionEnabled); } pxr::TfToken kindOfSchema; if(!pxr::UsdModelAPI(_prim).GetKind(&kindOfSchema)) { auto parent = _prim.GetParent(); pxr::UsdModelAPI(parent).GetKind(&kindOfSchema); } if ((_prim.HasAPI<pxr::UsdPhysicsRigidBodyAPI>() || pxr::KindRegistry::IsA(kindOfSchema, pxr::KindTokens->model)) && (!collisionEnabled || _prim.HasAPI<pxr::UsdPhysicsMassAPI>())) { double metersPerUnit = data.second->MetersPerUnit(); if (_prim.IsA<pxr::UsdGeomSphere>()) { ParseSphere(_prim, geom, _scale, metersPerUnit); vis.SetName("visual_sphere"); vis.SetGeom(geom); _link->AddVisual(vis); } else if (_prim.IsA<pxr::UsdGeomCylinder>()) { ParseCylinder(_prim, geom, _scale, metersPerUnit); vis.SetName("visual_cylinder"); vis.SetGeom(geom); _link->AddVisual(vis); } else if (_prim.IsA<pxr::UsdGeomCube>()) { ParseCube(_prim, geom, _scale, metersPerUnit); vis.SetName("visual_box"); vis.SetGeom(geom); _link->AddVisual(vis); } else if (_prim.IsA<pxr::UsdGeomMesh>()) { ignition::math::Pose3d poseTmp; errors = ParseMesh( _prim, &_link.value(), vis, geom, _scale, _usdData, poseTmp); if (!errors.empty()) { errors.emplace_back(UsdError( sdf::usd::UsdErrorCode::SDF_TO_USD_PARSING_ERROR, "Error parsing mesh")); return errors; } } } pxr::TfTokenVector schemasCollision = _prim.GetAppliedSchemas(); bool physxCollisionAPIenable = false; for (const auto & token : schemasCollision) { if (std::string(token.GetText()) == "PhysxCollisionAPI") { physxCollisionAPIenable = true; break; } } if (collisionEnabled || physxCollisionAPIenable) { sdf::Collision col; // add _collision extension std::string collisionName = _prim.GetPath().GetName() + "_collision"; col.SetName(collisionName); sdf::Geometry colGeom; ignition::math::Pose3d poseCol; ignition::math::Vector3d scaleCol(1, 1, 1); std::string linkName = pxr::TfStringify(_prim.GetPath()); auto found = linkName.find(_link->Name()); if (found != std::string::npos) { linkName = linkName.substr(0, found + _link->Name().size()); } GetTransform(_prim, _usdData, poseCol, scaleCol, linkName); scaleCol *= _scale; double metersPerUnit = data.second->MetersPerUnit(); if (_prim.IsA<pxr::UsdGeomSphere>()) { ParseSphere(_prim, colGeom, scaleCol, metersPerUnit); col.SetGeom(colGeom); col.SetRawPose(poseCol); } else if (_prim.IsA<pxr::UsdGeomCylinder>()) { ParseCylinder(_prim, colGeom, scaleCol, metersPerUnit); col.SetGeom(colGeom); col.SetRawPose(poseCol); } else if (_prim.IsA<pxr::UsdGeomCube>()) { ParseCube(_prim, colGeom, scaleCol, metersPerUnit); col.SetGeom(colGeom); col.SetRawPose(poseCol); } else if (_prim.IsA<pxr::UsdGeomMesh>()) { sdf::Visual visTmp; ignition::math::Pose3d poseTmp; errors = ParseMesh( _prim, &_link.value(), visTmp, colGeom, scaleCol, _usdData, poseTmp); if (!errors.empty()) { errors.emplace_back(UsdError( sdf::usd::UsdErrorCode::SDF_TO_USD_PARSING_ERROR, "Error parsing mesh")); return errors; } col.SetRawPose(poseTmp); col.SetGeom(colGeom); } else if (primType == "Plane") { sdf::Plane plane; colGeom.SetType(sdf::GeometryType::PLANE); plane.SetSize(ignition::math::Vector2d(100, 100)); colGeom.SetPlaneShape(plane); ignition::math::Pose3d pose; ignition::math::Vector3d scale(1, 1, 1); GetTransform( _prim, _usdData, pose, scale, pxr::TfStringify(_prim.GetPath())); col.SetRawPose(pose); col.SetGeom(colGeom); } _link->AddCollision(col); } } return errors; } } } }
30.140845
84
0.64537
robotics-upo
9670a4eeb240b1c0b16e6470a3f25e7d4d99184e
3,763
cpp
C++
coding/point_coding.cpp
ToshUxanoff/omim
a8acb5821c72bd78847d1c49968b14d15b1e06ee
[ "Apache-2.0" ]
13
2019-09-16T17:45:31.000Z
2022-01-29T15:51:52.000Z
coding/point_coding.cpp
MohammadMoeinfar/omim
7b7d1990143bc3cbe218ea14b5428d0fc02d78fc
[ "Apache-2.0" ]
37
2019-10-04T00:55:46.000Z
2019-12-27T15:13:19.000Z
coding/point_coding.cpp
vmihaylenko/omim
00087f340e723fc611cbc82e0ae898b9053b620a
[ "Apache-2.0" ]
13
2019-10-02T15:03:58.000Z
2020-12-28T13:06:22.000Z
#include "coding/point_coding.hpp" #include "geometry/mercator.hpp" #include "base/assert.hpp" #include "base/bits.hpp" #include "base/math.hpp" namespace { double CoordSize(uint8_t coordBits) { ASSERT_LESS_OR_EQUAL(coordBits, 32, ()); return static_cast<double>((uint64_t{1} << coordBits) - 1); } } // namespace uint32_t DoubleToUint32(double x, double min, double max, uint8_t coordBits) { ASSERT_GREATER_OR_EQUAL(coordBits, 1, ()); ASSERT_LESS_OR_EQUAL(coordBits, 32, ()); x = base::clamp(x, min, max); return static_cast<uint32_t>(0.5 + (x - min) / (max - min) * bits::GetFullMask(coordBits)); } double Uint32ToDouble(uint32_t x, double min, double max, uint8_t coordBits) { ASSERT_GREATER_OR_EQUAL(coordBits, 1, ()); ASSERT_LESS_OR_EQUAL(coordBits, 32, ()); return min + static_cast<double>(x) * (max - min) / bits::GetFullMask(coordBits); } m2::PointU PointDToPointU(double x, double y, uint8_t coordBits) { x = base::clamp(x, MercatorBounds::kMinX, MercatorBounds::kMaxX); y = base::clamp(y, MercatorBounds::kMinY, MercatorBounds::kMaxY); uint32_t const ix = static_cast<uint32_t>( 0.5 + (x - MercatorBounds::kMinX) / MercatorBounds::kRangeX * CoordSize(coordBits)); uint32_t const iy = static_cast<uint32_t>( 0.5 + (y - MercatorBounds::kMinY) / MercatorBounds::kRangeY * CoordSize(coordBits)); ASSERT_LESS_OR_EQUAL(ix, CoordSize(coordBits), ()); ASSERT_LESS_OR_EQUAL(iy, CoordSize(coordBits), ()); return m2::PointU(ix, iy); } m2::PointU PointDToPointU(m2::PointD const & pt, uint8_t coordBits) { return PointDToPointU(pt.x, pt.y, coordBits); } m2::PointD PointUToPointD(m2::PointU const & pt, uint8_t coordBits) { return m2::PointD(static_cast<double>(pt.x) * MercatorBounds::kRangeX / CoordSize(coordBits) + MercatorBounds::kMinX, static_cast<double>(pt.y) * MercatorBounds::kRangeY / CoordSize(coordBits) + MercatorBounds::kMinY); } // Obsolete functions ------------------------------------------------------------------------------ int64_t PointToInt64Obsolete(double x, double y, uint8_t coordBits) { int64_t const res = static_cast<int64_t>(PointUToUint64Obsolete(PointDToPointU(x, y, coordBits))); ASSERT_GREATER_OR_EQUAL(res, 0, ("Highest bits of (ix, iy) are not used, so res should be > 0.")); ASSERT_LESS_OR_EQUAL(static_cast<uint64_t>(res), uint64_t{3} << 2 * kPointCoordBits, ()); return res; } int64_t PointToInt64Obsolete(m2::PointD const & pt, uint8_t coordBits) { return PointToInt64Obsolete(pt.x, pt.y, coordBits); } m2::PointD Int64ToPointObsolete(int64_t v, uint8_t coordBits) { ASSERT_GREATER_OR_EQUAL(v, 0, ("Highest bits of (ix, iy) are not used, so res should be > 0.")); ASSERT_LESS_OR_EQUAL(static_cast<uint64_t>(v), uint64_t{3} << 2 * kPointCoordBits, ()); return PointUToPointD(Uint64ToPointUObsolete(static_cast<uint64_t>(v)), coordBits); } std::pair<int64_t, int64_t> RectToInt64Obsolete(m2::RectD const & r, uint8_t coordBits) { int64_t const p1 = PointToInt64Obsolete(r.minX(), r.minY(), coordBits); int64_t const p2 = PointToInt64Obsolete(r.maxX(), r.maxY(), coordBits); return std::make_pair(p1, p2); } m2::RectD Int64ToRectObsolete(std::pair<int64_t, int64_t> const & p, uint8_t coordBits) { m2::PointD const pt1 = Int64ToPointObsolete(p.first, coordBits); m2::PointD const pt2 = Int64ToPointObsolete(p.second, coordBits); return m2::RectD(pt1, pt2); } uint64_t PointUToUint64Obsolete(m2::PointU const & pt) { uint64_t const res = bits::BitwiseMerge(pt.x, pt.y); ASSERT_EQUAL(pt, Uint64ToPointUObsolete(res), ()); return res; } m2::PointU Uint64ToPointUObsolete(int64_t v) { m2::PointU res; bits::BitwiseSplit(v, res.x, res.y); return res; }
33.598214
100
0.69705
ToshUxanoff
9671460fad50fc96675723b56d38f5e2a22998ce
1,170
cpp
C++
codechef/STROPR.cpp
hardbeater/Coding-competition-solution
d75eb704caa26a33505f0488f91636cc27d4c849
[ "MIT" ]
1
2016-10-02T03:22:57.000Z
2016-10-02T03:22:57.000Z
codechef/STROPR.cpp
hardbeater/Coding-competition-solution
d75eb704caa26a33505f0488f91636cc27d4c849
[ "MIT" ]
null
null
null
codechef/STROPR.cpp
hardbeater/Coding-competition-solution
d75eb704caa26a33505f0488f91636cc27d4c849
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<vector> #include<cstdlib> #include<cmath> #include<cstring> typedef unsigned long long int lli; lli mod=1000000007; using namespace std; lli a[100010]; lli nu,de; lli power(lli a,lli b) { lli res = 1; while(b > 0) { if( b % 2 != 0) { res = (res * a) % mod; } a = (a * a) %mod; b /= 2; } return res; } lli calc(lli n,lli r) { de=(de*r)%mod; nu=(nu*(n+r-1))%mod; lli d=power(de,mod-2); lli c =(nu*d)%mod; return c; } int main() { int t; lli m,n,x; scanf("%d",&t); while(t--) { lli c=1; nu=1;de=1; scanf("%llu%llu%llu",&n,&x,&m); for(lli i=1;i<=n;i++) { scanf("%lld",&a[i]); } for(lli j=1;j<=x;j++) { a[j]=a[j]%mod; } m=m%mod; lli sum=a[x]; if(x==1) { printf("%llu\n",a[1]); } else if(x==2) { lli ans=(m*a[1]+a[2])%mod; printf("%llu\n",ans); } else { for(lli j=1;j<x;j++) { c=(calc(m,j)*a[x-j])%mod; sum=(sum+c)%mod; } printf("%llu\n",sum); } } return 0; }
13.295455
36
0.432479
hardbeater
96727133f2d1e8aa777c256e2a3acb64a6e9a900
2,113
cpp
C++
Siv3D/src/Siv3D/TexturedRoundRect/SivTexturedRoundRect.cpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
2
2021-11-22T00:52:48.000Z
2021-12-24T09:33:55.000Z
Siv3D/src/Siv3D/TexturedRoundRect/SivTexturedRoundRect.cpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/TexturedRoundRect/SivTexturedRoundRect.cpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
1
2021-12-31T05:08:00.000Z
2021-12-31T05:08:00.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2022 Ryo Suzuki // Copyright (c) 2016-2022 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/TexturedRoundRect.hpp> # include <Siv3D/Renderer2D/IRenderer2D.hpp> # include <Siv3D/Common/Siv3DEngine.hpp> namespace s3d { namespace detail { [[nodiscard]] inline constexpr Vertex2D::IndexType CaluculateFanQuality(const float r) noexcept { return r <= 1.0f ? 3 : r <= 6.0f ? 5 : r <= 12.0f ? 8 : static_cast<Vertex2D::IndexType>(Min(64.0f, r * 0.2f + 6)); } } TexturedRoundRect::TexturedRoundRect(const Texture& _texture, const float l, const float t, const float r, const float b, const RoundRect& _rect) : rect{ _rect } , texture{ _texture } , uvRect{ l, t, r, b } {} TexturedRoundRect::TexturedRoundRect(const Texture& _texture, const FloatRect& _uvRect, const RoundRect& _rect) : rect{ _rect } , texture{ _texture } , uvRect{ _uvRect } {} const RoundRect& TexturedRoundRect::draw(const ColorF& diffuse) const { SIV3D_ENGINE(Renderer2D)->addTexturedRoundRect(texture, FloatRect{ rect.x, rect.y, (rect.x + rect.w), (rect.y + rect.h) }, static_cast<float>(rect.w), static_cast<float>(rect.h), static_cast<float>(rect.r), uvRect, diffuse.toFloat4()); return rect; } RoundRect TexturedRoundRect::draw(const double x, const double y, const ColorF& diffuse) const { const RoundRect rr = rect.movedBy(x, y); return TexturedRoundRect{ texture, uvRect, rr }.draw(diffuse); } RoundRect TexturedRoundRect::draw(const Vec2& pos, const ColorF& diffuse) const { return draw(pos.x, pos.y, diffuse); } RoundRect TexturedRoundRect::drawAt(const double x, const double y, const ColorF& diffuse) const { return TexturedRoundRect(texture, uvRect, RoundRect(Arg::center(x, y), rect.w, rect.h, rect.r)).draw(diffuse); } RoundRect TexturedRoundRect::drawAt(const Vec2& pos, const ColorF& diffuse) const { return drawAt(pos.x, pos.y, diffuse); } }
28.945205
146
0.666351
tas9n
9678043ef21e664d14800ffd4eb8e8edaee80920
966
cpp
C++
source/uwp/Renderer/lib/AdaptiveToggleInputConfig.cpp
zhusongm/AdaptiveCards
c8c8d26d0f4c843c26364136fd58cae8a4aefa9b
[ "MIT" ]
null
null
null
source/uwp/Renderer/lib/AdaptiveToggleInputConfig.cpp
zhusongm/AdaptiveCards
c8c8d26d0f4c843c26364136fd58cae8a4aefa9b
[ "MIT" ]
null
null
null
source/uwp/Renderer/lib/AdaptiveToggleInputConfig.cpp
zhusongm/AdaptiveCards
c8c8d26d0f4c843c26364136fd58cae8a4aefa9b
[ "MIT" ]
null
null
null
#include "pch.h" #include "AdaptiveToggleInputConfig.h" #include "AdaptiveSeparationConfig.h" using namespace Microsoft::WRL; using namespace ABI::AdaptiveCards::XamlCardRenderer; namespace AdaptiveCards { namespace XamlCardRenderer { HRESULT AdaptiveToggleInputConfig::RuntimeClassInitialize() noexcept try { return S_OK; } CATCH_RETURN; HRESULT AdaptiveToggleInputConfig::RuntimeClassInitialize(ToggleInputConfig toggleInputConfig) noexcept { m_sharedToggleInputConfig = toggleInputConfig; return S_OK; } _Use_decl_annotations_ HRESULT AdaptiveToggleInputConfig::get_Separation(IAdaptiveSeparationConfig** separationConfig) { return MakeAndInitialize<AdaptiveSeparationConfig>(separationConfig, m_sharedToggleInputConfig.separation); } _Use_decl_annotations_ HRESULT AdaptiveToggleInputConfig::put_Separation(IAdaptiveSeparationConfig*) { return E_NOTIMPL; } } }
28.411765
115
0.771222
zhusongm
967814559a9e5ddd063914b6b6b097beb76a4241
458
cpp
C++
src/Thread.cpp
shalithasuranga/neutralino-server-linux
41bbb6a349af00c65bbbefc9aecd7661b99beea6
[ "MIT" ]
2
2021-01-20T09:32:58.000Z
2021-07-02T04:46:42.000Z
src/Thread.cpp
shalithasuranga/neutralinojs-server-linux
41bbb6a349af00c65bbbefc9aecd7661b99beea6
[ "MIT" ]
2
2018-06-14T15:21:39.000Z
2018-06-19T11:33:11.000Z
src/Thread.cpp
neutralinojs/neutralinojs-server-linux
41bbb6a349af00c65bbbefc9aecd7661b99beea6
[ "MIT" ]
null
null
null
/* * Author: Broglie * E-mail: yibo141@outlook.com */ #include <pthread.h> #include <assert.h> #include "Thread.h" void Thread::start() { assert(!started); started = true; if(pthread_create(&pthreadId, NULL, threadFunc, _arg)) started = false; //std::cout << "----------Thread created----------" << std::endl; } int Thread::join() { assert(started && !joined); joined = true; return pthread_join(pthreadId, NULL); }
19.083333
69
0.593886
shalithasuranga
967b278cf5c670082ad5a8f615252fd100ec0a30
471
cpp
C++
PAT/PAT-A/CPP/1019.General Palindromic Number (20 分).cpp
hao14293/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
950
2020-02-21T02:39:18.000Z
2022-03-31T07:27:36.000Z
PAT/PAT-A/CPP/1019.General Palindromic Number (20 分).cpp
RestmeF/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
6
2020-04-03T13:08:47.000Z
2022-03-07T08:54:56.000Z
PAT/PAT-A/CPP/1019.General Palindromic Number (20 分).cpp
RestmeF/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
131
2020-02-22T15:35:59.000Z
2022-03-21T04:23:57.000Z
#include <iostream> using namespace std; int main(){ int n, d; scanf("%d %d", &n, &d); int arr[40], index = 0; while(n != 0){ arr[index++] = n % d; n = n / d; } int flag = 0; for(int i = 0; i < index / 2; i++){ if(arr[i] != arr[index - i - 1]){ printf("No\n"); flag = 1; break; } } if(!flag) printf("Yes\n"); for(int i = index - 1; i >= 0; i--){ printf("%d", arr[i]); if(i != 0) printf(" "); } if(index == 0) printf("0"); return 0; }
16.241379
37
0.469214
hao14293
967d0c1d78f9f96380f7e150f1147a9a66c8626e
5,445
cpp
C++
drawmapfigure.cpp
AirSThib/MinetestMapperGUI
adb672841de32c1ac1ab36d78731831ecfc369d3
[ "CC-BY-3.0" ]
1
2021-08-05T08:58:04.000Z
2021-08-05T08:58:04.000Z
drawmapfigure.cpp
AirSThib/MinetestMapperGUI
adb672841de32c1ac1ab36d78731831ecfc369d3
[ "CC-BY-3.0" ]
null
null
null
drawmapfigure.cpp
AirSThib/MinetestMapperGUI
adb672841de32c1ac1ab36d78731831ecfc369d3
[ "CC-BY-3.0" ]
1
2021-04-08T14:44:27.000Z
2021-04-08T14:44:27.000Z
#include "drawmapfigure.h" QStringList DrawMapFigure::figuresList = QStringList() << QT_TR_NOOP("Unknown") << QT_TR_NOOP("Arrow") << QT_TR_NOOP("Circle") << QT_TR_NOOP("Ellipse") << QT_TR_NOOP("Line") << QT_TR_NOOP("Point") << QT_TR_NOOP("Rectangle") << QT_TR_NOOP("Text"); DrawMapFigure::DrawMapFigure(QObject *parent) : QObject(parent) { geometry = new Geometry(); } DrawMapFigure::DrawMapFigure(const QString &str, QObject *parent) : QObject(parent) { const QRegularExpression parser = QRegularExpression("^--draw(?<map>map)?(?<type>\\w+) \"(?<params>.+)*\"$"); QRegularExpressionMatch match = parser.match(str); QStringList xy; if(match.hasMatch()){ useImageCoordinates = (match.captured("map")=="map"); QString params = match.captured("params"); color.setNamedColor(params.section(' ', 1, 1)); figure = getFigure(match.captured("type")); if(color.isValid()){ switch (figure) { case Text: //parse text and fall through for point text = params.section(' ', 2);// everything after the 3rd whitespace case Point: //parse point and color xy = params.section(' ', 0, 0).split(','); point.setX(xy[0].toInt()); point.setY(xy[1].toInt()); break; case Circle: case Arrow: case Line: case Rectangle: case Ellipse: //parse geometry geometry = new Geometry(params.section(' ', 0, 0)); break; default: figure = Unknown; geometry = new Geometry(); break; } } else{ geometry = new Geometry(); figure = Unknown; } } else{ geometry = new Geometry(); figure = Unknown; } } bool DrawMapFigure::requiresPoint() const { return (figure == Text || figure == Point); } bool DrawMapFigure::requiresGeometry() const { return (figure != Text && figure != Point); } bool DrawMapFigure::requiresText() const { return (figure == Text); } QString DrawMapFigure::getString() const { QStringList splitted = getSplittedString(); return QString("%1 \"%2\"").arg(splitted.at(0)).arg(splitted.at(1)); } QStringList DrawMapFigure::getSplittedString() const { QString param; QString argument; param = "--draw"; if(useImageCoordinates) param += "map"; param += QString(metaFigure.key(figure)).toLower(); if(requiresGeometry()) argument += geometry->getString(); if(requiresPoint()) argument += QString("%1,%2").arg(point.x()).arg(point.y()); argument += ' '+ color.name(); if(requiresText()) argument += ' '+text; return QStringList()<<param<<argument; } bool DrawMapFigure::getUseImageCoordinates() const { return useImageCoordinates; } DrawMapFigure::Figure DrawMapFigure::getFigure() const { return figure; } DrawMapFigure::Figure DrawMapFigure::getFigure(const QString &str) const { const QString temp = str.left(1).toUpper()+str.mid(1); return static_cast<Figure>(metaFigure.keyToValue(temp.toUtf8().constData())); } int DrawMapFigure::getFigureIndex() const { QMetaEnum metaEnum = QMetaEnum::fromType<Figure>(); return metaEnum.value(figure); } QPoint DrawMapFigure::getPoint() const { return point; } QString DrawMapFigure::getText() const { return text; } QColor DrawMapFigure::getColor() const { return color; } QStringList DrawMapFigure::getFigureList() { return figuresList; } void DrawMapFigure::setFigure(const Figure &value) { figure = value; } void DrawMapFigure::setFigure(int value) { figure = static_cast<Figure>(value); } void DrawMapFigure::setText(const QString &value) { text = value; } void DrawMapFigure::setColor(const QColor &value) { color = value; } Geometry *DrawMapFigure::getGeometry() { return this->geometry; } void DrawMapFigure::setGeometry(Geometry *value) { geometry = value; } void DrawMapFigure::setUseImageCoordinates(bool value) { useImageCoordinates = value; } void DrawMapFigure::setPoint(const QPoint &value) { point = value; } void DrawMapFigure::setPoint(const QVariant &value) { point = value.toPoint(); } void DrawMapFigure::setPoint(const QString &value) { static const QRegularExpression regex("(\\-?\\d+)[ |,](\\-?\\d+)"); QRegularExpressionMatch match = regex.match(value); if(match.hasMatch()){ point = QPoint(match.captured(1).toInt(), match.captured(2).toInt()); } else{ qDebug() <<"Could not match point from String "<<value; point = QPoint(); } } QIcon DrawMapFigure::getIcon() const { return getIcon(figure); } QIcon DrawMapFigure::getIcon(DrawMapFigure::Figure figure) { const char* a = QMetaEnum::fromType<Figure>().key(figure); return QIcon(QString(":/images/draw-%1").arg(a).toLower()); }
23.571429
113
0.573737
AirSThib
9680cd5f4ce0ae495da1c59a55444ae5eae43263
5,946
cc
C++
yggdrasil_decision_forests/utils/evaluation_test.cc
isabella232/yggdrasil-decision-forests
52ed2571c46baa9738f81d7341dc27700dbfec73
[ "Apache-2.0" ]
135
2021-05-12T18:02:11.000Z
2022-03-30T16:48:44.000Z
yggdrasil_decision_forests/utils/evaluation_test.cc
google/yggdrasil-decision-forests
0b284d8afe7ac4773abcdeee88a77681f8681127
[ "Apache-2.0" ]
11
2021-06-25T17:25:38.000Z
2022-03-30T03:31:24.000Z
yggdrasil_decision_forests/utils/evaluation_test.cc
isabella232/yggdrasil-decision-forests
52ed2571c46baa9738f81d7341dc27700dbfec73
[ "Apache-2.0" ]
10
2021-05-27T02:51:36.000Z
2022-03-28T07:03:52.000Z
/* * Copyright 2021 Google LLC. * 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 * * https://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. */ // clang-format off #ifdef YDF_EVAL_TFRECORD #include "yggdrasil_decision_forests/utils/sharded_io_tfrecord.h" #endif // clang-format on #include "yggdrasil_decision_forests/utils/evaluation.h" #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "yggdrasil_decision_forests/dataset/example_reader.h" #include "yggdrasil_decision_forests/utils/filesystem.h" #include "yggdrasil_decision_forests/utils/test.h" namespace yggdrasil_decision_forests { namespace utils { namespace { using test::EqualsProto; using testing::ElementsAre; TEST(Evaluation, PredictionToExampleClassification) { dataset::proto::DataSpecification dataspec = PARSE_TEST_PROTO(R"pb( columns { type: CATEGORICAL name: "label" categorical { is_already_integerized: true number_of_unique_values: 3 } } )pb"); dataset::proto::DataSpecification expected_dataspec = PARSE_TEST_PROTO(R"pb( columns { type: NUMERICAL name: "1" } columns { type: NUMERICAL name: "2" } )pb"); EXPECT_THAT(PredictionDataspec(model::proto::Task::CLASSIFICATION, dataspec.columns(0)) .value(), EqualsProto(expected_dataspec)); model::proto::Prediction prediction = PARSE_TEST_PROTO(R"pb( classification { value: 1 ground_truth: 2 distribution { counts: 0 counts: 8 counts: 2 sum: 10 } } )pb"); dataset::proto::Example prediction_as_example; EXPECT_OK(PredictionToExample(model::proto::Task::CLASSIFICATION, dataspec.columns(0), prediction, &prediction_as_example)); dataset::proto::Example expected_prediction_as_example = PARSE_TEST_PROTO( R"pb( attributes { numerical: 0.8 } attributes { numerical: 0.2 } )pb"); EXPECT_THAT(prediction_as_example, EqualsProto(expected_prediction_as_example)); } TEST(Evaluation, PredictionToExampleRegression) { dataset::proto::DataSpecification dataspec = PARSE_TEST_PROTO(R"pb( columns { type: NUMERICAL name: "label" } )pb"); dataset::proto::DataSpecification expected_dataspec = PARSE_TEST_PROTO(R"pb( columns { type: NUMERICAL name: "label" } )pb"); EXPECT_THAT( PredictionDataspec(model::proto::Task::REGRESSION, dataspec.columns(0)) .value(), EqualsProto(expected_dataspec)); model::proto::Prediction prediction = PARSE_TEST_PROTO(R"pb( regression { value: 5 } )pb"); dataset::proto::Example prediction_as_example; EXPECT_OK(PredictionToExample(model::proto::Task::REGRESSION, dataspec.columns(0), prediction, &prediction_as_example)); dataset::proto::Example expected_prediction_as_example = PARSE_TEST_PROTO( R"pb( attributes { numerical: 5 } )pb"); EXPECT_THAT(prediction_as_example, EqualsProto(expected_prediction_as_example)); } TEST(Evaluation, ExportPredictionsToDataset) { std::vector<model::proto::Prediction> predictions; predictions.push_back(PARSE_TEST_PROTO("regression { value: 1 }")); predictions.push_back(PARSE_TEST_PROTO("regression { value: 2 }")); predictions.push_back(PARSE_TEST_PROTO("regression { value: 3 }")); dataset::proto::DataSpecification dataspec = PARSE_TEST_PROTO(R"pb( columns { type: NUMERICAL name: "label" } )pb"); const auto prediction_path = file::JoinPath(test::TmpDirectory(), "predictions.csv"); EXPECT_OK(ExportPredictions(predictions, model::proto::Task::REGRESSION, dataspec.columns(0), absl::StrCat("csv:", prediction_path), -1)); std::string csv_content = file::GetContent(prediction_path).value(); EXPECT_EQ(csv_content, "label\n1\n2\n3\n"); } #ifdef YDF_EVAL_TFRECORD TEST(Evaluation, ExportPredictionsToTFRecord) { std::vector<model::proto::Prediction> predictions; predictions.push_back(PARSE_TEST_PROTO("regression { value: 1 }")); predictions.push_back(PARSE_TEST_PROTO("regression { value: 2 }")); predictions.push_back(PARSE_TEST_PROTO("regression { value: 3 }")); dataset::proto::DataSpecification dataspec = PARSE_TEST_PROTO(R"pb( columns { type: NUMERICAL name: "label" } )pb"); const auto path = file::JoinPath(test::TmpDirectory(), "predictions.tfrecord-pred"); const auto typed_path = absl::StrCat("tfrecord+pred:", path); EXPECT_OK(ExportPredictions(predictions, model::proto::Task::REGRESSION, dataspec.columns(0), typed_path, -1)); auto reader = absl::make_unique<TFRecordShardedReader<model::proto::Prediction>>(); EXPECT_OK(reader->Open(path)); model::proto::Prediction prediction; EXPECT_TRUE(reader->Next(&prediction).value()); model::proto::Prediction tmp = PARSE_TEST_PROTO("regression { value: 1 }"); EXPECT_THAT(prediction, EqualsProto(tmp)); EXPECT_TRUE(reader->Next(&prediction).value()); tmp = PARSE_TEST_PROTO("regression { value: 2 }"); EXPECT_THAT(prediction, EqualsProto(tmp)); EXPECT_TRUE(reader->Next(&prediction).value()); tmp = PARSE_TEST_PROTO("regression { value: 3 }"); EXPECT_THAT(prediction, EqualsProto(tmp)); EXPECT_FALSE(reader->Next(&prediction).value()); } #endif } // namespace } // namespace utils } // namespace yggdrasil_decision_forests
36.931677
78
0.697107
isabella232
96826bd1490737b4122f9f80c92a5e14d535d4cc
6,420
hpp
C++
src/libraries/core/fields/fvPatchFields/derived/flowRateOutletVelocity/flowRateOutletVelocityFvPatchVectorField.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fields/fvPatchFields/derived/flowRateOutletVelocity/flowRateOutletVelocityFvPatchVectorField.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fields/fvPatchFields/derived/flowRateOutletVelocity/flowRateOutletVelocityFvPatchVectorField.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2014 Applied CCM Copyright (C) 2017 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::flowRateOutletVelocityFvPatchVectorField Description Velocity outlet boundary condition which corrects the extrapolated velocity to match the specified flow rate. For a mass-based flux: - the flow rate should be provided in kg/s - if \c rho is "none" the flow rate is in m^3/s - otherwise \c rho should correspond to the name of the density field - if the density field cannot be found in the database, the user must specify the outlet density using the \c rhoOutlet entry For a volumetric-based flux: - the flow rate is in m^3/s Usage \table Property | Description | Required | Default value massFlowRate | mass flow rate [kg/s] | no | volumetricFlowRate | volumetric flow rate [m^3/s]| no | rho | density field name | no | rho rhoOutlet | outlet density | no | \endtable Example of the boundary condition specification for a volumetric flow rate: \verbatim <patchName> { type flowRateOutletVelocity; volumetricFlowRate 0.2; value uniform (0 0 0); } \endverbatim Example of the boundary condition specification for a mass flow rate: \verbatim <patchName> { type flowRateOutletVelocity; massFlowRate 0.2; rhoOutlet 1.0; value uniform (0 0 0); } \endverbatim The \c flowRate entry is a \c DataEntry type, meaning that it can be specified as constant, a polynomial fuction of time, and ... Note - \c rhoOutlet is required for the case of a mass flow rate, where the density field is not available at start-up - The value is positive out of the domain (as an outlet) - May not work correctly for transonic outlets - Strange behaviour with potentialFoam since the U equation is not solved SeeAlso CML::DataEntry CML::fixedValueFvPatchField SourceFiles flowRateOutletVelocityFvPatchVectorField.cpp \*---------------------------------------------------------------------------*/ #ifndef flowRateOutletVelocityFvPatchVectorField_H #define flowRateOutletVelocityFvPatchVectorField_H #include "fixedValueFvPatchFields.hpp" #include "DataEntry.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class flowRateOutletVelocityFvPatchVectorField Declaration \*---------------------------------------------------------------------------*/ class flowRateOutletVelocityFvPatchVectorField : public fixedValueFvPatchVectorField { // Private data //- Outlet integral flow rate autoPtr<DataEntry<scalar>> flowRate_; //- Is volumetric? bool volumetric_; //- Name of the density field used to normalize the mass flux word rhoName_; //- Rho initialisation value (for start; if value not supplied) scalar rhoOutlet_; // Private member functions //- Update the patch values given the appropriate density type and value template<class RhoType> void updateValues(const RhoType& rho); public: //- Runtime type information TypeName("flowRateOutletVelocity"); // Constructors //- Construct from patch and internal field flowRateOutletVelocityFvPatchVectorField ( const fvPatch&, const DimensionedField<vector, volMesh>& ); //- Construct from patch, internal field and dictionary flowRateOutletVelocityFvPatchVectorField ( const fvPatch&, const DimensionedField<vector, volMesh>&, const dictionary& ); //- Construct by mapping given // flowRateOutletVelocityFvPatchVectorField // onto a new patch flowRateOutletVelocityFvPatchVectorField ( const flowRateOutletVelocityFvPatchVectorField&, const fvPatch&, const DimensionedField<vector, volMesh>&, const fvPatchFieldMapper& ); //- Construct as copy flowRateOutletVelocityFvPatchVectorField ( const flowRateOutletVelocityFvPatchVectorField& ); //- Construct and return a clone virtual tmp<fvPatchVectorField> clone() const { return tmp<fvPatchVectorField> ( new flowRateOutletVelocityFvPatchVectorField(*this) ); } //- Construct as copy setting internal field reference flowRateOutletVelocityFvPatchVectorField ( const flowRateOutletVelocityFvPatchVectorField&, const DimensionedField<vector, volMesh>& ); //- Construct and return a clone setting internal field reference virtual tmp<fvPatchVectorField> clone ( const DimensionedField<vector, volMesh>& iF ) const { return tmp<fvPatchVectorField> ( new flowRateOutletVelocityFvPatchVectorField(*this, iF) ); } // Member functions //- Update the coefficients associated with the patch field virtual void updateCoeffs(); //- Write virtual void write(Ostream&) const; }; } // End namespace CML #endif
30.42654
80
0.597975
MrAwesomeRocks
96827a485e500ad67408a91718f6ee81894de1d4
7,254
cpp
C++
skin_generator/generator.cpp
vicpopov/omim
664b458998fb0f2405f68ae830c2798e027b2dcc
[ "Apache-2.0" ]
7
2020-12-20T23:21:10.000Z
2020-12-23T23:38:58.000Z
skin_generator/generator.cpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
1
2018-11-26T15:44:46.000Z
2018-11-27T10:55:36.000Z
skin_generator/generator.cpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
null
null
null
#include "generator.hpp" #include "base/logging.hpp" #include "base/math.hpp" #include <algorithm> #include <fstream> #include <functional> #include <iostream> #include <iterator> #include <QtXml/QDomElement> #include <QtXml/QDomDocument> #include <QtCore/QDir> namespace tools { namespace { struct GreaterHeight { bool operator() (SkinGenerator::SymbolInfo const & left, SkinGenerator::SymbolInfo const & right) const { return (left.m_size.height() > right.m_size.height()); } }; struct MaxDimensions { uint32_t & m_width; uint32_t & m_height; MaxDimensions(uint32_t & width, uint32_t & height) : m_width(width), m_height(height) { m_width = 0; m_height = 0; } void operator()(SkinGenerator::SymbolInfo const & info) { m_width = std::max(std::max(m_width, m_height), static_cast<uint32_t>(info.m_size.width())); m_height = std::max(std::max(m_width, m_height), static_cast<uint32_t>(info.m_size.height())); } }; uint32_t NextPowerOf2(uint32_t n) { n = n - 1; n |= (n >> 1); n |= (n >> 2); n |= (n >> 4); n |= (n >> 8); n |= (n >> 16); return n + 1; } } void SkinGenerator::ProcessSymbols(std::string const & svgDataDir, std::string const & skinName, std::vector<QSize> const & symbolSizes, std::vector<std::string> const & suffixes) { for (size_t j = 0; j < symbolSizes.size(); ++j) { QDir dir(QString(svgDataDir.c_str())); QStringList fileNames = dir.entryList(QDir::Files); QDir pngDir = dir.absolutePath() + "/png"; fileNames += pngDir.entryList(QDir::Files); // Separate page for symbols. m_pages.emplace_back(SkinPageInfo()); SkinPageInfo & page = m_pages.back(); page.m_dir = skinName.substr(0, skinName.find_last_of("/") + 1); page.m_suffix = suffixes[j]; page.m_fileName = page.m_dir + "symbols" + page.m_suffix; for (int i = 0; i < fileNames.size(); ++i) { QString const & fileName = fileNames.at(i); QString symbolID = fileName.left(fileName.lastIndexOf(".")); if (fileName.endsWith(".svg")) { QString fullFileName = QString(dir.absolutePath()) + "/" + fileName; if (m_svgRenderer.load(fullFileName)) { QSize defaultSize = m_svgRenderer.defaultSize(); QSize symbolSize = symbolSizes[j]; QSize size = defaultSize * (symbolSize.width() / 24.0); // Fitting symbol into symbolSize, saving aspect ratio. if (size.width() > symbolSize.width()) { auto const h = static_cast<float>(size.height()) * symbolSize.width() / size.width(); size.setHeight(static_cast<int>(h)); size.setWidth(symbolSize.width()); } if (size.height() > symbolSize.height()) { auto const w = static_cast<float>(size.width()) * symbolSize.height() / size.height(); size.setWidth(static_cast<int>(w)); size.setHeight(symbolSize.height()); } page.m_symbols.emplace_back(size + QSize(4, 4), fullFileName, symbolID); } } else if (fileName.toLower().endsWith(".png")) { QString fullFileName = QString(pngDir.absolutePath()) + "/" + fileName; QPixmap pix(fullFileName); QSize s = pix.size(); page.m_symbols.emplace_back(s + QSize(4, 4), fullFileName, symbolID); } } } } bool SkinGenerator::RenderPages(uint32_t maxSize) { for (auto & page : m_pages) { std::sort(page.m_symbols.begin(), page.m_symbols.end(), GreaterHeight()); MaxDimensions dim(page.m_width, page.m_height); for_each(page.m_symbols.begin(), page.m_symbols.end(), dim); page.m_width = NextPowerOf2(page.m_width); page.m_height = NextPowerOf2(page.m_height); // Packing until we find a suitable rect. while (true) { page.m_packer = m2::Packer(page.m_width, page.m_height); page.m_packer.addOverflowFn(std::bind(&SkinGenerator::MarkOverflow, this), 10); m_overflowDetected = false; for (auto & s : page.m_symbols) { s.m_handle = page.m_packer.pack(static_cast<uint32_t>(s.m_size.width()), static_cast<uint32_t>(s.m_size.height())); if (m_overflowDetected) break; } if (m_overflowDetected) { // Enlarge packing area and try again. if (page.m_width == page.m_height) page.m_width *= 2; else page.m_height *= 2; if (page.m_width > maxSize) { page.m_width = maxSize; page.m_height *= 2; if (page.m_height > maxSize) return false; } continue; } break; } LOG(LINFO, ("Texture size =", page.m_width, "x", page.m_height)); std::vector<uchar> imgData(page.m_width * page.m_height * 4, 0); QImage img(imgData.data(), page.m_width, page.m_height, QImage::Format_ARGB32); QPainter painter(&img); painter.setClipping(true); for (auto const & s : page.m_symbols) { m2::RectU dstRect = page.m_packer.find(s.m_handle).second; QRect dstRectQt(dstRect.minX(), dstRect.minY(), dstRect.SizeX(), dstRect.SizeY()); painter.fillRect(dstRectQt, QColor(0, 0, 0, 0)); painter.setClipRect(dstRect.minX() + 2, dstRect.minY() + 2, dstRect.SizeX() - 4, dstRect.SizeY() - 4); QRect renderRect(dstRect.minX() + 2, dstRect.minY() + 2, dstRect.SizeX() - 4, dstRect.SizeY() - 4); QString fullLowerCaseName = s.m_fullFileName.toLower(); if (fullLowerCaseName.endsWith(".svg")) { m_svgRenderer.load(s.m_fullFileName); m_svgRenderer.render(&painter, renderRect); } else if (fullLowerCaseName.endsWith(".png")) { QPixmap pix(s.m_fullFileName); painter.drawPixmap(renderRect, pix); } } std::string s = page.m_fileName + ".png"; LOG(LINFO, ("saving skin image into: ", s)); img.save(s.c_str()); } return true; } void SkinGenerator::MarkOverflow() { m_overflowDetected = true; } bool SkinGenerator::WriteToFileNewStyle(std::string const &skinName) { QDomDocument doc = QDomDocument("skin"); QDomElement rootElem = doc.createElement("root"); doc.appendChild(rootElem); for (auto const & p : m_pages) { QDomElement fileNode = doc.createElement("file"); fileNode.setAttribute("width", p.m_width); fileNode.setAttribute("height", p.m_height); rootElem.appendChild(fileNode); for (auto const & s : p.m_symbols) { m2::RectU r = p.m_packer.find(s.m_handle).second; QDomElement symbol = doc.createElement("symbol"); symbol.setAttribute("minX", r.minX()); symbol.setAttribute("minY", r.minY()); symbol.setAttribute("maxX", r.maxX()); symbol.setAttribute("maxY", r.maxY()); symbol.setAttribute("name", s.m_symbolID.toLower()); fileNode.appendChild(symbol); } } QFile file(QString(skinName.c_str())); if (!file.open(QIODevice::ReadWrite | QIODevice::Truncate)) return false; QTextStream ts(&file); ts.setCodec("UTF-8"); ts << doc.toString(); return true; } }
29.13253
108
0.609181
vicpopov
968365c6410eec6015a053a24d4d9b633575d595
819
hpp
C++
runtime-lib/include/modules/ModuleFactory.hpp
edwino-stein/elrond-runtime-linux
77b64e9c960c53fa8a2a2e5b9d96e060b5c95533
[ "Apache-2.0" ]
null
null
null
runtime-lib/include/modules/ModuleFactory.hpp
edwino-stein/elrond-runtime-linux
77b64e9c960c53fa8a2a2e5b9d96e060b5c95533
[ "Apache-2.0" ]
13
2019-11-29T21:58:39.000Z
2020-04-02T03:30:43.000Z
runtime-lib/include/modules/ModuleFactory.hpp
edwino-stein/elrond-runtime
77b64e9c960c53fa8a2a2e5b9d96e060b5c95533
[ "Apache-2.0" ]
null
null
null
#if !defined _ELROND_RUNTIME_MODULE_FACTORY_HPP #define _ELROND_RUNTIME_MODULE_FACTORY_HPP #include "rtTypes.hpp" namespace elrond { namespace runtime { class ModuleFactory { protected: elrond::String _name; elrond::runtime::ModuleInfo _info; public: elrond::runtime::ModuleInfo const& info; ModuleFactory(elrond::String name); virtual ~ModuleFactory(); virtual elrond::interface::Module* newInstance(String const& instName)=0; virtual void deleteInstance(elrond::interface::Module* inst)=0; virtual bool match(elrond::String const& name) const; }; } } #endif
26.419355
93
0.545788
edwino-stein
968539cbbbb5705b37cc802cbf63090a1867ae15
14,005
cpp
C++
src/gtsamutils.cpp
tmcg0/bioslam
d59f07733cb3a9a1de8e6dea4b1fb745d706da09
[ "MIT" ]
6
2021-01-26T19:31:46.000Z
2022-03-10T15:33:49.000Z
src/gtsamutils.cpp
tmcg0/bioslam
d59f07733cb3a9a1de8e6dea4b1fb745d706da09
[ "MIT" ]
8
2021-01-26T16:12:22.000Z
2021-08-12T18:39:36.000Z
src/gtsamutils.cpp
tmcg0/bioslam
d59f07733cb3a9a1de8e6dea4b1fb745d706da09
[ "MIT" ]
1
2021-05-02T18:47:42.000Z
2021-05-02T18:47:42.000Z
// -------------------------------------------------------------------- // // (c) Copyright 2021 Massachusetts Institute of Technology // // Author: Tim McGrath // // All rights reserved. See LICENSE file for license information. // // -------------------------------------------------------------------- // #include <gtsam/nonlinear/NonlinearFactor.h> #include <mathutils.h> #include "gtsamutils.h" #include <fstream> #include <iomanip> #include <gtsam/navigation/CombinedImuFactor.h> #include <factors/ConstrainedJointCenterPositionFactor.h> #include <factors/ConstrainedJointCenterVelocityFactor.h> #include <gtsam/slam/PriorFactor.h> #include <gtsam/navigation/ImuFactor.h> #include <factors/AngularVelocityFactor.h> #include <factors/HingeJointFactors.h> #include <factors/SegmentLengthMagnitudeFactor.h> #include <factors/SegmentLengthDiscrepancyFactor.h> #include <factors/AngleBetweenAxisAndSegmentFactor.h> #include <factors/MagPose3Factor.h> #include <factors/Pose3Priors.h> #include <factors/Point3Priors.h> void print(const gtsam::Matrix& A, const std::string &s, std::ostream& stream); namespace gtsamutils{ Eigen::MatrixXd Point3VectorToEigenMatrix(const std::vector<gtsam::Point3>& p){ // vector<Rot3> => Nx4 Eigen::MatrixXd Eigen::MatrixXd M(p.size(),3); for(uint i=0; i<p.size(); i++){ gtsam::Vector3 pos=p[i].vector(); M(i,0)=pos[0]; M(i,1)=pos[1]; M(i,2)=pos[2]; } return M; } Eigen::MatrixXd Vector3VectorToEigenMatrix(const std::vector<gtsam::Vector3>& v){ // vector<Rot3> => Nx4 Eigen::MatrixXd Eigen::MatrixXd M(v.size(),3); for(uint i=0; i<v.size(); i++){ M(i,0)=v[i][0]; M(i,1)=v[i][1]; M(i,2)=v[i][2]; } return M; } Eigen::MatrixXd vectorRot3ToFlattedEigenMatrixXd(const std::vector<gtsam::Rot3>& R){ // make a Nx9 flatted Eigen::Matrix Eigen::MatrixXd M(R.size(),9); for(uint i=0; i<R.size(); i++){ gtsam::Matrix33 m=R[i].matrix(); M(i,0)=m(0,0); M(i,1)=m(0,1); M(i,2)=m(0,2); M(i,3)=m(1,0); M(i,4)=m(1,1); M(i,5)=m(1,2); M(i,6)=m(2,0); M(i,7)=m(2,1); M(i,8)=m(2,2); } return M; } void printErrorsInGraphByFactorType(const gtsam::NonlinearFactorGraph& graph, const gtsam::Values& vals){ // this is less fun in C++ than MATLAB. You'll need to automatically know every possible in your graph a priori. // for each factor, get a count of how many there are in the graph. If count>0, then find error and print it. double totalGraphError=graph.error(vals), startTic=clock(); std::cout<<"total error in graph = "<<totalGraphError<<std::endl; // now for each type of factor, create count, total error, and print results if some are found gtsamutils::printGraphErrorDueToFactorType<gtsam::PriorFactor<gtsam::Unit3>>(graph,vals," gtsam::PriorFactor<Unit3>:"); gtsamutils::printGraphErrorDueToFactorType<gtsam::PriorFactor<gtsam::Pose3>>(graph,vals," gtsam::PriorFactor<Pose3>:"); gtsamutils::printGraphErrorDueToFactorType<gtsam::PriorFactor<gtsam::Rot3>>(graph,vals," gtsam::PriorFactor<Rot3>:"); gtsamutils::printGraphErrorDueToFactorType<gtsam::PriorFactor<gtsam::Point3>>(graph,vals," gtsam::PriorFactor<Point3>:"); gtsamutils::printGraphErrorDueToFactorType<gtsam::PriorFactor<gtsam::Vector3>>(graph,vals," gtsam::PriorFactor<Vector3>:"); gtsamutils::printGraphErrorDueToFactorType<gtsam::PriorFactor<gtsam::imuBias::ConstantBias>>(graph,vals," gtsam::PriorFactor<imuBias::ConstantBias>:"); gtsamutils::printGraphErrorDueToFactorType<gtsam::CombinedImuFactor>(graph,vals," gtsam::CombinedImuFactor:"); gtsamutils::printGraphErrorDueToFactorType<gtsam::ImuFactor>(graph,vals," gtsam::ImuFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::Pose3TranslationPrior>(graph,vals," bioslam::Pose3TranslationPrior:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::Pose3CompassPrior>(graph,vals," bioslam::Pose3CompassPrior:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::AngularVelocityFactor>(graph,vals," bioslam::AngularVelocityFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::ConstrainedJointCenterPositionFactor>(graph, vals, " bioslam::ConstrainedJointCenterPositionFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::ConstrainedJointCenterNormPositionFactor>(graph, vals, " bioslam::ConstrainedJointCenterNormPositionFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::HingeJointConstraintVecErrEstAngVel>(graph, vals, " bioslam::HingeJointConstraintVecErrEstAngVel:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::HingeJointConstraintNormErrEstAngVel>(graph, vals, " bioslam::HingeJointConstraintNormErrEstAngVel:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::SegmentLengthMagnitudeFactor>(graph,vals," bioslam::SegmentLengthMagnitudeFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::SegmentLengthMaxMagnitudeFactor>(graph,vals," bioslam::SegmentLengthMaxMagnitudeFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::SegmentLengthMinMagnitudeFactor>(graph,vals," bioslam::SegmentLengthMinMagnitudeFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::ConstrainedJointCenterVelocityFactor>(graph,vals," bioslam::ConstrainedJointCenterVelocityFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::ConstrainedJointCenterNormVelocityFactor>(graph, vals, " bioslam::ConstrainedJointCenterNormVelocityFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::SegmentLengthDiscrepancyFactor>(graph,vals," bioslam::SegmentLengthDiscrepancyFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::AngleBetweenAxisAndSegmentFactor>(graph,vals," bioslam::AngleBetweenAxisAndSegmentFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::MinAngleBetweenAxisAndSegmentFactor>(graph,vals," bioslam::MinAngleBetweenAxisAndSegmentFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::MaxAngleBetweenAxisAndSegmentFactor>(graph,vals," bioslam::MaxAngleBetweenAxisAndSegmentFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::Point3MagnitudeDifferenceFactor>(graph,vals," bioslam::Point3MagnitudeDifferenceFactor:"); gtsamutils::printGraphErrorDueToFactorType<bioslam::MagPose3Factor>(graph,vals," bioslam::MagPose3Factor:"); std::cout<<" graph error printing complete. ("<<(clock()-startTic)/CLOCKS_PER_SEC<<" seconds)"<<std::endl; } std::vector<gtsam::Rot3> imuOrientation(const imu& myImu){ std::vector<std::vector<double>> q=myImu.quaternion(); std::vector<Eigen::Vector4d,Eigen::aligned_allocator<Eigen::Vector4d>> qAPDM=mathutils::VectorVectorDoubleToVectorEigenVector(q); std::vector<gtsam::Rot3> orientation_Rot3=mathutils::QuaternionVectorToRot3Vector(qAPDM); return orientation_Rot3; } std::vector<gtsam::Rot3> Pose3VectorToRot3Vector(const std::vector<gtsam::Pose3>& poses){ std::vector<gtsam::Rot3> rots(poses.size()); for(uint k=0; k<poses.size();k++){ rots[k]=poses[k].rotation(); } return rots; } std::vector<gtsam::Point3> Pose3VectorToPoint3Vector(const std::vector<gtsam::Pose3>& poses){ std::vector<gtsam::Point3> pos(poses.size()); for(uint k=0; k<poses.size();k++){ pos[k]=poses[k].translation(); } return pos; } std::vector<double> vectorSetMagnitudes(const std::vector<Eigen::Vector3d>& v){ std::vector<double> mags(v.size()); for(uint i=0;i<v.size();i++){ mags[i]=v[i].norm(); } return mags; } gtsam::Vector3 accel_Vector3(const imu& myImu, const int& idx){ gtsam::Vector3 x; x[0]=myImu.ax[idx]; x[1]=myImu.ay[idx]; x[2]=myImu.az[idx]; return x; } gtsam::Vector3 mags_Vector3(const imu& myImu, const int& idx){ gtsam::Vector3 x; x[0]=myImu.mx[idx]; x[1]=myImu.my[idx]; x[2]=myImu.mz[idx]; return x; } gtsam::Vector3 gyros_Vector3(const imu& myImu, const int& idx){ gtsam::Vector3 x; x[0]=myImu.gx[idx]; x[1]=myImu.gy[idx]; x[2]=myImu.gz[idx]; return x; } Eigen::MatrixXd gyroMatrix(const imu& myImu){ Eigen::MatrixXd gyros(myImu.length(),3); for(uint k=0; k<myImu.length();k++){ gyros(k,0)=myImu.gx[k]; gyros(k,1)=myImu.gy[k]; gyros(k,2)=myImu.gz[k]; } return gyros; } Eigen::MatrixXd accelMatrix(const imu& myImu){ Eigen::MatrixXd accels(myImu.length(),3); for(uint k=0; k<myImu.length();k++){ accels(k,0)=myImu.ax[k]; accels(k,1)=myImu.ay[k]; accels(k,2)=myImu.az[k]; } return accels; } double median(std::vector<double> len){ assert(!len.empty()); if (len.size() % 2 == 0) { const auto median_it1 = len.begin() + len.size() / 2 - 1; const auto median_it2 = len.begin() + len.size() / 2; std::nth_element(len.begin(), median_it1 , len.end()); const auto e1 = *median_it1; std::nth_element(len.begin(), median_it2 , len.end()); const auto e2 = *median_it2; return (e1 + e2) / 2; } else { const auto median_it = len.begin() + len.size() / 2; std::nth_element(len.begin(), median_it , len.end()); return *median_it; } } uint nearestIdxToVal(std::vector<double> v, double val){ // this is gonna be ugly. copies entire vector and brute force searches for index nearest to value val. uint nearestIdx; double dist=9.0e9; for (uint k=0; k<v.size(); k++){ if(abs(v[k]-val)<dist){ // update nearest index nearestIdx=k; dist=abs(v[k]-val); // update smallest found distance } } return nearestIdx; } std::vector<double> vectorizePoint3x(std::vector<gtsam::Point3> p){ std::vector<double> x(p.size()); for(uint i=0; i<p.size(); i++){ x[i]=p[i].x(); } return x; } std::vector<double> vectorizePoint3y(std::vector<gtsam::Point3> p){ std::vector<double> y(p.size()); for(uint i=0; i<p.size(); i++){ y[i]=p[i].y(); } return y; } std::vector<double> vectorizePoint3z(std::vector<gtsam::Point3> p){ std::vector<double> z(p.size()); for(uint i=0; i<p.size(); i++){ z[i]=p[i].z(); } return z; } std::vector<double> vectorizeVector3X(std::vector<gtsam::Vector3> v){ std::vector<double> a(v.size()); for(uint i=0; i<v.size(); i++){ a[i]=v[i](0); } return a; } std::vector<double> vectorizeVector3Y(std::vector<gtsam::Vector3> v){ std::vector<double> a(v.size()); for(uint i=0; i<v.size(); i++){ a[i]=v[i](1); } return a; } std::vector<double> vectorizeVector3Z(std::vector<gtsam::Vector3> v){ std::vector<double> a(v.size()); for(uint i=0; i<v.size(); i++){ a[i]=v[i](2); } return a; } std::vector<double> vectorizeQuaternionS(std::vector<Eigen::Vector4d,Eigen::aligned_allocator<Eigen::Vector4d>> q){ std::vector<double> a(q.size()); for(uint i=0; i<q.size(); i++){ a[i]=q[i](0); } return a; } std::vector<double> vectorizeQuaternionX(std::vector<Eigen::Vector4d,Eigen::aligned_allocator<Eigen::Vector4d>> q){ std::vector<double> a(q.size()); for(uint i=0; i<q.size(); i++){ a[i]=q[i](1); } return a; } std::vector<double> vectorizeQuaternionY(std::vector<Eigen::Vector4d,Eigen::aligned_allocator<Eigen::Vector4d>> q){ std::vector<double> a(q.size()); for(uint i=0; i<q.size(); i++){ a[i]=q[i](2); } return a; } std::vector<double> vectorizeQuaternionZ(std::vector<Eigen::Vector4d,Eigen::aligned_allocator<Eigen::Vector4d>> q){ std::vector<double> a(q.size()); for(uint i=0; i<q.size(); i++){ a[i]=q[i](3); } return a; } void saveMatrixToFile(const gtsam::Matrix& A, const std::string &s, const std::string& filename) { std::fstream stream(filename.c_str(), std::fstream::out | std::fstream::app); print(A, s + "=", stream); stream.close(); } void writeEigenMatrixToCsvFile(const std::string& name, const Eigen::MatrixXd& matrix, const Eigen::IOFormat& CSVFormat){ std::ofstream file(name.c_str()); file << matrix.format(CSVFormat); file.close(); } Eigen::MatrixXd vectorRot3ToYprMatrix(const std::vector<gtsam::Rot3>& R){ Eigen::MatrixXd yprMatrix(R.size(),3); for(uint k=0; k<R.size(); k++){ gtsam::Vector3 ypr=R[k].ypr(); yprMatrix(k,0)=ypr(0); yprMatrix(k,1)=ypr(1); yprMatrix(k,2)=ypr(2); } return yprMatrix; } } // helper functions void print(const gtsam::Matrix& A, const std::string &s, std::ostream& stream) { size_t m = A.rows(), n = A.cols(); // print out all elements stream << s << "[\n"; for( size_t i = 0 ; i < m ; i++) { for( size_t j = 0 ; j < n ; j++) { double aij = A(i,j); if(aij != 0.0) stream << std::setw(12) << std::setprecision(9) << aij << ",\t"; else stream << " 0.0,\t"; } stream << std::endl; } stream << "];" << std::endl; }
46.374172
173
0.619564
tmcg0