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
8d4ad4031da83251876e2aa4242449879d011992
2,189
cpp
C++
problemsets/Codejam/2009/ROUND 1A 2009/PC/PC.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2009/ROUND 1A 2009/PC/PC.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2009/ROUND 1A 2009/PC/PC.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <algorithm> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <cstring> using namespace std; #define FOR(i,a,b) for (int (i) = (a); (i) < (b); (i)++) #define ALL(M) (M).begin(), (M).end() #define CLR(M, v) memset(M, v, sizeof(M)) #define SI(V) (int)(V.size()) #define PB push_back typedef long long i64; typedef vector<int> VI; typedef vector<string> VS; const int INF = 0x3F3F3F3F; const double EPS = 1E-14; template<class T> T SQR(T x) { return x*x; } //////////////////////////////////////////////////////////////////////////////// const int MAXV = 41; double DP[MAXV]; double P[MAXV][MAXV]; int C, N; double solve(int R) { double &ret = DP[R]; if (ret > -EPS) return ret; ret = 0; double tmp, p = 0; FOR(i,1,N+1) { tmp = P[R][i] * P[C-R][N-i] / P[C][N]; if (R-i >= 0) ret += tmp * solve(R-i), p += tmp; } ret = (ret + 1.) / p; return ret; } int main() { // freopen("C.in","r",stdin); // freopen("C-small-practice.in","r",stdin);freopen("C-small-practice.out","w",stdout); freopen("C-large-practice.in","r",stdin);freopen("C-large-practice.out","w",stdout); // freopen("C-small-attempt0.in","r",stdin);freopen("C-small-attempt0.out","w",stdout); // freopen("C-small-attempt1.in","r",stdin);freopen("C-small-attempt1.out","w",stdout); // freopen("C-small-attempt2.in","r",stdin);freopen("C-small-attempt2.out","w",stdout); // freopen("C-large.in","r",stdin);freopen("C-large.ans","w",stdout); FOR(j,0,MAXV) P[0][j] = 0.; P[0][0] = 1.; FOR(i,0,MAXV) { P[i][0] = 1.; FOR(j,1,MAXV) P[i][j]=P[i-1][j]+P[i-1][j-1]; } int TC; scanf("%d", &TC); for (int tc = 1; tc <= TC; tc++) { // Read input. scanf("%d %d", &C, &N); // Compute. FOR(i,1,C+1) DP[i] = -1; DP[0] = 0; double ret = solve(C); // Prints result. printf("Case #%d: %.8lf\n", tc, ret); } return 0; }
23.793478
87
0.535861
juarezpaulino
8d4bd36bebd7ebb592f68d170be19909aec44c0d
13,564
cpp
C++
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/corelib/doc/snippets/code/src_corelib_global_qglobal.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/corelib/doc/snippets/code/src_corelib_global_qglobal.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/corelib/doc/snippets/code/src_corelib_global_qglobal.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] label->setAlignment(Qt::AlignLeft | Qt::AlignTop); //! [0] //! [1] class MyClass { public: enum Option { NoOptions = 0x0, ShowTabs = 0x1, ShowAll = 0x2, SqueezeBlank = 0x4 }; Q_DECLARE_FLAGS(Options, Option) ... }; Q_DECLARE_OPERATORS_FOR_FLAGS(MyClass::Options) //! [1] //! [meta-object flags] Q_FLAG(Options) //! [meta-object flags] //! [2] typedef QFlags<Enum> Flags; //! [2] //! [3] int myValue = 10; int minValue = 2; int maxValue = 6; int boundedValue = qBound(minValue, myValue, maxValue); // boundedValue == 6 //! [3] //! [4] if (!driver()->isOpen() || driver()->isOpenError()) { qWarning("QSqlQuery::exec: database not open"); return false; } //! [4] //! [5] qint64 value = Q_INT64_C(932838457459459); //! [5] //! [6] quint64 value = Q_UINT64_C(932838457459459); //! [6] //! [7] void myMsgHandler(QtMsgType, const char *); //! [7] //! [8] qint64 value = Q_INT64_C(932838457459459); //! [8] //! [9] quint64 value = Q_UINT64_C(932838457459459); //! [9] //! [10] int absoluteValue; int myValue = -4; absoluteValue = qAbs(myValue); // absoluteValue == 4 //! [10] //! [11A] double valueA = 2.3; double valueB = 2.7; int roundedValueA = qRound(valueA); // roundedValueA = 2 int roundedValueB = qRound(valueB); // roundedValueB = 3 //! [11A] //! [11B] float valueA = 2.3; float valueB = 2.7; int roundedValueA = qRound(valueA); // roundedValueA = 2 int roundedValueB = qRound(valueB); // roundedValueB = 3 //! [11B] //! [12A] double valueA = 42949672960.3; double valueB = 42949672960.7; qint64 roundedValueA = qRound64(valueA); // roundedValueA = 42949672960 qint64 roundedValueB = qRound64(valueB); // roundedValueB = 42949672961 //! [12A] //! [12B] float valueA = 42949672960.3; float valueB = 42949672960.7; qint64 roundedValueA = qRound64(valueA); // roundedValueA = 42949672960 qint64 roundedValueB = qRound64(valueB); // roundedValueB = 42949672961 //! [12B] //! [13] int myValue = 6; int yourValue = 4; int minValue = qMin(myValue, yourValue); // minValue == yourValue //! [13] //! [14] int myValue = 6; int yourValue = 4; int maxValue = qMax(myValue, yourValue); // maxValue == myValue //! [14] //! [15] int myValue = 10; int minValue = 2; int maxValue = 6; int boundedValue = qBound(minValue, myValue, maxValue); // boundedValue == 6 //! [15] //! [16] #if QT_VERSION >= 0x040100 QIcon icon = style()->standardIcon(QStyle::SP_TrashIcon); #else QPixmap pixmap = style()->standardPixmap(QStyle::SP_TrashIcon); QIcon icon(pixmap); #endif //! [16] //! [17] // File: div.cpp #include <QtGlobal> int divide(int a, int b) { Q_ASSERT(b != 0); return a / b; } //! [17] //! [18] ASSERT: "b != 0" in file div.cpp, line 7 //! [18] //! [19] // File: div.cpp #include <QtGlobal> int divide(int a, int b) { Q_ASSERT_X(b != 0, "divide", "division by zero"); return a / b; } //! [19] //! [20] ASSERT failure in divide: "division by zero", file div.cpp, line 7 //! [20] //! [21] int *a; Q_CHECK_PTR(a = new int[80]); // WRONG! a = new (nothrow) int[80]; // Right Q_CHECK_PTR(a); //! [21] //! [22] template<typename TInputType> const TInputType &myMin(const TInputType &value1, const TInputType &value2) { qDebug() << Q_FUNC_INFO << "was called with value1:" << value1 << "value2:" << value2; if(value1 < value2) return value1; else return value2; } //! [22] //! [23] #include <qapplication.h> #include <stdio.h> #include <stdlib.h> void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); switch (type) { case QtDebugMsg: fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtInfoMsg: fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtWarningMsg: fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtCriticalMsg: fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtFatalMsg: fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); abort(); } } int main(int argc, char **argv) { qInstallMessageHandler(myMessageOutput); QApplication app(argc, argv); ... return app.exec(); } //! [23] //! [24] qDebug("Items in list: %d", myList.size()); //! [24] //! [25] qDebug() << "Brush:" << myQBrush << "Other value:" << i; //! [25] //! [qInfo_printf] qInfo("Items in list: %d", myList.size()); //! [qInfo_printf] //! [qInfo_stream] qInfo() << "Brush:" << myQBrush << "Other value:" << i; //! [qInfo_stream] //! [26] void f(int c) { if (c > 200) qWarning("f: bad argument, c == %d", c); } //! [26] //! [27] qWarning() << "Brush:" << myQBrush << "Other value:" << i; //! [27] //! [28] void load(const QString &fileName) { QFile file(fileName); if (!file.exists()) qCritical("File '%s' does not exist!", qUtf8Printable(fileName)); } //! [28] //! [29] qCritical() << "Brush:" << myQBrush << "Other value:" << i; //! [29] //! [30] int divide(int a, int b) { if (b == 0) // program error qFatal("divide: cannot divide by zero"); return a / b; } //! [30] //! [31] forever { ... } //! [31] //! [32] CONFIG += no_keywords //! [32] //! [33] CONFIG += no_keywords //! [33] //! [34] QString FriendlyConversation::greeting(int type) { static const char *greeting_strings[] = { QT_TR_NOOP("Hello"), QT_TR_NOOP("Goodbye") }; return tr(greeting_strings[type]); } //! [34] //! [35] static const char *greeting_strings[] = { QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"), QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye") }; QString FriendlyConversation::greeting(int type) { return tr(greeting_strings[type]); } QString global_greeting(int type) { return qApp->translate("FriendlyConversation", greeting_strings[type]); } //! [35] //! [36] static { const char *source; const char *comment; } greeting_strings[] = { QT_TRANSLATE_NOOP3("FriendlyConversation", "Hello", "A really friendly hello"), QT_TRANSLATE_NOOP3("FriendlyConversation", "Goodbye", "A really friendly goodbye") }; QString FriendlyConversation::greeting(int type) { return tr(greeting_strings[type].source, greeting_strings[type].comment); } QString global_greeting(int type) { return qApp->translate("FriendlyConversation", greeting_strings[type].source, greeting_strings[type].comment); } //! [36] //! [qttrid] //% "%n fooish bar(s) found.\n" //% "Do you want to continue?" QString text = qtTrId("qtn_foo_bar", n); //! [qttrid] //! [qttrid_noop] static const char * const ids[] = { //% "This is the first text." QT_TRID_NOOP("qtn_1st_text"), //% "This is the second text." QT_TRID_NOOP("qtn_2nd_text"), 0 }; void TheClass::addLabels() { for (int i = 0; ids[i]; ++i) new QLabel(qtTrId(ids[i]), this); } //! [qttrid_noop] //! [37] qWarning("%s: %s", qUtf8Printable(key), qUtf8Printable(value)); //! [37] //! [qUtf16Printable] qWarning("%ls: %ls", qUtf16Printable(key), qUtf16Printable(value)); //! [qUtf16Printable] //! [38] struct Point2D { int x; int y; }; Q_DECLARE_TYPEINFO(Point2D, Q_PRIMITIVE_TYPE); //! [38] //! [39] class Point2D { public: Point2D() { data = new int[2]; } Point2D(const Point2D &other) { ... } ~Point2D() { delete[] data; } Point2D &operator=(const Point2D &other) { ... } int x() const { return data[0]; } int y() const { return data[1]; } private: int *data; }; Q_DECLARE_TYPEINFO(Point2D, Q_MOVABLE_TYPE); //! [39] //! [40] #if Q_BYTE_ORDER == Q_BIG_ENDIAN ... #endif or #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN ... #endif //! [40] //! [41] #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN ... #endif //! [41] //! [42] #if Q_BYTE_ORDER == Q_BIG_ENDIAN ... #endif //! [42] //! [begin namespace macro] namespace QT_NAMESPACE { //! [begin namespace macro] //! [end namespace macro] } //! [end namespace macro] //! [43] class MyClass : public QObject { private: Q_DISABLE_COPY(MyClass) }; //! [43] //! [44] class MyClass : public QObject { private: MyClass(const MyClass &); MyClass &operator=(const MyClass &); }; //! [44] //! [45] QWidget w = QWidget(); //! [45] //! [46] // Instead of comparing with 0.0 qFuzzyCompare(0.0,1.0e-200); // This will return false // Compare adding 1 to both values will fix the problem qFuzzyCompare(1 + 0.0, 1 + 1.0e-200); // This will return true //! [46] //! [47] CApaApplication *myApplicationFactory(); //! [47] //! [49] void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &); //! [49] //! [50] class B {...}; class C {...}; class D {...}; struct A : public B { C c; D d; }; //! [50] //! [51] template<> class QTypeInfo<A> : public QTypeInfoMerger<A, B, C, D> {}; //! [51] //! [52] struct Foo { void overloadedFunction(); void overloadedFunction(int, QString); }; ... qOverload<>(&Foo::overloadedFunction) ... qOverload<int, QString>(&Foo::overloadedFunction) //! [52] //! [53] ... QOverload<>::of(&Foo::overloadedFunction) ... QOverload<int, QString>::of(&Foo::overloadedFunction) //! [53] //! [54] struct Foo { void overloadedFunction(int, QString); void overloadedFunction(int, QString) const; }; ... qConstOverload<int, QString>(&Foo::overloadedFunction) ... qNonConstOverload<int, QString>(&Foo::overloadedFunction) //! [54] //! [qlikely] // the condition inside the "if" will be successful most of the times for (int i = 1; i <= 365; i++) { if (Q_LIKELY(isWorkingDay(i))) { ... } ... } //! [qlikely] //! [qunlikely] bool readConfiguration(const QFile &file) { // We expect to be asked to read an existing file if (Q_UNLIKELY(!file.exists())) { qWarning() << "File not found"; return false; } ... return true; } //! [qunlikely] //! [qunreachable-enum] enum Shapes { Rectangle, Triangle, Circle, NumShapes }; //! [qunreachable-enum] //! [qunreachable-switch] switch (shape) { case Rectangle: return rectangle(); case Triangle: return triangle(); case Circle: return circle(); case NumShapes: Q_UNREACHABLE(); break; } //! [qunreachable-switch] //! [qt-version-check] #include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif //! [qt-version-check]
19.947059
122
0.617148
GrinCash
8d4d75eba468a4a2046fb087e3730c283fee453c
490
cpp
C++
ch04/DemoConstCast.cpp
imshenzhuo/CppPrimer
87c74c0a36223e86571c2aedd9da428c06b04f4d
[ "CC0-1.0" ]
3
2019-09-21T13:03:57.000Z
2020-04-05T02:42:53.000Z
ch04/DemoConstCast.cpp
imshenzhuo/CppPrimer
87c74c0a36223e86571c2aedd9da428c06b04f4d
[ "CC0-1.0" ]
null
null
null
ch04/DemoConstCast.cpp
imshenzhuo/CppPrimer
87c74c0a36223e86571c2aedd9da428c06b04f4d
[ "CC0-1.0" ]
null
null
null
/************************************************************************* > File Name: DemoConstCast.cpp > Author: shenzhuo > Mail: im.shenzhuo@gmail.com > Created Time: 2019年08月29日 星期四 10时39分19秒 ************************************************************************/ #include<iostream> using namespace std; int main() { int i = 99; const int *p = &i; // error // *p = -99; int *newp = const_cast<int *>(p); *newp = -99; cout << i << endl; return 0; }
18.148148
74
0.408163
imshenzhuo
8d4f50cddfb2355f2a867d814a27879a5dc18d15
8,129
cpp
C++
ql/experimental/commodities/energycommodity.cpp
igitur/quantlib
3f6b7271a68004cdb6db90f0e87346e8208234a2
[ "BSD-3-Clause" ]
1
2021-04-28T02:21:54.000Z
2021-04-28T02:21:54.000Z
ql/experimental/commodities/energycommodity.cpp
wangpeng-personal/QuantLib
2e4e4f1662bf15d18d19b396079feb36acb60150
[ "BSD-3-Clause" ]
4
2021-02-08T06:07:05.000Z
2022-03-29T12:23:40.000Z
ql/experimental/commodities/energycommodity.cpp
westonsteimel/QuantLib
739ea894961dc6da5e8aa0b61c392d40637d39c1
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 J. Erik Radmall This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <ql/currencies/exchangeratemanager.hpp> #include <ql/experimental/commodities/commoditysettings.hpp> #include <ql/experimental/commodities/energycommodity.hpp> #include <ql/experimental/commodities/unitofmeasureconversionmanager.hpp> #include <iomanip> #include <utility> namespace QuantLib { EnergyDailyPosition::EnergyDailyPosition() = default; EnergyDailyPosition::EnergyDailyPosition(const Date& date, Real payLegPrice, Real receiveLegPrice, bool unrealized) : date(date), quantityAmount(0), payLegPrice(payLegPrice), receiveLegPrice(receiveLegPrice), unrealized(unrealized) {} std::ostream& operator<<(std::ostream& out, const EnergyDailyPositions& dailyPositions) { out << std::setw(12) << std::left << "positions" << std::setw(12) << std::right << "pay" << std::setw(12) << std::right << "receive" << std::setw(10) << std::right << "qty" << std::setw(14) << std::right << "delta" << std::setw(10) << std::right << "open" << std::endl; for (const auto& i : dailyPositions) { const EnergyDailyPosition& dailyPosition = i.second; out << std::setw(4) << io::iso_date(i.first) << " " << std::setw(12) << std::right << std::fixed << std::setprecision(6) << dailyPosition.payLegPrice << std::setw(12) << std::right << std::fixed << std::setprecision(6) << dailyPosition.receiveLegPrice << std::setw(10) << std::right << std::fixed << std::setprecision(2) << dailyPosition.quantityAmount << std::setw(14) << std::right << std::fixed << std::setprecision(2) << dailyPosition.riskDelta << std::setw(10) << std::right << std::fixed << std::setprecision(2) << (dailyPosition.unrealized ? dailyPosition.quantityAmount : 0) << std::endl; } return out; } void EnergyCommodity::setupArguments(PricingEngine::arguments* args) const { auto* arguments = dynamic_cast<EnergyCommodity::arguments*>(args); QL_REQUIRE(arguments != nullptr, "wrong argument type"); //arguments->legs = legs_; //arguments->payer = payer_; } void EnergyCommodity::fetchResults(const PricingEngine::results* r) const { Instrument::fetchResults(r); const auto* results = dynamic_cast<const EnergyCommodity::results*>(r); QL_REQUIRE(results != nullptr, "wrong result type"); } EnergyCommodity::EnergyCommodity(CommodityType commodityType, const ext::shared_ptr<SecondaryCosts>& secondaryCosts) : Commodity(secondaryCosts), commodityType_(std::move(commodityType)) {} const CommodityType& EnergyCommodity::commodityType() const { return commodityType_; } Real EnergyCommodity::calculateUomConversionFactor( const CommodityType& commodityType, const UnitOfMeasure& fromUnitOfMeasure, const UnitOfMeasure& toUnitOfMeasure) { if (toUnitOfMeasure != fromUnitOfMeasure) { UnitOfMeasureConversion uomConv = UnitOfMeasureConversionManager::instance().lookup( commodityType, fromUnitOfMeasure, toUnitOfMeasure); return uomConv.conversionFactor(); } return 1; } Real EnergyCommodity::calculateFxConversionFactor( const Currency& fromCurrency, const Currency& toCurrency, const Date& evaluationDate) { if (fromCurrency != toCurrency) { ExchangeRate exchRate = ExchangeRateManager::instance().lookup( fromCurrency, toCurrency, evaluationDate /*, ExchangeRate::Direct*/); if (fromCurrency == exchRate.target()) return 1.0 / exchRate.rate(); return exchRate.rate(); } return 1; } Real EnergyCommodity::calculateUnitCost(const CommodityType& commodityType, const CommodityUnitCost& unitCost, const Date& evaluationDate) const { if (unitCost.amount().value() != 0) { const Currency& baseCurrency = CommoditySettings::instance().currency(); const UnitOfMeasure baseUnitOfMeasure = CommoditySettings::instance().unitOfMeasure(); Real unitCostUomConversionFactor = calculateUomConversionFactor(commodityType, unitCost.unitOfMeasure(), baseUnitOfMeasure); Real unitCostFxConversionFactor = calculateFxConversionFactor(unitCost.amount().currency(), baseCurrency, evaluationDate); return unitCost.amount().value() * unitCostUomConversionFactor * unitCostFxConversionFactor; } return 0; } void EnergyCommodity::calculateSecondaryCostAmounts( const CommodityType& commodityType, Real totalQuantityValue, const Date& evaluationDate) const { secondaryCostAmounts_.clear(); if (secondaryCosts_ != nullptr) { const Currency& baseCurrency = CommoditySettings::instance().currency(); try { for (SecondaryCosts::const_iterator i = secondaryCosts_->begin(); i != secondaryCosts_->end(); ++i) { if (boost::any_cast<CommodityUnitCost>(&i->second) != nullptr) { Real value = calculateUnitCost( commodityType, boost::any_cast<CommodityUnitCost>(i->second), evaluationDate) * totalQuantityValue; secondaryCostAmounts_[i->first] = Money(baseCurrency, value); } else if (boost::any_cast<Money>(&i->second) != nullptr) { const Money& amount = boost::any_cast<Money>(i->second); Real fxConversionFactor = calculateFxConversionFactor(amount.currency(), baseCurrency, evaluationDate); secondaryCostAmounts_[i->first] = Money(baseCurrency, amount.value() * fxConversionFactor); } } } catch (const std::exception& e) { QL_FAIL("error calculating secondary costs: " << e.what()); } } } }
45.926554
100
0.546193
igitur
8d500d841fbeb3da1487ce1ee1fcdbc288e73149
171
cxx
C++
tests/nonsmoke/functional/CompileTests/unparse_template_from_ast/kripke-tpl-005.cxx
ouankou/rose
76f2a004bd6d8036bc24be2c566a14e33ba4f825
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
tests/nonsmoke/functional/CompileTests/unparse_template_from_ast/kripke-tpl-005.cxx
WildeGeist/rose
17db6454e8baba0014e30a8ec23df1a11ac55a0c
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
tests/nonsmoke/functional/CompileTests/unparse_template_from_ast/kripke-tpl-005.cxx
WildeGeist/rose
17db6454e8baba0014e30a8ec23df1a11ac55a0c
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
namespace N { template <typename T0> void foo(); template <typename T1> struct A {}; } template<typename T2> void bar() { N::foo<typename N::A<T2>::X::Y>(); }
13.153846
36
0.602339
ouankou
8d52f5de01200eee6b2c6a4af694c61dbc8cd553
4,026
cpp
C++
10b/Chapter_13_Binary_Search_Tree_Code.cpp
mparsakia/pic-ucla
bca66812d2ce9daa8dcaa7ab126260c75f9c9ab4
[ "Unlicense" ]
1
2020-08-07T13:03:14.000Z
2020-08-07T13:03:14.000Z
10b/Chapter_13_Binary_Search_Tree_Code.cpp
mparsakia/pic-ucla
bca66812d2ce9daa8dcaa7ab126260c75f9c9ab4
[ "Unlicense" ]
null
null
null
10b/Chapter_13_Binary_Search_Tree_Code.cpp
mparsakia/pic-ucla
bca66812d2ce9daa8dcaa7ab126260c75f9c9ab4
[ "Unlicense" ]
null
null
null
#include <vector> #include <iostream> #include <assert.h> #include <stdio.h> #include <algorithm> #include <fstream> #include <cstring> #include <string> #include <iomanip> #include <sstream> #include <map> #include <set> #include <list> // Binary Search Tree using namespace std; class TreeNode { public: void insert_node(TreeNode* new_node); void print_nodes() const; bool find(string value) const; private: string data; TreeNode* left; TreeNode* right; }; class BinarySearchTree { public: BinarySearchTree(); void insert(string data); void erase(string data); int count(string data) const; void print() const; private: TreeNode* root; }; BinarySearchTree::BinarySearchTree() { root = NULL; } void BinarySearchTree::print() const { if (root != NULL) root->print_nodes(); } void BinarySearchTree::insert(string data) { TreeNode* new_node = new TreeNode; new_node->data = data; new_node->left = NULL; new_node->right = NULL; if (root == NULL) root = new_node; else root->insert_node(new_node); } void TreeNode::insert_node(TreeNode* new_node) { if (new_node->data < data) { if (left == NULL) left = new_node; else left->insert_node(new_node); } else if (data < new_node->data) { if (right == NULL) right = new_node; else right->insert_node(new_node); } } int BinarySearchTree::count(string data) const { if (root == NULL) return 0; else if (root->find(data)) return 1; else return 0; } void BinarySearchTree::erase(string data) { // Find node to be removed TreeNode* to_be_removed = root; TreeNode* parent = NULL; bool found = false; while (!found && to_be_removed != NULL) { if (to_be_removed->data < data) { parent = to_be_removed; to_be_removed = to_be_removed->right; } else if (data < to_be_removed->data) { parent = to_be_removed; to_be_removed = to_be_removed->left; } else found = true; } if (!found) return; // to_be_removed contains data // If one of the children is empty, use the other if (to_be_removed->left == NULL || to_be_removed->right == NULL) { TreeNode* new_child; if (to_be_removed->left == NULL) new_child = to_be_removed->right; else new_child = to_be_removed->left; if (parent == NULL) // Found in root root = new_child; else if (parent->left == to_be_removed) parent->left = new_child; else parent->right = new_child; return; } // Neither subtree is empty // Find smallest element of the right subtree TreeNode* smallest_parent = to_be_removed; TreeNode* smallest = to_be_removed->right; while (smallest->left != NULL) { smallest_parent = smallest; smallest = smallest->left; } // smallest contains smallest child in right subtree // Move contents, unlink child to_be_removed->data = smallest->data; if (smallest_parent == to_be_removed) smallest_parent->right = smallest->right; else smallest_parent->left = smallest->right; } bool TreeNode::find(string value) const { if (value < data) { if (left == NULL) return false; else return left->find(value); } else if (data < value) { if (right == NULL) return false; else return right->find(value); } else { return true; } } void TreeNode::print_nodes() const { if (left != NULL) // LEFT left->print_nodes(); cout << data << "\n"; // DATA if (right != NULL) right->print_nodes(); // RIGHT THIS IS LDR (IN ORDER) } int main() { BinarySearchTree t; t.insert("D"); t.insert("B"); t.insert("A"); t.insert("C"); t.insert("F"); t.insert("E"); t.insert("I"); t.insert("G"); t.insert("H"); t.insert("J"); t.erase("A"); // Removing leaf t.erase("B"); // Removing element with one child t.erase("F"); // Removing element with two children t.erase("D"); // Removing root t.print(); cout << t.count("E") << "\n"; cout << t.count("F") << "\n"; return 0; }
19.930693
66
0.633631
mparsakia
8d55c465e9037f1d5bb43fa3ec412752ad98af06
984
hpp
C++
sdk/storage/azure-storage-files-datalake/test/ut/datalake_file_system_client_test.hpp
varchar-io/azure-sdk-for-cpp
4d498c59baf21fa9160ea913d379380ecc60e65d
[ "MIT" ]
null
null
null
sdk/storage/azure-storage-files-datalake/test/ut/datalake_file_system_client_test.hpp
varchar-io/azure-sdk-for-cpp
4d498c59baf21fa9160ea913d379380ecc60e65d
[ "MIT" ]
null
null
null
sdk/storage/azure-storage-files-datalake/test/ut/datalake_file_system_client_test.hpp
varchar-io/azure-sdk-for-cpp
4d498c59baf21fa9160ea913d379380ecc60e65d
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #include <azure/storage/files/datalake.hpp> #include "datalake_service_client_test.hpp" #include "test/ut/test_base.hpp" namespace Azure { namespace Storage { namespace Test { class DataLakeFileSystemClientTest : public DataLakeServiceClientTest { protected: void SetUp(); void TearDown(); void CreateDirectoryList(); std::vector<Files::DataLake::Models::PathItem> ListAllPaths( bool recursive, const std::string& directory = std::string()); Files::DataLake::Models::PathHttpHeaders GetInterestingHttpHeaders(); std::shared_ptr<Files::DataLake::DataLakeFileSystemClient> m_fileSystemClient; std::string m_fileSystemName; // Path related std::vector<std::string> m_pathNameSetA; std::string m_directoryA; std::vector<std::string> m_pathNameSetB; std::string m_directoryB; }; }}} // namespace Azure::Storage::Test
28.941176
82
0.727642
varchar-io
8d5a723da6ca46440e400b17cb83be03294901c3
596
hpp
C++
tcob/include/tcob/game/Config.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
2
2021-08-18T19:14:35.000Z
2021-12-01T14:14:49.000Z
tcob/include/tcob/game/Config.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
tcob/include/tcob/game/Config.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Tobias Bohnen // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #pragma once #include <tcob/tcob_config.hpp> #include <tcob/script/LuaScript.hpp> #include <tcob/script/LuaTable.hpp> namespace tcob { //////////////////////////////////////////////////////////// class Config final : public script::lua::Table { public: Config() = default; ~Config() override; void save() const; auto load() -> bool; private: auto operator=(const script::lua::Ref& other) -> Config&; script::lua::Script _script {}; }; }
22.074074
61
0.60906
TobiasBohnen
8d5d6cf442e98fae60465115280eb60a6be1bb76
20,343
cpp
C++
xfa/fwl/core/ifwl_datetimepicker.cpp
isabella232/pdfium-1
d8f710cedd62c1d28beee15d7dc3d31ddd148437
[ "BSD-3-Clause" ]
38
2015-11-25T02:25:25.000Z
2022-01-04T01:11:15.000Z
xfa/fwl/core/ifwl_datetimepicker.cpp
isabella232/pdfium-1
d8f710cedd62c1d28beee15d7dc3d31ddd148437
[ "BSD-3-Clause" ]
1
2021-02-23T22:36:54.000Z
2021-02-23T22:36:54.000Z
xfa/fwl/core/ifwl_datetimepicker.cpp
isabella232/pdfium-1
d8f710cedd62c1d28beee15d7dc3d31ddd148437
[ "BSD-3-Clause" ]
13
2016-08-03T02:35:18.000Z
2020-12-17T10:14:04.000Z
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fwl/core/ifwl_datetimepicker.h" #include "third_party/base/ptr_util.h" #include "xfa/fwl/core/cfwl_evteditchanged.h" #include "xfa/fwl/core/cfwl_evtselectchanged.h" #include "xfa/fwl/core/cfwl_msgmouse.h" #include "xfa/fwl/core/cfwl_msgsetfocus.h" #include "xfa/fwl/core/cfwl_themebackground.h" #include "xfa/fwl/core/cfwl_widgetmgr.h" #include "xfa/fwl/core/fwl_noteimp.h" #include "xfa/fwl/core/ifwl_formproxy.h" #include "xfa/fwl/core/ifwl_spinbutton.h" #include "xfa/fwl/core/ifwl_themeprovider.h" namespace { const int kDateTimePickerWidth = 100; const int kDateTimePickerHeight = 20; } // namespace IFWL_DateTimePicker::IFWL_DateTimePicker( const IFWL_App* app, std::unique_ptr<CFWL_WidgetProperties> properties) : IFWL_Widget(app, std::move(properties), nullptr), m_iBtnState(1), m_iYear(-1), m_iMonth(-1), m_iDay(-1), m_iCurYear(2010), m_iCurMonth(3), m_iCurDay(29), m_bLBtnDown(false) { m_rtBtn.Set(0, 0, 0, 0); m_pProperties->m_dwStyleExes = FWL_STYLEEXT_DTP_ShortDateFormat; auto monthProp = pdfium::MakeUnique<CFWL_WidgetProperties>(this); monthProp->m_dwStyles = FWL_WGTSTYLE_Popup | FWL_WGTSTYLE_Border; monthProp->m_dwStates = FWL_WGTSTATE_Invisible; monthProp->m_pParent = this; monthProp->m_pThemeProvider = m_pProperties->m_pThemeProvider; m_pMonthCal.reset( new IFWL_MonthCalendar(m_pOwnerApp, std::move(monthProp), this)); CFX_RectF rtMonthCal; m_pMonthCal->GetWidgetRect(rtMonthCal, true); rtMonthCal.Set(0, 0, rtMonthCal.width, rtMonthCal.height); m_pMonthCal->SetWidgetRect(rtMonthCal); auto editProp = pdfium::MakeUnique<CFWL_WidgetProperties>(); editProp->m_pParent = this; editProp->m_pThemeProvider = m_pProperties->m_pThemeProvider; m_pEdit.reset(new IFWL_DateTimeEdit(m_pOwnerApp, std::move(editProp), this)); RegisterEventTarget(m_pMonthCal.get()); RegisterEventTarget(m_pEdit.get()); } IFWL_DateTimePicker::~IFWL_DateTimePicker() { UnregisterEventTarget(); } FWL_Type IFWL_DateTimePicker::GetClassID() const { return FWL_Type::DateTimePicker; } void IFWL_DateTimePicker::GetWidgetRect(CFX_RectF& rect, bool bAutoSize) { if (m_pWidgetMgr->IsFormDisabled()) { DisForm_GetWidgetRect(rect, bAutoSize); return; } if (!bAutoSize) { rect = m_pProperties->m_rtWidget; return; } rect.Set(0, 0, kDateTimePickerWidth, kDateTimePickerHeight); IFWL_Widget::GetWidgetRect(rect, true); } void IFWL_DateTimePicker::Update() { if (m_pWidgetMgr->IsFormDisabled()) { DisForm_Update(); return; } if (m_iLock) return; if (!m_pProperties->m_pThemeProvider) m_pProperties->m_pThemeProvider = GetAvailableTheme(); m_pEdit->SetThemeProvider(m_pProperties->m_pThemeProvider); GetClientRect(m_rtClient); FX_FLOAT* pFWidth = static_cast<FX_FLOAT*>( GetThemeCapacity(CFWL_WidgetCapacity::ScrollBarWidth)); if (!pFWidth) return; FX_FLOAT fBtn = *pFWidth; m_rtBtn.Set(m_rtClient.right() - fBtn, m_rtClient.top, fBtn - 1, m_rtClient.height - 1); CFX_RectF rtEdit; rtEdit.Set(m_rtClient.left, m_rtClient.top, m_rtClient.width - fBtn, m_rtClient.height); m_pEdit->SetWidgetRect(rtEdit); ResetEditAlignment(); m_pEdit->Update(); if (!(m_pMonthCal->GetThemeProvider())) m_pMonthCal->SetThemeProvider(m_pProperties->m_pThemeProvider); if (m_pProperties->m_pDataProvider) { IFWL_DateTimePickerDP* pData = static_cast<IFWL_DateTimePickerDP*>(m_pProperties->m_pDataProvider); pData->GetToday(this, m_iCurYear, m_iCurMonth, m_iCurDay); } CFX_RectF rtMonthCal; m_pMonthCal->GetWidgetRect(rtMonthCal, true); CFX_RectF rtPopUp; rtPopUp.Set(rtMonthCal.left, rtMonthCal.top + kDateTimePickerHeight, rtMonthCal.width, rtMonthCal.height); m_pMonthCal->SetWidgetRect(rtPopUp); m_pMonthCal->Update(); return; } FWL_WidgetHit IFWL_DateTimePicker::HitTest(FX_FLOAT fx, FX_FLOAT fy) { if (m_pWidgetMgr->IsFormDisabled()) return DisForm_HitTest(fx, fy); if (m_rtClient.Contains(fx, fy)) return FWL_WidgetHit::Client; if (IsMonthCalendarVisible()) { CFX_RectF rect; m_pMonthCal->GetWidgetRect(rect); if (rect.Contains(fx, fy)) return FWL_WidgetHit::Client; } return FWL_WidgetHit::Unknown; } void IFWL_DateTimePicker::DrawWidget(CFX_Graphics* pGraphics, const CFX_Matrix* pMatrix) { if (!pGraphics) return; if (!m_pProperties->m_pThemeProvider) return; IFWL_ThemeProvider* pTheme = m_pProperties->m_pThemeProvider; if (HasBorder()) DrawBorder(pGraphics, CFWL_Part::Border, pTheme, pMatrix); if (HasEdge()) DrawEdge(pGraphics, CFWL_Part::Edge, pTheme, pMatrix); if (!m_rtBtn.IsEmpty()) DrawDropDownButton(pGraphics, pTheme, pMatrix); if (m_pWidgetMgr->IsFormDisabled()) { DisForm_DrawWidget(pGraphics, pMatrix); return; } } void IFWL_DateTimePicker::SetThemeProvider(IFWL_ThemeProvider* pTP) { m_pProperties->m_pThemeProvider = pTP; m_pMonthCal->SetThemeProvider(pTP); } void IFWL_DateTimePicker::GetCurSel(int32_t& iYear, int32_t& iMonth, int32_t& iDay) { iYear = m_iYear; iMonth = m_iMonth; iDay = m_iDay; } void IFWL_DateTimePicker::SetCurSel(int32_t iYear, int32_t iMonth, int32_t iDay) { if (iYear <= 0 || iYear >= 3000) return; if (iMonth <= 0 || iMonth >= 13) return; if (iDay <= 0 || iDay >= 32) return; m_iYear = iYear; m_iMonth = iMonth; m_iDay = iDay; m_pMonthCal->SetSelect(iYear, iMonth, iDay); } void IFWL_DateTimePicker::SetEditText(const CFX_WideString& wsText) { if (!m_pEdit) return; m_pEdit->SetText(wsText); Repaint(&m_rtClient); CFWL_EvtEditChanged ev; DispatchEvent(&ev); } void IFWL_DateTimePicker::GetEditText(CFX_WideString& wsText, int32_t nStart, int32_t nCount) const { if (m_pEdit) m_pEdit->GetText(wsText, nStart, nCount); } void IFWL_DateTimePicker::GetBBox(CFX_RectF& rect) const { if (m_pWidgetMgr->IsFormDisabled()) { DisForm_GetBBox(rect); return; } rect = m_pProperties->m_rtWidget; if (IsMonthCalendarVisible()) { CFX_RectF rtMonth; m_pMonthCal->GetWidgetRect(rtMonth); rtMonth.Offset(m_pProperties->m_rtWidget.left, m_pProperties->m_rtWidget.top); rect.Union(rtMonth); } } void IFWL_DateTimePicker::ModifyEditStylesEx(uint32_t dwStylesExAdded, uint32_t dwStylesExRemoved) { m_pEdit->ModifyStylesEx(dwStylesExAdded, dwStylesExRemoved); } void IFWL_DateTimePicker::DrawDropDownButton(CFX_Graphics* pGraphics, IFWL_ThemeProvider* pTheme, const CFX_Matrix* pMatrix) { if ((m_pProperties->m_dwStyleExes & FWL_STYLEEXT_DTP_Spin) == FWL_STYLEEXT_DTP_Spin) { return; } CFWL_ThemeBackground param; param.m_pWidget = this; param.m_iPart = CFWL_Part::DropDownButton; param.m_dwStates = m_iBtnState; param.m_pGraphics = pGraphics; param.m_rtPart = m_rtBtn; if (pMatrix) param.m_matrix.Concat(*pMatrix); pTheme->DrawBackground(&param); } void IFWL_DateTimePicker::FormatDateString(int32_t iYear, int32_t iMonth, int32_t iDay, CFX_WideString& wsText) { if ((m_pProperties->m_dwStyleExes & FWL_STYLEEXT_DTP_ShortDateFormat) == FWL_STYLEEXT_DTP_ShortDateFormat) { wsText.Format(L"%d-%d-%d", iYear, iMonth, iDay); } else if ((m_pProperties->m_dwStyleExes & FWL_STYLEEXT_DTP_LongDateFormat) == FWL_STYLEEXT_DTP_LongDateFormat) { wsText.Format(L"%d Year %d Month %d Day", iYear, iMonth, iDay); } } void IFWL_DateTimePicker::ShowMonthCalendar(bool bActivate) { if (m_pWidgetMgr->IsFormDisabled()) return DisForm_ShowMonthCalendar(bActivate); if (IsMonthCalendarVisible() == bActivate) return; if (!m_pForm) InitProxyForm(); if (!bActivate) { m_pForm->EndDoModal(); return; } CFX_RectF rtMonth; m_pMonthCal->GetWidgetRect(rtMonth); CFX_RectF rtAnchor; rtAnchor.Set(0, 0, m_pProperties->m_rtWidget.width, m_pProperties->m_rtWidget.height); GetPopupPos(0, rtMonth.height, rtAnchor, rtMonth); m_pForm->SetWidgetRect(rtMonth); rtMonth.left = rtMonth.top = 0; m_pMonthCal->SetStates(FWL_WGTSTATE_Invisible, !bActivate); m_pMonthCal->SetWidgetRect(rtMonth); m_pMonthCal->Update(); m_pForm->DoModal(); } bool IFWL_DateTimePicker::IsMonthCalendarVisible() const { if (m_pWidgetMgr->IsFormDisabled()) return DisForm_IsMonthCalendarVisible(); if (!m_pForm) return false; return !(m_pForm->GetStates() & FWL_WGTSTATE_Invisible); } void IFWL_DateTimePicker::ResetEditAlignment() { if (!m_pEdit) return; uint32_t dwAdd = 0; switch (m_pProperties->m_dwStyleExes & FWL_STYLEEXT_DTP_EditHAlignMask) { case FWL_STYLEEXT_DTP_EditHCenter: { dwAdd |= FWL_STYLEEXT_EDT_HCenter; break; } case FWL_STYLEEXT_DTP_EditHFar: { dwAdd |= FWL_STYLEEXT_EDT_HFar; break; } default: { dwAdd |= FWL_STYLEEXT_EDT_HNear; break; } } switch (m_pProperties->m_dwStyleExes & FWL_STYLEEXT_DTP_EditVAlignMask) { case FWL_STYLEEXT_DTP_EditVCenter: { dwAdd |= FWL_STYLEEXT_EDT_VCenter; break; } case FWL_STYLEEXT_DTP_EditVFar: { dwAdd |= FWL_STYLEEXT_EDT_VFar; break; } default: { dwAdd |= FWL_STYLEEXT_EDT_VNear; break; } } if (m_pProperties->m_dwStyleExes & FWL_STYLEEXT_DTP_EditJustified) dwAdd |= FWL_STYLEEXT_EDT_Justified; if (m_pProperties->m_dwStyleExes & FWL_STYLEEXT_DTP_EditDistributed) dwAdd |= FWL_STYLEEXT_EDT_Distributed; m_pEdit->ModifyStylesEx(dwAdd, FWL_STYLEEXT_EDT_HAlignMask | FWL_STYLEEXT_EDT_HAlignModeMask | FWL_STYLEEXT_EDT_VAlignMask); } void IFWL_DateTimePicker::ProcessSelChanged(int32_t iYear, int32_t iMonth, int32_t iDay) { m_iYear = iYear; m_iMonth = iMonth; m_iDay = iDay; CFX_WideString wsText; FormatDateString(m_iYear, m_iMonth, m_iDay, wsText); m_pEdit->SetText(wsText); m_pEdit->Update(); Repaint(&m_rtClient); CFWL_EvtSelectChanged ev; ev.m_pSrcTarget = this; ev.iYear = m_iYear; ev.iMonth = m_iMonth; ev.iDay = m_iDay; DispatchEvent(&ev); } void IFWL_DateTimePicker::InitProxyForm() { if (m_pForm) return; if (!m_pMonthCal) return; auto prop = pdfium::MakeUnique<CFWL_WidgetProperties>(); prop->m_dwStyles = FWL_WGTSTYLE_Popup; prop->m_dwStates = FWL_WGTSTATE_Invisible; prop->m_pOwner = this; m_pForm = pdfium::MakeUnique<IFWL_FormProxy>(m_pOwnerApp, std::move(prop), m_pMonthCal.get()); m_pMonthCal->SetParent(m_pForm.get()); } bool IFWL_DateTimePicker::DisForm_IsMonthCalendarVisible() const { if (!m_pMonthCal) return false; return !(m_pMonthCal->GetStates() & FWL_WGTSTATE_Invisible); } void IFWL_DateTimePicker::DisForm_ShowMonthCalendar(bool bActivate) { if (IsMonthCalendarVisible() == bActivate) return; if (bActivate) { CFX_RectF rtMonthCal; m_pMonthCal->GetWidgetRect(rtMonthCal, true); FX_FLOAT fPopupMin = rtMonthCal.height; FX_FLOAT fPopupMax = rtMonthCal.height; CFX_RectF rtAnchor(m_pProperties->m_rtWidget); rtAnchor.width = rtMonthCal.width; rtMonthCal.left = m_rtClient.left; rtMonthCal.top = rtAnchor.Height(); GetPopupPos(fPopupMin, fPopupMax, rtAnchor, rtMonthCal); m_pMonthCal->SetWidgetRect(rtMonthCal); if (m_iYear > 0 && m_iMonth > 0 && m_iDay > 0) m_pMonthCal->SetSelect(m_iYear, m_iMonth, m_iDay); m_pMonthCal->Update(); } m_pMonthCal->SetStates(FWL_WGTSTATE_Invisible, !bActivate); if (bActivate) { CFWL_MsgSetFocus msg; msg.m_pDstTarget = m_pMonthCal.get(); msg.m_pSrcTarget = m_pEdit.get(); m_pEdit->GetDelegate()->OnProcessMessage(&msg); } CFX_RectF rtInvalidate, rtCal; rtInvalidate.Set(0, 0, m_pProperties->m_rtWidget.width, m_pProperties->m_rtWidget.height); m_pMonthCal->GetWidgetRect(rtCal); rtInvalidate.Union(rtCal); rtInvalidate.Inflate(2, 2); Repaint(&rtInvalidate); } FWL_WidgetHit IFWL_DateTimePicker::DisForm_HitTest(FX_FLOAT fx, FX_FLOAT fy) const { CFX_RectF rect; rect.Set(0, 0, m_pProperties->m_rtWidget.width, m_pProperties->m_rtWidget.height); if (rect.Contains(fx, fy)) return FWL_WidgetHit::Edit; if (DisForm_IsNeedShowButton()) rect.width += m_fBtn; if (rect.Contains(fx, fy)) return FWL_WidgetHit::Client; if (IsMonthCalendarVisible()) { m_pMonthCal->GetWidgetRect(rect); if (rect.Contains(fx, fy)) return FWL_WidgetHit::Client; } return FWL_WidgetHit::Unknown; } bool IFWL_DateTimePicker::DisForm_IsNeedShowButton() const { return m_pProperties->m_dwStates & FWL_WGTSTATE_Focused || m_pMonthCal->GetStates() & FWL_WGTSTATE_Focused || m_pEdit->GetStates() & FWL_WGTSTATE_Focused; } void IFWL_DateTimePicker::DisForm_Update() { if (m_iLock) return; if (!m_pProperties->m_pThemeProvider) m_pProperties->m_pThemeProvider = GetAvailableTheme(); m_pEdit->SetThemeProvider(m_pProperties->m_pThemeProvider); GetClientRect(m_rtClient); m_pEdit->SetWidgetRect(m_rtClient); ResetEditAlignment(); m_pEdit->Update(); if (!m_pMonthCal->GetThemeProvider()) m_pMonthCal->SetThemeProvider(m_pProperties->m_pThemeProvider); if (m_pProperties->m_pDataProvider) { IFWL_DateTimePickerDP* pData = static_cast<IFWL_DateTimePickerDP*>(m_pProperties->m_pDataProvider); pData->GetToday(this, m_iCurYear, m_iCurMonth, m_iCurDay); } FX_FLOAT* pWidth = static_cast<FX_FLOAT*>( GetThemeCapacity(CFWL_WidgetCapacity::ScrollBarWidth)); if (!pWidth) return; m_fBtn = *pWidth; CFX_RectF rtMonthCal; m_pMonthCal->GetWidgetRect(rtMonthCal, true); CFX_RectF rtPopUp; rtPopUp.Set(rtMonthCal.left, rtMonthCal.top + kDateTimePickerHeight, rtMonthCal.width, rtMonthCal.height); m_pMonthCal->SetWidgetRect(rtPopUp); m_pMonthCal->Update(); } void IFWL_DateTimePicker::DisForm_GetWidgetRect(CFX_RectF& rect, bool bAutoSize) { rect = m_pProperties->m_rtWidget; if (DisForm_IsNeedShowButton()) rect.width += m_fBtn; } void IFWL_DateTimePicker::DisForm_GetBBox(CFX_RectF& rect) const { rect = m_pProperties->m_rtWidget; if (DisForm_IsNeedShowButton()) rect.width += m_fBtn; if (!IsMonthCalendarVisible()) return; CFX_RectF rtMonth; m_pMonthCal->GetWidgetRect(rtMonth); rtMonth.Offset(m_pProperties->m_rtWidget.left, m_pProperties->m_rtWidget.top); rect.Union(rtMonth); } void IFWL_DateTimePicker::DisForm_DrawWidget(CFX_Graphics* pGraphics, const CFX_Matrix* pMatrix) { if (!pGraphics) return; if (m_pEdit) { CFX_RectF rtEdit; m_pEdit->GetWidgetRect(rtEdit); CFX_Matrix mt; mt.Set(1, 0, 0, 1, rtEdit.left, rtEdit.top); if (pMatrix) mt.Concat(*pMatrix); m_pEdit->DrawWidget(pGraphics, &mt); } if (!IsMonthCalendarVisible()) return; CFX_RectF rtMonth; m_pMonthCal->GetWidgetRect(rtMonth); CFX_Matrix mt; mt.Set(1, 0, 0, 1, rtMonth.left, rtMonth.top); if (pMatrix) mt.Concat(*pMatrix); m_pMonthCal->DrawWidget(pGraphics, &mt); } void IFWL_DateTimePicker::OnProcessMessage(CFWL_Message* pMessage) { if (!pMessage) return; switch (pMessage->GetClassID()) { case CFWL_MessageType::SetFocus: OnFocusChanged(pMessage, true); break; case CFWL_MessageType::KillFocus: OnFocusChanged(pMessage, false); break; case CFWL_MessageType::Mouse: { CFWL_MsgMouse* pMouse = static_cast<CFWL_MsgMouse*>(pMessage); switch (pMouse->m_dwCmd) { case FWL_MouseCommand::LeftButtonDown: OnLButtonDown(pMouse); break; case FWL_MouseCommand::LeftButtonUp: OnLButtonUp(pMouse); break; case FWL_MouseCommand::Move: OnMouseMove(pMouse); break; case FWL_MouseCommand::Leave: OnMouseLeave(pMouse); break; default: break; } break; } case CFWL_MessageType::Key: { if (m_pEdit->GetStates() & FWL_WGTSTATE_Focused) { m_pEdit->GetDelegate()->OnProcessMessage(pMessage); return; } break; } default: break; } IFWL_Widget::OnProcessMessage(pMessage); } void IFWL_DateTimePicker::OnDrawWidget(CFX_Graphics* pGraphics, const CFX_Matrix* pMatrix) { DrawWidget(pGraphics, pMatrix); } void IFWL_DateTimePicker::OnFocusChanged(CFWL_Message* pMsg, bool bSet) { if (!pMsg) return; if (m_pWidgetMgr->IsFormDisabled()) return DisForm_OnFocusChanged(pMsg, bSet); if (bSet) { m_pProperties->m_dwStates |= (FWL_WGTSTATE_Focused); Repaint(&m_rtClient); } else { m_pProperties->m_dwStates &= ~(FWL_WGTSTATE_Focused); Repaint(&m_rtClient); } if (pMsg->m_pSrcTarget == m_pMonthCal.get() && IsMonthCalendarVisible()) { ShowMonthCalendar(false); } Repaint(&m_rtClient); } void IFWL_DateTimePicker::OnLButtonDown(CFWL_MsgMouse* pMsg) { if (!pMsg) return; if ((m_pProperties->m_dwStates & FWL_WGTSTATE_Focused) == 0) SetFocus(true); if (!m_rtBtn.Contains(pMsg->m_fx, pMsg->m_fy)) return; if (IsMonthCalendarVisible()) { ShowMonthCalendar(false); return; } if (!(m_pProperties->m_dwStyleExes & FWL_STYLEEXT_DTP_TimeFormat)) ShowMonthCalendar(true); m_bLBtnDown = true; Repaint(&m_rtClient); } void IFWL_DateTimePicker::OnLButtonUp(CFWL_MsgMouse* pMsg) { if (!pMsg) return; m_bLBtnDown = false; if (m_rtBtn.Contains(pMsg->m_fx, pMsg->m_fy)) m_iBtnState = CFWL_PartState_Hovered; else m_iBtnState = CFWL_PartState_Normal; Repaint(&m_rtBtn); } void IFWL_DateTimePicker::OnMouseMove(CFWL_MsgMouse* pMsg) { if (!m_rtBtn.Contains(pMsg->m_fx, pMsg->m_fy)) m_iBtnState = CFWL_PartState_Normal; Repaint(&m_rtBtn); } void IFWL_DateTimePicker::OnMouseLeave(CFWL_MsgMouse* pMsg) { if (!pMsg) return; m_iBtnState = CFWL_PartState_Normal; Repaint(&m_rtBtn); } void IFWL_DateTimePicker::DisForm_OnFocusChanged(CFWL_Message* pMsg, bool bSet) { CFX_RectF rtInvalidate(m_rtBtn); if (bSet) { m_pProperties->m_dwStates |= FWL_WGTSTATE_Focused; if (m_pEdit && !(m_pEdit->GetStylesEx() & FWL_STYLEEXT_EDT_ReadOnly)) { m_rtBtn.Set(m_pProperties->m_rtWidget.width, 0, m_fBtn, m_pProperties->m_rtWidget.height - 1); } rtInvalidate = m_rtBtn; pMsg->m_pDstTarget = m_pEdit.get(); m_pEdit->GetDelegate()->OnProcessMessage(pMsg); } else { m_pProperties->m_dwStates &= ~FWL_WGTSTATE_Focused; m_rtBtn.Set(0, 0, 0, 0); if (DisForm_IsMonthCalendarVisible()) ShowMonthCalendar(false); if (m_pEdit->GetStates() & FWL_WGTSTATE_Focused) { pMsg->m_pSrcTarget = m_pEdit.get(); m_pEdit->GetDelegate()->OnProcessMessage(pMsg); } } rtInvalidate.Inflate(2, 2); Repaint(&rtInvalidate); } void IFWL_DateTimePicker::GetCaption(IFWL_Widget* pWidget, CFX_WideString& wsCaption) {} int32_t IFWL_DateTimePicker::GetCurDay(IFWL_Widget* pWidget) { return m_iCurDay; } int32_t IFWL_DateTimePicker::GetCurMonth(IFWL_Widget* pWidget) { return m_iCurMonth; } int32_t IFWL_DateTimePicker::GetCurYear(IFWL_Widget* pWidget) { return m_iCurYear; }
29.611354
80
0.683331
isabella232
8d618f3d9bb286ce6ea6d94a5238071ee910f1c1
23,407
cxx
C++
panda/src/display/graphicsWindow.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/display/graphicsWindow.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/display/graphicsWindow.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file graphicsWindow.cxx * @author mike * @date 1997-01-09 */ #include "graphicsWindow.h" #include "graphicsPipe.h" #include "config_display.h" #include "mouseButton.h" #include "keyboardButton.h" #include "lightMutexHolder.h" #include "lightReMutexHolder.h" #include "throw_event.h" #include "string_utils.h" using std::string; TypeHandle GraphicsWindow::_type_handle; /** * Normally, the GraphicsWindow constructor is not called directly; these are * created instead via the GraphicsEngine::make_window() function. */ GraphicsWindow:: GraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, const string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, GraphicsStateGuardian *gsg, GraphicsOutput *host) : GraphicsOutput(engine, pipe, name, fb_prop, win_prop, flags, gsg, host, true), _input_lock("GraphicsWindow::_input_lock"), _properties_lock("GraphicsWindow::_properties_lock") { #ifdef DO_MEMORY_USAGE MemoryUsage::update_type(this, this); #endif if (display_cat.is_debug()) { display_cat.debug() << "Creating new window " << get_name() << "\n"; } _properties.set_open(false); _properties.set_undecorated(false); _properties.set_fullscreen(false); _properties.set_minimized(false); _properties.set_cursor_hidden(false); request_properties(WindowProperties::get_default()); request_properties(win_prop); _window_event = "window-event"; _got_expose_event = false; _unexposed_draw = win_unexposed_draw; set_pixel_zoom(pixel_zoom); } /** * */ GraphicsWindow:: ~GraphicsWindow() { // Clean up python event handlers. #ifdef HAVE_PYTHON PythonWinProcClasses::iterator iter; for (iter = _python_window_proc_classes.begin(); iter != _python_window_proc_classes.end(); ++iter) { delete *iter; } #endif } /** * Returns the current properties of the window. */ const WindowProperties GraphicsWindow:: get_properties() const { WindowProperties result; { LightReMutexHolder holder(_properties_lock); result = _properties; } return result; } /** * Returns the properties of the window that are currently requested. These * properties will be applied to the window (if valid) at the next execution * of process_events(). */ const WindowProperties GraphicsWindow:: get_requested_properties() const { WindowProperties result; { LightReMutexHolder holder(_properties_lock); result = _requested_properties; } return result; } /** * Empties the set of failed properties that will be returned by * get_rejected_properties(). */ void GraphicsWindow:: clear_rejected_properties() { LightReMutexHolder holder(_properties_lock); _rejected_properties.clear(); } /** * Returns the set of properties that have recently been requested, but could * not be applied to the window for some reason. This set of properties will * remain unchanged until they are changed by a new failed request, or * clear_rejected_properties() is called. */ WindowProperties GraphicsWindow:: get_rejected_properties() const { WindowProperties result; { LightReMutexHolder holder(_properties_lock); result = _rejected_properties; } return result; } /** * Requests a property change on the window. For example, use this method to * request a window change size or minimize or something. * * The change is not made immediately; rather, the request is saved and will * be applied the next time the window task is run (probably at the next * frame). */ void GraphicsWindow:: request_properties(const WindowProperties &requested_properties) { LightReMutexHolder holder(_properties_lock); _requested_properties.add_properties(requested_properties); if (!_has_size && _requested_properties.has_size()) { // If we just requested a particular size, anticipate that it will stick. // This is helpful for the MultitexReducer, which needs to know the size // of the textures that it will be working with, even if the texture // hasn't been fully generated yet. _size = _requested_properties.get_size(); // Don't set _has_size yet, because we don't really know yet. } } /** * Returns true if the window is ready to be rendered into, false otherwise. */ bool GraphicsWindow:: is_active() const { // Make this smarter? return GraphicsOutput::is_active() && _properties.get_open() && !_properties.get_minimized(); } /** * Changes the name of the event that is generated when this window is * modified externally, e.g. to be resized or closed by the user. * * By default, all windows have the same window event unless they are * explicitly changed. When the event is generated, it includes one * parameter: the window itself. */ void GraphicsWindow:: set_window_event(const string &window_event) { LightReMutexHolder holder(_properties_lock); _window_event = window_event; } /** * Returns the name of the event that is generated when this window is * modified externally, e.g. to be resized or closed by the user. See * set_window_event(). */ string GraphicsWindow:: get_window_event() const { string result; LightReMutexHolder holder(_properties_lock); result = _window_event; return result; } /** * Sets the event that is triggered when the user requests to close the * window, e.g. via alt-F4, or clicking on the close box. * * The default for each window is for this event to be the empty string, which * means the window-close request is handled immediately by Panda (and the * window will be closed without the app getting a chance to intervene). If * you set this to a nonempty string, then the window is not closed, but * instead the event is thrown. It is then up to the app to respond * appropriately, for instance by presenting an "are you sure?" dialog box, * and eventually calling close_window() when the user is sure. * * It is considered poor form to set this string and then not handle the * event. This can frustrate the user by making it difficult for him to * cleanly shut down the application (and may force the user to hard-kill the * app, or reboot the machine). */ void GraphicsWindow:: set_close_request_event(const string &close_request_event) { LightReMutexHolder holder(_properties_lock); _close_request_event = close_request_event; } /** * Returns the name of the event set via set_close_request_event(). If this * string is nonempty, then when the user requests to close window, this event * will be generated instead. See set_close_request_event(). */ string GraphicsWindow:: get_close_request_event() const { string result; LightReMutexHolder holder(_properties_lock); result = _close_request_event; return result; } /** * Returns the number of separate input devices associated with the window. * Typically, a window will have exactly one input device: the keyboard/mouse * pair. However, some windows may have no input devices, and others may add * additional devices, for instance for a joystick. */ int GraphicsWindow:: get_num_input_devices() const { int result; { LightMutexHolder holder(_input_lock); result = _input_devices.size(); } return result; } /** * Returns the name of the nth input device. */ string GraphicsWindow:: get_input_device_name(int device) const { string result; { LightMutexHolder holder(_input_lock); nassertr(device >= 0 && device < (int)_input_devices.size(), ""); result = _input_devices[device].get_name(); } return result; } /** * Returns true if the nth input device has a screen-space pointer (for * instance, a mouse), false otherwise. */ bool GraphicsWindow:: has_pointer(int device) const { bool result; { LightMutexHolder holder(_input_lock); nassertr(device >= 0 && device < (int)_input_devices.size(), false); result = _input_devices[device].has_pointer(); } return result; } /** * Returns true if the nth input device has a keyboard, false otherwise. */ bool GraphicsWindow:: has_keyboard(int device) const { bool result; { LightMutexHolder holder(_input_lock); nassertr(device >= 0 && device < (int)_input_devices.size(), false); result = _input_devices[device].has_keyboard(); } return result; } /** * Returns a ButtonMap containing the association between raw buttons and * virtual buttons. */ ButtonMap *GraphicsWindow:: get_keyboard_map() const { return nullptr; } /** * Turn on the generation of pointer events. */ void GraphicsWindow:: enable_pointer_events(int device) { LightMutexHolder holder(_input_lock); nassertv(device >= 0 && device < (int)_input_devices.size()); _input_devices[device].enable_pointer_events(); } /** * Turn off the generation of pointer events. */ void GraphicsWindow:: disable_pointer_events(int device) { LightMutexHolder holder(_input_lock); nassertv(device >= 0 && device < (int)_input_devices.size()); _input_devices[device].disable_pointer_events(); } /** * See GraphicsWindowInputDevice::enable_pointer_mode */ void GraphicsWindow:: enable_pointer_mode(int device, double speed) { LightMutexHolder holder(_input_lock); nassertv(device >= 0 && device < (int)_input_devices.size()); _input_devices[device].enable_pointer_mode(speed); } /** * See GraphicsWindowInputDevice::disable_pointer_mode */ void GraphicsWindow:: disable_pointer_mode(int device) { LightMutexHolder holder(_input_lock); nassertv(device >= 0 && device < (int)_input_devices.size()); _input_devices[device].disable_pointer_mode(); } /** * Returns the MouseData associated with the nth input device's pointer. This * is deprecated; use get_pointer_device().get_pointer() instead, or for raw * mice, use the InputDeviceManager interface. */ MouseData GraphicsWindow:: get_pointer(int device) const { MouseData result; { LightMutexHolder holder(_input_lock); nassertr(device >= 0 && device < (int)_input_devices.size(), MouseData()); result = _input_devices[device].get_pointer(); } return result; } /** * Forces the pointer to the indicated position within the window, if * possible. * * Returns true if successful, false on failure. This may fail if the mouse * is not currently within the window, or if the API doesn't support this * operation. */ bool GraphicsWindow:: move_pointer(int, int, int) { return false; } /** * Forces the ime window to close if any * */ void GraphicsWindow:: close_ime() { return; } /** * Returns true if the indicated device has a pending button event (a mouse * button or keyboard button down/up), false otherwise. If this returns true, * the particular event may be extracted via get_button_event(). */ bool GraphicsWindow:: has_button_event(int device) const { bool result; { LightMutexHolder holder(_input_lock); nassertr(device >= 0 && device < (int)_input_devices.size(), false); result = _input_devices[device].has_button_event(); } return result; } /** * Assuming a previous call to has_button_event() returned true, this returns * the pending button event. */ ButtonEvent GraphicsWindow:: get_button_event(int device) { ButtonEvent result; { LightMutexHolder holder(_input_lock); nassertr(device >= 0 && device < (int)_input_devices.size(), ButtonEvent()); nassertr(_input_devices[device].has_button_event(), ButtonEvent()); result = _input_devices[device].get_button_event(); } return result; } /** * Returns true if the indicated device has a pending pointer event (a mouse * movement). If this returns true, the particular event may be extracted via * get_pointer_events(). */ bool GraphicsWindow:: has_pointer_event(int device) const { bool result; { LightMutexHolder holder(_input_lock); nassertr(device >= 0 && device < (int)_input_devices.size(), false); result = _input_devices[device].has_pointer_event(); } return result; } /** * Assuming a previous call to has_pointer_event() returned true, this returns * the pending pointer event list. */ PT(PointerEventList) GraphicsWindow:: get_pointer_events(int device) { PT(PointerEventList) result; { LightMutexHolder holder(_input_lock); nassertr(device >= 0 && device < (int)_input_devices.size(), nullptr); nassertr(_input_devices[device].has_pointer_event(), nullptr); result = _input_devices[device].get_pointer_events(); } return result; } /** * Determines which of the indicated window sizes are supported by available * hardware (e.g. in fullscreen mode). * * On entry, dimen is an array containing contiguous x,y pairs specifying * possible display sizes; it is numsizes*2 words long. The function will * zero out any invalid x,y size pairs. The return value is the number of * valid sizes that were found. * * Note this doesn't guarantee a resize attempt will work; you still need to * check the return value. * * (It might be better to implement some sort of query interface that returns * an array of supported sizes, but this way is somewhat simpler and will do * the job on most cards, assuming they handle the std sizes the app knows * about.) */ int GraphicsWindow:: verify_window_sizes(int numsizes, int *dimen) { return numsizes; } /** * This is called by the GraphicsEngine to request that the window (or * whatever) open itself or, in general, make itself valid, at the next call * to process_events(). */ void GraphicsWindow:: request_open() { WindowProperties open_properties; open_properties.set_open(true); request_properties(open_properties); } /** * This is called by the GraphicsEngine to request that the window (or * whatever) close itself or, in general, make itself invalid, at the next * call to process_events(). By that time we promise the gsg pointer will be * cleared. */ void GraphicsWindow:: request_close() { WindowProperties close_properties; close_properties.set_open(false); request_properties(close_properties); } /** * This is called by the GraphicsEngine to insist that the window be closed * immediately. This is only called from the window thread. */ void GraphicsWindow:: set_close_now() { WindowProperties close_properties; close_properties.set_open(false); set_properties_now(close_properties); } /** * Do whatever processing is necessary to ensure that the window responds to * user events. Also, honor any requests recently made via * request_properties(). * * This function is called only within the window thread. */ void GraphicsWindow:: process_events() { if (_requested_properties.is_any_specified()) { // We don't bother to grab the mutex until after we have already checked // whether any properties have been specified. This is technically // sloppy, but it ought to be o.k. since it's just a bitmask after all. WindowProperties properties; { LightReMutexHolder holder(_properties_lock); properties = _requested_properties; _requested_properties.clear(); set_properties_now(properties); if (properties.is_any_specified()) { display_cat.info() << "Unable to set window properties: " << properties << "\n"; _rejected_properties.add_properties(properties); } } } } /** * Applies the requested set of properties to the window, if possible, for * instance to request a change in size or minimization status. * * The window properties are applied immediately, rather than waiting until * the next frame. This implies that this method may *only* be called from * within the window thread. * * The properties that have been applied are cleared from the structure by * this function; so on return, whatever remains in the properties structure * are those that were unchanged for some reason (probably because the * underlying interface does not support changing that property on an open * window). */ void GraphicsWindow:: set_properties_now(WindowProperties &properties) { if (properties.has_open() && properties.get_open() != _properties.get_open()) { // Open or close a new window. In this case we can get all of the // properties at once. _properties.add_properties(properties); properties.clear(); if (_properties.get_open()) { if (open_window()) { // When the window is first opened, force its size to be broadcast to // its display regions. _is_valid = true; set_size_and_recalc(_properties.get_x_size(), _properties.get_y_size()); } else { // Since we can't even open the window, tag the _rejected_properties // with all of the window properties that failed. _rejected_properties.add_properties(_properties); // And mark the window closed. _properties.set_open(false); _is_valid = false; } } else { // We used to resist closing a window before its GSG has been released. // Now it seems we never release a GSG, so go ahead and close the // window. close_window(); _is_valid = false; } return; } if (!_properties.get_open()) { // The window is not currently open; we can set properties at will. _properties.add_properties(properties); properties.clear(); return; } properties.clear_open(); // The window is already open; we are limited to what we can change on the // fly. if (properties.has_size() || properties.has_origin()) { // Consider changing the window's size andor position. WindowProperties reshape_props; if (properties.has_size()) { reshape_props.set_size(properties.get_x_size(), properties.get_y_size()); } else { reshape_props.set_size(_properties.get_x_size(), _properties.get_y_size()); } if (properties.has_origin() && !is_fullscreen()) { reshape_props.set_origin(properties.get_x_origin(), properties.get_y_origin()); } else if (_properties.has_origin()) { reshape_props.set_origin(_properties.get_x_origin(), _properties.get_y_origin()); } bool has_origin = reshape_props.has_origin(); int x_origin = 0, y_origin = 0; if (has_origin) { x_origin = reshape_props.get_x_origin(); y_origin = reshape_props.get_y_origin(); } if (reshape_props.get_x_size() != _properties.get_x_size() || reshape_props.get_y_size() != _properties.get_y_size() || (has_origin && (x_origin != _properties.get_x_origin() || y_origin != _properties.get_y_origin()))) { if (do_reshape_request(x_origin, y_origin, has_origin, reshape_props.get_x_size(), reshape_props.get_y_size())) { properties.clear_size(); properties.clear_origin(); } } else { properties.clear_size(); properties.clear_origin(); } } if (properties.has_fullscreen() && properties.get_fullscreen() == _properties.get_fullscreen()) { // Fullscreen property specified, but unchanged. properties.clear_fullscreen(); } if (properties.has_mouse_mode() && properties.get_mouse_mode() == _properties.get_mouse_mode()) { // Mouse mode specified, but unchanged. properties.clear_mouse_mode(); } } /** * Closes the window right now. Called from the window thread. */ void GraphicsWindow:: close_window() { display_cat.info() << "Closing " << get_type() << "\n"; // Tell our parent window (if any) that we're no longer its child. if (_window_handle != nullptr && _parent_window_handle != nullptr) { _parent_window_handle->detach_child(_window_handle); } _window_handle = nullptr; _parent_window_handle = nullptr; _is_valid = false; } /** * Opens the window right now. Called from the window thread. Returns true * if the window is successfully opened, or false if there was a problem. */ bool GraphicsWindow:: open_window() { return false; } /** * resets the window framebuffer from its derived children. Does nothing * here. */ void GraphicsWindow:: reset_window(bool swapchain) { display_cat.info() << "Resetting " << get_type() << "\n"; } /** * Called from the window thread in response to a request from within the code * (via request_properties()) to change the size and/or position of the * window. Returns true if the window is successfully changed, or false if * there was a problem. */ bool GraphicsWindow:: do_reshape_request(int x_origin, int y_origin, bool has_origin, int x_size, int y_size) { return false; } /** * Should be called (from within the window thread) when process_events() * detects an external change in some important window property; for instance, * when the user resizes the window. */ void GraphicsWindow:: system_changed_properties(const WindowProperties &properties) { if (display_cat.is_debug()) { display_cat.debug() << "system_changed_properties(" << properties << ")\n"; } LightReMutexHolder holder(_properties_lock); if (properties.has_size()) { system_changed_size(properties.get_x_size(), properties.get_y_size()); } WindowProperties old_properties = _properties; _properties.add_properties(properties); if (_properties != old_properties) { throw_event(_window_event, this); } } /** * An internal function to update all the DisplayRegions with the new size of * the window. This should always be called before changing the _size members * of the _properties structure. */ void GraphicsWindow:: system_changed_size(int x_size, int y_size) { if (display_cat.is_debug()) { display_cat.debug() << "system_changed_size(" << x_size << ", " << y_size << ")\n"; } if (!_properties.has_size() || (x_size != _properties.get_x_size() || y_size != _properties.get_y_size())) { set_size_and_recalc(x_size, y_size); } } /** * Adds a GraphicsWindowInputDevice to the vector. Returns the index of the * new device. */ int GraphicsWindow:: add_input_device(const GraphicsWindowInputDevice &device) { LightMutexHolder holder(_input_lock); int index = (int)_input_devices.size(); _input_devices.push_back(device); _input_devices.back().set_device_index(index); return index; } /** * detaches mouse. Only mouse delta from now on. * */ void GraphicsWindow:: mouse_mode_relative() { } /** * reattaches mouse to location * */ void GraphicsWindow:: mouse_mode_absolute() { } /** * Returns whether the specified event msg is a touch message. * */ bool GraphicsWindow:: is_touch_event(GraphicsWindowProcCallbackData* callbackData){ return false; } /** * Returns the current number of touches on this window. * */ int GraphicsWindow:: get_num_touches(){ return 0; } /** * Returns the TouchInfo object describing the specified touch. * */ TouchInfo GraphicsWindow:: get_touch_info(int index){ return TouchInfo(); } /** * Returns whether this window supports adding of Windows proc handlers. * */ bool GraphicsWindow::supports_window_procs() const{ return false; }
29.222222
95
0.714487
cmarshall108
8d6310fd33b694d7de753c98720e6f3ad6f039a6
10,705
cc
C++
extensions/browser/guest_view/app_view/app_view_guest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
extensions/browser/guest_view/app_view/app_view_guest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
extensions/browser/guest_view/app_view/app_view_guest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/guest_view/app_view/app_view_guest.h" #include <utility> #include "base/bind.h" #include "base/command_line.h" #include "base/lazy_instance.h" #include "components/guest_view/browser/guest_view_manager.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/api/app_runtime/app_runtime_api.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/app_window/app_delegate.h" #include "extensions/browser/bad_message.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/guest_view/app_view/app_view_constants.h" #include "extensions/browser/lazy_context_id.h" #include "extensions/browser/lazy_context_task_queue.h" #include "extensions/browser/process_manager.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/api/app_runtime.h" #include "extensions/common/extension_messages.h" #include "extensions/strings/grit/extensions_strings.h" #include "ipc/ipc_message_macros.h" namespace app_runtime = extensions::api::app_runtime; using content::RenderFrameHost; using content::WebContents; using extensions::ExtensionHost; using guest_view::GuestViewBase; namespace extensions { namespace { struct ResponseInfo { scoped_refptr<const Extension> guest_extension; base::WeakPtr<AppViewGuest> app_view_guest; GuestViewBase::WebContentsCreatedCallback callback; ResponseInfo(const Extension* guest_extension, const base::WeakPtr<AppViewGuest>& app_view_guest, GuestViewBase::WebContentsCreatedCallback callback) : guest_extension(guest_extension), app_view_guest(app_view_guest), callback(std::move(callback)) {} ~ResponseInfo() {} }; using PendingResponseMap = std::map<int, std::unique_ptr<ResponseInfo>>; base::LazyInstance<PendingResponseMap>::DestructorAtExit g_pending_response_map = LAZY_INSTANCE_INITIALIZER; } // namespace // static. const char AppViewGuest::Type[] = "appview"; // static. bool AppViewGuest::CompletePendingRequest( content::BrowserContext* browser_context, const GURL& url, int guest_instance_id, const std::string& guest_extension_id, content::RenderProcessHost* guest_render_process_host) { PendingResponseMap* response_map = g_pending_response_map.Pointer(); auto it = response_map->find(guest_instance_id); // Kill the requesting process if it is not the real guest. if (it == response_map->end()) { // The requester used an invalid |guest_instance_id|. bad_message::ReceivedBadMessage(guest_render_process_host, bad_message::AVG_BAD_INST_ID); return false; } ResponseInfo* response_info = it->second.get(); if (!response_info->app_view_guest || (response_info->guest_extension->id() != guest_extension_id)) { // The app is trying to communicate with an <appview> not assigned to it, or // the <appview> is already dead "nullptr". bad_message::BadMessageReason reason = !response_info->app_view_guest ? bad_message::AVG_NULL_AVG : bad_message::AVG_BAD_EXT_ID; bad_message::ReceivedBadMessage(guest_render_process_host, reason); return false; } response_info->app_view_guest->CompleteCreateWebContents( url, response_info->guest_extension.get(), std::move(response_info->callback)); response_map->erase(guest_instance_id); return true; } // static GuestViewBase* AppViewGuest::Create(WebContents* owner_web_contents) { return new AppViewGuest(owner_web_contents); } AppViewGuest::AppViewGuest(WebContents* owner_web_contents) : GuestView<AppViewGuest>(owner_web_contents), app_view_guest_delegate_( ExtensionsAPIClient::Get()->CreateAppViewGuestDelegate()) { if (app_view_guest_delegate_) { app_delegate_.reset( app_view_guest_delegate_->CreateAppDelegate(owner_web_contents)); } } AppViewGuest::~AppViewGuest() { } bool AppViewGuest::HandleContextMenu( content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params) { if (app_view_guest_delegate_) { return app_view_guest_delegate_->HandleContextMenu(web_contents(), params); } return false; } void AppViewGuest::RequestMediaAccessPermission( WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { if (!app_delegate_) { WebContentsDelegate::RequestMediaAccessPermission(web_contents, request, std::move(callback)); return; } const ExtensionSet& enabled_extensions = ExtensionRegistry::Get(browser_context())->enabled_extensions(); const Extension* guest_extension = enabled_extensions.GetByID(guest_extension_id_); app_delegate_->RequestMediaAccessPermission( web_contents, request, std::move(callback), guest_extension); } bool AppViewGuest::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { if (!app_delegate_) { return WebContentsDelegate::CheckMediaAccessPermission( render_frame_host, security_origin, type); } const ExtensionSet& enabled_extensions = ExtensionRegistry::Get(browser_context())->enabled_extensions(); const Extension* guest_extension = enabled_extensions.GetByID(guest_extension_id_); return app_delegate_->CheckMediaAccessPermission( render_frame_host, security_origin, type, guest_extension); } void AppViewGuest::CreateWebContents(const base::DictionaryValue& create_params, WebContentsCreatedCallback callback) { std::string app_id; if (!create_params.GetString(appview::kAppID, &app_id)) { std::move(callback).Run(nullptr); return; } // Verifying that the appId is not the same as the host application. if (owner_host() == app_id) { std::move(callback).Run(nullptr); return; } const base::DictionaryValue* data = nullptr; if (!create_params.GetDictionary(appview::kData, &data)) { std::move(callback).Run(nullptr); return; } const ExtensionSet& enabled_extensions = ExtensionRegistry::Get(browser_context())->enabled_extensions(); const Extension* guest_extension = enabled_extensions.GetByID(app_id); const Extension* embedder_extension = enabled_extensions.GetByID(GetOwnerSiteURL().host()); if (!guest_extension || !guest_extension->is_platform_app() || !embedder_extension || !embedder_extension->is_platform_app()) { std::move(callback).Run(nullptr); return; } const LazyContextId context_id(browser_context(), guest_extension->id()); LazyContextTaskQueue* queue = context_id.GetTaskQueue(); if (queue->ShouldEnqueueTask(browser_context(), guest_extension)) { queue->AddPendingTask( context_id, base::BindOnce(&AppViewGuest::LaunchAppAndFireEvent, weak_ptr_factory_.GetWeakPtr(), data->CreateDeepCopy(), std::move(callback))); return; } ProcessManager* process_manager = ProcessManager::Get(browser_context()); ExtensionHost* host = process_manager->GetBackgroundHostForExtension(guest_extension->id()); DCHECK(host); LaunchAppAndFireEvent( data->CreateDeepCopy(), std::move(callback), std::make_unique<LazyContextTaskQueue::ContextInfo>(host)); } void AppViewGuest::DidInitialize(const base::DictionaryValue& create_params) { ExtensionsAPIClient::Get()->AttachWebContentsHelpers(web_contents()); if (!url_.is_valid()) return; web_contents()->GetController().LoadURL( url_, content::Referrer(), ui::PAGE_TRANSITION_LINK, std::string()); } const char* AppViewGuest::GetAPINamespace() const { return appview::kEmbedderAPINamespace; } int AppViewGuest::GetTaskPrefix() const { return IDS_EXTENSION_TASK_MANAGER_APPVIEW_TAG_PREFIX; } void AppViewGuest::CompleteCreateWebContents( const GURL& url, const Extension* guest_extension, WebContentsCreatedCallback callback) { if (!url.is_valid()) { std::move(callback).Run(nullptr); return; } url_ = url; guest_extension_id_ = guest_extension->id(); WebContents::CreateParams params( browser_context(), content::SiteInstance::CreateForURL(browser_context(), guest_extension->url())); params.guest_delegate = this; // TODO(erikchen): Fix ownership semantics for guest views. // https://crbug.com/832879. std::move(callback).Run(WebContents::Create(params).release()); } void AppViewGuest::LaunchAppAndFireEvent( std::unique_ptr<base::DictionaryValue> data, WebContentsCreatedCallback callback, std::unique_ptr<LazyContextTaskQueue::ContextInfo> context_info) { bool has_event_listener = EventRouter::Get(browser_context()) ->ExtensionHasEventListener( context_info->extension_id, app_runtime::OnEmbedRequested::kEventName); if (!has_event_listener) { std::move(callback).Run(nullptr); return; } const Extension* const extension = extensions::ExtensionRegistry::Get(context_info->browser_context) ->enabled_extensions() .GetByID(context_info->extension_id); g_pending_response_map.Get().insert(std::make_pair( guest_instance_id(), std::make_unique<ResponseInfo>(extension, weak_ptr_factory_.GetWeakPtr(), std::move(callback)))); std::unique_ptr<base::DictionaryValue> embed_request( new base::DictionaryValue()); embed_request->SetInteger(appview::kGuestInstanceID, guest_instance_id()); embed_request->SetString(appview::kEmbedderID, owner_host()); embed_request->Set(appview::kData, std::move(data)); AppRuntimeEventRouter::DispatchOnEmbedRequestedEvent( browser_context(), std::move(embed_request), extension); } void AppViewGuest::SetAppDelegateForTest(AppDelegate* delegate) { app_delegate_.reset(delegate); } std::vector<int> AppViewGuest::GetAllRegisteredInstanceIdsForTesting() { std::vector<int> instances; for (const auto& key_value : g_pending_response_map.Get()) { instances.push_back(key_value.first); } return instances; } } // namespace extensions
35.802676
80
0.725642
Ron423c
8d64dc75a23e683306389a96bd8e232ccdb68390
1,179
hpp
C++
src/HTMLElements/HTMLElement.hpp
windlessStorm/WebWhir
0ed261427d4f4e4f81b62816dc0d94bfacd0890b
[ "MIT" ]
90
2017-04-03T21:42:57.000Z
2022-01-22T11:08:56.000Z
src/HTMLElements/HTMLElement.hpp
windlessStorm/WebWhir
0ed261427d4f4e4f81b62816dc0d94bfacd0890b
[ "MIT" ]
21
2017-03-06T21:45:36.000Z
2017-03-06T21:45:37.000Z
src/HTMLElements/HTMLElement.hpp
windlessStorm/WebWhir
0ed261427d4f4e4f81b62816dc0d94bfacd0890b
[ "MIT" ]
17
2017-04-15T22:42:13.000Z
2021-12-20T09:50:15.000Z
#ifndef HTMLELEMENT_H #define HTMLELEMENT_H #include <string> #include <vector> #include <memory> class HTMLElement { public: HTMLElement(); HTMLElement(const HTMLElement &element); virtual ~HTMLElement(); std::wstring get_id() const; std::wstring get_title() const; void set_title(const std::wstring &element_title); void add_child(const std::shared_ptr<HTMLElement> child_node); std::vector<std::shared_ptr<HTMLElement>> get_children() const; void add_text(const std::shared_ptr<HTMLElement> text_node); // Text Node functions virtual bool is_text_node() const { return false; }; virtual void add_char(const wchar_t &next_char) {}; virtual void add_char(const std::wstring &next_char) {}; virtual wchar_t get_char() const { return L'\0'; }; virtual std::wstring get_text() const { return L""; }; // Paragraph Node functions virtual bool is_paragraph_node() const { return false; }; protected: std::wstring id; std::wstring title; std::vector<std::shared_ptr<HTMLElement>> child_nodes; }; #endif
31.026316
71
0.64631
windlessStorm
8d65d0ce0bc4f84d1a9f3a7f41375fea055d62b3
18,694
cpp
C++
src/materialsystem/checkmaterials.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/materialsystem/checkmaterials.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/materialsystem/checkmaterials.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #include "pch_materialsystem.h" // NOTE: currently this file is marked as "exclude from build" //#define _CHECK_MATERIALS_FOR_PROBLEMS 1 #ifdef _CHECK_MATERIALS_FOR_PROBLEMS #include "vtf/vtf.h" #include "tier1/utlbuffer.h" #include "tier1/utlstring.h" void CheckMateralsInDirectoryRecursive( const char *pRoot, const char *pDirectory ); #endif #ifdef _CHECK_MATERIALS_FOR_PROBLEMS //----------------------------------------------------------------------------- // Does a texture have alpha? //----------------------------------------------------------------------------- static bool DoesTextureUseAlpha( const char *pTextureName, const char *pMaterialName ) { if ( IsX360() ) { // not supporting return false; } // Special textures start with '_'.. if ( pTextureName[0] == '_' ) return false; // The texture name doubles as the relative file name // It's assumed to have already been set by this point // Compute the cache name char pCacheFileName[MATERIAL_MAX_PATH]; Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName ); CUtlBuffer buf; FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" ); if ( fileHandle == FILESYSTEM_INVALID_HANDLE) { Warning( "Material \"%s\": can't open texture \"%s\"\n", pMaterialName, pCacheFileName ); return false; } // Check the .vtf for an alpha channel IVTFTexture *pVTFTexture = CreateVTFTexture(); int nHeaderSize = VTFFileHeaderSize( VTF_MAJOR_VERSION ); buf.EnsureCapacity( nHeaderSize ); // read the header first.. it's faster!! g_pFullFileSystem->Read( buf.Base(), nHeaderSize, fileHandle ); buf.SeekPut( CUtlBuffer::SEEK_HEAD, nHeaderSize ); // Unserialize the header bool bUsesAlpha = false; if (!pVTFTexture->Unserialize( buf, true )) { Warning( "Error reading material \"%s\"\n", pCacheFileName ); g_pFullFileSystem->Close(fileHandle); } else { if ( pVTFTexture->Flags() & (TEXTUREFLAGS_ONEBITALPHA | TEXTUREFLAGS_EIGHTBITALPHA) ) { bUsesAlpha = true; } } DestroyVTFTexture( pVTFTexture ); g_pFullFileSystem->Close( fileHandle ); return bUsesAlpha; } //----------------------------------------------------------------------------- // Does a texture have alpha? //----------------------------------------------------------------------------- static bool DoesTextureUseNormal( const char *pTextureName, const char *pMaterialName, bool &bUsesAlpha, bool &bIsCompressed, int &nSizeInBytes ) { nSizeInBytes = 0; bUsesAlpha = false; if ( IsX360() ) { // not supporting return false; } // Special textures start with '_'.. if ( !pTextureName || ( pTextureName[0] == '_' ) || ( pTextureName[0] == 0 ) ) return false; // The texture name doubles as the relative file name // It's assumed to have already been set by this point // Compute the cache name char pCacheFileName[MATERIAL_MAX_PATH]; Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName ); CUtlBuffer buf; FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" ); if ( fileHandle == FILESYSTEM_INVALID_HANDLE) { // Warning( "Material \"%s\": can't open texture \"%s\"\n", pMaterialName, pCacheFileName ); return false; } // Check the .vtf for an alpha channel IVTFTexture *pVTFTexture = CreateVTFTexture(); int nHeaderSize = VTFFileHeaderSize( VTF_MAJOR_VERSION ); buf.EnsureCapacity( nHeaderSize ); // read the header first.. it's faster!! g_pFullFileSystem->Read( buf.Base(), nHeaderSize, fileHandle ); buf.SeekPut( CUtlBuffer::SEEK_HEAD, nHeaderSize ); // Unserialize the header bool bUsesNormal = false; if ( !pVTFTexture->Unserialize( buf, true ) ) { Warning( "Error reading material \"%s\"\n", pCacheFileName ); } else { if ( pVTFTexture->Flags() & TEXTUREFLAGS_NORMAL ) { bUsesAlpha = false; bUsesNormal = true; bIsCompressed = ImageLoader::IsCompressed( pVTFTexture->Format() ) || ( pVTFTexture->Format() == IMAGE_FORMAT_A8 ); nSizeInBytes = pVTFTexture->ComputeTotalSize(); if ( pVTFTexture->Flags() & (TEXTUREFLAGS_ONEBITALPHA | TEXTUREFLAGS_EIGHTBITALPHA) ) { bUsesAlpha = true; } } } DestroyVTFTexture( pVTFTexture ); g_pFullFileSystem->Close( fileHandle ); return bUsesNormal; } //----------------------------------------------------------------------------- // Is this a real texture //----------------------------------------------------------------------------- static bool IsTexture( const char *pTextureName ) { // Special textures start with '_'.. if ( pTextureName[0] == '_' ) return false; // The texture name doubles as the relative file name // It's assumed to have already been set by this point // Compute the cache name char pCacheFileName[MATERIAL_MAX_PATH]; Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName ); FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" ); if ( fileHandle == FILESYSTEM_INVALID_HANDLE) return false; g_pFullFileSystem->Close( fileHandle ); return true; } //----------------------------------------------------------------------------- // Scan material + all subsections for key //----------------------------------------------------------------------------- static float MaterialFloatKeyValue( KeyValues *pKeyValues, const char *pKeyName, float flDefault ) { float flValue = pKeyValues->GetFloat( pKeyName, flDefault ); if ( flValue != flDefault ) return flValue; for( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() ) { float flValue = MaterialFloatKeyValue( pSubKey, pKeyName, flDefault ); if ( flValue != flDefault ) return flValue; } return flDefault; } int ParseVectorFromKeyValueString( KeyValues *pKeyValue, const char *pMaterialName, float vecVal[4] ); static bool AsVectorsEqual( int nDim1, float *pVector1, int nDim2, float *pVector2 ) { if ( nDim1 != nDim2 ) return false; for ( int i = 0; i < nDim1; ++i ) { if ( fabs( pVector1[i] - pVector2[i] ) > 1e-3 ) return false; } return true; } static bool MaterialVectorKeyValue( KeyValues *pKeyValues, const char *pKeyName, int nDefaultDim, float *pDefault, int *pDim, float *pVector ) { int nDim; float retVal[4]; KeyValues *pValue = pKeyValues->FindKey( pKeyName ); if ( pValue ) { switch( pValue->GetDataType() ) { case KeyValues::TYPE_INT: { int nInt = pValue->GetInt(); for ( int i = 0; i < 4; ++i ) { retVal[i] = nInt; } if ( !AsVectorsEqual( nDefaultDim, pDefault, nDefaultDim, retVal ) ) { *pDim = nDefaultDim; memcpy( pVector, retVal, nDefaultDim * sizeof(float) ); return true; } } break; case KeyValues::TYPE_FLOAT: { float flFloat = pValue->GetFloat(); for ( int i = 0; i < 4; ++i ) { retVal[i] = flFloat; } if ( !AsVectorsEqual( nDefaultDim, pDefault, nDefaultDim, retVal ) ) { *pDim = nDefaultDim; memcpy( pVector, retVal, nDefaultDim * sizeof(float) ); return true; } } break; case KeyValues::TYPE_STRING: { nDim = ParseVectorFromKeyValueString( pValue, "", retVal ); if ( !AsVectorsEqual( nDefaultDim, pDefault, nDim, retVal ) ) { *pDim = nDim; memcpy( pVector, retVal, nDim * sizeof(float) ); return true; } } break; } } for( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() ) { if ( MaterialVectorKeyValue( pSubKey, pKeyName, nDefaultDim, pDefault, &nDim, retVal ) ) { *pDim = nDim; memcpy( pVector, retVal, nDim * sizeof(float) ); return true; } } *pDim = nDefaultDim; memcpy( pVector, pDefault, nDefaultDim * sizeof(float) ); return false; } //----------------------------------------------------------------------------- // Scan material + all subsections for key //----------------------------------------------------------------------------- static bool DoesMaterialHaveKey( KeyValues *pKeyValues, const char *pKeyName ) { if ( pKeyValues->GetString( pKeyName, NULL ) != NULL ) return true; for( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() ) { if ( DoesMaterialHaveKey( pSubKey, pKeyName ) ) return true; } return false; } //----------------------------------------------------------------------------- // Scan all materials for errors //----------------------------------------------------------------------------- static int s_nNormalBytes; static int s_nNormalCompressedBytes; static int s_nNormalPalettizedBytes; static int s_nNormalWithAlphaBytes; static int s_nNormalWithAlphaCompressedBytes; struct VTFInfo_t { CUtlString m_VTFName; bool m_bFoundInVMT; }; void CheckKeyValues( KeyValues *pKeyValues, CUtlVector<VTFInfo_t> &vtf ) { for ( KeyValues *pSubKey = pKeyValues->GetFirstValue(); pSubKey; pSubKey = pSubKey->GetNextValue() ) { if ( pSubKey->GetDataType() != KeyValues::TYPE_STRING ) continue; if ( IsTexture( pSubKey->GetString() ) ) { int nLen = Q_strlen( pSubKey->GetString() ) + 1; char *pTemp = (char*)_alloca( nLen ); memcpy( pTemp, pSubKey->GetString(), nLen ); Q_FixSlashes( pTemp ); int nCount = vtf.Count(); for ( int i = 0; i < nCount; ++i ) { if ( Q_stricmp( vtf[i].m_VTFName, pTemp ) ) continue; vtf[i].m_bFoundInVMT = true; break; } } } for ( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() ) { CheckKeyValues( pSubKey, vtf ); } } void CheckMaterial( KeyValues *pKeyValues, const char *pRoot, const char *pFileName, CUtlVector<VTFInfo_t> &vtf ) { const char *pShaderName = pKeyValues->GetName(); /* if ( Q_stristr( pShaderName, "Water" ) || Q_stristr( pShaderName, "Eyeball" ) || Q_stristr( pShaderName, "Shadow" ) || Q_stristr( pShaderName, "Refract" ) || Q_stristr( pShaderName, "Predator" ) || Q_stristr( pShaderName, "ParticleSphere" ) || Q_stristr( pShaderName, "DebugLuxels" ) || Q_stristr( pShaderName, "GooInGlass" ) || Q_stristr( pShaderName, "Modulate" ) || Q_stristr( pShaderName, "UnlitTwoTexture" ) || Q_stristr( pShaderName, "Cloud" ) || Q_stristr( pShaderName, "WorldVertexTransition" ) || Q_stristr( pShaderName, "DecalModulate" ) || Q_stristr( pShaderName, "DecalBaseTimesLightmapAlphaBlendSelfIllum" ) || Q_stristr( pShaderName, "Sprite" ) ) { return; } // Check for alpha channels const char *pBaseTextureName = pKeyValues->GetString( "$basetexture", NULL ); if ( pBaseTextureName != NULL ) { if ( DoesTextureUseAlpha( pBaseTextureName, pFileName ) ) { float flAlpha = MaterialFloatKeyValue( pKeyValues, "$alpha", 1.0f ); bool bHasVertexAlpha = DoesMaterialHaveKey( pKeyValues, "$vertexalpha" ); // Modulation always happens here whether we want it to or not bool bHasAlphaTest = DoesMaterialHaveKey( pKeyValues, "$alphatest" ); bool bHasTranslucent = DoesMaterialHaveKey( pKeyValues, "$translucent" ); bool bHasSelfIllum = DoesMaterialHaveKey( pKeyValues, "$selfillum" ); bool bHasBaseAlphaEnvMapMask = DoesMaterialHaveKey( pKeyValues, "$basealphaenvmapmask" ); if ( (flAlpha == 1.0f) && !bHasVertexAlpha && !bHasAlphaTest && !bHasTranslucent && !bHasSelfIllum && !bHasBaseAlphaEnvMapMask ) { Warning("Material \"%s\": BASETEXTURE \"%s\"\n", pFileName, pBaseTextureName ); } } } */ /* // Check for bump, spec, and no normalmapalphaenvmapmask const char *pBumpmapName = pKeyValues->GetString( "$bumpmap", NULL ); if ( pBumpmapName != NULL ) { if ( DoesTextureUseAlpha( pBumpmapName, pFileName ) ) { bool bHasEnvmap = DoesMaterialHaveKey( pKeyValues, "$envmap" ); bool bHasNormalMapAlphaEnvMapMask = DoesMaterialHaveKey( pKeyValues, "$normalmapalphaenvmapmask" ); if ( !bHasEnvmap || !bHasNormalMapAlphaEnvMapMask ) { Warning("Material \"%s\": BUMPMAP \"%s\"\n", pFileName, pBumpmapName ); } } } */ /* if ( !Q_stristr( pShaderName, "LightmappedGeneric" ) && !Q_stristr( pShaderName, "VertexLitGeneric" ) ) { return; } if ( DoesMaterialHaveKey( pKeyValues, "$envmap" ) && DoesMaterialHaveKey( pKeyValues, "$bumpmap" ) ) { int nDim; float retVal[4]; float defaultVal[4] = { 1, 1, 1, 1 }; if ( MaterialVectorKeyValue( pKeyValues, "$envmaptint", 3, defaultVal, &nDim, retVal ) ) { Warning("ENVMAP + ENVMAPTINT : Material \"%s\"\n", pFileName ); } // else // { // Warning("ENVMAP only: Material \"%s\"\n", pFileName ); // } } */ /* if ( !Q_stristr( pShaderName, "Refract" ) ) { return; } if ( !DoesMaterialHaveKey( pKeyValues, "$envmap" ) ) { bool bUsesAlpha, bIsCompressed, bIsPalettized; int nSizeInBytes; if ( DoesTextureUseNormal( pKeyValues->GetString( "$normalmap" ), pFileName, bUsesAlpha, bIsCompressed, bIsPalettized, nSizeInBytes ) ) { if ( bIsCompressed ) { Warning("Bad : Material compressed \"%s\"\n", pFileName ); } else { Warning("Bad : Material \"%s\"\n", pFileName ); } } } */ /* if ( !Q_stristr( pShaderName, "WorldTwoTextureBlend" ) ) { return; } if ( DoesMaterialHaveKey( pKeyValues, "$envmap" ) || DoesMaterialHaveKey( pKeyValues, "$parallaxmap" ) || DoesMaterialHaveKey( pKeyValues, "$bumpmap" ) || DoesMaterialHaveKey( pKeyValues, "$vertexcolor" ) || DoesMaterialHaveKey( pKeyValues, "$basetexture2" ) ) { Warning("Bad : Material \"%s\"\n", pFileName ); } */ for ( KeyValues *pSubKey = pKeyValues->GetFirstValue(); pSubKey; pSubKey = pSubKey->GetNextValue() ) { // Msg( " Checking %s\n", pSubKey->GetString() ); if ( pSubKey->GetDataType() != KeyValues::TYPE_STRING ) continue; bool bUsesAlpha, bIsCompressed; int nSizeInBytes; if ( DoesTextureUseNormal( pSubKey->GetString(), pFileName, bUsesAlpha, bIsCompressed, nSizeInBytes ) ) { if ( bUsesAlpha ) { if ( bIsCompressed ) { s_nNormalWithAlphaCompressedBytes += nSizeInBytes; } else { s_nNormalWithAlphaBytes += nSizeInBytes; Msg( "Normal texture w alpha uncompressed %s\n", pSubKey->GetString() ); } } else { if ( bIsCompressed ) { s_nNormalCompressedBytes += nSizeInBytes; } else { s_nNormalBytes += nSizeInBytes; } } } } /* if ( !Q_stristr( pShaderName, "VertexLitGeneric" ) ) return; if ( !DoesMaterialHaveKey( pKeyValues, "$envmap" ) && DoesMaterialHaveKey( pKeyValues, "$bumpmap" ) ) { Warning("BUMPMAP + no ENVMAP : Material \"%s\"\n", pFileName ); } */ // CheckKeyValues( pKeyValues, vtf ); } //----------------------------------------------------------------------------- // Build list of all VTFs //----------------------------------------------------------------------------- void CheckVTFInDirectoryRecursive( const char *pRoot, const char *pDirectory, CUtlVector< VTFInfo_t > &vtf ) { #define BUF_SIZE 1024 char buf[BUF_SIZE]; WIN32_FIND_DATA wfd; HANDLE findHandle; sprintf( buf, "%s/%s/*.vtf", pRoot, pDirectory ); findHandle = FindFirstFile( buf, &wfd ); if ( findHandle != INVALID_HANDLE_VALUE ) { do { int i = vtf.AddToTail( ); char buf[MAX_PATH]; char buf2[MAX_PATH]; Q_snprintf( buf, MAX_PATH, "%s/%s", pDirectory, wfd.cFileName ); Q_FixSlashes( buf ); Q_StripExtension( buf, buf2, sizeof(buf2) ); Assert( !Q_strnicmp( buf2, "materials\\", 10 ) ); vtf[i].m_VTFName = &buf2[10]; vtf[i].m_bFoundInVMT = false; } while ( FindNextFile ( findHandle, &wfd ) ); FindClose ( findHandle ); } // do subdirectories sprintf( buf, "%s/%s/*.*", pRoot, pDirectory ); findHandle = FindFirstFile( buf, &wfd ); if ( findHandle != INVALID_HANDLE_VALUE ) { do { if( wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { if( ( strcmp( wfd.cFileName, ".." ) == 0 ) || ( strcmp( wfd.cFileName, "." ) == 0 ) ) { continue; } char buf[MAX_PATH]; Q_snprintf( buf, MAX_PATH, "%s/%s", pDirectory, wfd.cFileName ); CheckVTFInDirectoryRecursive( pRoot, buf, vtf ); } } while ( FindNextFile ( findHandle, &wfd ) ); FindClose ( findHandle ); } #undef BUF_SIZE } //----------------------------------------------------------------------------- // Scan all materials for errors //----------------------------------------------------------------------------- void _CheckMateralsInDirectoryRecursive( const char *pRoot, const char *pDirectory, CUtlVector< VTFInfo_t > &vtf ) { #define BUF_SIZE 1024 char buf[BUF_SIZE]; WIN32_FIND_DATA wfd; HANDLE findHandle; sprintf( buf, "%s/%s/*.vmt", pRoot, pDirectory ); findHandle = FindFirstFile( buf, &wfd ); if ( findHandle != INVALID_HANDLE_VALUE ) { do { KeyValues * vmtKeyValues = new KeyValues("vmt"); char pFileName[MAX_PATH]; Q_snprintf( pFileName, sizeof( pFileName ), "%s/%s", pDirectory, wfd.cFileName ); if ( !vmtKeyValues->LoadFromFile( g_pFullFileSystem, pFileName, "GAME" ) ) { Warning( "CheckMateralsInDirectoryRecursive: can't open \"%s\"\n", pFileName ); continue; } CheckMaterial( vmtKeyValues, pRoot, pFileName, vtf ); vmtKeyValues->deleteThis(); } while ( FindNextFile ( findHandle, &wfd ) ); FindClose ( findHandle ); } // do subdirectories sprintf( buf, "%s/%s/*.*", pRoot, pDirectory ); findHandle = FindFirstFile( buf, &wfd ); if ( findHandle != INVALID_HANDLE_VALUE ) { do { if( wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { if( ( strcmp( wfd.cFileName, ".." ) == 0 ) || ( strcmp( wfd.cFileName, "." ) == 0 ) ) { continue; } char buf[MAX_PATH]; Q_snprintf( buf, MAX_PATH, "%s/%s", pDirectory, wfd.cFileName ); _CheckMateralsInDirectoryRecursive( pRoot, buf, vtf ); } } while ( FindNextFile ( findHandle, &wfd ) ); FindClose ( findHandle ); } // Msg( "Normal only %d/%d/%d Normal w alpha %d/%d\n", s_nNormalBytes, s_nNormalPalettizedBytes, s_nNormalCompressedBytes, s_nNormalWithAlphaBytes, s_nNormalWithAlphaCompressedBytes ); #undef BUF_SIZE } void CheckMateralsInDirectoryRecursive( const char *pRoot, const char *pDirectory ) { CUtlVector< VTFInfo_t > vtfNames; // CheckVTFInDirectoryRecursive( pRoot, pDirectory, vtfNames ); _CheckMateralsInDirectoryRecursive( pRoot, pDirectory, vtfNames ); /* int nCount = vtfNames.Count(); for ( int i = 0; i < nCount; ++i ) { if ( !vtfNames[i].m_bFoundInVMT ) { Msg( "Unused VTF %s\n", vtfNames[i].m_VTFName ); } } */ } #endif // _CHECK_MATERIALS_FOR_PROBLEMS
28.111278
184
0.626993
cstom4994
8d66d37fee5dcf53c2a2864894cf5d9dc2201831
4,844
cc
C++
tests/whitebox/db/wb_redis_db.cc
rohitjoshi/waflz
220945e6472762af8d8d7e0849699adcfd488605
[ "Apache-2.0" ]
null
null
null
tests/whitebox/db/wb_redis_db.cc
rohitjoshi/waflz
220945e6472762af8d8d7e0849699adcfd488605
[ "Apache-2.0" ]
null
null
null
tests/whitebox/db/wb_redis_db.cc
rohitjoshi/waflz
220945e6472762af8d8d7e0849699adcfd488605
[ "Apache-2.0" ]
null
null
null
//: ---------------------------------------------------------------------------- //: Copyright (C) 2016 Verizon. All Rights Reserved. //: All Rights Reserved //: //: \file: TODO.cc //: \details: TODO //: \author: Reed P. Morrison //: \date: 12/06/2016 //: //: Licensed under the Apache License, Version 2.0 (the "License"); //: you may not use this file except in compliance with the License. //: You may obtain a copy of the License at //: //: http://www.apache.org/licenses/LICENSE-2.0 //: //: Unless required by applicable law or agreed to in writing, software //: distributed under the License is distributed on an "AS IS" BASIS, //: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //: See the License for the specific language governing permissions and //: limitations under the License. //: //: ---------------------------------------------------------------------------- //: ---------------------------------------------------------------------------- //: includes //: ---------------------------------------------------------------------------- #include "catch/catch.hpp" #include "waflz/def.h" #include "waflz/db/redis_db.h" #include "support/time_util.h" #include "support/ndebug.h" #include <unistd.h> #include <string.h> //: ---------------------------------------------------------------------------- //: constants //: ---------------------------------------------------------------------------- #define MONKEY_KEY "TEST::KEY::MONKEY::BONGO" #define BANANA_KEY "TEST::KEY::BANANA::SMELLY" //: ---------------------------------------------------------------------------- //: kycb_db //: ---------------------------------------------------------------------------- TEST_CASE( "redis db test", "[redis]" ) { SECTION("validate bad init") { ns_waflz::redis_db l_db; REQUIRE((l_db.get_init() == false)); const char l_bad_host[] = "128.0.0.1"; int32_t l_s; l_s = l_db.set_opt(ns_waflz::redis_db::OPT_REDIS_HOST, l_bad_host, strlen(l_bad_host)); REQUIRE((l_s == WAFLZ_STATUS_OK)); l_s = l_db.init(); REQUIRE((l_s == WAFLZ_STATUS_ERROR)); //printf("error: %s\n", l_db.get_err_msg()); } SECTION("validate good init") { ns_waflz::redis_db l_db; REQUIRE((l_db.get_init() == false)); const char l_host[] = "127.0.0.1"; int32_t l_s; l_s = l_db.set_opt(ns_waflz::redis_db::OPT_REDIS_HOST, l_host, strlen(l_host)); l_s = l_db.set_opt(ns_waflz::redis_db::OPT_REDIS_PORT, NULL, 6379); REQUIRE((l_s == WAFLZ_STATUS_OK)); l_s = l_db.init(); REQUIRE((l_s == WAFLZ_STATUS_OK)); int64_t l_val; l_s = l_db.increment_key(l_val, MONKEY_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 1)); l_s = l_db.increment_key(l_val, MONKEY_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 2)); l_s = l_db.increment_key(l_val, BANANA_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 1)); l_s = l_db.increment_key(l_val, BANANA_KEY, 1000); l_s = l_db.increment_key(l_val, BANANA_KEY, 1000); //NDBG_PRINT("PRINT ALL KEYS\n"); //l_db.print_all_keys(); l_s = l_db.get_key(l_val, MONKEY_KEY, strlen(MONKEY_KEY)); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 2)); l_s = l_db.increment_key(l_val, MONKEY_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //printf("l_val: %ld\n", l_val); REQUIRE((l_val == 3)); l_s = l_db.increment_key(l_val, BANANA_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 4)); //sprintf("error: %s\n", l_db.get_err_msg()); // wait for monkey key to expire sleep(1); l_s = l_db.get_key(l_val, MONKEY_KEY, strlen(MONKEY_KEY)); REQUIRE((l_s == WAFLZ_STATUS_ERROR)); l_s = l_db.increment_key(l_val, MONKEY_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 1)); } }
47.029126
103
0.469447
rohitjoshi
8d691b5bf46f1cc7c697cf58e3cef0557cf27f99
3,307
cpp
C++
console/src/boost_1_78_0/libs/system/test/std_interop_test6.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
1
2019-10-27T21:15:52.000Z
2019-10-27T21:15:52.000Z
console/src/boost_1_78_0/libs/system/test/std_interop_test6.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
null
null
null
console/src/boost_1_78_0/libs/system/test/std_interop_test6.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
1
2021-08-24T08:49:34.000Z
2021-08-24T08:49:34.000Z
// Copyright 2021 Peter Dimov. // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt #include <boost/system/error_code.hpp> #include <boost/core/lightweight_test.hpp> #include <boost/config/pragma_message.hpp> #include <cerrno> #if !defined(BOOST_SYSTEM_HAS_SYSTEM_ERROR) BOOST_PRAGMA_MESSAGE( "BOOST_SYSTEM_HAS_SYSTEM_ERROR not defined, test will be skipped" ) int main() {} #else #include <system_error> int main() { { boost::system::error_code e1; boost::system::error_condition en = e1.default_error_condition(); BOOST_TEST_EQ( e1, en ); BOOST_TEST_NOT( e1 != en ); std::error_code e2( e1 ); BOOST_TEST_EQ( e2, e1 ); BOOST_TEST_NOT( e2 != e1 ); #if defined(_LIBCPP_VERSION) // Under MS STL and libstdc++, std::error_code() does not compare // equal to std::error_condition(). Go figure. BOOST_TEST_EQ( e2, en ); BOOST_TEST_NOT( e2 != en ); boost::system::error_code e3( e2 ); BOOST_TEST_EQ( e3, en ); BOOST_TEST_NOT( e3 != en ); #endif } { boost::system::error_code e1( 0, boost::system::system_category() ); boost::system::error_condition en = e1.default_error_condition(); BOOST_TEST_EQ( e1, en ); BOOST_TEST_NOT( e1 != en ); std::error_code e2( e1 ); BOOST_TEST_EQ( e2, e1 ); BOOST_TEST_NOT( e2 != e1 ); #if defined(_LIBCPP_VERSION) BOOST_TEST_EQ( e2, en ); BOOST_TEST_NOT( e2 != en ); boost::system::error_code e3( e2 ); BOOST_TEST_EQ( e3, en ); BOOST_TEST_NOT( e3 != en ); #endif } { boost::system::error_code e1( 5, boost::system::system_category() ); boost::system::error_condition en = e1.default_error_condition(); BOOST_TEST_EQ( e1, en ); BOOST_TEST_NOT( e1 != en ); std::error_code e2( e1 ); BOOST_TEST_EQ( e2, e1 ); BOOST_TEST_NOT( e2 != e1 ); BOOST_TEST_EQ( e2, en ); BOOST_TEST_NOT( e2 != en ); boost::system::error_code e3( e2 ); BOOST_TEST_EQ( e3, en ); BOOST_TEST_NOT( e3 != en ); } { boost::system::error_code e1( 0, boost::system::generic_category() ); boost::system::error_condition en = e1.default_error_condition(); BOOST_TEST_EQ( e1, en ); BOOST_TEST_NOT( e1 != en ); std::error_code e2( e1 ); BOOST_TEST_EQ( e2, e1 ); BOOST_TEST_NOT( e2 != e1 ); BOOST_TEST_EQ( e2, en ); BOOST_TEST_NOT( e2 != en ); boost::system::error_code e3( e2 ); BOOST_TEST_EQ( e3, en ); BOOST_TEST_NOT( e3 != en ); } { boost::system::error_code e1( 5, boost::system::generic_category() ); boost::system::error_condition en = e1.default_error_condition(); BOOST_TEST_EQ( e1, en ); BOOST_TEST_NOT( e1 != en ); std::error_code e2( e1 ); BOOST_TEST_EQ( e2, e1 ); BOOST_TEST_NOT( e2 != e1 ); BOOST_TEST_EQ( e2, en ); BOOST_TEST_NOT( e2 != en ); boost::system::error_code e3( e2 ); BOOST_TEST_EQ( e3, en ); BOOST_TEST_NOT( e3 != en ); } return boost::report_errors(); } #endif
23.453901
89
0.584215
vany152
8d6b3da54cce67b24cb62b1e53dfa99e7b0679be
5,147
cpp
C++
codeset/CPP/6-3.cpp
onyiny-ang/chloroplasts
06ea45454f5fd1de88a7ae366130f0521410a7d5
[ "MIT" ]
1
2019-04-29T19:36:15.000Z
2019-04-29T19:36:15.000Z
codeset/CPP/6-3.cpp
onyiny-ang/chloroplasts
06ea45454f5fd1de88a7ae366130f0521410a7d5
[ "MIT" ]
13
2019-08-19T17:53:32.000Z
2022-03-02T03:53:20.000Z
codeset/CPP/6-3.cpp
onyiny-ang/chloroplasts-2
06ea45454f5fd1de88a7ae366130f0521410a7d5
[ "MIT" ]
3
2019-04-26T21:34:43.000Z
2021-01-07T19:48:53.000Z
/** Name: Phoenix Bishea Eid: pnb338 */ #include <iostream> using namespace std; /// global constant for fixed rows and cols of the 2D array int iterationsR = 0, iterationsC = 0, gameCounter = 0, gameCounterMax = 0, aliveCounters = 0, temp = 0; const int rownumber = 10, columnnumber = 10, minimum = 0, maximum = 9; const bool alive; // Don't douch the declarations void showGrid(const bool[][columnnumber]); void startGrid(bool[][columnnumber]); void initializeGrid(bool[][columnnumber]); void getGridCopy(bool grid[][columnnumber]); //hard copies created grid for game use int returnNeighbor(const bool[][columnnumber], int r, int c); int main() { // reads in the number of numIterate to run int numIterate; cin >> numIterate; cin.ignore(); // consumes the newline character at the end of the first line // initializes a 2d bool array with the number of rows and cols bool arr[rownumber][columnnumber]; initializeGrid(arr); // prints the game we are playing cout << "Game Of Life rows=" << rownumber << " cols=" << columnnumber << " numIterate=" << numIterate << endl; // prints the initial board showGrid(arr); // completes x numIterate for (int i = 0; i < numIterate; i++) { cout << endl; startGrid(arr); showGrid(arr); } return 0; /// return a ok } void showGrid(const bool arr[][columnnumber]) { // converts the bool array into the board of life // '*' is true and '.' is false for (const i = 0; i < rownumber; i++) { for (const j = 0; j < columnnumber; j++) { if (arr[i][j]) { cout << '*'; } else { cout << '.'; } } cout << endl; } } void getgrid(char line[], bool grid[][columnnumber]) { //Local Declarations char c; int iterationsC = 0; while (iterationsC < columnnumber) { c = line[iterationsC]; cout << c; if ((isNotNullChar(c)) && (c == '.') || (c != 32)) { grid[iterationsR][iterationsC] = false; } else if ((c == '*') && ((isNotNullChar(c)) || (c != 32))) { grid[iterationsR][iterationsC] = true; } iterationsC++; } iterationsR++; cout << endl; if (iterationsR >= 10) { getGridCopy(grid); } } void initializeGrid(bool arr[][columnnumber]) { char line[columnnumber + 1]; // line to take in r input // gets the first line cin.getline(line, columnnumber + 1); // sets values to true and false in the bool array // '*' is true and '.' is false for (const i = 0; i < rownumber; i++) { for (const j = 0; j < columnnumber; j++) { if (line[j] == '*') { arr[i][j] = 1; } else { arr[i][j] = 0; } } cin.getline(line, columnnumber + 1); } } bool isNotNullChar(char c) { if (c == '\0') { return 0 } else { return 1 } } void getGridCopy(bool grid[][NUM_COLS]) { //Declarations iterationsR = 0, iterationsC = 0; while (iterationsR < NUM_ROWS) { while (iterationsC < NUM_COLS) { gridCopy[iterationsR][iterationsC] = grid[iterationsR][iterationsC]; iterationsC++; } iterationsR++; iterationsC = 0; } } void startGrid(bool board[][columnnumber]) { bool tempBoard[rownumber][columnnumber]; for (const i = 0; i < rownumber; i++) { for (const j = 0; j < columnnumber; j++) { tempBoard[i][j] = board[i][j]; } } for (const i = 0; i < rownumber; i++) { for (const j = 0; j < columnnumber; j++) { int neighbors = returnNeighbor(tempBoard, i, j); bool alive = tempBoard[i][j]; if (alive && (neighbors < 2 || neighbors > 3)) { board[i][j] = 0; } else if (!alive && (neighbors == 3)) { board[i][j] = 1; } } } } int returnNeighbor(const bool board[][columnnumber], int r, int c) { int neighbors = 0; // initializes starting neighbors // sets up the boundaries int a = c+1, b = r+1, d = c-1, e = r-1; bool ifcolumnmax = (a) <= maximum; bool ifrowmax = (b) <= maximum; bool ifcolmin = (d) >= minimum; bool ifrowmin = (e) >= minimum; if (ifcolumnmax && board[r][c + 1]) neighbors++; else if (ifcolmin && board[r][c - 1]) neighbors++; else if (ifrowmax && board[r + 1][c]) neighbors++; else if (ifrowmin && board[r - 1][c]) neighbors++; else if (ifrowmax && ifcolumnmax && board[r + 1][c + 1]) neighbors++; else if (ifrowmin && ifcolumnmax && board[r - 1][c + 1]) neighbors++; else if (ifrowmax && ifcolmin && board[r + 1][c - 1]) neighbors++; else (ifrowmin&& ifcolmin && board[r - 1][c - 1]) neighbors++; return neighbors; }
26.260204
104
0.520109
onyiny-ang
8d6cb3dee50f6e889499ed9969d9f70c016d518e
752
cpp
C++
test/transducer/remove.cpp
Yohsi/zug
ec11ca4642c51eb07de76a5b4a3b90a675cc428e
[ "BSL-1.0" ]
163
2019-11-19T20:58:55.000Z
2022-03-07T10:30:10.000Z
test/transducer/remove.cpp
Yohsi/zug
ec11ca4642c51eb07de76a5b4a3b90a675cc428e
[ "BSL-1.0" ]
26
2019-09-16T18:09:44.000Z
2022-01-25T10:04:13.000Z
test/transducer/remove.cpp
Yohsi/zug
ec11ca4642c51eb07de76a5b4a3b90a675cc428e
[ "BSL-1.0" ]
16
2019-09-08T15:22:18.000Z
2022-02-11T20:33:04.000Z
// // zug: transducers for C++ // Copyright (C) 2019 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #include <catch2/catch.hpp> #include <zug/compose.hpp> #include <zug/transduce.hpp> #include <zug/transducer/map.hpp> #include <zug/transducer/remove.hpp> #include <zug/util.hpp> using namespace zug; TEST_CASE("remove, simple") { // example1 { auto v = std::vector<int>{1, 2, 3, 6}; auto times2 = [](int x) { return x * 2; }; auto odd = [](int x) { return x % 2 == 0; }; auto res = transduce(remove(odd) | map(times2), std::plus<int>{}, 1, v); CHECK(res == 9); // } }
25.931034
79
0.631649
Yohsi
8d6e3fb5d66937ef9de5f31123ca3d62f514b952
1,343
cpp
C++
source/hougfx/test/hou/gfx/test_text_box_formatting_params.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/hougfx/test/hou/gfx/test_text_box_formatting_params.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/hougfx/test/hou/gfx/test_text_box_formatting_params.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #include "hou/test.hpp" #include "hou/gfx/text_box_formatting_params.hpp" using namespace hou; using namespace testing; namespace { class test_text_box_formatting_params : public Test {}; } // namespace TEST_F(test_text_box_formatting_params, constructor) { text_flow text_flow_ref = text_flow::left_right; vec2f max_size_ref(1.f, 2.f); text_box_formatting_params tbfp(text_flow_ref, max_size_ref); EXPECT_EQ(text_flow_ref, tbfp.get_text_flow()); EXPECT_FLOAT_CLOSE(max_size_ref, tbfp.get_max_size()); } TEST_F(test_text_box_formatting_params, text_flow_values) { std::vector<text_flow> text_flow_values{text_flow::left_right, text_flow::right_left, text_flow::top_bottom, text_flow::bottom_top}; for(auto textFlow : text_flow_values) { text_box_formatting_params tbfp(textFlow, vec2f::zero()); EXPECT_EQ(textFlow, tbfp.get_text_flow()); } } TEST_F(test_text_box_formatting_params, max_size_values) { std::vector<vec2f> max_size_values{ vec2f(-1.f, -2.f), vec2f::zero(), vec2f(1.f, 2.f), vec2f(1024.5f, 768.25f), }; for(auto max_size : max_size_values) { text_box_formatting_params tbfp(text_flow::left_right, max_size); EXPECT_EQ(max_size, tbfp.get_max_size()); } }
21.31746
73
0.743857
DavideCorradiDev
8d6f6fdd2ef9f412f9df1d3eae1dbe0bb7401d1e
2,056
hpp
C++
Lib/Chip/MB9AF14xM.hpp
cjsmeele/Kvasir
c8d2acd8313ae52d78259ee2d409b963925f77d7
[ "Apache-2.0" ]
376
2015-07-17T01:41:20.000Z
2022-03-26T04:02:49.000Z
Lib/Chip/MB9AF14xM.hpp
cjsmeele/Kvasir
c8d2acd8313ae52d78259ee2d409b963925f77d7
[ "Apache-2.0" ]
59
2015-07-03T21:30:13.000Z
2021-03-05T11:30:08.000Z
Lib/Chip/MB9AF14xM.hpp
cjsmeele/Kvasir
c8d2acd8313ae52d78259ee2d409b963925f77d7
[ "Apache-2.0" ]
53
2015-07-14T12:17:06.000Z
2021-06-04T07:28:40.000Z
#pragma once #include <Chip/Unknown/Spansion/MB9AF14xM/FLASH_IF.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/CRG.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/CRTRIM.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/SWWDT.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/HWWDT.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/DTIM.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BTIOSEL03.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BTIOSEL47.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/SBSSR.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BT0.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BT1.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BT2.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BT3.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BT4.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BT5.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BT6.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/BT7.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/WC.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/ADC0.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/ADC1.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/EXTI.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/INTREQ.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/GPIO.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/HDMICEC0.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/HDMICEC1.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/LVD.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/DS.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/MFS0.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/MFS1.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/MFS2.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/MFS3.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/MFS4.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/MFS5.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/MFS6.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/MFS7.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/RTC.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/CRC.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/EXBUS.hpp> #include <Chip/Unknown/Spansion/MB9AF14xM/DMAC.hpp>
50.146341
56
0.808366
cjsmeele
8d71618d28f083bd7dab902c7ca84346c8354bd5
8,527
cc
C++
src/quantadb/TxEntry.cc
nliao6622/QuantaDB-1
e5db80c7b9e9f5b3c2c6715ce77c56d56e4c4c94
[ "Apache-2.0" ]
12
2021-01-20T23:20:27.000Z
2021-12-10T12:14:26.000Z
src/quantadb/TxEntry.cc
nliao6622/QuantaDB-1
e5db80c7b9e9f5b3c2c6715ce77c56d56e4c4c94
[ "Apache-2.0" ]
null
null
null
src/quantadb/TxEntry.cc
nliao6622/QuantaDB-1
e5db80c7b9e9f5b3c2c6715ce77c56d56e4c4c94
[ "Apache-2.0" ]
2
2021-01-13T02:03:32.000Z
2022-01-20T17:26:55.000Z
/* Copyright 2020 Futurewei Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include "TxEntry.h" #include "ConcurrentBitmap.h" namespace QDB { TxEntry::TxEntry(uint32_t _readSetSize, uint32_t _writeSetSize) { if (_readSetSize > TUPLE_ENTRY_MAX || _writeSetSize > TUPLE_ENTRY_MAX) { printf("read or write set of the transaction exceeded the maximum supported size: %d", TUPLE_ENTRY_MAX); exit(1); } sstamp = std::numeric_limits<uint64_t>::max(); pstamp = 0; txState = TX_PENDING; commitIntentState = TX_CI_UNQUEUED; cts = 0; writeSetSize = _writeSetSize; readSetSize = _readSetSize; readSetIndex = writeSetIndex = 0; if (writeSetSize > 0) { writeSet.reset(new KVLayout *[writeSetSize]); writeSetHash.reset(new uint64_t[writeSetSize]); writeSetInStore.reset(new KVLayout *[writeSetSize]); writeSetKVSPtr.reset(new void *[writeSetSize]); for (uint32_t i = 0; i < writeSetSize; i++) { writeSet[i] = NULL; writeSetInStore[i] = NULL; writeSetKVSPtr[i] = NULL; writeTupleSkipLock[i] = false; } } if (readSetSize > 0) { readSet.reset(new KVLayout *[readSetSize]); readSetHash.reset(new uint64_t[readSetSize]); readSetInStore.reset(new KVLayout *[readSetSize]); readSetKVSPtr.reset(new void *[readSetSize]); for (uint32_t i = 0; i < readSetSize; i++) { readSet[i] = NULL; readSetInStore[i] = NULL; readSetKVSPtr[i] = NULL; readTupleSkipLock[i] = false; } } rpcHandle = NULL; } TxEntry::~TxEntry() { //Free KVLayout allocated in txCommit RPC handler for (uint32_t i = 0; i < writeSetSize; i++) { if (writeSet[i]) { if (writeSet[i]->meta().cStamp > 0) continue; //a RMW - let it be free from read set delete writeSet[i]; writeSet[i] = NULL; } } for (uint32_t i = 0; i < readSetSize; i++) { if (readSet[i]) { delete readSet[i]; readSet[i] = NULL; } } } bool TxEntry::insertReadSet(KVLayout* kv, uint32_t i) { assert(i < readSetSize); readSet[i] = kv; uint64_t hash = kv->k.getKeyHash(); readSetHash[i] = hash; //Apply local lock filter uint64_t loc = ConcurrentBitmap::getBitLocation(hash); auto lookup = lockTableFilter.find(loc); if (lookup != lockTableFilter.end()) { readTupleSkipLock[i] = true; } else { lockTableFilter.insert(loc); } return true; } bool TxEntry::insertWriteSet(KVLayout* kv, uint32_t i) { assert(i < writeSetSize); writeSet[i] = kv; uint64_t hash = kv->k.getKeyHash(); writeSetHash[i] = hash; //Apply local lock filter uint64_t loc = ConcurrentBitmap::getBitLocation(hash); auto lookup = lockTableFilter.find(loc); if (lookup != lockTableFilter.end()) { writeTupleSkipLock[i] = true; } else { lockTableFilter.insert(loc); } return true; } bool TxEntry::correctReadSet(uint32_t size) { //This is a workaround function to correct the size of a possibly over-provisioned readSet. //Because scoped_array vars are used, we do not need to worry about memory leak. //If there is over-provisioning, the null elements will be at the tail of the arrays. //By changing the readSetSize, the handling of the readSet will be the same as if there //were no over-provisioning at all. //The proper solution is to have the commit intent pass the correct readSet size //so that txEntry will have the correct readSet size at instantiation. readSetSize = size; return true; } uint32_t TxEntry::serializeSize(uint32_t *wsSzRet, uint32_t *rsSzRet, uint32_t *psSzRet) { uint32_t sz = sizeof(cts) + sizeof(txState) + sizeof(pstamp) + sizeof(sstamp); uint32_t wsSz = 0, rsSz = 0, psSz = 0; if (txState == TX_PENDING || txState == TX_FABRICATED) { sz += sizeof(commitIntentState); // writeSet wsSz += sizeof(uint32_t); for (uint32_t i = 0; i < getWriteSetSize(); i++) { if (writeSet[i]) wsSz += writeSet[i]->serializeSize(); } sz += wsSz; // readSet rsSz += sizeof(uint32_t); for (uint32_t i = 0; i < getReadSetSize(); i++) { if (readSet[i]) rsSz += readSet[i]->serializeSize(); } sz += rsSz; // peerSet psSz += sizeof(uint32_t); psSz += peerSet.size() * sizeof(uint64_t); psSz += sizeof(uint8_t); sz += psSz; } if (wsSzRet) *wsSzRet = wsSz; if (psSzRet) *psSzRet = psSz; if (rsSzRet) *rsSzRet = rsSz; return sz; } void TxEntry::serialize( outMemStream& out ) { out.write(&cts, sizeof(cts)); uint32_t tmp = txState; out.write(&tmp, sizeof(txState)); out.write(&pstamp, sizeof(pstamp)); out.write(&sstamp, sizeof(sstamp)); if (txState == TX_PENDING || txState == TX_FABRICATED) { tmp = commitIntentState; out.write(&tmp, sizeof((uint32_t)commitIntentState)); // count writeSet #entry uint32_t nWriteSet = 0; for (uint32_t i = 0; i < getWriteSetSize(); i++) { if (writeSet[i]) nWriteSet++; } // assert(nWriteSet == getWriteSetSize()); // According to Henry, the writeSet[] should be full of valid entries // writeSet out.write(&nWriteSet, sizeof(nWriteSet)); for (uint32_t i = 0; i < nWriteSet; i++) { assert (writeSet[i]); writeSet[i]->serialize(out); } // count readSet #entry uint32_t nReadSet = 0; for (uint32_t i = 0; i < getReadSetSize(); i++) { if (readSet[i]) nReadSet++; } // readSet out.write(&nReadSet, sizeof(nReadSet)); for (uint32_t i = 0; i < nReadSet; i++) { assert (readSet[i]); readSet[i]->serialize(out); } // peerSet uint32_t peerSetSize = peerSet.size(); out.write(&peerSetSize, sizeof(peerSetSize)); for(std::set<uint64_t>::iterator it = peerSet.begin(); it != peerSet.end(); it++) { uint64_t peer = *it; out.write(&peer, sizeof(peer)); } out.write(&myPeerPosition, sizeof(myPeerPosition)); } } void TxEntry::deSerialize_common( inMemStream& in ) { in.read(&cts, sizeof(cts)); uint32_t tmp; in.read(&tmp, sizeof(txState)); txState = tmp; in.read(&pstamp, sizeof(pstamp)); in.read(&sstamp, sizeof(sstamp)); } void TxEntry::deSerialize_additional( inMemStream& in ) { uint32_t nWriteSet, nReadSet; uint32_t tmp; in.read(&tmp, sizeof(commitIntentState)); commitIntentState = tmp; // writeSet in.read(&nWriteSet, sizeof(nWriteSet)); writeSetSize = nWriteSet; writeSet.reset(new KVLayout *[nWriteSet]); for (uint32_t i = 0; i < nWriteSet; i++) { KVLayout* kv = new KVLayout(0); kv->deSerialize(in); writeSet[i] = kv; } // readSet in.read(&nReadSet, sizeof(nReadSet)); readSetSize = nReadSet; readSet.reset(new KVLayout *[nReadSet]); for (uint32_t i = 0; i < nReadSet; i++) { KVLayout* kv = new KVLayout(0); kv->deSerialize(in); readSet[i] = kv; } // peerSet uint32_t peerSetSize; in.read(&peerSetSize, sizeof(peerSetSize)); peerSet.clear(); for(uint32_t idx = 0; idx < peerSetSize; idx++) { uint64_t peer; in.read(&peer, sizeof(peer)); insertPeerSet(peer); } in.read(&myPeerPosition, sizeof(myPeerPosition)); } void TxEntry::deSerialize( inMemStream& in ) { deSerialize_common( in ); if (txState == TX_PENDING || txState == TX_FABRICATED) { deSerialize_additional( in ); } } } // end TxEntry class
30.024648
120
0.602205
nliao6622
8d724197a25d463b41babf68fd595e0f1a389599
42,743
cpp
C++
pkgs/apps/fluidanimate/src/pthreads.cpp
mariobadr/parsec-benchmarks
df65311b02d96fc6525fd49cf915a1885987d5a1
[ "BSD-3-Clause" ]
null
null
null
pkgs/apps/fluidanimate/src/pthreads.cpp
mariobadr/parsec-benchmarks
df65311b02d96fc6525fd49cf915a1885987d5a1
[ "BSD-3-Clause" ]
null
null
null
pkgs/apps/fluidanimate/src/pthreads.cpp
mariobadr/parsec-benchmarks
df65311b02d96fc6525fd49cf915a1885987d5a1
[ "BSD-3-Clause" ]
null
null
null
//Code written by Richard O. Lee and Christian Bienia //Modified by Christian Fensch #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #if defined(WIN32) #define NOMINMAX #include <windows.h> #endif #include <math.h> #include <pthread.h> #include <assert.h> #include <float.h> #include "fluid.hpp" #include "cellpool.hpp" #include <pthread.h> #ifdef ENABLE_VISUALIZATION #include "fluidview.hpp" #endif #ifdef ENABLE_PARSEC_HOOKS #include <hooks.h> #endif //Uncomment to add code to check that Courant–Friedrichs–Lewy condition is satisfied at runtime //#define ENABLE_CFL_CHECK //////////////////////////////////////////////////////////////////////////////// cellpool *pools; //each thread has its private cell pool fptype restParticlesPerMeter, h, hSq; fptype densityCoeff, pressureCoeff, viscosityCoeff; int nx, ny, nz; // number of grid cells in each dimension Vec3 delta; // cell dimensions int numParticles = 0; int numCells = 0; Cell *cells = 0; Cell *cells2 = 0; int *cnumPars = 0; int *cnumPars2 = 0; Cell **last_cells = NULL; //helper array with pointers to last cell structure of "cells" array lists #ifdef ENABLE_VISUALIZATION Vec3 vMax(0.0,0.0,0.0); Vec3 vMin(0.0,0.0,0.0); #endif int XDIVS = 1; // number of partitions in X int ZDIVS = 1; // number of partitions in Z #define NUM_GRIDS ((XDIVS) * (ZDIVS)) #define MUTEXES_PER_CELL 1 #define CELL_MUTEX_ID 0 struct Grid { union { struct { int sx, sy, sz; int ex, ey, ez; }; unsigned char pp[CACHELINE_SIZE]; }; } *grids; bool *border; pthread_attr_t attr; pthread_t *thread; pthread_mutex_t **mutex; // used to lock cells in RebuildGrid and also particles in other functions pthread_barrier_t barrier; // global barrier used by all threads #ifdef ENABLE_VISUALIZATION pthread_barrier_t visualization_barrier; // global barrier to separate (serial) visualization phase from (parallel) fluid simulation #endif typedef struct __thread_args { int tid; //thread id, determines work partition int frames; //number of frames to compute } thread_args; //arguments for threads //////////////////////////////////////////////////////////////////////////////// /* * hmgweight * * Computes the hamming weight of x * * x - input value * lsb - if x!=0 position of smallest bit set, else -1 * * return - the hamming weight */ unsigned int hmgweight(unsigned int x, int *lsb) { unsigned int weight=0; unsigned int mask= 1; unsigned int count=0; *lsb=-1; while(x > 0) { unsigned int temp; temp=(x&mask); if((x&mask) == 1) { weight++; if(*lsb == -1) *lsb = count; } x >>= 1; count++; } return weight; } void InitSim(char const *fileName, unsigned int threadnum) { //Compute partitioning based on square root of number of threads //NOTE: Other partition sizes are possible as long as XDIVS * ZDIVS == threadnum, // but communication is minimal (and hence optimal) if XDIVS == ZDIVS int lsb; if(hmgweight(threadnum,&lsb) != 1) { std::cerr << "Number of threads must be a power of 2" << std::endl; exit(1); } XDIVS = 1<<(lsb/2); ZDIVS = 1<<(lsb/2); if(XDIVS*ZDIVS != threadnum) XDIVS*=2; assert(XDIVS * ZDIVS == threadnum); thread = new pthread_t[NUM_GRIDS]; grids = new struct Grid[NUM_GRIDS]; assert(sizeof(Grid) <= CACHELINE_SIZE); // as we put and aligh grid on the cacheline size to avoid false-sharing // if asserts fails - increase pp union member in Grid declarationi // and change this macro pools = new cellpool[NUM_GRIDS]; //Load input particles std::cout << "Loading file \"" << fileName << "\"..." << std::endl; std::ifstream file(fileName, std::ios::binary); if(!file) { std::cerr << "Error opening file. Aborting." << std::endl; exit(1); } //Always use single precision float variables b/c file format uses single precision float restParticlesPerMeter_le; int numParticles_le; file.read((char *)&restParticlesPerMeter_le, FILE_SIZE_FLOAT); file.read((char *)&numParticles_le, FILE_SIZE_INT); if(!isLittleEndian()) { restParticlesPerMeter = bswap_float(restParticlesPerMeter_le); numParticles = bswap_int32(numParticles_le); } else { restParticlesPerMeter = restParticlesPerMeter_le; numParticles = numParticles_le; } for(int i=0; i<NUM_GRIDS; i++) cellpool_init(&pools[i], numParticles/NUM_GRIDS); h = kernelRadiusMultiplier / restParticlesPerMeter; hSq = h*h; #ifndef ENABLE_DOUBLE_PRECISION fptype coeff1 = 315.0 / (64.0*pi*powf(h,9.0)); fptype coeff2 = 15.0 / (pi*powf(h,6.0)); fptype coeff3 = 45.0 / (pi*powf(h,6.0)); #else fptype coeff1 = 315.0 / (64.0*pi*pow(h,9.0)); fptype coeff2 = 15.0 / (pi*pow(h,6.0)); fptype coeff3 = 45.0 / (pi*pow(h,6.0)); #endif //ENABLE_DOUBLE_PRECISION fptype particleMass = 0.5*doubleRestDensity / (restParticlesPerMeter*restParticlesPerMeter*restParticlesPerMeter); densityCoeff = particleMass * coeff1; pressureCoeff = 3.0*coeff2 * 0.50*stiffnessPressure * particleMass; viscosityCoeff = viscosity * coeff3 * particleMass; Vec3 range = domainMax - domainMin; nx = (int)(range.x / h); ny = (int)(range.y / h); nz = (int)(range.z / h); assert(nx >= 1 && ny >= 1 && nz >= 1); numCells = nx*ny*nz; std::cout << "Number of cells: " << numCells << std::endl; delta.x = range.x / nx; delta.y = range.y / ny; delta.z = range.z / nz; assert(delta.x >= h && delta.y >= h && delta.z >= h); std::cout << "Grids steps over x, y, z: " << delta.x << " " << delta.y << " " << delta.z << std::endl; assert(nx >= XDIVS && nz >= ZDIVS); int gi = 0; int sx, sz, ex, ez; ex = 0; for(int i = 0; i < XDIVS; ++i) { sx = ex; ex = (int)((fptype)(nx)/(fptype)(XDIVS) * (i+1) + 0.5); assert(sx < ex); ez = 0; for(int j = 0; j < ZDIVS; ++j, ++gi) { sz = ez; ez = (int)((fptype)(nz)/(fptype)(ZDIVS) * (j+1) + 0.5); assert(sz < ez); grids[gi].sx = sx; grids[gi].ex = ex; grids[gi].sy = 0; grids[gi].ey = ny; grids[gi].sz = sz; grids[gi].ez = ez; } } assert(gi == NUM_GRIDS); border = new bool[numCells]; for(int i = 0; i < NUM_GRIDS; ++i) for(int iz = grids[i].sz; iz < grids[i].ez; ++iz) for(int iy = grids[i].sy; iy < grids[i].ey; ++iy) for(int ix = grids[i].sx; ix < grids[i].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; border[index] = false; for(int dk = -1; dk <= 1; ++dk) { for(int dj = -1; dj <= 1; ++dj) { for(int di = -1; di <= 1; ++di) { int ci = ix + di; int cj = iy + dj; int ck = iz + dk; if(ci < 0) ci = 0; else if(ci > (nx-1)) ci = nx-1; if(cj < 0) cj = 0; else if(cj > (ny-1)) cj = ny-1; if(ck < 0) ck = 0; else if(ck > (nz-1)) ck = nz-1; if( ci < grids[i].sx || ci >= grids[i].ex || cj < grids[i].sy || cj >= grids[i].ey || ck < grids[i].sz || ck >= grids[i].ez ) { border[index] = true; break; } } // for(int di = -1; di <= 1; ++di) if(border[index]) break; } // for(int dj = -1; dj <= 1; ++dj) if(border[index]) break; } // for(int dk = -1; dk <= 1; ++dk) } pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); mutex = new pthread_mutex_t *[numCells]; for(int i = 0; i < numCells; ++i) { assert(CELL_MUTEX_ID < MUTEXES_PER_CELL); int n = (border[i] ? MUTEXES_PER_CELL : CELL_MUTEX_ID+1); mutex[i] = new pthread_mutex_t[n]; for(int j = 0; j < n; ++j) pthread_mutex_init(&mutex[i][j], NULL); } pthread_barrier_init(&barrier, NULL, NUM_GRIDS); #ifdef ENABLE_VISUALIZATION //visualization barrier is used by all NUM_GRIDS worker threads and 1 master thread pthread_barrier_init(&visualization_barrier, NULL, NUM_GRIDS+1); #endif //make sure Cell structure is multiple of estiamted cache line size assert(sizeof(Cell) % CACHELINE_SIZE == 0); //make sure helper Cell structure is in sync with real Cell structure assert(offsetof(struct Cell_aux, padding) == offsetof(struct Cell, padding)); #if defined(WIN32) cells = (struct Cell*)_aligned_malloc(sizeof(struct Cell) * numCells, CACHELINE_SIZE); cells2 = (struct Cell*)_aligned_malloc(sizeof(struct Cell) * numCells, CACHELINE_SIZE); cnumPars = (int*)_aligned_malloc(sizeof(int) * numCells, CACHELINE_SIZE); cnumPars2 = (int*)_aligned_malloc(sizeof(int) * numCells, CACHELINE_SIZE); last_cells = (struct Cell **)_aligned_malloc(sizeof(struct Cell *) * numCells, CACHELINE_SIZE); assert((cells!=NULL) && (cells2!=NULL) && (cnumPars!=NULL) && (cnumPars2!=NULL) && (last_cells!=NULL)); #elif defined(SPARC_SOLARIS) cells = (Cell*)memalign(CACHELINE_SIZE, sizeof(struct Cell) * numCells); cells2 = (Cell*)memalign(CACHELINE_SIZE, sizeof(struct Cell) * numCells); cnumPars = (int*)memalign(CACHELINE_SIZE, sizeof(int) * numCells); cnumPars2 = (int*)memalign(CACHELINE_SIZE, sizeof(int) * numCells); last_cells = (Cell**)memalign(CACHELINE_SIZE, sizeof(struct Cell *) * numCells); assert((cells!=0) && (cells2!=0) && (cnumPars!=0) && (cnumPars2!=0) && (last_cells!=0)); #else int rv0 = posix_memalign((void **)(&cells), CACHELINE_SIZE, sizeof(struct Cell) * numCells); int rv1 = posix_memalign((void **)(&cells2), CACHELINE_SIZE, sizeof(struct Cell) * numCells); int rv2 = posix_memalign((void **)(&cnumPars), CACHELINE_SIZE, sizeof(int) * numCells); int rv3 = posix_memalign((void **)(&cnumPars2), CACHELINE_SIZE, sizeof(int) * numCells); int rv4 = posix_memalign((void **)(&last_cells), CACHELINE_SIZE, sizeof(struct Cell *) * numCells); assert((rv0==0) && (rv1==0) && (rv2==0) && (rv3==0) && (rv4==0)); #endif // because cells and cells2 are not allocated via new // we construct them here for(int i=0; i<numCells; ++i) { new (&cells[i]) Cell; new (&cells2[i]) Cell; } memset(cnumPars, 0, numCells*sizeof(int)); //Always use single precision float variables b/c file format uses single precision float int pool_id = 0; float px, py, pz, hvx, hvy, hvz, vx, vy, vz; for(int i = 0; i < numParticles; ++i) { file.read((char *)&px, FILE_SIZE_FLOAT); file.read((char *)&py, FILE_SIZE_FLOAT); file.read((char *)&pz, FILE_SIZE_FLOAT); file.read((char *)&hvx, FILE_SIZE_FLOAT); file.read((char *)&hvy, FILE_SIZE_FLOAT); file.read((char *)&hvz, FILE_SIZE_FLOAT); file.read((char *)&vx, FILE_SIZE_FLOAT); file.read((char *)&vy, FILE_SIZE_FLOAT); file.read((char *)&vz, FILE_SIZE_FLOAT); if(!isLittleEndian()) { px = bswap_float(px); py = bswap_float(py); pz = bswap_float(pz); hvx = bswap_float(hvx); hvy = bswap_float(hvy); hvz = bswap_float(hvz); vx = bswap_float(vx); vy = bswap_float(vy); vz = bswap_float(vz); } int ci = (int)((px - domainMin.x) / delta.x); int cj = (int)((py - domainMin.y) / delta.y); int ck = (int)((pz - domainMin.z) / delta.z); if(ci < 0) ci = 0; else if(ci > (nx-1)) ci = nx-1; if(cj < 0) cj = 0; else if(cj > (ny-1)) cj = ny-1; if(ck < 0) ck = 0; else if(ck > (nz-1)) ck = nz-1; int index = (ck*ny + cj)*nx + ci; Cell *cell = &cells[index]; //go to last cell structure in list int np = cnumPars[index]; while(np > PARTICLES_PER_CELL) { cell = cell->next; np = np - PARTICLES_PER_CELL; } //add another cell structure if everything full if( (np % PARTICLES_PER_CELL == 0) && (cnumPars[index] != 0) ) { //Get cells from pools in round-robin fashion to balance load during parallel phase cell->next = cellpool_getcell(&pools[pool_id]); pool_id = (pool_id+1) % NUM_GRIDS; cell = cell->next; np = np - PARTICLES_PER_CELL; } cell->p[np].x = px; cell->p[np].y = py; cell->p[np].z = pz; cell->hv[np].x = hvx; cell->hv[np].y = hvy; cell->hv[np].z = hvz; cell->v[np].x = vx; cell->v[np].y = vy; cell->v[np].z = vz; #ifdef ENABLE_VISUALIZATION vMin.x = std::min(vMin.x, cell->v[np].x); vMax.x = std::max(vMax.x, cell->v[np].x); vMin.y = std::min(vMin.y, cell->v[np].y); vMax.y = std::max(vMax.y, cell->v[np].y); vMin.z = std::min(vMin.z, cell->v[np].z); vMax.z = std::max(vMax.z, cell->v[np].z); #endif ++cnumPars[index]; } std::cout << "Number of particles: " << numParticles << std::endl; } //////////////////////////////////////////////////////////////////////////////// void SaveFile(char const *fileName) { std::cout << "Saving file \"" << fileName << "\"..." << std::endl; std::ofstream file(fileName, std::ios::binary); assert(file); //Always use single precision float variables b/c file format uses single precision if(!isLittleEndian()) { float restParticlesPerMeter_le; int numParticles_le; restParticlesPerMeter_le = bswap_float((float)restParticlesPerMeter); numParticles_le = bswap_int32(numParticles); file.write((char *)&restParticlesPerMeter_le, FILE_SIZE_FLOAT); file.write((char *)&numParticles_le, FILE_SIZE_INT); } else { file.write((char *)&restParticlesPerMeter, FILE_SIZE_FLOAT); file.write((char *)&numParticles, FILE_SIZE_INT); } int count = 0; for(int i = 0; i < numCells; ++i) { Cell *cell = &cells[i]; int np = cnumPars[i]; for(int j = 0; j < np; ++j) { //Always use single precision float variables b/c file format uses single precision float px, py, pz, hvx, hvy, hvz, vx,vy, vz; if(!isLittleEndian()) { px = bswap_float((float)(cell->p[j % PARTICLES_PER_CELL].x)); py = bswap_float((float)(cell->p[j % PARTICLES_PER_CELL].y)); pz = bswap_float((float)(cell->p[j % PARTICLES_PER_CELL].z)); hvx = bswap_float((float)(cell->hv[j % PARTICLES_PER_CELL].x)); hvy = bswap_float((float)(cell->hv[j % PARTICLES_PER_CELL].y)); hvz = bswap_float((float)(cell->hv[j % PARTICLES_PER_CELL].z)); vx = bswap_float((float)(cell->v[j % PARTICLES_PER_CELL].x)); vy = bswap_float((float)(cell->v[j % PARTICLES_PER_CELL].y)); vz = bswap_float((float)(cell->v[j % PARTICLES_PER_CELL].z)); } else { px = (float)(cell->p[j % PARTICLES_PER_CELL].x); py = (float)(cell->p[j % PARTICLES_PER_CELL].y); pz = (float)(cell->p[j % PARTICLES_PER_CELL].z); hvx = (float)(cell->hv[j % PARTICLES_PER_CELL].x); hvy = (float)(cell->hv[j % PARTICLES_PER_CELL].y); hvz = (float)(cell->hv[j % PARTICLES_PER_CELL].z); vx = (float)(cell->v[j % PARTICLES_PER_CELL].x); vy = (float)(cell->v[j % PARTICLES_PER_CELL].y); vz = (float)(cell->v[j % PARTICLES_PER_CELL].z); } file.write((char *)&px, FILE_SIZE_FLOAT); file.write((char *)&py, FILE_SIZE_FLOAT); file.write((char *)&pz, FILE_SIZE_FLOAT); file.write((char *)&hvx, FILE_SIZE_FLOAT); file.write((char *)&hvy, FILE_SIZE_FLOAT); file.write((char *)&hvz, FILE_SIZE_FLOAT); file.write((char *)&vx, FILE_SIZE_FLOAT); file.write((char *)&vy, FILE_SIZE_FLOAT); file.write((char *)&vz, FILE_SIZE_FLOAT); ++count; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } assert(count == numParticles); } //////////////////////////////////////////////////////////////////////////////// void CleanUpSim() { // first return extended cells to cell pools for(int i=0; i< numCells; ++i) { Cell& cell = cells[i]; while(cell.next) { Cell *temp = cell.next; cell.next = temp->next; cellpool_returncell(&pools[0], temp); } } // now return cell pools //NOTE: Cells from cell pools can migrate to different pools during the parallel phase. // This is no problem as long as all cell pools are destroyed together. Each pool // uses its internal meta information to free exactly the cells which it allocated // itself. This guarantees that all allocated cells will be freed but it might // render other cell pools unusable so they also have to be destroyed. for(int i=0; i<NUM_GRIDS; i++) cellpool_destroy(&pools[i]); pthread_attr_destroy(&attr); for(int i = 0; i < numCells; ++i) { assert(CELL_MUTEX_ID < MUTEXES_PER_CELL); int n = (border[i] ? MUTEXES_PER_CELL : CELL_MUTEX_ID+1); for(int j = 0; j < n; ++j) pthread_mutex_destroy(&mutex[i][j]); delete[] mutex[i]; } delete[] mutex; pthread_barrier_destroy(&barrier); #ifdef ENABLE_VISUALIZATION pthread_barrier_destroy(&visualization_barrier); #endif delete[] border; #if defined(WIN32) _aligned_free(cells); _aligned_free(cells2); _aligned_free(cnumPars); _aligned_free(cnumPars2); _aligned_free(last_cells); #else free(cells); free(cells2); free(cnumPars); free(cnumPars2); free(last_cells); #endif delete[] thread; delete[] grids; } //////////////////////////////////////////////////////////////////////////////// void ClearParticlesMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; cnumPars[index] = 0; cells[index].next = NULL; last_cells[index] = &cells[index]; } } //////////////////////////////////////////////////////////////////////////////// void RebuildGridMT(int tid) { // Note, in parallel versions the below swaps // occure outside RebuildGrid() // swap src and dest arrays with particles // std::swap(cells, cells2); // swap src and dest arrays with counts of particles // std::swap(cnumPars, cnumPars2); //iterate through source cell lists for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index2 = (iz*ny + iy)*nx + ix; Cell *cell2 = &cells2[index2]; int np2 = cnumPars2[index2]; //iterate through source particles for(int j = 0; j < np2; ++j) { //get destination for source particle int ci = (int)((cell2->p[j % PARTICLES_PER_CELL].x - domainMin.x) / delta.x); int cj = (int)((cell2->p[j % PARTICLES_PER_CELL].y - domainMin.y) / delta.y); int ck = (int)((cell2->p[j % PARTICLES_PER_CELL].z - domainMin.z) / delta.z); if(ci < 0) ci = 0; else if(ci > (nx-1)) ci = nx-1; if(cj < 0) cj = 0; else if(cj > (ny-1)) cj = ny-1; if(ck < 0) ck = 0; else if(ck > (nz-1)) ck = nz-1; #if 0 assert(ci>=ix-1); assert(ci<=ix+1); assert(cj>=iy-1); assert(cj<=iy+1); assert(ck>=iz-1); assert(ck<=iz+1); #endif #ifdef ENABLE_CFL_CHECK //check that source cell is a neighbor of destination cell bool cfl_cond_satisfied=false; for(int di = -1; di <= 1; ++di) for(int dj = -1; dj <= 1; ++dj) for(int dk = -1; dk <= 1; ++dk) { int ii = ci + di; int jj = cj + dj; int kk = ck + dk; if(ii >= 0 && ii < nx && jj >= 0 && jj < ny && kk >= 0 && kk < nz) { int index = (kk*ny + jj)*nx + ii; if(index == index2) { cfl_cond_satisfied=true; break; } } } if(!cfl_cond_satisfied) { std::cerr << "FATAL ERROR: Courant–Friedrichs–Lewy condition not satisfied." << std::endl; exit(1); } #endif //ENABLE_CFL_CHECK int index = (ck*ny + cj)*nx + ci; // this assumes that particles cannot travel more than one grid cell per time step if(border[index]) pthread_mutex_lock(&mutex[index][CELL_MUTEX_ID]); Cell *cell = last_cells[index]; int np = cnumPars[index]; //add another cell structure if everything full if( (np % PARTICLES_PER_CELL == 0) && (cnumPars[index] != 0) ) { cell->next = cellpool_getcell(&pools[tid]); cell = cell->next; last_cells[index] = cell; } ++cnumPars[index]; if(border[index]) pthread_mutex_unlock(&mutex[index][CELL_MUTEX_ID]); //copy source to destination particle cell->p[np % PARTICLES_PER_CELL] = cell2->p[j % PARTICLES_PER_CELL]; cell->hv[np % PARTICLES_PER_CELL] = cell2->hv[j % PARTICLES_PER_CELL]; cell->v[np % PARTICLES_PER_CELL] = cell2->v[j % PARTICLES_PER_CELL]; //move pointer to next source cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { Cell *temp = cell2; cell2 = cell2->next; //return cells to pool that are not statically allocated head of lists if(temp != &cells2[index2]) { //NOTE: This is thread-safe because temp and pool are thread-private, no need to synchronize cellpool_returncell(&pools[tid], temp); } } } // for(int j = 0; j < np2; ++j) //return cells to pool that are not statically allocated head of lists if((cell2 != NULL) && (cell2 != &cells2[index2])) { cellpool_returncell(&pools[tid], cell2); } } } //////////////////////////////////////////////////////////////////////////////// int InitNeighCellList(int ci, int cj, int ck, int *neighCells) { int numNeighCells = 0; // have the nearest particles first -> help branch prediction int my_index = (ck*ny + cj)*nx + ci; neighCells[numNeighCells] = my_index; ++numNeighCells; for(int di = -1; di <= 1; ++di) for(int dj = -1; dj <= 1; ++dj) for(int dk = -1; dk <= 1; ++dk) { int ii = ci + di; int jj = cj + dj; int kk = ck + dk; if(ii >= 0 && ii < nx && jj >= 0 && jj < ny && kk >= 0 && kk < nz) { int index = (kk*ny + jj)*nx + ii; if((index < my_index) && (cnumPars[index] != 0)) { neighCells[numNeighCells] = index; ++numNeighCells; } } } return numNeighCells; } //////////////////////////////////////////////////////////////////////////////// void InitDensitiesAndForcesMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { cell->density[j % PARTICLES_PER_CELL] = 0.0; cell->a[j % PARTICLES_PER_CELL] = externalAcceleration; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// void ComputeDensitiesMT(int tid) { int neighCells[3*3*3]; for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; int np = cnumPars[index]; if(np == 0) continue; int numNeighCells = InitNeighCellList(ix, iy, iz, neighCells); Cell *cell = &cells[index]; for(int ipar = 0; ipar < np; ++ipar) { for(int inc = 0; inc < numNeighCells; ++inc) { int indexNeigh = neighCells[inc]; Cell *neigh = &cells[indexNeigh]; int numNeighPars = cnumPars[indexNeigh]; for(int iparNeigh = 0; iparNeigh < numNeighPars; ++iparNeigh) { //Check address to make sure densities are computed only once per pair if(&neigh->p[iparNeigh % PARTICLES_PER_CELL] < &cell->p[ipar % PARTICLES_PER_CELL]) { fptype distSq = (cell->p[ipar % PARTICLES_PER_CELL] - neigh->p[iparNeigh % PARTICLES_PER_CELL]).GetLengthSq(); if(distSq < hSq) { fptype t = hSq - distSq; fptype tc = t*t*t; if(border[index]) { pthread_mutex_lock(&mutex[index][ipar % MUTEXES_PER_CELL]); cell->density[ipar % PARTICLES_PER_CELL] += tc; pthread_mutex_unlock(&mutex[index][ipar % MUTEXES_PER_CELL]); } else cell->density[ipar % PARTICLES_PER_CELL] += tc; if(border[indexNeigh]) { pthread_mutex_lock(&mutex[indexNeigh][iparNeigh % MUTEXES_PER_CELL]); neigh->density[iparNeigh % PARTICLES_PER_CELL] += tc; pthread_mutex_unlock(&mutex[indexNeigh][iparNeigh % MUTEXES_PER_CELL]); } else neigh->density[iparNeigh % PARTICLES_PER_CELL] += tc; } } //move pointer to next cell in list if end of array is reached if(iparNeigh % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { neigh = neigh->next; } } } //move pointer to next cell in list if end of array is reached if(ipar % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// void ComputeDensities2MT(int tid) { const fptype tc = hSq*hSq*hSq; for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { cell->density[j % PARTICLES_PER_CELL] += tc; cell->density[j % PARTICLES_PER_CELL] *= densityCoeff; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// void ComputeForcesMT(int tid) { int neighCells[3*3*3]; for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; int np = cnumPars[index]; if(np == 0) continue; int numNeighCells = InitNeighCellList(ix, iy, iz, neighCells); Cell *cell = &cells[index]; for(int ipar = 0; ipar < np; ++ipar) { for(int inc = 0; inc < numNeighCells; ++inc) { int indexNeigh = neighCells[inc]; Cell *neigh = &cells[indexNeigh]; int numNeighPars = cnumPars[indexNeigh]; for(int iparNeigh = 0; iparNeigh < numNeighPars; ++iparNeigh) { //Check address to make sure forces are computed only once per pair if(&neigh->p[iparNeigh % PARTICLES_PER_CELL] < &cell->p[ipar % PARTICLES_PER_CELL]) { Vec3 disp = cell->p[ipar % PARTICLES_PER_CELL] - neigh->p[iparNeigh % PARTICLES_PER_CELL]; fptype distSq = disp.GetLengthSq(); if(distSq < hSq) { #ifndef ENABLE_DOUBLE_PRECISION fptype dist = sqrtf(std::max(distSq, (fptype)1e-12)); #else fptype dist = sqrt(std::max(distSq, 1e-12)); #endif //ENABLE_DOUBLE_PRECISION fptype hmr = h - dist; Vec3 acc = disp * pressureCoeff * (hmr*hmr/dist) * (cell->density[ipar % PARTICLES_PER_CELL]+neigh->density[iparNeigh % PARTICLES_PER_CELL] - doubleRestDensity); acc += (neigh->v[iparNeigh % PARTICLES_PER_CELL] - cell->v[ipar % PARTICLES_PER_CELL]) * viscosityCoeff * hmr; acc /= cell->density[ipar % PARTICLES_PER_CELL] * neigh->density[iparNeigh % PARTICLES_PER_CELL]; if( border[index]) { pthread_mutex_lock(&mutex[index][ipar % MUTEXES_PER_CELL]); cell->a[ipar % PARTICLES_PER_CELL] += acc; pthread_mutex_unlock(&mutex[index][ipar % MUTEXES_PER_CELL]); } else cell->a[ipar % PARTICLES_PER_CELL] += acc; if( border[indexNeigh]) { pthread_mutex_lock(&mutex[indexNeigh][iparNeigh % MUTEXES_PER_CELL]); neigh->a[iparNeigh % PARTICLES_PER_CELL] -= acc; pthread_mutex_unlock(&mutex[indexNeigh][iparNeigh % MUTEXES_PER_CELL]); } else neigh->a[iparNeigh % PARTICLES_PER_CELL] -= acc; } } //move pointer to next cell in list if end of array is reached if(iparNeigh % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { neigh = neigh->next; } } } //move pointer to next cell in list if end of array is reached if(ipar % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// // ProcessCollisions() with container walls // Under the assumptions that // a) a particle will not penetrate a wall // b) a particle will not migrate further than once cell // c) the parSize is smaller than a cell // then only the particles at the perimiters may be influenced by the walls #if 0 void ProcessCollisionsMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { Vec3 pos = cell->p[j % PARTICLES_PER_CELL] + cell->hv[j % PARTICLES_PER_CELL] * timeStep; fptype diff = parSize - (pos.x - domainMin.x); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].x += stiffnessCollisions*diff - damping*cell->v[j % PARTICLES_PER_CELL].x; diff = parSize - (domainMax.x - pos.x); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].x -= stiffnessCollisions*diff + damping*cell->v[j % PARTICLES_PER_CELL].x; diff = parSize - (pos.y - domainMin.y); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].y += stiffnessCollisions*diff - damping*cell->v[j % PARTICLES_PER_CELL].y; diff = parSize - (domainMax.y - pos.y); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].y -= stiffnessCollisions*diff + damping*cell->v[j % PARTICLES_PER_CELL].y; diff = parSize - (pos.z - domainMin.z); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].z += stiffnessCollisions*diff - damping*cell->v[j % PARTICLES_PER_CELL].z; diff = parSize - (domainMax.z - pos.z); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].z -= stiffnessCollisions*diff + damping*cell->v[j % PARTICLES_PER_CELL].z; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } #else void ProcessCollisionsMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) { for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) { for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { if(!((ix==0)||(iy==0)||(iz==0)||(ix==(nx-1))||(iy==(ny-1))==(iz==(nz-1)))) continue; // not on domain wall int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { int ji = j % PARTICLES_PER_CELL; Vec3 pos = cell->p[ji] + cell->hv[ji] * timeStep; if(ix==0) { fptype diff = parSize - (pos.x - domainMin.x); if(diff > epsilon) cell->a[ji].x += stiffnessCollisions*diff - damping*cell->v[ji].x; } if(ix==(nx-1)) { fptype diff = parSize - (domainMax.x - pos.x); if(diff > epsilon) cell->a[ji].x -= stiffnessCollisions*diff + damping*cell->v[ji].x; } if(iy==0) { fptype diff = parSize - (pos.y - domainMin.y); if(diff > epsilon) cell->a[ji].y += stiffnessCollisions*diff - damping*cell->v[ji].y; } if(iy==(ny-1)) { fptype diff = parSize - (domainMax.y - pos.y); if(diff > epsilon) cell->a[ji].y -= stiffnessCollisions*diff + damping*cell->v[ji].y; } if(iz==0) { fptype diff = parSize - (pos.z - domainMin.z); if(diff > epsilon) cell->a[ji].z += stiffnessCollisions*diff - damping*cell->v[ji].z; } if(iz==(nz-1)) { fptype diff = parSize - (domainMax.z - pos.z); if(diff > epsilon) cell->a[ji].z -= stiffnessCollisions*diff + damping*cell->v[ji].z; } //move pointer to next cell in list if end of array is reached if(ji == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } } } #endif #define USE_ImpeneratableWall #if defined(USE_ImpeneratableWall) void ProcessCollisions2MT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) { for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) { for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { #if 0 // Chris, the following test should be valid // *** provided that a particle does not migrate more than 1 cell // *** per integration step. This does not appear to be the case // *** in the pthreads version. Serial version it seems to be OK if(!((ix==0)||(iy==0)||(iz==0)||(ix==(nx-1))||(iy==(ny-1))==(iz==(nz-1)))) continue; // not on domain wall #endif int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { int ji = j % PARTICLES_PER_CELL; Vec3 pos = cell->p[ji]; if(ix==0) { fptype diff = pos.x - domainMin.x; if(diff < Zero) { cell->p[ji].x = domainMin.x - diff; cell->v[ji].x = -cell->v[ji].x; cell->hv[ji].x = -cell->hv[ji].x; } } if(ix==(nx-1)) { fptype diff = domainMax.x - pos.x; if(diff < Zero) { cell->p[ji].x = domainMax.x + diff; cell->v[ji].x = -cell->v[ji].x; cell->hv[ji].x = -cell->hv[ji].x; } } if(iy==0) { fptype diff = pos.y - domainMin.y; if(diff < Zero) { cell->p[ji].y = domainMin.y - diff; cell->v[ji].y = -cell->v[ji].y; cell->hv[ji].y = -cell->hv[ji].y; } } if(iy==(ny-1)) { fptype diff = domainMax.y - pos.y; if(diff < Zero) { cell->p[ji].y = domainMax.y + diff; cell->v[ji].y = -cell->v[ji].y; cell->hv[ji].y = -cell->hv[ji].y; } } if(iz==0) { fptype diff = pos.z - domainMin.z; if(diff < Zero) { cell->p[ji].z = domainMin.z - diff; cell->v[ji].z = -cell->v[ji].z; cell->hv[ji].z = -cell->hv[ji].z; } } if(iz==(nz-1)) { fptype diff = domainMax.z - pos.z; if(diff < Zero) { cell->p[ji].z = domainMax.z + diff; cell->v[ji].z = -cell->v[ji].z; cell->hv[ji].z = -cell->hv[ji].z; } } //move pointer to next cell in list if end of array is reached if(ji == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } } } #endif //////////////////////////////////////////////////////////////////////////////// void AdvanceParticlesMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { Vec3 v_half = cell->hv[j % PARTICLES_PER_CELL] + cell->a[j % PARTICLES_PER_CELL]*timeStep; #if defined(USE_ImpeneratableWall) // N.B. The integration of the position can place the particle // outside the domain. Although we could place a test in this loop // we would be unnecessarily testing particles on interior cells. // Therefore, to reduce the amount of computations we make a later // pass on the perimiter cells to account for particle migration // beyond domain #endif cell->p[j % PARTICLES_PER_CELL] += v_half * timeStep; cell->v[j % PARTICLES_PER_CELL] = cell->hv[j % PARTICLES_PER_CELL] + v_half; cell->v[j % PARTICLES_PER_CELL] *= 0.5; cell->hv[j % PARTICLES_PER_CELL] = v_half; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// void AdvanceFrameMT(int tid) { //swap src and dest arrays with particles if(tid==0) { std::swap(cells, cells2); std::swap(cnumPars, cnumPars2); } pthread_barrier_wait(&barrier); ClearParticlesMT(tid); pthread_barrier_wait(&barrier); RebuildGridMT(tid); pthread_barrier_wait(&barrier); InitDensitiesAndForcesMT(tid); pthread_barrier_wait(&barrier); ComputeDensitiesMT(tid); pthread_barrier_wait(&barrier); ComputeDensities2MT(tid); pthread_barrier_wait(&barrier); ComputeForcesMT(tid); pthread_barrier_wait(&barrier); ProcessCollisionsMT(tid); pthread_barrier_wait(&barrier); AdvanceParticlesMT(tid); pthread_barrier_wait(&barrier); #if defined(USE_ImpeneratableWall) // N.B. The integration of the position can place the particle // outside the domain. We now make a pass on the perimiter cells // to account for particle migration beyond domain. ProcessCollisions2MT(tid); pthread_barrier_wait(&barrier); #endif } #ifndef ENABLE_VISUALIZATION void *AdvanceFramesMT(void *args) { thread_args *targs = (thread_args *)args; for(int i = 0; i < targs->frames; ++i) { AdvanceFrameMT(targs->tid); } return NULL; } #else //Frame advancement function for worker threads void *AdvanceFramesMT(void *args) { thread_args *targs = (thread_args *)args; #if 1 while(1) #else for(int i = 0; i < targs->frames; ++i) #endif { pthread_barrier_wait(&visualization_barrier); //Phase 1: Compute frame, visualization code blocked AdvanceFrameMT(targs->tid); pthread_barrier_wait(&visualization_barrier); //Phase 2: Visualize, worker threads blocked } return NULL; } //Frame advancement function for master thread (executes serial visualization code) void AdvanceFrameVisualization() { //End of phase 2: Worker threads blocked, visualization code busy (last frame) pthread_barrier_wait(&visualization_barrier); //Phase 1: Visualization thread blocked, worker threads busy (next frame) pthread_barrier_wait(&visualization_barrier); //Begin of phase 2: Worker threads blocked, visualization code busy (next frame) } #endif //ENABLE_VISUALIZATION //////////////////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { #ifdef PARSEC_VERSION #define __PARSEC_STRING(x) #x #define __PARSEC_XSTRING(x) __PARSEC_STRING(x) std::cout << "PARSEC Benchmark Suite Version "__PARSEC_XSTRING(PARSEC_VERSION) << std::endl << std::flush; #else std::cout << "PARSEC Benchmark Suite" << std::endl << std::flush; #endif //PARSEC_VERSION #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_begin(__parsec_fluidanimate); #endif if(argc < 4 || argc >= 6) { std::cout << "Usage: " << argv[0] << " <threadnum> <framenum> <.fluid input file> [.fluid output file]" << std::endl; return -1; } int threadnum = atoi(argv[1]); int framenum = atoi(argv[2]); //Check arguments if(threadnum < 1) { std::cerr << "<threadnum> must at least be 1" << std::endl; return -1; } if(framenum < 1) { std::cerr << "<framenum> must at least be 1" << std::endl; return -1; } #ifdef ENABLE_CFL_CHECK std::cout << "WARNING: Check for Courant–Friedrichs–Lewy condition enabled. Do not use for performance measurements." << std::endl; #endif InitSim(argv[3], threadnum); #ifdef ENABLE_VISUALIZATION InitVisualizationMode(&argc, argv, &AdvanceFrameVisualization, &numCells, &cells, &cnumPars); #endif #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_begin(); #endif #if defined(WIN32) thread_args* targs = (thread_args*)alloca(sizeof(thread_args)*threadnum); #else thread_args targs[threadnum]; #endif for(int i = 0; i < threadnum; ++i) { targs[i].tid = i; targs[i].frames = framenum; pthread_create(&thread[i], &attr, AdvanceFramesMT, &targs[i]); } // *** PARALLEL PHASE *** // #ifdef ENABLE_VISUALIZATION Visualize(); #endif for(int i = 0; i < threadnum; ++i) { pthread_join(thread[i], NULL); } #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_end(); #endif if(argc > 4) SaveFile(argv[4]); CleanUpSim(); #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_end(); #endif return 0; } ////////////////////////////////////////////////////////////////////////////////
33.445227
179
0.563624
mariobadr
8d736a42ca153192fb308eac032136f93f9f8d9b
4,668
cpp
C++
src/GuiLayout.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
14
2020-06-27T18:51:41.000Z
2022-03-30T18:20:02.000Z
src/GuiLayout.cpp
codenamecpp/GLKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
1
2020-06-07T09:48:11.000Z
2020-06-07T09:48:11.000Z
src/GuiLayout.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
2
2020-08-27T09:38:10.000Z
2021-08-12T01:17:30.000Z
#include "pch.h" #include "GuiLayout.h" #include "GuiWidget.h" GuiLayout::GuiLayout() : mOrientation(eGuiLayoutOrientation_Horizontal) , mCols(1) , mRows(1) , mSpacingHorz() , mSpacingVert() , mPaddingL() , mPaddingT() , mPaddingR() , mPaddingB() , mLayoutType(eGuiLayout_None) { } void GuiLayout::LoadProperties(cxx::json_node_object documentNode) { cxx::json_get_attribute(documentNode, "type", mLayoutType); cxx::json_get_attribute(documentNode, "orientation", mOrientation); if (cxx::json_get_attribute(documentNode, "num_cols", mCols)) { if (mCols < 1) { debug_assert(false); mCols = 1; } } if (cxx::json_get_attribute(documentNode, "num_rows", mRows)) { if (mRows < 1) { debug_assert(false); mRows = 1; } } if (cxx::json_node_object spacingNode = documentNode["spacing"]) { cxx::json_get_attribute(spacingNode, "horz", mSpacingHorz); cxx::json_get_attribute(spacingNode, "vert", mSpacingVert); } if (cxx::json_node_object paddingNode = documentNode["padding"]) { cxx::json_get_attribute(paddingNode, "left", mPaddingL); cxx::json_get_attribute(paddingNode, "top", mPaddingT); cxx::json_get_attribute(paddingNode, "bottom", mPaddingB); cxx::json_get_attribute(paddingNode, "right", mPaddingR); } } void GuiLayout::Clear() { mLayoutType = eGuiLayout_None; mOrientation = eGuiLayoutOrientation_Horizontal; mCols = 1; mRows = 1; mSpacingHorz = 0; mSpacingVert = 0; mPaddingL = 0; mPaddingT = 0; mPaddingR = 0; mPaddingB = 0; } void GuiLayout::SetOrientation(eGuiLayoutOrientation orientation) { if (orientation == mOrientation) return; mOrientation = orientation; } void GuiLayout::SetColsCount(int numCols) { if (numCols < 1) numCols = 1; if (numCols == mCols) return; mCols = numCols; } void GuiLayout::SetRowsCount(int numRows) { if (numRows < 1) numRows = 1; if (numRows == mRows) return; mRows = numRows; } void GuiLayout::SetSpacing(int spacingHorz, int spacingVert) { if (mSpacingHorz == spacingHorz && mSpacingVert == spacingVert) return; mSpacingHorz = spacingHorz; mSpacingVert = spacingVert; } void GuiLayout::SetPadding(int paddingL, int paddingT, int paddingR, int paddingB) { if (mPaddingB == paddingB && mPaddingL == paddingL && mPaddingR == paddingR && mPaddingT == paddingT) { return; } mPaddingB = paddingB; mPaddingL = paddingL; mPaddingR = paddingR; mPaddingT = paddingT; } void GuiLayout::LayoutSimpleGrid(GuiWidget* container) { Point currPos(mPaddingL, mPaddingT); int currIndex = 0; int currLineMaxElementSize = 0; const int maxElementsInLine = mOrientation == eGuiLayoutOrientation_Horizontal ? mCols : mRows; debug_assert(maxElementsInLine > 0); for (GuiWidget* curr_child = container->GetChild(); curr_child; curr_child = curr_child->NextSibling()) { if (!curr_child->IsVisible()) continue; curr_child->SetPosition(currPos); if (mOrientation == eGuiLayoutOrientation_Horizontal) { if (currLineMaxElementSize < curr_child->mSize.y) currLineMaxElementSize = curr_child->mSize.y; currPos.x += curr_child->mSize.x + mSpacingHorz; } else // vertical { if (currLineMaxElementSize < curr_child->mSize.x) currLineMaxElementSize = curr_child->mSize.x; currPos.y += curr_child->mSize.y + mSpacingVert; } if (++currIndex == maxElementsInLine) { if (mOrientation == eGuiLayoutOrientation_Horizontal) { currPos.x = mPaddingL; currPos.y += currLineMaxElementSize + mSpacingVert; } else // vertical { currPos.x += currLineMaxElementSize + mSpacingHorz; currPos.y = mPaddingT; } currLineMaxElementSize = 0; currIndex = 0; } } // for } void GuiLayout::LayoutElements(GuiWidget* container) { if (container == nullptr) { debug_assert(false); return; } switch (mLayoutType) { case eGuiLayout_SimpleGrid: LayoutSimpleGrid(container); break; } }
25.096774
99
0.591688
codenamecpp
8d740ee14c6eba58a6d514970a59c5e79e2c3b21
550
hpp
C++
src/AST/Statements/ProcedureCallStatement.hpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
src/AST/Statements/ProcedureCallStatement.hpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
src/AST/Statements/ProcedureCallStatement.hpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <memory> #include "Statement.hpp" #include <src/AST/Expressions/Expression.hpp> #include <src/AST/Expressions/ExpressionList.hpp> struct ProcedureCallStatement : Statement { std::string id; std::vector<std::shared_ptr<Expression>> args; ProcedureCallStatement(char *, ExpressionList *); ~ProcedureCallStatement() override = default; void print() const override; void fold_constants() override; void emit(SymbolTable &table, RegisterPool &pool) override; };
22.916667
63
0.732727
CarsonFox
8d7600502f946ed0f5cb6f0ce49cf39a1d62ff17
2,691
cpp
C++
src/viewlinecache.cpp
alexezh/trv
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
[ "MIT" ]
null
null
null
src/viewlinecache.cpp
alexezh/trv
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
[ "MIT" ]
2
2016-11-25T19:52:09.000Z
2017-04-15T14:49:52.000Z
src/viewlinecache.cpp
alexezh/trv
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
[ "MIT" ]
null
null
null
// Copyright (c) 2013 Alexandre Grigorovitch (alexezh@gmail.com). // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "stdafx.h" #include <strsafe.h> #include "traceapp.h" #include "viewlinecache.h" #include "js/apphost.h" ViewLineCache::ViewLineCache(IDispatchQueue* uiQueue, Js::IAppHost* host) { m_UiQueue = uiQueue; m_Host = host; } void ViewLineCache::SetCacheRange(DWORD dwStart, DWORD dwEnd) { if (m_Cache.GetItemCount() < 2000) return; m_Cache.ResetIfNot(dwStart, dwEnd); } bool ViewLineCache::ProcessNextLine(const std::function<std::unique_ptr<ViewLine>(DWORD)>& func) { DWORD idx; { std::lock_guard<std::mutex> guard(m_Lock); if (m_RequestedLines.size() == 0) return false; idx = m_RequestedLines.back(); auto& line = func(idx); m_Cache.Set(idx, std::move(line)); // remove line from list and map m_RequestedLines.pop_back(); m_RequestedMap.erase(idx); } m_UiQueue->Post([this, idx]() { if (!m_OnLineAvailable) return; m_OnLineAvailable(idx); }); return true; } const ViewLine* ViewLineCache::GetLine(DWORD idx) { std::lock_guard<std::mutex> guard(m_Lock); const ViewLine* line = nullptr; if(idx < m_Cache.GetSize()) line = m_Cache.GetAt(idx).get(); if (line == nullptr && m_RequestedMap.find(idx) == m_RequestedMap.end()) { m_RequestedLines.push_back(idx); m_RequestedMap.insert(idx); m_Host->RequestViewLine(); } return line; } void ViewLineCache::RegisterLineAvailableListener(const LiveAvailableHandler& handler) { m_OnLineAvailable = handler; } void ViewLineCache::Resize(size_t n) { m_Cache.Resize(n); } void ViewLineCache::Reset() { m_Cache.ResetIfNot(-1, -1); }
26.126214
96
0.733928
alexezh
8d76ce6d49188f6daad29d6f68a26819f056b6c3
1,087
hpp
C++
missions/_missions1/dcg.takistan/cfgParams.hpp
ademirt/Arma3
f75c28f59deb45e56d021d9d1d3458b145432bd8
[ "MIT" ]
null
null
null
missions/_missions1/dcg.takistan/cfgParams.hpp
ademirt/Arma3
f75c28f59deb45e56d021d9d1d3458b145432bd8
[ "MIT" ]
null
null
null
missions/_missions1/dcg.takistan/cfgParams.hpp
ademirt/Arma3
f75c28f59deb45e56d021d9d1d3458b145432bd8
[ "MIT" ]
null
null
null
/* Types (SCALAR, BOOL, SIDE) */ class dcg_main_debug { title = "Debug Mode"; values[] = {0,1}; texts[] = {"Off", "On"}; default = 0; setParam = 1; typeName = ""; }; class dcg_main_loadData { title = "Load Mission Data"; values[] = {0,1}; texts[] = {"Off", "On"}; default = 1; setParam = 1; typeName = "BOOL"; }; class dcg_main_enemySide { title = "Enemy Side"; values[] = {0,2}; texts[] = {"East", "Independent"}; default = 0; setParam = 1; typeName = "SIDE"; }; class dcg_mission_disableCam { title = "Disable Third Person Camera"; values[] = {0,1}; texts[] = {"Off", "On"}; default = 0; setParam = 1; typeName = "BOOL"; }; class dcg_weather_season { title = "Season"; values[] = {-1,0,1,2,3}; texts[] = {"Random","Summer","Fall","Winter","Spring"}; default = -1; setParam = 1; typeName = ""; }; class dcg_weather_time { title = "Time of Day"; values[] = {-1,0,1,2,3}; texts[] = {"Random","Morning","Midday","Evening","Night"}; default = 0; setParam = 1; typeName = ""; };
20.903846
61
0.543698
ademirt
8d7711a46890e79e299c6f3a5a3576b8420c06a6
2,153
hpp
C++
modules/kvm/include/virt86/kvm/kvm_platform.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
148
2019-02-19T11:05:28.000Z
2022-02-26T11:57:05.000Z
modules/kvm/include/virt86/kvm/kvm_platform.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
16
2019-02-19T02:51:48.000Z
2019-12-11T21:17:12.000Z
modules/kvm/include/virt86/kvm/kvm_platform.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
17
2019-02-19T04:05:33.000Z
2021-05-02T12:14:13.000Z
/* Declares the implementation class for the KVM hypervisor platform adapter. Include this file to use KVM as a platform. The platform instance is exposed as a singleton: auto& instance = virt86::kvm::KvmPlatform::Instance(); ------------------------------------------------------------------------------- MIT License Copyright (c) 2019 Ivan Roberto de Oliveira 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 "virt86/platform/platform.hpp" namespace virt86::kvm { class KvmPlatform : public Platform { public: ~KvmPlatform() noexcept final; // Prevent copy construction and copy assignment KvmPlatform(const KvmPlatform&) = delete; KvmPlatform& operator=(const KvmPlatform&) = delete; // Prevent move construction and move assignment KvmPlatform(KvmPlatform&&) = delete; KvmPlatform&& operator=(KvmPlatform&&) = delete; // Disallow taking the address KvmPlatform *operator&() = delete; static KvmPlatform& Instance() noexcept; protected: std::unique_ptr<VirtualMachine> CreateVMImpl(const VMSpecifications& specifications) override; private: KvmPlatform() noexcept; int m_fd; }; }
34.174603
98
0.739898
dmiller423
8d779bfbd4330c55301b272fca2090606cc1782d
8,244
cc
C++
sandbox/win/src/lpc_policy_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
sandbox/win/src/lpc_policy_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
sandbox/win/src/lpc_policy_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// 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. // These tests have been added to specifically tests issues arising from (A)LPC // lock down. #include <algorithm> #include <cctype> #include <windows.h> #include <winioctl.h> #include "base/win/windows_version.h" #include "build/build_config.h" #include "sandbox/win/src/heap_helper.h" #include "sandbox/win/src/sandbox.h" #include "sandbox/win/src/sandbox_factory.h" #include "sandbox/win/src/sandbox_policy.h" #include "sandbox/win/tests/common/controller.h" #include "sandbox/win/tests/common/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace sandbox { namespace { bool CsrssDisconnectSupported() { // This functionality has not been verified on versions before Win10. if (base::win::GetVersion() < base::win::Version::WIN10) return false; // Does not work on 32-bit on x64 (ie Wow64). return (base::win::OSInfo::GetInstance()->wow64_status() != base::win::OSInfo::WOW64_ENABLED); } } // namespace // Converts LCID to std::wstring for passing to sbox tests. std::wstring LcidToWString(LCID lcid) { wchar_t buff[10] = {0}; int res = swprintf_s(buff, sizeof(buff) / sizeof(buff[0]), L"%08x", lcid); if (-1 != res) { return std::wstring(buff); } return std::wstring(); } // Converts LANGID to std::wstring for passing to sbox tests. std::wstring LangidToWString(LANGID langid) { wchar_t buff[10] = {0}; int res = swprintf_s(buff, sizeof(buff) / sizeof(buff[0]), L"%04x", langid); if (-1 != res) { return std::wstring(buff); } return std::wstring(); } SBOX_TESTS_COMMAND int Lpc_GetUserDefaultLangID(int argc, wchar_t** argv) { if (argc != 1) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; std::wstring expected_langid_string(argv[0]); // This will cause an exception if not warmed up suitably. LANGID langid = ::GetUserDefaultLangID(); std::wstring langid_string = LangidToWString(langid); if (0 == wcsncmp(langid_string.c_str(), expected_langid_string.c_str(), 4)) { return SBOX_TEST_SUCCEEDED; } return SBOX_TEST_FAILED; } TEST(LpcPolicyTest, GetUserDefaultLangID) { LANGID langid = ::GetUserDefaultLangID(); std::wstring cmd = L"Lpc_GetUserDefaultLangID " + LangidToWString(langid); TestRunner runner; EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(cmd.c_str())); } SBOX_TESTS_COMMAND int Lpc_GetUserDefaultLCID(int argc, wchar_t** argv) { if (argc != 1) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; std::wstring expected_lcid_string(argv[0]); // This will cause an exception if not warmed up suitably. LCID lcid = ::GetUserDefaultLCID(); std::wstring lcid_string = LcidToWString(lcid); if (0 == wcsncmp(lcid_string.c_str(), expected_lcid_string.c_str(), 8)) { return SBOX_TEST_SUCCEEDED; } return SBOX_TEST_FAILED; } TEST(LpcPolicyTest, GetUserDefaultLCID) { LCID lcid = ::GetUserDefaultLCID(); std::wstring cmd = L"Lpc_GetUserDefaultLCID " + LcidToWString(lcid); TestRunner runner; EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(cmd.c_str())); } // GetUserDefaultLocaleName is not available on WIN XP. So we'll // load it on-the-fly. const wchar_t kKernel32DllName[] = L"kernel32.dll"; typedef int(WINAPI* GetUserDefaultLocaleNameFunction)(LPWSTR lpLocaleName, int cchLocaleName); SBOX_TESTS_COMMAND int Lpc_GetUserDefaultLocaleName(int argc, wchar_t** argv) { if (argc != 1) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; std::wstring expected_locale_name(argv[0]); static GetUserDefaultLocaleNameFunction GetUserDefaultLocaleName_func = nullptr; if (!GetUserDefaultLocaleName_func) { // GetUserDefaultLocaleName is not available on WIN XP. So we'll // load it on-the-fly. HMODULE kernel32_dll = ::GetModuleHandle(kKernel32DllName); if (!kernel32_dll) { return SBOX_TEST_FAILED; } GetUserDefaultLocaleName_func = reinterpret_cast<GetUserDefaultLocaleNameFunction>( GetProcAddress(kernel32_dll, "GetUserDefaultLocaleName")); if (!GetUserDefaultLocaleName_func) { return SBOX_TEST_FAILED; } } wchar_t locale_name[LOCALE_NAME_MAX_LENGTH] = {0}; // This will cause an exception if not warmed up suitably. int ret = GetUserDefaultLocaleName_func( locale_name, LOCALE_NAME_MAX_LENGTH * sizeof(wchar_t)); if (!ret) { return SBOX_TEST_FAILED; } if (!wcsnlen(locale_name, LOCALE_NAME_MAX_LENGTH)) { return SBOX_TEST_FAILED; } if (0 == wcsncmp(locale_name, expected_locale_name.c_str(), LOCALE_NAME_MAX_LENGTH)) { return SBOX_TEST_SUCCEEDED; } return SBOX_TEST_FAILED; } TEST(LpcPolicyTest, GetUserDefaultLocaleName) { static GetUserDefaultLocaleNameFunction GetUserDefaultLocaleName_func = nullptr; if (!GetUserDefaultLocaleName_func) { // GetUserDefaultLocaleName is not available on WIN XP. So we'll // load it on-the-fly. HMODULE kernel32_dll = ::GetModuleHandle(kKernel32DllName); EXPECT_NE(nullptr, kernel32_dll); GetUserDefaultLocaleName_func = reinterpret_cast<GetUserDefaultLocaleNameFunction>( GetProcAddress(kernel32_dll, "GetUserDefaultLocaleName")); EXPECT_NE(nullptr, GetUserDefaultLocaleName_func); } wchar_t locale_name[LOCALE_NAME_MAX_LENGTH] = {0}; EXPECT_NE(0, GetUserDefaultLocaleName_func( locale_name, LOCALE_NAME_MAX_LENGTH * sizeof(wchar_t))); EXPECT_NE(0U, wcsnlen(locale_name, LOCALE_NAME_MAX_LENGTH)); std::wstring cmd = L"Lpc_GetUserDefaultLocaleName " + std::wstring(locale_name); TestRunner runner; EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(cmd.c_str())); } // Closing ALPC port can invalidate its heap. // Test that all heaps are valid. SBOX_TESTS_COMMAND int Lpc_TestValidProcessHeaps(int argc, wchar_t** argv) { if (argc != 0) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; // Retrieves the number of heaps in the current process. DWORD number_of_heaps = ::GetProcessHeaps(0, nullptr); // Try to retrieve a handle to all the heaps owned by this process. Returns // false if the number of heaps has changed. // // This is inherently racy as is, but it's not something that we observe a lot // in Chrome, the heaps tend to be created at startup only. std::unique_ptr<HANDLE[]> all_heaps(new HANDLE[number_of_heaps]); if (::GetProcessHeaps(number_of_heaps, all_heaps.get()) != number_of_heaps) return SBOX_TEST_FIRST_ERROR; for (size_t i = 0; i < number_of_heaps; ++i) { HANDLE handle = all_heaps[i]; ULONG HeapInformation; bool result = HeapQueryInformation(handle, HeapCompatibilityInformation, &HeapInformation, sizeof(HeapInformation), nullptr); if (!result) return SBOX_TEST_SECOND_ERROR; } return SBOX_TEST_SUCCEEDED; } TEST(LpcPolicyTest, TestValidProcessHeaps) { TestRunner runner; EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Lpc_TestValidProcessHeaps")); } // All processes should have a shared heap with csrss.exe. This test ensures // that this heap can be found. TEST(LpcPolicyTest, TestCanFindCsrPortHeap) { if (!CsrssDisconnectSupported()) { return; } HANDLE csr_port_handle = sandbox::FindCsrPortHeap(); EXPECT_NE(nullptr, csr_port_handle); } // Fails on Windows ARM64: https://crbug.com/905328 #if defined(ARCH_CPU_ARM64) #define MAYBE_TestHeapFlags DISABLED_TestHeapFlags #else #define MAYBE_TestHeapFlags TestHeapFlags #endif TEST(LpcPolicyTest, MAYBE_TestHeapFlags) { if (!CsrssDisconnectSupported()) { // This functionality has not been verified on versions before Win10. return; } // Windows does not support callers supplying arbritary flag values. So we // write some non-trivial value to reduce the chance we match this in random // data. DWORD flags = 0x41007; HANDLE heap = HeapCreate(flags, 0, 0); EXPECT_NE(nullptr, heap); DWORD actual_flags = 0; EXPECT_TRUE(sandbox::HeapFlags(heap, &actual_flags)); EXPECT_EQ(flags, actual_flags); EXPECT_TRUE(HeapDestroy(heap)); } } // namespace sandbox
34.78481
80
0.724648
sarang-apps
8d78a7cbedccd8599f2906804066cfde7f4782a4
553
cpp
C++
gamma/system/packed_data.cpp
mbellman/gamma
a11a15492366682c2aec0a4570c6d091a83fe632
[ "Unlicense" ]
null
null
null
gamma/system/packed_data.cpp
mbellman/gamma
a11a15492366682c2aec0a4570c6d091a83fe632
[ "Unlicense" ]
null
null
null
gamma/system/packed_data.cpp
mbellman/gamma
a11a15492366682c2aec0a4570c6d091a83fe632
[ "Unlicense" ]
null
null
null
#include "system/packed_data.h" #include "system/type_aliases.h" #define CLAMP(f) (f < 0.0f ? 0.0f : f > 1.0f ? 1.0f : f) namespace Gamma { /** * pVec4 * ----- */ pVec4::pVec4(const Vec3f& value) { r = uint8(CLAMP(value.x) * 255.0f); g = uint8(CLAMP(value.y) * 255.0f); b = uint8(CLAMP(value.z) * 255.0f); a = 255; } pVec4::pVec4(const Vec4f& value) { r = uint8(CLAMP(value.x) * 255.0f); g = uint8(CLAMP(value.y) * 255.0f); b = uint8(CLAMP(value.z) * 255.0f); a = uint8(CLAMP(value.w) * 255.0f); } }
23.041667
56
0.551537
mbellman
8d7930c6c57473ce4bfd2a0f3acb576cb0a0a2b0
6,468
cpp
C++
serverS.cpp
ksuryakrishna/Socket-Programming
03c8903f060a59f126156214da191799b0653ac1
[ "MIT" ]
null
null
null
serverS.cpp
ksuryakrishna/Socket-Programming
03c8903f060a59f126156214da191799b0653ac1
[ "MIT" ]
null
null
null
serverS.cpp
ksuryakrishna/Socket-Programming
03c8903f060a59f126156214da191799b0653ac1
[ "MIT" ]
null
null
null
/* ** serverS.cpp: - Creates a map of scores and names - Receives requests from the central and sends the scores to the central - Closes the socket - by Surya Krishna Kasiviswanathan, USC ID: 9083261716 */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <string> #include <map> #include <fstream> #include <cstring> using namespace std; #define MYPORT "22716" // the port users will be connecting to #define CENTRAL_PORT "24716" //the port S uses to connect to central #define MAXBUFLEN 512 int sockfd_binded, sockfd_to_central; struct addrinfo hints, *servinfo, *p; int rv; int numbytes; struct sockaddr_storage their_addr; char buf[MAXBUFLEN]; socklen_t addr_len; char s[INET6_ADDRSTRLEN]; string st1, st2; string file_name = "scores.txt"; map<string,int> m; //map created based on string as key and score as value int numVertices = 0, numVfromC = 0; //total no.of vertices int Vertno = 0; fstream fs(file_name); struct score_map{ //struct to convert map to struct to be sent to central int score_value; char names[512]; }obj_score[400]; struct numV{ //struct that stores the number of vertices in the graph sent int numstruct; }numobj; struct convert_map_to_struct{ //struct to store the map received int indexvalue; char names[512]; }obj[400]; // // get sockaddr, IPv4 or IPv6: // void *get_in_addr(struct sockaddr *sa) // { // if (sa->sa_family == AF_INET) { // return &(((struct sockaddr_in*)sa)->sin_addr); // } // return &(((struct sockaddr_in6*)sa)->sin6_addr); // } //function to connect to central through UDP socket and send the scores //snippets from Beej's guide is used here to establish connection and use sendto void Connect_to_Central_to_send_score(){ //add content of talker here memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; if ((rv = getaddrinfo("127.0.0.1", CENTRAL_PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return; } // loop through all the results and make a socket for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd_to_central = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("talker: socket"); continue; } break; } if (p == NULL) { fprintf(stderr, "talker: failed to create socket\n"); return; } //send map as struct objs for (auto x = 0; x < numVertices; x++){ if ((numbytes = sendto(sockfd_to_central, (char*) &obj_score[x], sizeof(score_map), 0, p->ai_addr, p->ai_addrlen)) == -1) { perror("talker: sendto"); exit(1); } for(int w = 0; w < 1000; w++); //delay to wait for other side to process // printf("talker: sent %d bytes to central\n", numbytes); } freeaddrinfo(servinfo); close(sockfd_to_central); } //function that receives the required from central //snippets from Beej's guide is used to recvfrom the central void Recv_from_central(){ addr_len = sizeof their_addr; if ((numbytes = recvfrom(sockfd_binded, (char*) &numobj, sizeof(numobj), 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } numVfromC = numobj.numstruct; // cout << "numobj.numstruct (numVertices) = "<<numVertices<<endl; // printf("listener: got packet from %s\n", // inet_ntop(their_addr.ss_family, // get_in_addr((struct sockaddr *)&their_addr), // s, sizeof s)); // printf("listener: packet is %d bytes long\n", numbytes); //get ready to receive the adjacency matrix and the map in the form of struct objects //get the map of nodes for(auto x = 0; x < numVfromC; x++){ addr_len = sizeof their_addr; if ((numbytes = recvfrom(sockfd_binded, (char*) &obj[x], sizeof(convert_map_to_struct), 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } } // cout<<"going to display received map \n"; // //sample display // for(auto x = 0; x<numVertices;x++){ // cout<<x<<": \t" <<obj[x].indexvalue<<" "<<obj[x].names<<endl; // } } //function that reads the contents of score.txt and forms a map based on the names and score void generate_score_map(){ while(fs>>st1){ //cout<<s<<endl; if(fs>>st2){ if(!m.count(st1)){ m.insert(make_pair(st1,stoi(st2))); } numVertices += 1; } } // //sample display map<string,int>::iterator i; // for(i=m.begin();i!=m.end();i++) { // cout<<i->first<<"\t"<<i->second<<endl; // } fs.close(); //add the map values on to a struct obj - total numVertices for(i=m.begin(); i!=m.end(), Vertno < numVertices; Vertno++, i++){ obj_score[Vertno].score_value = i->second; strcpy(obj_score[Vertno].names, i->first.c_str()); } // //sample display // for(Vertno = 0; Vertno < numVertices; Vertno++){ // cout<<obj_score[Vertno].score_value<<"\t"; // printf("%s\n",obj_score[Vertno].names); // } } // the main function // Snippets from Beej's guide are used for binding the UDP socket and listen int main(){ generate_score_map(); memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo("127.0.0.1", MYPORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd_binded = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("listener: socket"); continue; } if (bind(sockfd_binded, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd_binded); perror("listener: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "listener: failed to bind socket\n"); return 2; } freeaddrinfo(servinfo); printf("The ServerS is up and running using UDP on port 22716.\n"); while(1){ Recv_from_central(); // received the two usernames up until this point printf("The ServerS received a request from Central to get the scores.\n"); //send the score map Connect_to_Central_to_send_score(); printf("The ServerS finished sending the scores to Central.\n"); } return 1; }
26.4
92
0.655071
ksuryakrishna
8d7a0c4969e09c863b8e69d40d7da40793af029e
493
cpp
C++
digitanks/src/dtintro/main.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
5
2015-07-03T18:42:32.000Z
2017-08-25T10:28:12.000Z
digitanks/src/dtintro/main.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
digitanks/src/dtintro/main.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
#include "intro_window.h" extern tvector<Color> FullScreenShot(int& iWidth, int& iHeight); void CreateApplication(int argc, char** argv) { int iWidth, iHeight; tvector<Color> aclrScreenshot = FullScreenShot(iWidth, iHeight); CIntroWindow oWindow(argc, argv); oWindow.SetScreenshot(aclrScreenshot, iWidth, iHeight); oWindow.OpenWindow(); oWindow.SetupEngine(); oWindow.Run(); } int main(int argc, char** argv) { CreateApplicationWithErrorHandling(CreateApplication, argc, argv); }
22.409091
67
0.762677
BSVino
8d7c18984a43edbda71911ed108cf2c37a42bc24
2,892
cc
C++
test/tilehierarchy.cc
molind/valhalla
7d4cde8587d38fcb20f7a9ea9df34a8fc49bf68c
[ "BSD-2-Clause", "MIT" ]
79
2017-02-15T17:35:48.000Z
2022-03-30T06:16:10.000Z
test/tilehierarchy.cc
molind/valhalla
7d4cde8587d38fcb20f7a9ea9df34a8fc49bf68c
[ "BSD-2-Clause", "MIT" ]
null
null
null
test/tilehierarchy.cc
molind/valhalla
7d4cde8587d38fcb20f7a9ea9df34a8fc49bf68c
[ "BSD-2-Clause", "MIT" ]
12
2017-06-16T06:30:54.000Z
2021-12-16T00:43:12.000Z
#include "baldr/tilehierarchy.h" #include "baldr/graphid.h" #include "midgard/pointll.h" #include "test.h" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using namespace std; using namespace valhalla::baldr; using namespace valhalla::midgard; namespace { void test_parse() { if(TileHierarchy::levels().size() != 3) throw runtime_error("Incorrect number of hierarchy levels"); if((++TileHierarchy::levels().begin())->second.name != "arterial") throw runtime_error("Middle hierarchy should be named arterial"); if(TileHierarchy::levels().begin()->second.level != 0) throw runtime_error("Top hierarchy should have level 0"); if(TileHierarchy::levels().rbegin()->second.tiles.TileSize() != .25f) throw runtime_error("Bottom hierarchy should have tile size of .25f"); if(TileHierarchy::levels().find(5) != TileHierarchy::levels().end()) throw runtime_error("There should only be levels 0, 1, 2"); if(TileHierarchy::levels().find(2) == TileHierarchy::levels().end()) throw runtime_error("There should be a level 2"); GraphId id = TileHierarchy::GetGraphId(PointLL(0,0), 34); if(id.Is_Valid()) throw runtime_error("GraphId should be invalid as the level doesn't exist"); //there are 1440 cols and 720 rows, this spot lands on col 414 and row 522 id = TileHierarchy::GetGraphId(PointLL(-76.5, 40.5), 2); if(id.level() != 2 || id.tileid() != (522 * 1440) + 414 || id.id() != 0) throw runtime_error("Expected different graph id for this location"); if(TileHierarchy::levels().begin()->second.importance != RoadClass::kPrimary) throw runtime_error("Importance should be set to primary"); if((++TileHierarchy::levels().begin())->second.importance != RoadClass::kTertiary) throw runtime_error("Importance should be set to tertiary"); if(TileHierarchy::levels().rbegin()->second.importance != RoadClass::kServiceOther) throw runtime_error("Importance should be set to service/other"); } void test_tiles() { //there are 1440 cols and 720 rows, this spot lands on col 414 and row 522 AABB2<PointLL> bbox{{-76.49, 40.51}, {-76.48, 40.52}}; auto ids = TileHierarchy::GetGraphIds(bbox, 2); if (ids.size() != 1) { throw runtime_error("Should have only found one result."); } auto id = ids[0]; if (id.level() != 2 || id.tileid() != (522 * 1440) + 414 || id.id() != 0) { throw runtime_error("Didn't find correct tile ID."); } bbox = AABB2<PointLL>{{-76.51, 40.49}, {-76.49, 40.51}}; ids = TileHierarchy::GetGraphIds(bbox, 2); if (ids.size() != 4) { throw runtime_error("Should have found 4 results."); } } } int main(void) { test::suite suite("tilehierarchy"); suite.test(TEST_CASE(test_parse)); suite.test(TEST_CASE(test_tiles)); return suite.tear_down(); }
39.616438
87
0.667358
molind
8d7e5dfd75db551d178140dcaacb404d3444bc49
11,236
cpp
C++
installer/hachi_patch.cpp
LRFLEW/AM64DS_WiiU
37d4ada1d06a2b02d0ad82cd9b235018f6a25939
[ "Apache-2.0" ]
8
2021-11-02T04:07:37.000Z
2022-01-15T22:49:36.000Z
installer/hachi_patch.cpp
LRFLEW/AM64DS_WiiU
37d4ada1d06a2b02d0ad82cd9b235018f6a25939
[ "Apache-2.0" ]
null
null
null
installer/hachi_patch.cpp
LRFLEW/AM64DS_WiiU
37d4ada1d06a2b02d0ad82cd9b235018f6a25939
[ "Apache-2.0" ]
null
null
null
#include "hachi_patch.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstring> #include <numeric> #include <string> #include <string_view> #include <utility> #include <vector> #include <elf.h> #include "exception.hpp" #include "iosufsa.hpp" #include "log.hpp" #include "util.hpp" #include "zlib.hpp" #include "inject_bin.h" #include "inject_s.h" using namespace std::string_view_literals; namespace { constexpr Elf32_Half RPX_TYPE = 0xFE01; constexpr unsigned char RPX_ABI1 = 0xCA; constexpr unsigned char RPX_ABI2 = 0xFE; constexpr Elf32_Word RPX_CRCS = 0x80000003; constexpr std::uint32_t ZLIB_SECT = 0x08000000; constexpr std::string_view hachi_file = "/code/hachihachi_ntr.rpx"sv; constexpr std::uint32_t magic_amds = util::magic_const("AMDS"); static_assert(sizeof(Elf32_Ehdr) == 52); static_assert(sizeof(Elf32_Shdr) == 40); constexpr Elf32_Ehdr expected_ehdr = { { ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3, ELFCLASS32, ELFDATA2MSB, EV_CURRENT, RPX_ABI1, RPX_ABI2 }, RPX_TYPE, EM_PPC, EV_CURRENT, 0x02026798, 0x00, 0x40, 0, sizeof(Elf32_Ehdr), 0, 0, sizeof(Elf32_Shdr), 29, 26, }; constexpr std::array<std::uint32_t, expected_ehdr.e_shnum> expected_crcs = { 0x00000000, 0x14596B94, 0x165C39F2, 0xFA312336, 0x9BF039EE, 0xB3241733, 0x00000000, 0x60DA42CF, 0xEB7267F9, 0xF124402E, 0x01F80C21, 0x5E06092F, 0xD4CE0752, 0x72FA23E0, 0x940942DB, 0xBCFBF24D, 0x6B6574C9, 0x8D5FEDD5, 0x040E8EE3, 0xD5CEFF4A, 0xCFB2B47E, 0xE94CF6E0, 0x085C47BB, 0x279F690F, 0x598C85C9, 0x82F59D73, 0x2316975E, 0x00000000, 0x7D6C2996, }; bool good_layout(const std::vector<Elf32_Shdr> &shdr, const std::vector<std::size_t> &sorted) { std::uint32_t last_off = 0x40 + sizeof(Elf32_Shdr) * shdr.size(); for (std::size_t i : sorted) { const Elf32_Shdr &sect = shdr[i]; LOG("Check Header %d", i); if (sect.sh_offset - last_off >= 0x40) return false; last_off = sect.sh_offset + sect.sh_size; } return true; } bool decompress_sect(Elf32_Shdr &shdr, std::vector<std::uint8_t> &data) { if (!(shdr.sh_flags & ZLIB_SECT)) return true; if (shdr.sh_size != data.size()) return false; if (shdr.sh_size < 4) return false; std::uint32_t dec_len = *reinterpret_cast<const std::uint32_t *>(data.data()); LOG("Inflate"); data = Zlib::decompress(data, dec_len, true); shdr.sh_size = dec_len; shdr.sh_flags &= ~ZLIB_SECT; return true; } bool compress_sect(Elf32_Shdr &shdr, std::vector<std::uint8_t> &data) { if (shdr.sh_flags & ZLIB_SECT) return true; if (shdr.sh_size != data.size()) return false; std::vector<std::uint8_t> cmp; LOG("Deflate"); cmp = Zlib::compress(data, true); if (cmp.size() < data.size()) { shdr.sh_size = cmp.size(); data = std::move(cmp); shdr.sh_flags |= ZLIB_SECT; } return true; } void shift_for_resize(std::size_t resized, std::vector<Elf32_Shdr> &shdr, const std::vector<std::size_t> &sorted) { auto it = std::find(sorted.begin(), sorted.end(), resized); if (it == sorted.end()) return; Elf32_Shdr &resized_sect = shdr[*it]; std::uint32_t last_off = resized_sect.sh_offset + resized_sect.sh_size; for (++it; it != sorted.end(); ++it) { Elf32_Shdr &sect = shdr[*it]; sect.sh_offset = (last_off + 0x3F) & ~0x3F; last_off = sect.sh_offset + sect.sh_size; } } void make_b(std::vector<std::uint8_t> &data, std::size_t offset, std::size_t target) { std::uint32_t inst = (0x48000000 | (target - offset)) & 0xFFFFFFFC; *reinterpret_cast<std::uint32_t *>(data.data() + offset) = inst; } void make_u16(std::vector<std::uint8_t> &data, std::size_t offset, std::uint16_t value) { *reinterpret_cast<std::uint16_t *>(data.data() + offset) = value; } const std::uint8_t zero_pad[0x40] = { }; class HachiPatch : public Patch { public: HachiPatch(const IOSUFSA &fsa, std::string_view title) : fsa(fsa), path(util::concat_sv({ title, hachi_file })) { } virtual ~HachiPatch() override = default; virtual void Read() override { LOG("Open RPX"); IOSUFSA::File rpx(fsa); if (!rpx.open(path, "rb")) throw error("RPX: Read FileOpen"); LOG("Read Header"); if (!rpx.readall(&ehdr, sizeof(ehdr))) throw error("RPX: Read Header"); if (!util::memequal(ehdr, expected_ehdr)) throw error("RPX: Invalid Header"); LOG("Read Sections Table"); shdr.resize(ehdr.e_shnum); LOG("Read Sections Table - seek %X", ehdr.e_shoff); if (!rpx.seek(ehdr.e_shoff)) throw error("RPX: Seek Sections"); LOG("Read Sections Table - read"); if (!rpx.readall(shdr)) throw error("RPX: Read Sections"); LOG("Read Sections Table - done"); LOG("Get Sorted Sections"); sorted_sects.resize(ehdr.e_shnum); std::iota(sorted_sects.begin(), sorted_sects.end(), 0); sorted_sects.erase(std::remove_if(sorted_sects.begin(), sorted_sects.end(), [this](std::size_t i) -> bool { return shdr[i].sh_offset == 0; }), sorted_sects.end()); std::sort(sorted_sects.begin(), sorted_sects.end(), [this](std::size_t a, std::size_t b) -> bool { return shdr[a].sh_offset < shdr[b].sh_offset; }); LOG("Validate Sorted Sections"); if (!good_layout(shdr, sorted_sects)) throw error("RPX: Bad Layout"); sections.resize(ehdr.e_shnum); for (std::size_t i : sorted_sects) { if (shdr[i].sh_size > 0) { LOG("Read Section %d", i); sections[i].resize(shdr[i].sh_size); if (!rpx.seek(shdr[i].sh_offset)) throw error("RPX: Seek Sect"); if (!rpx.readall(sections[i])) throw error("RPX: Read Sect"); } } LOG("Close RPX"); if (!rpx.close()) throw error("RPX: Read CloseFile"); } virtual void Modify() override { Elf32_Shdr &text_hdr = shdr[2]; std::vector<std::uint8_t> &text = sections[2]; LOG("Decompress Text"); if (!decompress_sect(text_hdr, text)) throw error("RPX: Decompress Text"); LOG("Patch Loaded Text"); make_u16(text, 0x006CEA, 0x6710); make_b( text, 0x00CC1C, text.size() + off_inject_apply_angle - off_inject_start); make_b( text, 0x01DA28, text.size() + off_inject_comp_angle - off_inject_start); make_u16(text, 0x01DA42, 0x0018); // vpad->rstick.y offset make_u16(text, 0x01DAD2, 0x0014); // vpad->rstick.x offset make_u16(text, 0x03ED0E, 0x0BB0); make_b( text, 0x050938, text.size() + off_inject_init_angle - off_inject_start); make_b( text, 0x053F70, text.size() + off_inject_get_angle - off_inject_start); text.insert(text.end(), inject_bin, inject_bin_end); text_hdr.sh_size += inject_bin_size; LOG("CRC Calc"); std::uint32_t crc = Zlib::crc32(text); reinterpret_cast<std::uint32_t *>(sections[27].data())[2] = crc; LOG("Compress Text"); if (!compress_sect(text_hdr, text)) throw error("RPX: Compress Text"); LOG("Shift for Resize"); shift_for_resize(2, shdr, sorted_sects); } virtual void Write() override { LOG("Open RPX Write"); IOSUFSA::File rpx(fsa); if (!rpx.open(path, "wb")) throw error("RPX: Write FileOpen"); LOG("Write Header"); if (!rpx.writeall(&ehdr, sizeof(ehdr))) throw error("RPX: Write Header"); LOG("Write Pad"); if (!rpx.writeall(&magic_amds, sizeof(magic_amds))) throw error("RPX: Write Magic"); if (!rpx.writeall(zero_pad, ehdr.e_shoff - sizeof(ehdr) - sizeof(magic_amds))) throw error("RPX: Write ShPad"); LOG("Write Section Table"); if (!rpx.writeall(shdr)) throw error("RPX: Write Sections"); std::uint32_t last_off = 0x40 + sizeof(Elf32_Shdr) * shdr.size(); for (std::size_t i : sorted_sects) { if (shdr[i].sh_size > 0) { LOG("Write Section %d", i); const Elf32_Shdr &sect = shdr[i]; if (!rpx.writeall(zero_pad, sect.sh_offset - last_off)) throw error("RPX: Write StPad"); if (!rpx.writeall(sections[i])) throw error("RPX: Write Sect"); last_off = sect.sh_offset + sect.sh_size; } } if (!rpx.writeall(zero_pad, -last_off & 0x3F)) throw error("RPX: Write FlPad"); LOG("Close RPX Write"); if (!rpx.close()) throw error("RPX: Write FileClose"); } private: const IOSUFSA &fsa; std::string path; Elf32_Ehdr ehdr; std::vector<Elf32_Shdr> shdr; std::vector<std::size_t> sorted_sects; std::vector<std::vector<std::uint8_t>> sections; }; } #define ret(X) do { rpx.close(); return X; } while(0) Patch::Status hachi_check(const IOSUFSA &fsa, std::string_view title) { std::string rpx_path = util::concat_sv({ title, hachi_file }); LOG("Open RPX"); IOSUFSA::File rpx(fsa); if (!rpx.open(rpx_path, "rb")) ret(Patch::Status::MISSING_RPX); LOG("Read Header"); Elf32_Ehdr ehdr; if (!rpx.readall(&ehdr, sizeof(ehdr))) ret(Patch::Status::INVALID_RPX); if (!util::memequal(ehdr, expected_ehdr)) ret(Patch::Status::INVALID_RPX); LOG("Read Patch Signature"); std::uint32_t sig; if (!rpx.readall(&sig, sizeof(sig))) ret(Patch::Status::INVALID_RPX); if (sig == magic_amds) ret(Patch::Status::PATCHED); LOG("Read CRC Section Header"); Elf32_Shdr crc_shdr; if (!rpx.seek(ehdr.e_shoff + 27 * sizeof(Elf32_Shdr))) ret(Patch::Status::INVALID_RPX); if (!rpx.readall(&crc_shdr, sizeof(crc_shdr))) ret(Patch::Status::INVALID_RPX); if (crc_shdr.sh_type != RPX_CRCS) ret(Patch::Status::INVALID_RPX); if (crc_shdr.sh_size != sizeof(expected_crcs)) ret(Patch::Status::INVALID_RPX); LOG("Read CRC Data"); std::array<std::uint32_t, expected_ehdr.e_shnum> crcs; if (!rpx.seek(crc_shdr.sh_offset)) ret(Patch::Status::INVALID_RPX); if (!rpx.readall(&crcs, sizeof(crcs))) ret(Patch::Status::INVALID_RPX); if (!util::memequal(crcs, expected_crcs)) ret(Patch::Status::INVALID_RPX); LOG("HACHI GOOD"); ret(Patch::Status::RPX_ONLY); } std::unique_ptr<Patch> hachi_patch(const IOSUFSA &fsa, std::string_view title) { return std::make_unique<HachiPatch>(fsa, title); }
39.424561
99
0.590068
LRFLEW
8d82a5e8779fa9593eed9764ca39849885b44c95
7,924
cpp
C++
vcf/build/vc60/add-ins/COMToVCFClassWizard/Test/tmp/FilgraphManager.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
vcf/build/vc60/add-ins/COMToVCFClassWizard/Test/tmp/FilgraphManager.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
vcf/build/vc60/add-ins/COMToVCFClassWizard/Test/tmp/FilgraphManager.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
//FilgraphManager.cpp #include "QuartzTypeLib.h" #include "QuartzTypeLibInterfaces.h" #include "FilgraphManager.h" using namespace VCF; using namespace QuartzTypeLib; FilgraphManager::FilgraphManager() { } FilgraphManager::~FilgraphManager() { } void FilgraphManager::Run( ) { } void FilgraphManager::Pause( ) { } void FilgraphManager::Stop( ) { } void FilgraphManager::GetState( long msTimeout, long* pfs ) { } void FilgraphManager::RenderFile( BSTR strFilename ) { } void FilgraphManager::AddSourceFilter( BSTR strFilename, IDispatch** ppUnk ) { } IDispatch* FilgraphManager::getFilterCollection( ) { IDispatch* result; return result; } IDispatch* FilgraphManager::getRegFilterCollection( ) { IDispatch* result; return result; } void FilgraphManager::StopWhenReady( ) { } void FilgraphManager::GetEventHandle( LONG_PTR* hEvent ) { } void FilgraphManager::GetEvent( long* lEventCode, LONG_PTR* lParam1, LONG_PTR* lParam2, long msTimeout ) { } void FilgraphManager::WaitForCompletion( long msTimeout, long* pEvCode ) { } void FilgraphManager::CancelDefaultHandling( long lEvCode ) { } void FilgraphManager::RestoreDefaultHandling( long lEvCode ) { } void FilgraphManager::FreeEventParams( long lEvCode, LONG_PTR lParam1, LONG_PTR lParam2 ) { } double FilgraphManager::getDuration( ) { double result; return result; } void FilgraphManager::setCurrentPosition( double Val ) { } double FilgraphManager::getCurrentPosition( ) { double result; return result; } double FilgraphManager::getStopTime( ) { double result; return result; } void FilgraphManager::setStopTime( double Val ) { } double FilgraphManager::getPrerollTime( ) { double result; return result; } void FilgraphManager::setPrerollTime( double Val ) { } void FilgraphManager::setRate( double Val ) { } double FilgraphManager::getRate( ) { double result; return result; } long FilgraphManager::CanSeekForward( ) { } long FilgraphManager::CanSeekBackward( ) { } void FilgraphManager::setVolume( long Val ) { } long FilgraphManager::getVolume( ) { long result; return result; } void FilgraphManager::setBalance( long Val ) { } long FilgraphManager::getBalance( ) { long result; return result; } double FilgraphManager::getAvgTimePerFrame( ) { double result; return result; } long FilgraphManager::getBitRate( ) { long result; return result; } long FilgraphManager::getBitErrorRate( ) { long result; return result; } long FilgraphManager::getVideoWidth( ) { long result; return result; } long FilgraphManager::getVideoHeight( ) { long result; return result; } void FilgraphManager::setSourceLeft( long Val ) { } long FilgraphManager::getSourceLeft( ) { long result; return result; } void FilgraphManager::setSourceWidth( long Val ) { } long FilgraphManager::getSourceWidth( ) { long result; return result; } void FilgraphManager::setSourceTop( long Val ) { } long FilgraphManager::getSourceTop( ) { long result; return result; } void FilgraphManager::setSourceHeight( long Val ) { } long FilgraphManager::getSourceHeight( ) { long result; return result; } void FilgraphManager::setDestinationLeft( long Val ) { } long FilgraphManager::getDestinationLeft( ) { long result; return result; } void FilgraphManager::setDestinationWidth( long Val ) { } long FilgraphManager::getDestinationWidth( ) { long result; return result; } void FilgraphManager::setDestinationTop( long Val ) { } long FilgraphManager::getDestinationTop( ) { long result; return result; } void FilgraphManager::setDestinationHeight( long Val ) { } long FilgraphManager::getDestinationHeight( ) { long result; return result; } void FilgraphManager::SetSourcePosition( long Left, long Top, long Width, long Height ) { } void FilgraphManager::GetSourcePosition( long* pLeft, long* pTop, long* pWidth, long* pHeight ) { } void FilgraphManager::SetDefaultSourcePosition( ) { } void FilgraphManager::SetDestinationPosition( long Left, long Top, long Width, long Height ) { } void FilgraphManager::GetDestinationPosition( long* pLeft, long* pTop, long* pWidth, long* pHeight ) { } void FilgraphManager::SetDefaultDestinationPosition( ) { } void FilgraphManager::GetVideoSize( long* pWidth, long* pHeight ) { } void FilgraphManager::GetVideoPaletteEntries( long StartIndex, long Entries, long* pRetrieved, long* pPalette ) { } void FilgraphManager::GetCurrentImage( long* pBufferSize, long* pDIBImage ) { } void FilgraphManager::IsUsingDefaultSource( ) { } void FilgraphManager::IsUsingDefaultDestination( ) { } void FilgraphManager::setCaption( BSTR Val ) { } BSTR FilgraphManager::getCaption( ) { BSTR result; return result; } void FilgraphManager::setWindowStyle( long Val ) { } long FilgraphManager::getWindowStyle( ) { long result; return result; } void FilgraphManager::setWindowStyleEx( long Val ) { } long FilgraphManager::getWindowStyleEx( ) { long result; return result; } void FilgraphManager::setAutoShow( long Val ) { } long FilgraphManager::getAutoShow( ) { long result; return result; } void FilgraphManager::setWindowState( long Val ) { } long FilgraphManager::getWindowState( ) { long result; return result; } void FilgraphManager::setBackgroundPalette( long Val ) { } long FilgraphManager::getBackgroundPalette( ) { long result; return result; } void FilgraphManager::setVisible( long Val ) { } long FilgraphManager::getVisible( ) { long result; return result; } void FilgraphManager::setLeft( long Val ) { } long FilgraphManager::getLeft( ) { long result; return result; } void FilgraphManager::setWidth( long Val ) { } long FilgraphManager::getWidth( ) { long result; return result; } void FilgraphManager::setTop( long Val ) { } long FilgraphManager::getTop( ) { long result; return result; } void FilgraphManager::setHeight( long Val ) { } long FilgraphManager::getHeight( ) { long result; return result; } void FilgraphManager::setOwner( LONG_PTR Val ) { } LONG_PTR FilgraphManager::getOwner( ) { LONG_PTR result; return result; } void FilgraphManager::setMessageDrain( LONG_PTR Val ) { } LONG_PTR FilgraphManager::getMessageDrain( ) { LONG_PTR result; return result; } long FilgraphManager::getBorderColor( ) { long result; return result; } void FilgraphManager::setBorderColor( long Val ) { } long FilgraphManager::getFullScreenMode( ) { long result; return result; } void FilgraphManager::setFullScreenMode( long Val ) { } void FilgraphManager::SetWindowForeground( long Focus ) { } void FilgraphManager::NotifyOwnerMessage( LONG_PTR hwnd, long uMsg, LONG_PTR wParam, LONG_PTR lParam ) { } void FilgraphManager::SetWindowPosition( long Left, long Top, long Width, long Height ) { } void FilgraphManager::GetWindowPosition( long* pLeft, long* pTop, long* pWidth, long* pHeight ) { } void FilgraphManager::GetMinIdealImageSize( long* pWidth, long* pHeight ) { } void FilgraphManager::GetMaxIdealImageSize( long* pWidth, long* pHeight ) { } void FilgraphManager::GetRestorePosition( long* pLeft, long* pTop, long* pWidth, long* pHeight ) { } void FilgraphManager::HideCursor( long HideCursor ) { } void FilgraphManager::IsCursorHidden( long* CursorHidden ) { }
13.228715
112
0.675164
tharindusathis
8d838ece296a499f0a7e6ab06e5cb82f6a51d141
1,755
hpp
C++
psychic-ui/components/Button.hpp
WolfieWerewolf/psychic-ui
d67fc4871a3957cd16c15a42d9ed3e64b65f56bf
[ "MIT" ]
29
2018-01-31T04:58:35.000Z
2022-03-24T16:37:02.000Z
psychic-ui/components/Button.hpp
WolfieWerewolf/psychic-ui
d67fc4871a3957cd16c15a42d9ed3e64b65f56bf
[ "MIT" ]
2
2018-03-27T22:43:46.000Z
2022-03-25T14:09:32.000Z
psychic-ui/components/Button.hpp
WolfieWerewolf/psychic-ui
d67fc4871a3957cd16c15a42d9ed3e64b65f56bf
[ "MIT" ]
11
2017-08-28T16:36:49.000Z
2020-03-26T00:02:55.000Z
#pragma once #include <functional> #include <utility> #include "psychic-ui/psychic-ui.hpp" #include "psychic-ui/Component.hpp" #include "psychic-ui/Skin.hpp" #include "Label.hpp" namespace psychic_ui { class Button; class ButtonSkin : public Skin<Button> { public: ButtonSkin() : Skin<Button>() { setTag("ButtonSkin"); } virtual void setLabel(const std::string &/*label*/) {}; }; class Button : public Component<ButtonSkin> { public: Button(const std::string &label, ClickCallback onClick); explicit Button(const std::string &label = "") : Button(label, nullptr) {} explicit Button(const ClickCallback &onClick) : Button("", std::move(onClick)) {} const std::string &label() const; void setLabel(const std::string &label); bool toggle() const { return _toggle; } Button *setToggle(const bool toggle) { _toggle = toggle; return this; } bool autoToggle() const { return _autoToggle; } Button *setAutoToggle(const bool autoToggle) { _autoToggle = autoToggle; return this; } bool selected() const; Button *setSelected(bool selected); bool active() const override; Button *onChange(std::function<void(bool)> onChange) { _onChange = std::move(onChange); return this; } protected: std::string _label{}; bool _toggle{false}; bool _autoToggle{true}; bool _selected{false}; std::function<void(bool)> _onChange{nullptr}; void skinChanged() override; }; }
25.808824
89
0.565812
WolfieWerewolf
8d83e7a98ffa6b357a0aceb795764b3e31830639
3,002
cpp
C++
Tools/Common/Tool_Vertex.cpp
Cooolrik/BDR
2c2bda49259c37bb160daa0f18ac1c666643136f
[ "MIT" ]
1
2021-08-07T14:28:14.000Z
2021-08-07T14:28:14.000Z
Tools/Common/Tool_Vertex.cpp
Cooolrik/BDR
2c2bda49259c37bb160daa0f18ac1c666643136f
[ "MIT" ]
null
null
null
Tools/Common/Tool_Vertex.cpp
Cooolrik/BDR
2c2bda49259c37bb160daa0f18ac1c666643136f
[ "MIT" ]
null
null
null
#include "Tool_Vertex.h" typedef uint32_t uint; using std::vector; inline float clamp( float val, float low, float hi ) { if( val <= low ) return low; if( val >= hi ) return hi; return val; } inline int16_t normalizedFloatToInt16( float val ) { val = clamp( val, -1.f, 1.f ); val *= 32767.f; val = roundf( val ); return (int16_t)val; } inline float signLessThanZero( float val ) { return ( val < 0.f ) ? -1.0f : 1.0f; } inline float int16ToNormalizedFloat( int16_t val ) { float fval = float( val ); fval /= 32767.f; fval = clamp( fval, -1.f, 1.f ); return fval; } inline glm::vec3 octDecodeNormal( const int16_t encoded[2] ) { float x = int16ToNormalizedFloat( encoded[0] ); float y = int16ToNormalizedFloat( encoded[1] ); glm::vec3 n = glm::vec3( x, y, 1.f - fabs( x ) - fabs( y ) ); float t = glm::max( -n.z, 0.f ); n.x += ( n.x > 0.f ) ? -t : t; n.y += ( n.y > 0.f ) ? -t : t; return glm::normalize( n ); } inline glm::uint octEncodeNormal( const glm::vec3& normal ) { const float invL1Norm = ( 1.f ) / ( fabs( normal[0] ) + fabs( normal[1] ) + fabs( normal[2] ) ); int16_t encoded[2]; if( normal[2] < 0.f ) { encoded[0] = normalizedFloatToInt16( ( 1.f - fabs( normal[1] * invL1Norm ) ) * signLessThanZero( normal[0] ) ); encoded[1] = normalizedFloatToInt16( ( 1.f - fabs( normal[0] * invL1Norm ) ) * signLessThanZero( normal[1] ) ); } else { encoded[0] = normalizedFloatToInt16( normal[0] * invL1Norm ); encoded[1] = normalizedFloatToInt16( normal[1] * invL1Norm ); } // try a few encodning variants in the vicinity of the encoded vector // which might give a better result than the found vector uint32_t ret; int16_t* best_encoded = (int16_t*)( &ret ); float best_error = FLT_MAX; for( int16_t i = -1; i < 2; ++i ) { for( int16_t j = -1; j < 2; ++j ) { int16_t test_round[2] = { encoded[0] + i , encoded[1] + j }; glm::vec3 test_normal = octDecodeNormal( test_round ); // check the cos(angle) between the original normal, and the (decoded) encoded normal // since we are encoding direction vectors, we want to get as close to 1 as possible float test_error = fabs( 1.f - glm::dot( test_normal, normal ) ); if( test_error < best_error ) { best_error = test_error; best_encoded[0] = test_round[0]; best_encoded[1] = test_round[1]; } } } return ret; } inline uint16_t floatToUint16( float& val ) { int rval = int(trunc( val )); if( rval < 0 ) rval = 0; if( rval > 0xffff ) rval = 0xffff; return uint16_t(rval); } Tools::Compressed16Vertex Tools::Vertex::Compress( float scale, glm::vec3& translate ) { Compressed16Vertex ret; glm::vec3 coords = ( this->Coords - translate ) / scale; ret.Coords[0] = floatToUint16( coords.x ); ret.Coords[1] = floatToUint16( coords.y ); ret.Coords[2] = floatToUint16( coords.z ); ret._unnused = 0; ret.Normal = octEncodeNormal( this->Normal ); ret.TexCoords = glm::packHalf2x16( this->TexCoords ); return ret; }
25.440678
113
0.635909
Cooolrik
8d844ed49c38fe1290550146747d7df716f1fa77
5,781
cpp
C++
test/blackbox/ReqRepHelloWorldRequester.cpp
ihmcrobotics/Fast-RTPS
340f5a9fa1c504483c59b73c540f52ab659e1f46
[ "Apache-2.0" ]
5
2020-04-04T08:01:19.000Z
2020-11-25T21:33:15.000Z
test/blackbox/ReqRepHelloWorldRequester.cpp
ihmcrobotics/Fast-RTPS
340f5a9fa1c504483c59b73c540f52ab659e1f46
[ "Apache-2.0" ]
1
2021-03-05T12:08:31.000Z
2021-03-05T12:08:31.000Z
test/blackbox/ReqRepHelloWorldRequester.cpp
ihmcrobotics/Fast-RTPS
340f5a9fa1c504483c59b73c540f52ab659e1f46
[ "Apache-2.0" ]
3
2020-07-15T01:54:02.000Z
2021-06-14T04:26:14.000Z
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 ReqRepHelloWorldRequester.cpp * */ #include "ReqRepHelloWorldRequester.hpp" #include <fastrtps/Domain.h> #include <fastrtps/participant/Participant.h> #include <fastrtps/attributes/ParticipantAttributes.h> #include <fastrtps/subscriber/Subscriber.h> #include <fastrtps/subscriber/SampleInfo.h> #include <fastrtps/publisher/Publisher.h> #include <gtest/gtest.h> using namespace eprosima::fastrtps; using namespace eprosima::fastrtps::rtps; ReqRepHelloWorldRequester::ReqRepHelloWorldRequester(): reply_listener_(*this), request_listener_(*this), current_number_(std::numeric_limits<uint16_t>::max()), number_received_(std::numeric_limits<uint16_t>::max()), participant_(nullptr), reply_subscriber_(nullptr), request_publisher_(nullptr), initialized_(false), matched_(0) { // By default, memory mode is preallocated (the most restritive) sattr.historyMemoryPolicy = PREALLOCATED_MEMORY_MODE; puattr.historyMemoryPolicy = PREALLOCATED_MEMORY_MODE; } ReqRepHelloWorldRequester::~ReqRepHelloWorldRequester() { if(participant_ != nullptr) Domain::removeParticipant(participant_); } void ReqRepHelloWorldRequester::init() { ParticipantAttributes pattr; pattr.rtps.builtin.domainId = (uint32_t)GET_PID() % 230; participant_ = Domain::createParticipant(pattr); ASSERT_NE(participant_, nullptr); // Register type ASSERT_EQ(Domain::registerType(participant_,&type_), true); //Create subscriber sattr.topic.topicKind = NO_KEY; sattr.topic.topicDataType = "HelloWorldType"; configSubscriber("Reply"); reply_subscriber_ = Domain::createSubscriber(participant_, sattr, &reply_listener_); ASSERT_NE(reply_subscriber_, nullptr); //Create publisher puattr.topic.topicKind = NO_KEY; puattr.topic.topicDataType = "HelloWorldType"; configPublisher("Request"); request_publisher_ = Domain::createPublisher(participant_, puattr, &request_listener_); ASSERT_NE(request_publisher_, nullptr); initialized_ = true; } void ReqRepHelloWorldRequester::init_with_latency( const eprosima::fastrtps::Duration_t& latency_budget_duration_pub, const eprosima::fastrtps::Duration_t& latency_budget_duration_sub) { ParticipantAttributes pattr; participant_ = Domain::createParticipant(pattr); ASSERT_NE(participant_, nullptr); // Register type ASSERT_EQ(Domain::registerType(participant_,&type_), true); //Create subscriber sattr.topic.topicKind = NO_KEY; sattr.topic.topicDataType = "HelloWorldType"; sattr.qos.m_latencyBudget.duration = latency_budget_duration_sub; reply_subscriber_ = Domain::createSubscriber(participant_, sattr, &reply_listener_); ASSERT_NE(reply_subscriber_, nullptr); //Create publisher puattr.topic.topicKind = NO_KEY; puattr.topic.topicDataType = "HelloWorldType"; puattr.qos.m_latencyBudget.duration = latency_budget_duration_pub; request_publisher_ = Domain::createPublisher(participant_, puattr, &request_listener_); ASSERT_NE(request_publisher_, nullptr); initialized_ = true; } void ReqRepHelloWorldRequester::newNumber(SampleIdentity related_sample_identity, uint16_t number) { std::unique_lock<std::mutex> lock(mutex_); ASSERT_EQ(related_sample_identity_, related_sample_identity); number_received_ = number; ASSERT_EQ(current_number_, number_received_); if(current_number_ == number_received_) cv_.notify_one(); } void ReqRepHelloWorldRequester::block(const std::chrono::seconds &seconds) { std::unique_lock<std::mutex> lock(mutex_); if(current_number_ != number_received_) { ASSERT_EQ(cv_.wait_for(lock, seconds), std::cv_status::no_timeout); } ASSERT_EQ(current_number_, number_received_); } void ReqRepHelloWorldRequester::wait_discovery() { std::unique_lock<std::mutex> lock(mutexDiscovery_); std::cout << "Requester is waiting discovery..." << std::endl; cvDiscovery_.wait(lock, [&](){return matched_ > 1;}); std::cout << "Requester discovery finished..." << std::endl; } void ReqRepHelloWorldRequester::matched() { std::unique_lock<std::mutex> lock(mutexDiscovery_); ++matched_; if(matched_ > 1) { cvDiscovery_.notify_one(); } } void ReqRepHelloWorldRequester::ReplyListener::onNewDataMessage(Subscriber *sub) { ASSERT_NE(sub, nullptr); HelloWorld hello; SampleInfo_t info; if(sub->takeNextData((void*)&hello, &info)) { if(info.sampleKind == ALIVE) { ASSERT_EQ(hello.message().compare("GoodBye"), 0); requester_.newNumber(info.related_sample_identity, hello.index()); } } } void ReqRepHelloWorldRequester::send(const uint16_t number) { WriteParams wparams; HelloWorld hello; hello.index(number); hello.message("HelloWorld"); std::unique_lock<std::mutex> lock(mutex_); ASSERT_EQ(request_publisher_->write((void*)&hello, wparams), true); related_sample_identity_ = wparams.sample_identity(); ASSERT_NE(related_sample_identity_.sequence_number(), SequenceNumber_t()); current_number_ = number; }
31.939227
114
0.736551
ihmcrobotics
8d866fcdbb9ed25e8f69fe779755689557e29aa3
35,494
cpp
C++
lib/ProgramOptions.cpp
ToolsOnAir/gl-frame-bender
f2c24ad3ddaeea50b6d69f50890c09a5d59a3a18
[ "MIT" ]
6
2015-03-20T00:46:06.000Z
2021-02-01T09:04:59.000Z
lib/ProgramOptions.cpp
ToolsOnAir/gl-frame-bender
f2c24ad3ddaeea50b6d69f50890c09a5d59a3a18
[ "MIT" ]
null
null
null
lib/ProgramOptions.cpp
ToolsOnAir/gl-frame-bender
f2c24ad3ddaeea50b6d69f50890c09a5d59a3a18
[ "MIT" ]
2
2016-11-28T20:26:17.000Z
2021-02-01T09:05:00.000Z
/* Copyright (c) 2015 Heinrich Fink <hfink@toolsonair.com> * Copyright (c) 2014 ToolsOnAir Broadcast Engineering GmbH * * 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 "Precompile.h" #include "ProgramOptions.h" #include "Utils.h" #include <fstream> #include <sstream> #include <stdexcept> #include <iostream> #include <algorithm> #include "boost/program_options.hpp" #include "boost/filesystem.hpp" #include "FormatConverterStage.h" namespace fb = toa::frame_bender; namespace po = boost::program_options; namespace bf = boost::filesystem; fb::InvalidInput::InvalidInput(const char* what) { if (what != nullptr) { msg_ = std::string(what); } } const char* fb::InvalidInput::what() const NOEXCEPT{ return msg_.c_str(); } std::unique_ptr<const fb::ProgramOptions> fb::ProgramOptions::global_options = nullptr; const fb::ProgramOptions& fb::ProgramOptions::global() { if (global_options) { return *global_options; } else { throw std::runtime_error("Global options are not initialized yet."); } } void fb::ProgramOptions::initialize_global(int argc, const char* argv[]) { fb::ProgramOptions::global_options = utils::make_unique<fb::ProgramOptions>(argc, argv); } void fb::ProgramOptions::set_global(const ProgramOptions& opts) { fb::ProgramOptions::global_options = utils::make_unique<fb::ProgramOptions>(opts); } namespace boost { namespace program_options { template <> void validate<fb::StreamDispatch::FlagContainer, char> (boost::any& v, const std::vector<std::string>& values, fb::StreamDispatch::FlagContainer* target_type, long) { fb::StreamDispatch::FlagContainer combined_flags; // Check if we have assigned something previously if (!v.empty()) { combined_flags = boost::any_cast<fb::StreamDispatch::FlagContainer>(v); } for(const auto& token : values) { fb::StreamDispatch::Flags new_token; std::istringstream ss(token); ss >> new_token; if (ss.fail()) { throw po::validation_error(po::validation_error::invalid_option_value); } combined_flags.set(static_cast<size_t>(new_token)); } v = boost::any(combined_flags); } } } fb::ProgramOptions::ProgramOptions(int argc, const char* argv[]) { try { // These are the options which can only be set via the command line po::options_description generic("Generic options"); generic.add_options() ("help", "Print out help message") ("config,c", po::value<std::string>(&config_file_)->default_value(""), "Set the path to a configuration file to use. Leave empty to " "disable file-based configuration loading."); po::options_description config("Configuration"); config.add_options() ("opengl.context.debug", po::value<bool>(&use_debug_gl_context_)->default_value(false), "If set to true, a debug OpenGL context is created, and OpenGL debugging is forwarded to the logger.") ("logging.output_file", po::value<std::string>(&log_file_)->default_value("FrameBender.log"), "Set the file which should contain logging of this program. " "Set to empty in order to disable file-based logging.h") ("logging.write_to_stdout", po::value<bool>(&log_to_stdout_)->default_value(false), "If set to true, logging to stdout will be enabled. " "Set to false in order to disable console-output of the logger.") ("logging.min_severity", po::value<logging::Severity>(&min_logging_severity_)->default_value(logging::Severity::warning), "Sets the minimum logging level that should be reported. Can be " "debug,info,warning,error,critical." ) ("opengl.context.debug.is_synchronous", po::value<bool>(&arb_debug_synchronous_mode_)->default_value(false), "If set to true, and if a debug context is requested, the ARB GL " "debug output will be delivered synchronously to the driver, i.e. " "breakpoints can be set.") ("pipeline.upload.gl_pbo_count", po::value<size_t>(&upload_pbo_rr_count_)->default_value(3), "Sets the size of the round-robin queue for upload PBO buffers.") ("pipeline.upload.copy_to_unmap_queue_token_count", po::value<size_t>(&upload_copy_to_unmap_pipeline_size_)->default_value(2), "TODO: write documentation") ("pipeline.upload.unmap_to_unpack_queue_token_count", po::value<size_t>(&upload_unmap_to_unpack_pipeline_size_)->default_value(1), "TODO: write documentation") ("pipeline.download.gl_pbo_count", po::value<size_t>(&download_pbo_rr_count_)->default_value(3), "Sets the size of the round-robin queue for download PBO buffers.") ("pipeline.upload.gl_texture_count", po::value<size_t>(&source_texture_rr_count_)->default_value(3), "Sets the size of the round-robin queue for source textures.") ("pipeline.download.gl_texture_count", po::value<size_t>(&destination_texture_rr_count_)->default_value(3), "Sets the size of the round-robin queue for destination textures.") ("pipeline.output.token_count", po::value<size_t>(&frame_output_cache_count_)->default_value(3), "Sets the size of the frame output cache, i.e. the number of " "pre-allocated output frames.") ("pipeline.input.token_count", po::value<size_t>(&frame_input_pipeline_size_)->default_value(3), "TODO: write doc.") ("pipeline.download.map_to_copy_queue_token_count", po::value<size_t>(&download_map_to_copy_pipeline_size_)->default_value(2), "Sets the size of the pipeline from download 'map' stage to async 'copy'" " stage. This value added by 'pipeline.download.pack_to_map_queue_token_count' " "has to be the sum of 'pipeline.download.gl_pbo_count'.") ("pipeline.download.pack_to_map_queue_token_count", po::value<size_t>(&download_pack_to_map_pipeline_size_)->default_value(1), "Sets the size of the pipeline from download 'pack' stage to 'map'" " stage. This value added by 'pipeline.download.map_to_copy_queue_token_count' " "has to be the sum of 'pipeline.download.gl_pbo_count'.") ("player.width", po::value<size_t>(&player_width_)->default_value(640), "Width of the player screen.") ("player.height", po::value<size_t>(&player_height_)->default_value(360), "Height of the player screen.") ("player.is_fullscreen", po::value<bool>(&player_is_fullscreen_)->default_value(false), "If set to true, the player will start in fullscreen mode.") ("player.sync_to_vertical_refresh", po::value<bool>(&player_use_vsync_)->default_value(true), "If set to true, the player will synchronize with the VSync interval.") ("program.glsl_sources_location", po::value<std::string>(&glsl_folder_)->default_value("./glsl"), "Sets the folder in which GLSL source files should be searched for.") ("player.is_enabled", po::value<bool>(&blit_to_player_)->default_value(true), "If set to true, each rendered video frame will be blit to " "player's framebuffer and the player will use double-buffering.") ("render.format_conversion.v210.bitextraction_in_shader_is_enabled", po::value<bool>(&v210_use_shader_for_component_access_)->default_value(true), "If set to true, shaders will be used for unpacking the V210 " "compressed word into three 10-bit components. If false, a " "GL_UNSIGNED_INT_2_10_10_10_REV will be used for unpacking. ") ("input.sequence.pixel_format", po::value<fb::ImageFormat::PixelFormat>(&input_sequence_pixel_format_)->default_value(ImageFormat::PixelFormat::YUV_10BIT_V210), "The pixel format of the input sequence. Use -help for a list of supported pixel format.") ("program.sequences_location", po::value<std::string>(&input_sequences_folder_)->default_value("test_data"), "The folder in which input sequences are stored. Everything sequence_name + pattern is relative to this.") ("input.sequence.id", po::value<std::string>(&input_sequence_name_)->default_value("horse_v210_1920_1080p_short"), "The name (i.e. folder) of the sequence within the input sequence folder.") ("input.sequence.file_pattern", po::value<std::string>(&input_sequence_pattern_)->default_value(".*\\.v210"), "The pattern of the sequence frames to load.") ("input.sequence.width", po::value<size_t>(&input_sequence_width_)->default_value(1920), "Image width of the input sequence's frames.") ("input.sequence.height", po::value<size_t>(&input_sequence_height_)->default_value(1080), "Image height of the input sequence's frames.") ("input.sequence.loop_count", po::value<size_t>(&input_sequence_loop_count_)->default_value(10), "Number of times to replay the input sequence.") ("input.sequence.image_origin", po::value<fb::ImageFormat::Origin>(&input_sequence_origin_)->default_value(fb::ImageFormat::Origin::UPPER_LEFT), "Image origin of the input sequence's frames.") ("input.sequence.frame_duration", po::value<fb::Time>(&input_sequence_frame_duration_)->default_value(fb::Time(1, 25)), "Time duration of one input sequence's frame (inverse of " "framerate, e.g. 1/25 for 25fps).") ("input.sequence.image_transfer", po::value<fb::ImageFormat::Transfer>(&input_sequence_transfer_)->default_value(fb::ImageFormat::Transfer::BT_709), "Image transfer of the input sequence's frames.") ("program.textures_location", po::value<std::string>(&textures_folder_)->default_value("textures"), "The folder from which textures are loaded.") ("render.pixel_format", po::value<fb::ImageFormat::PixelFormat>(&render_pixel_format_)->default_value(ImageFormat::PixelFormat::RGBA_8BIT), "The internal pixel format of the renderer. Use -help for a list of supported pixel format.") ("render.image_transfer", po::value<fb::ImageFormat::Transfer>(&render_transfer_)->default_value(ImageFormat::Transfer::LINEAR), "The internal transfer of the renderer. Use -help for a list of supported transfers.") ("profiling.stage_sampling_is_enabled", po::value<bool>(&sample_stages_)->default_value(false), "If enable, then the stages of the pipeline will be sampled, and a statistics summary report will be added to the log output.") ("debug.output_is_enabled", po::value<bool>(&enable_output_stages_)->default_value(true), "Enables/disables the execution of the output pipeline stages, i.e. downloading of video frames.") ("debug.input_is_enabled", po::value<bool>(&enable_input_stages_)->default_value(true), "Enables/disables the execution of the input pipeline stages, i.e. uploading to video frames.") ("debug.rendering_is_enabled", po::value<bool>(&enable_render_stages_)->default_value(true), "Enables/disables the execution of the render pipeline stages, i.e. rendering onto video frames.") ("debug.passthrough_renderer_is_forced", po::value<bool>(&force_passthrough_renderer_)->default_value(false), "When enabled, the renderer used is the passthrough renderer.") ("profiling.statistics.first_frames_skipped_count", po::value<size_t>(&statistics_skip_first_num_frames_)->default_value(20), "Skip the first N frames for calculating the statistics summary. " "Use this value 'warmup' of the pipeline execution in order to " "retrieve more accurate statistics.") ("debug.host_input_copy_is_enabled", po::value<bool>(&enable_host_copy_upload_)->default_value(true), "Enable/Disable host-side copy operation into mapped GPU memory " "for the upload phase.") ("debug.host_output_copy_is_enabled", po::value<bool>(&enable_host_copy_download_)->default_value(true), "Enable/Disable host-side copy operation into mapped GPU memory " "for the download phase.") ("profiling.upload_gl_timer_queries_are_enabled", po::value<bool>(&enable_upload_gl_timer_queries_)->default_value(false), "Enables the use of GL timer queries to report on GL-side timings of the upload operations.") ("profiling.render_gl_timer_queries_are_enabled", po::value<bool>(&enable_render_gl_timer_queries_)->default_value(false), "Enables the use of GL timer queries to report on GL-side timings of the render operations.") ("profiling.download_gl_timer_queries_are_enabled", po::value<bool>(&enable_download_gl_timer_queries_)->default_value(false), "Enables the use of GL timer queries to report on GL-side timings of the download operations.") ("render.format_conversion_mode", po::value<Mode>(&format_conversion_mode_)->default_value(Mode::glsl_420_no_buffer_attachment_ext), "Sets the mode to use for the format conversion. Note that the hardware is required to support it. Otherwise the program will exit with an error.") ("render.format_conversion.v210.decode.glsl_430_work_group_size", po::value<size_t>(&v210_decode_glsl_430_work_group_size_)->default_value(16), "Sets the local work group size for the GLSL 430 compute shader " "decoding of V210 images. This option is only effective if " "render.format_conversion_mode is set to glsl_430_compute.") ("render.format_conversion.v210.encode.glsl_430_work_group_size", po::value<size_t>(&v210_encode_glsl_430_work_group_size_)->default_value(16), "Sets the local work group size for the GLSL 430 compute shader " "encoding of V210 images. This option is only effective if " "render.format_conversion_mode is set to glsl_430_compute.") ("render.demo.lower_third_image", po::value<std::string>(&demo_renderer_lower_third_image_)->default_value("fine_trans_lower_third_1080_8bit.png"), "Sets the lower third image for the demo renderer.") ("render.demo.logo_image", po::value<std::string>(&demo_renderer_logo_image_)->default_value("fine_trans_logo_1080_8bit.png"), "Sets the logo image for the demo renderer.") ("render.format_conversion.v210.decode.chroma_filter_type", po::value<fb::ChromaFilter>(&v210_decode_glsl_chroma_filter_)->default_value(ChromaFilter::basic), "Sets the complexity of the filter for YCbCr 422 decoding (upscaling filter).") ("render.format_conversion.v210.encode.chroma_filter_type", po::value<fb::ChromaFilter>(&v210_encode_glsl_chroma_filter_)->default_value(ChromaFilter::basic), "Sets the complexity of the filter for YCbCr 422 encoding (decimation filter).") ("player.user_input_is_enabled", po::value<bool>(&enable_window_user_input_)->default_value(true), "Must be enabled in order to react to user input evenst (mouse/keyboard).") ("output.is_enabled", po::value<bool>(&enable_write_output_)->default_value(false), "If enabled, all renderer frames will be written to 'output.location'.") ("output.location", po::value<std::string>(&write_output_folder_)->default_value("./render_output"), "Destination folder for rendered output frames.") ("write_output_swap_endianness", po::value<bool>(&write_output_swap_endianness_)->default_value(false), "If enabled, the output frame's raw image data will be byte-swapped.") ("write_output_swap_endianness_word_size", po::value<size_t>(&write_output_swap_endianness_word_size_)->default_value(2), "Sets the word size for any byte-swapping.") ("enable_linear_space_rendering", po::value<bool>(&enable_linear_space_rendering_)->default_value(true), "If enabled, rendering is performed in linear-space RGB. This " "option is likely to be removed in the future, as this should be " "derived automatically from the input/output vs. render image " "formats.") // TODO: these should be validated with a custom validator ("pipeline.optimization_flags", po::value<StreamDispatch::FlagContainer>(&optimization_flags_)->multitoken(), "Can hold multiple optimizations flags. Use --help to print out possible flag values.") ("opengl.context.debug.min_severity", po::value<gl::Context::DebugSeverity>(&min_debug_gl_context_severity_)->default_value(gl::Context::DebugSeverity::MEDIUM), "Sets the reported debug GL context severity. This option has no effect unless opengl.context.debug is set to true.") ("pipeline.download.pack_to_map_load_constraint_count", po::value<size_t>(&pipeline_download_pack_to_map_load_constraint_count_)->default_value(0), "Sets how many tokens are required for the download's map PBO " "stage to be in the input queue. In other words, how many times " "must the pack PBO phase run before the map PBO phase is executed.") ("pipeline.upload.unmap_to_unpack_load_constraint_count", po::value<size_t>(&pipeline_upload_unmap_to_unpack_load_constraint_count_)->default_value(0), "See above.") ("pipeline.download.format_converter_to_pack_load_constraint_count", po::value<size_t>(&pipeline_download_format_converter_to_pack_load_constraint_count_)->default_value(0), "See above.") ("pipeline.upload.unpack_to_format_converter_load_constraint_count", po::value<size_t>(&pipeline_upload_unpack_to_format_converter_load_constraint_count_)->default_value(0), "See above.") ("profiling.trace_output_file", po::value<std::string>(&trace_output_file_)->default_value(""), "If profiling.stage_sampling_is_enabled is active, and if the " "value of this option is not the empty string (default value), " "then a trace file is written to the given location.") ("program.config_output_file", po::value<std::string>(&config_output_file_)->default_value(""), "If this path is not the empty string, then a config file with " "the parsed configuration will be written to this file.") ("profiling.trace_name", po::value<std::string>(&profiling_trace_name_)->default_value(""), "The name of the tracing can optionally be overriden by this parameter. " "If not set, the name of the configuration file will be used instead.") ; // TODO: add any eventual validation methods for folders validation po::options_description cmdline_options; cmdline_options.add(generic).add(config); // First parse only the generic options po::variables_map vm; po::store(po::parse_command_line(argc, argv, cmdline_options), vm); po::notify(vm); // Save the help string, in case we need to show help. std::ostringstream oss; oss << cmdline_options; oss << "Supported pixel formats: \n"; // Also the available pixel formats for (int32_t i = 0; i<static_cast<int32_t>(ImageFormat::PixelFormat::COUNT); ++i) { ImageFormat::PixelFormat pf = ImageFormat::PixelFormat(i); if (pf == ImageFormat::PixelFormat::INVALID) continue; oss << "\t'" << pf << "'\n"; } oss << "Supported transfers: \n"; // Also the available pixel formats for (int32_t i = 0; i<static_cast<int32_t>(ImageFormat::Transfer::COUNT); ++i) { ImageFormat::Transfer pf = ImageFormat::Transfer(i); oss << "\t'" << pf << "'\n"; } oss << "Supported conversion modes (FormatConverter): \n"; for (int32_t i = 0; i<static_cast<int32_t>(Mode::count); ++i) { Mode pf = Mode(i); oss << "\t'" << pf << "'\n"; } oss << "Supported chroma filter complexities (FormatConverter): \n"; for (int32_t i = 0; i<static_cast<int32_t>(ChromaFilter::count); ++i) { ChromaFilter pf = ChromaFilter(i); oss << "\t'" << pf << "'\n"; } oss << "Possible optimization flags (StreamDispatch implementation): \n"; for (int32_t i = 0; i<static_cast<int32_t>(StreamDispatch::Flags::COUNT); ++i) { StreamDispatch::Flags pf = StreamDispatch::Flags(i); oss << "\t'" << pf << "'\n"; } help_ = oss.str(); if (vm.count("help")) { show_help_ = true; } else { show_help_ = false; } if (!config_file_.empty()) { std::ifstream ifs(config_file_.c_str()); if (ifs) { po::store(po::parse_config_file(ifs, config), vm); notify(vm); } else { std::cerr << "Configuration file '" << config_file_ << "' does not exist. Not loading options from there." << std::endl; } } po::store(po::parse_command_line(argc, argv, cmdline_options), vm); po::notify(vm); std::ostringstream oss_config; for (const auto& entry : vm) { if (entry.first == "config" || entry.first == "program.config_output_file") continue; oss_config << entry.first << "="; const boost::any * value = &entry.second.value(); // I know, this is ugly, but works const bool* const bool_val = boost::any_cast<const bool>(value); const std::string* const string_val = boost::any_cast<const std::string>(value); const logging::Severity* const log_sev_val = boost::any_cast<const logging::Severity>(value); const size_t* const size_t_val = boost::any_cast<const size_t>(value); const ImageFormat::PixelFormat* const pix_fmt_val = boost::any_cast<const ImageFormat::PixelFormat>(value); const ImageFormat::Origin* const img_origin_val = boost::any_cast<const ImageFormat::Origin>(value); const ImageFormat::Transfer* const img_transfer_val = boost::any_cast<const ImageFormat::Transfer>(value); const Time* const time_val = boost::any_cast<const Time>(value); const Mode * const fmt_conv_stage_mode_val = boost::any_cast<const Mode >(value); const ChromaFilter* const chroma_filter_val = boost::any_cast<const ChromaFilter>(value); const StreamDispatch::FlagContainer* const opt_flag_val = boost::any_cast<const StreamDispatch::FlagContainer>(value); const gl::Context::DebugSeverity* const gl_debug_sev_val = boost::any_cast<const gl::Context::DebugSeverity>(value); if (bool_val != nullptr) { oss_config << std::boolalpha << *bool_val; } else if (string_val != nullptr) { oss_config << *string_val; } else if (log_sev_val != nullptr) { oss_config << *log_sev_val; } else if (size_t_val != nullptr) { oss_config << *size_t_val; } else if (pix_fmt_val != nullptr) { oss_config << *pix_fmt_val; } else if (img_origin_val != nullptr) { oss_config << *img_origin_val; } else if (img_transfer_val != nullptr) { oss_config << *img_transfer_val; } else if (time_val != nullptr) { oss_config << *time_val; } else if (fmt_conv_stage_mode_val != nullptr) { oss_config << *fmt_conv_stage_mode_val; } else if (chroma_filter_val != nullptr) { oss_config << *chroma_filter_val; } else if (opt_flag_val != nullptr) { for (size_t i = 0; i<static_cast<size_t>(StreamDispatch::Flags::COUNT); ++i) { StreamDispatch::Flags pf = StreamDispatch::Flags(i); if ((*opt_flag_val)[i]) { if (i != 0) { oss_config << "\n"; oss_config << entry.first << "="; } oss_config << pf; } } } else if (gl_debug_sev_val != nullptr) { oss_config << *gl_debug_sev_val; } else { throw std::runtime_error("Missing a type in options print-out."); } oss_config << "\n"; } config_output_file_contents_ = oss_config.str(); } catch (const po::error& e) { throw InvalidInput(e.what()); } } const std::string& fb::ProgramOptions::config_file() const { return config_file_; } bool fb::ProgramOptions::use_debug_gl_context() const { return use_debug_gl_context_; } bool fb::ProgramOptions::show_help() const { return show_help_; } const std::string& fb::ProgramOptions::help() const { return help_; } const std::string& fb::ProgramOptions::log_file() const { return log_file_; } bool fb::ProgramOptions::log_to_stdout() const { return log_to_stdout_; } fb::logging::Severity fb::ProgramOptions::min_logging_severity() const { return min_logging_severity_; } bool fb::ProgramOptions::arb_debug_synchronous_mode() const { return arb_debug_synchronous_mode_; } size_t fb::ProgramOptions::upload_pbo_rr_count() const { return upload_pbo_rr_count_; } size_t fb::ProgramOptions::upload_copy_to_unmap_pipeline_size() const { return upload_copy_to_unmap_pipeline_size_; } size_t fb::ProgramOptions::upload_unmap_to_unpack_pipeline_size() const { return upload_unmap_to_unpack_pipeline_size_; } size_t fb::ProgramOptions::download_pbo_rr_count() const { return download_pbo_rr_count_; } size_t fb::ProgramOptions::source_texture_rr_count() const { return source_texture_rr_count_; } size_t fb::ProgramOptions::destination_texture_rr_count() const { return destination_texture_rr_count_; } size_t fb::ProgramOptions::frame_input_pipeline_size() const { return frame_input_pipeline_size_; } size_t fb::ProgramOptions::frame_output_cache_count() const { return frame_output_cache_count_; } size_t fb::ProgramOptions::download_map_to_copy_pipeline_size() const { return download_map_to_copy_pipeline_size_; } size_t fb::ProgramOptions::download_pack_to_map_pipeline_size() const { return download_pack_to_map_pipeline_size_; } size_t fb::ProgramOptions::player_width() const { return player_width_; } size_t fb::ProgramOptions::player_height() const { return player_height_; } bool fb::ProgramOptions::player_is_fullscreen() const { return player_is_fullscreen_; } bool fb::ProgramOptions::player_use_vsync() const { return player_use_vsync_; } const std::string& fb::ProgramOptions::glsl_folder() const { return glsl_folder_; } bool fb::ProgramOptions::blit_to_player() const { return blit_to_player_; } bool fb::ProgramOptions::v210_use_shader_for_component_access() const { return v210_use_shader_for_component_access_; } fb::ImageFormat::PixelFormat fb::ProgramOptions::input_sequence_pixel_format() const { return input_sequence_pixel_format_; } const std::string& fb::ProgramOptions::input_sequences_folder() const { return input_sequences_folder_; } const std::string& fb::ProgramOptions::input_sequence_name() const { return input_sequence_name_; } const std::string& fb::ProgramOptions::input_sequence_pattern() const { return input_sequence_pattern_; } size_t fb::ProgramOptions::input_sequence_width() const { return input_sequence_width_; } size_t fb::ProgramOptions::input_sequence_height() const { return input_sequence_height_; } size_t fb::ProgramOptions::input_sequence_loop_count() const { return input_sequence_loop_count_; } fb::ImageFormat::Origin fb::ProgramOptions::input_sequence_origin() const { return input_sequence_origin_; } const fb::Time& fb::ProgramOptions::input_sequence_frame_duration() const { return input_sequence_frame_duration_; } const std::string& fb::ProgramOptions::textures_folder() const { return textures_folder_; } fb::ImageFormat::PixelFormat fb::ProgramOptions::render_pixel_format() const { return render_pixel_format_; } fb::ImageFormat::Transfer fb::ProgramOptions::render_transfer() const { return render_transfer_; } fb::ImageFormat::Transfer fb::ProgramOptions::input_sequence_transfer() const { return input_sequence_transfer_; } bool fb::ProgramOptions::sample_stages() const { return sample_stages_; } bool fb::ProgramOptions::enable_output_stages() const { return enable_output_stages_; } bool fb::ProgramOptions::enable_input_stages() const { return enable_input_stages_; } bool fb::ProgramOptions::enable_render_stages() const { return enable_render_stages_; } bool fb::ProgramOptions::force_passthrough_renderer() const { return force_passthrough_renderer_; } size_t fb::ProgramOptions::statistics_skip_first_num_frames() const { return statistics_skip_first_num_frames_; } bool fb::ProgramOptions::enable_host_copy_upload() const { return enable_host_copy_upload_; } bool fb::ProgramOptions::enable_host_copy_download() const { return enable_host_copy_download_; } bool fb::ProgramOptions::enable_upload_gl_timer_queries() const { return enable_upload_gl_timer_queries_; } bool fb::ProgramOptions::enable_render_gl_timer_queries() const { return enable_render_gl_timer_queries_; } bool fb::ProgramOptions::enable_download_gl_timer_queries() const { return enable_download_gl_timer_queries_; } fb::Mode fb::ProgramOptions::format_conversion_mode() const { return format_conversion_mode_; } size_t fb::ProgramOptions::v210_decode_glsl_430_work_group_size() const { return v210_decode_glsl_430_work_group_size_; } size_t fb::ProgramOptions::v210_encode_glsl_430_work_group_size() const { return v210_encode_glsl_430_work_group_size_; } const std::string& fb::ProgramOptions::demo_renderer_lower_third_image() const { return demo_renderer_lower_third_image_; } const std::string& fb::ProgramOptions::demo_renderer_logo_image() const { return demo_renderer_logo_image_; } fb::ChromaFilter fb::ProgramOptions::v210_decode_glsl_chroma_filter() const { return v210_decode_glsl_chroma_filter_; } fb::ChromaFilter fb::ProgramOptions::v210_encode_glsl_chroma_filter() const { return v210_encode_glsl_chroma_filter_; } bool fb::ProgramOptions::enable_window_user_input() const { return enable_window_user_input_; } const std::string& fb::ProgramOptions::write_output_folder() const { return write_output_folder_; } bool fb::ProgramOptions::enable_write_output() const { return enable_write_output_; } bool fb::ProgramOptions::write_output_swap_endianness() const { return write_output_swap_endianness_; } size_t fb::ProgramOptions::write_output_swap_endianness_word_size() const { return write_output_swap_endianness_word_size_; } bool fb::ProgramOptions::enable_linear_space_rendering() const { return enable_linear_space_rendering_; } const fb::StreamDispatch::FlagContainer& fb::ProgramOptions::optimization_flags() const { return optimization_flags_; } fb::gl::Context::DebugSeverity fb::ProgramOptions::min_debug_gl_context_severity() const { return min_debug_gl_context_severity_; } size_t fb::ProgramOptions::pipeline_download_pack_to_map_load_constraint_count() const { return pipeline_download_pack_to_map_load_constraint_count_; } size_t fb::ProgramOptions::pipeline_upload_unmap_to_unpack_load_constraint_count() const { return pipeline_upload_unmap_to_unpack_load_constraint_count_; } size_t fb::ProgramOptions::pipeline_download_format_converter_to_pack_load_constraint_count() const { return pipeline_download_format_converter_to_pack_load_constraint_count_; } size_t fb::ProgramOptions::pipeline_upload_unpack_to_format_converter_load_constraint_count() const { return pipeline_upload_unpack_to_format_converter_load_constraint_count_; } const std::string& fb::ProgramOptions::trace_output_file() const { return trace_output_file_; } const std::string& fb::ProgramOptions::config_output_file() const { return config_output_file_; } void fb::ProgramOptions::write_config_to_file(const std::string& file_path) const { bf::path out_path(file_path); bf::ofstream writer(out_path, std::ios::out); if (!writer.good()) throw std::runtime_error("Could not open writer for config out file."); writer << config_output_file_contents_; writer.close(); FB_LOG_INFO << "Wrote config file to '" << file_path << "'."; } const std::string& fb::ProgramOptions::profiling_trace_name() const { return profiling_trace_name_; }
42.558753
159
0.665549
ToolsOnAir
8d8c3e1b5f9188fcb7dd5f617a2c59533ae50128
1,715
cpp
C++
Courses/001 - Algorithms Toolbox/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/placing_parentheses.cpp
aKhfagy/Data-Structures-and-Algorithms-Specialization
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
1
2021-01-25T09:56:15.000Z
2021-01-25T09:56:15.000Z
Courses/001 - Algorithms Toolbox/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/placing_parentheses.cpp
aKhfagy/data-structures-algorithms
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
null
null
null
Courses/001 - Algorithms Toolbox/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/placing_parentheses.cpp
aKhfagy/data-structures-algorithms
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <cassert> #include <string> #include <vector> #include <cmath> #include <algorithm> #include <climits> using std::vector; using std::string; using std::max; using std::min; using ll = long long; long long eval(long long a, long long b, char op) { if (op == '*') { return a * b; } else if (op == '+') { return a + b; } else if (op == '-') { //puts("HAHA"); return b - a; } else { assert(0); } } ll mi[30][30] = {}; ll ma[30][30] = {}; long long get_maximum_value(const string& exp) { int n = exp.size() / 2 + (exp.size() & 1); for (int i = 0; i < n; ++i) { int num = exp[2 * i] - '0'; mi[i][i] = ma[i][i] = num; } for (int s = 0; s < n - 1; ++s) { for (int i = 0; i < n - s - 1; ++i) { int j = i + s + 1; ll mn = LLONG_MAX, mx = LLONG_MIN; for (int k = i; k < j; ++k) { ll num[4] = { eval(mi[k + 1][j], mi[i][k], exp[k * 2 + 1]), eval(mi[k + 1][j], ma[i][k], exp[k * 2 + 1]), eval(ma[k + 1][j], mi[i][k], exp[k * 2 + 1]), eval(ma[k + 1][j], ma[i][k], exp[k * 2 + 1]) }; for (int t = 0; t < 4; ++t) { //std::cout << num[t] << " \n"[t == 3]; mn = min(mn, num[t]); mx = max(mx, num[t]); } } //std::cout << mn << ' ' << mx << '\n'; mi[i][j] = mn; ma[i][j] = mx; } } --n; return ma[0][n]; } int main() { string s; std::cin >> s; std::cout << get_maximum_value(s) << '\n'; }
23.175676
75
0.377843
aKhfagy
8d8caec8ba8a05cb849aab8543e869882170d457
8,111
cc
C++
old/rama_dialogblocks/sweep.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
null
null
null
old/rama_dialogblocks/sweep.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
127
2017-11-01T01:28:28.000Z
2021-03-18T05:12:21.000Z
old/rama_dialogblocks/sweep.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
2
2017-10-20T01:16:49.000Z
2018-11-04T02:36:53.000Z
///////////////////////////////////////////////////////////////////////////// // Name: sweep.cc // Purpose: // Author: // Modified by: // Created: // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// // Precompiled header: #include "../stdwx.h" ////@begin includes ////@end includes #include "sweep.h" #include "../cavity.h" #include "../../toolkit/mystring.h" ////@begin XPM images ////@end XPM images /* * SweepDialog type definition */ IMPLEMENT_DYNAMIC_CLASS( SweepDialog, wxDialog ) /* * SweepDialog event table definition */ BEGIN_EVENT_TABLE( SweepDialog, wxDialog ) ////@begin SweepDialog event table entries EVT_CHOICE( ID_SWEEP_PARAMETER, SweepDialog::OnSweepParameterSelected ) EVT_BUTTON( wxID_OK, SweepDialog::OnOk ) ////@end SweepDialog event table entries END_EVENT_TABLE() /* * SweepDialog constructors */ SweepDialog::SweepDialog() { Init(); } SweepDialog::SweepDialog( wxWindow* parent, Cavity* viewer, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); viewer_ = viewer; Create(parent, id, caption, pos, size, style); } /* * Sweep creator */ bool SweepDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin SweepDialog creation SetExtraStyle(wxWS_EX_BLOCK_EVENTS); wxDialog::Create( parent, id, caption, pos, size, style ); CreateControls(); if (GetSizer()) { GetSizer()->SetSizeHints(this); } Centre(); ////@end SweepDialog creation return true; } /* * SweepDialog destructor */ SweepDialog::~SweepDialog() { ////@begin SweepDialog destruction ////@end SweepDialog destruction } /* * Member initialisation */ void SweepDialog::Init() { ////@begin SweepDialog member initialisation parameters_ctrl_ = NULL; start_value_ctrl_ = NULL; end_value_ctrl_ = NULL; num_steps_text_ = NULL; num_steps_ctrl_ = NULL; ////@end SweepDialog member initialisation viewer_ = NULL; integer_ = false; start_value_ = end_value_ = min_value_ = max_value_ = 0; num_steps_ = 0; } /* * Control creation for Sweep */ void SweepDialog::CreateControls() { ////@begin SweepDialog content construction SweepDialog* itemDialog1 = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); itemDialog1->SetSizer(itemBoxSizer2); wxFlexGridSizer* itemFlexGridSizer3 = new wxFlexGridSizer(0, 2, 0, 0); itemBoxSizer2->Add(itemFlexGridSizer3, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxStaticText* itemStaticText4 = new wxStaticText( itemDialog1, wxID_STATIC, _("Parameter to sweep"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(itemStaticText4, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString parameters_ctrl_Strings; parameters_ctrl_ = new wxChoice( itemDialog1, ID_SWEEP_PARAMETER, wxDefaultPosition, wxDefaultSize, parameters_ctrl_Strings, 0 ); itemFlexGridSizer3->Add(parameters_ctrl_, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText6 = new wxStaticText( itemDialog1, wxID_STATIC, _("Start value"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(itemStaticText6, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); start_value_ctrl_ = new wxTextCtrl( itemDialog1, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(start_value_ctrl_, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText8 = new wxStaticText( itemDialog1, wxID_STATIC, _("End value"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(itemStaticText8, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); end_value_ctrl_ = new wxTextCtrl( itemDialog1, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(end_value_ctrl_, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); num_steps_text_ = new wxStaticText( itemDialog1, wxID_STATIC, _("Number of steps"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(num_steps_text_, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); num_steps_ctrl_ = new wxTextCtrl( itemDialog1, wxID_ANY, _("50"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(num_steps_ctrl_, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticLine* itemStaticLine12 = new wxStaticLine( itemDialog1, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); itemBoxSizer2->Add(itemStaticLine12, 0, wxGROW|wxALL, 5); wxBoxSizer* itemBoxSizer13 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(itemBoxSizer13, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxButton* itemButton14 = new wxButton( itemDialog1, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); itemButton14->SetDefault(); itemBoxSizer13->Add(itemButton14, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* itemButton15 = new wxButton( itemDialog1, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer13->Add(itemButton15, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); ////@end SweepDialog content construction std::vector<std::string> names; viewer_->GetParamControlNames(&names); for (int i = 0; i < names.size(); i++) { parameters_ctrl_->Append(names[i]); } parameters_ctrl_->SetSelection(0); if (!names.empty()) { SetParameter(names[0]); } } /* * Should we show tooltips? */ bool SweepDialog::ShowToolTips() { return true; } /* * Get bitmap resources */ wxBitmap SweepDialog::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin SweepDialog bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end SweepDialog bitmap retrieval } /* * Get icon resources */ wxIcon SweepDialog::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin SweepDialog icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end SweepDialog icon retrieval } /* * wxEVT_COMMAND_CHOICE_SELECTED event handler for ID_SWEEP_PARAMETER */ void SweepDialog::OnSweepParameterSelected( wxCommandEvent& event ) { SetParameter((const char*) parameters_ctrl_->GetString(event.GetInt()).c_str()); } void SweepDialog::SetParameter(const std::string &name) { parameter_ = name; const Parameter &param = viewer_->GetParameter(name); start_value_ctrl_->SetValue(wxString::Format("%.10g", param.the_min)); end_value_ctrl_->SetValue(wxString::Format("%.10g", param.the_max)); num_steps_ctrl_->Enable(!param.integer); num_steps_text_->Enable(!param.integer); integer_ = param.integer; min_value_ = param.the_min; max_value_ = param.the_max; } void SweepDialog::OnOk( wxCommandEvent& event ) { if (!StrToDouble(start_value_ctrl_->GetValue().c_str(), &start_value_)) { wxLogError("Bad start value"); return; } if (!StrToDouble(end_value_ctrl_->GetValue().c_str(), &end_value_)) { wxLogError("Bad end value"); return; } if (!StrToInt(num_steps_ctrl_->GetValue().c_str(), &num_steps_) || num_steps_ <= 0) { wxLogError("Bad number of steps"); return; } if (start_value_ >= end_value_) { wxLogError("Start value must be less than end value"); return; } if (start_value_ < min_value_ || end_value_ > max_value_) { wxLogError("Start and end must be in the range %g to %g", min_value_, max_value_); return; } if (integer_) { if (start_value_ != int(start_value_) || end_value_ != int(end_value_)) { wxLogError("Start and end values must be integers"); return; } } event.Skip(); }
30.152416
153
0.670078
teenylasers
8d8d3317296e0016bc5ce73a2f7d0e60fe2f33d7
12,565
cpp
C++
compiler/luci/import/src/GraphBuilderRegistry.cpp
wateret/ONE
4b1c4721248887d68a18f97d6903e459675163fc
[ "Apache-2.0" ]
null
null
null
compiler/luci/import/src/GraphBuilderRegistry.cpp
wateret/ONE
4b1c4721248887d68a18f97d6903e459675163fc
[ "Apache-2.0" ]
1
2020-09-23T23:12:23.000Z
2020-09-23T23:20:34.000Z
compiler/luci/import/src/GraphBuilderRegistry.cpp
s-barannikov/ONE
608121ca5a790a36a87889934f78574d27df7077
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "luci/Import/GraphBuilderRegistry.h" #include "luci/Import/Nodes.h" #include <memory> namespace luci { GraphBuilderRegistry::GraphBuilderRegistry() { #define CIRCLE_NODE(OPCODE, CLASS) add(circle::BuiltinOperator_##OPCODE, std::make_unique<CLASS>()); CIRCLE_NODE(ABS, CircleAbsGraphBuilder); // 101 CIRCLE_NODE(ADD, CircleAddGraphBuilder); // 0 CIRCLE_NODE(ADD_N, CircleAddNGraphBuilder); // 106 CIRCLE_NODE(ARG_MAX, CircleArgMaxGraphBuilder); // 56 CIRCLE_NODE(ARG_MIN, CircleArgMinGraphBuilder); // 79 CIRCLE_NODE(AVERAGE_POOL_2D, CircleAveragePool2DGraphBuilder); // 1 CIRCLE_NODE(BATCH_MATMUL, CircleBatchMatMulGraphBuilder); // 126 CIRCLE_NODE(BATCH_TO_SPACE_ND, CircleBatchToSpaceNDGraphBuilder); // 37 CIRCLE_NODE(BCQ_FULLY_CONNECTED, CircleBCQFullyConnectedGraphBuilder); // 253 CIRCLE_NODE(BCQ_GATHER, CircleBCQGatherGraphBuilder); // 252 CIRCLE_NODE(CAST, CircleCastGraphBuilder); // 53 CIRCLE_NODE(CEIL, CircleCeilGraphBuilder); // 104 CIRCLE_NODE(CUSTOM, CircleCustomGraphBuilder); // 32 CIRCLE_NODE(CONCATENATION, CircleConcatenationGraphBuilder); // 2 CIRCLE_NODE(CONV_2D, CircleConv2DGraphBuilder); // 3 CIRCLE_NODE(COS, CircleCosGraphBuilder); // 108 CIRCLE_NODE(DEPTH_TO_SPACE, CircleDepthToSpaceGraphBuilder); // 5 CIRCLE_NODE(DEPTHWISE_CONV_2D, CircleDepthwiseConv2DGraphBuilder); // 4 CIRCLE_NODE(DEQUANTIZE, CircleDequantizeGraphBuilder); // 6 CIRCLE_NODE(DIV, CircleDivGraphBuilder); // 42 CIRCLE_NODE(ELU, CircleEluGraphBuilder); // 111 CIRCLE_NODE(EQUAL, CircleEqualGraphBuilder); // 71 CIRCLE_NODE(EXP, CircleExpGraphBuilder); // 47 CIRCLE_NODE(EXPAND_DIMS, CircleExpandDimsGraphBuilder); // 70 CIRCLE_NODE(FILL, CircleFillGraphBuilder); // 94 CIRCLE_NODE(FLOOR, CircleFloorGraphBuilder); // 8 CIRCLE_NODE(FLOOR_DIV, CircleFloorDivGraphBuilder); // 90 CIRCLE_NODE(FLOOR_MOD, CircleFloorModGraphBuilder); // 95 CIRCLE_NODE(FULLY_CONNECTED, CircleFullyConnectedGraphBuilder); // 9 CIRCLE_NODE(GATHER, CircleGatherGraphBuilder); // 36 CIRCLE_NODE(GATHER_ND, CircleGatherNdGraphBuilder); // 107 CIRCLE_NODE(GREATER, CircleGreaterGraphBuilder); // 61 CIRCLE_NODE(GREATER_EQUAL, CircleGreaterEqualGraphBuilder); // 62 CIRCLE_NODE(IF, CircleIfGraphBuilder); // 118 CIRCLE_NODE(INSTANCE_NORM, CircleInstanceNormGraphBuilder); // 254 CIRCLE_NODE(L2_NORMALIZATION, CircleL2NormalizeGraphBuilder); // 11 CIRCLE_NODE(L2_POOL_2D, CircleL2Pool2DGraphBuilder); // 12 CIRCLE_NODE(LEAKY_RELU, CircleLeakyReluGraphBuilder); // 98, CIRCLE_NODE(LESS, CircleLessGraphBuilder); // 58 CIRCLE_NODE(LESS_EQUAL, CircleLessEqualGraphBuilder); // 63 CIRCLE_NODE(LOCAL_RESPONSE_NORMALIZATION, CircleLocalResponseNormalizationGraphBuilder); // 13 CIRCLE_NODE(LOG, CircleLogGraphBuilder); // 73 CIRCLE_NODE(LOGICAL_AND, CircleLogicalAndGraphBuilder); // 86 CIRCLE_NODE(LOGICAL_NOT, CircleLogicalNotGraphBuilder); // 87 CIRCLE_NODE(LOGICAL_OR, CircleLogicalOrGraphBuilder); // 84 CIRCLE_NODE(LOGISTIC, CircleLogisticGraphBuilder); // 14 CIRCLE_NODE(LOG_SOFTMAX, CircleLogSoftmaxGraphBuilder); // 50 CIRCLE_NODE(MATRIX_DIAG, CircleMatrixDiagGraphBuilder); // 113 CIRCLE_NODE(MATRIX_SET_DIAG, CircleMatrixSetDiagGraphBuilder); // 115 CIRCLE_NODE(MAXIMUM, CircleMaximumGraphBuilder); // 55 CIRCLE_NODE(MAX_POOL_2D, CircleMaxPool2DGraphBuilder); // 17 CIRCLE_NODE(MEAN, CircleMeanGraphBuilder); // 40 CIRCLE_NODE(MINIMUM, CircleMinimumGraphBuilder); // 57 CIRCLE_NODE(MIRROR_PAD, CircleMirrorPadGraphBuilder); // 100 CIRCLE_NODE(MUL, CircleMulGraphBuilder); // 18 CIRCLE_NODE(NEG, CircleNegGraphBuilder); // 59 CIRCLE_NODE(NON_MAX_SUPPRESSION_V4, CircleNonMaxSuppressionV4GraphBuilder); // 120, CIRCLE_NODE(NON_MAX_SUPPRESSION_V5, CircleNonMaxSuppressionV5GraphBuilder); // 121, CIRCLE_NODE(NOT_EQUAL, CircleNotEqualGraphBuilder); // 72 CIRCLE_NODE(ONE_HOT, CircleOneHotGraphBuilder); // 85 CIRCLE_NODE(PACK, CirclePackGraphBuilder); // 83 CIRCLE_NODE(PAD, CirclePadGraphBuilder); // 34 CIRCLE_NODE(PADV2, CirclePadV2GraphBuilder); // 60 CIRCLE_NODE(POW, CirclePowGraphBuilder); // 78 CIRCLE_NODE(PRELU, CirclePReluGraphBuilder); // 54, CIRCLE_NODE(RANGE, CircleRangeGraphBuilder); // 96 CIRCLE_NODE(RANK, CircleRankGraphBuilder); // 110 CIRCLE_NODE(REDUCE_ANY, CircleReduceAnyGraphBuilder); // 91 CIRCLE_NODE(REDUCE_MAX, CircleReduceMaxGraphBuilder); // 82 CIRCLE_NODE(REDUCE_MIN, CircleReduceMinGraphBuilder); // 89 CIRCLE_NODE(REDUCE_PROD, CircleReduceProdGraphBuilder); // 81 CIRCLE_NODE(RELU, CircleReluGraphBuilder); // 19 CIRCLE_NODE(RELU6, CircleRelu6GraphBuilder); // 21 CIRCLE_NODE(RELU_N1_TO_1, CircleReluN1To1GraphBuilder); // 20 CIRCLE_NODE(RESHAPE, CircleReshapeGraphBuilder); // 22 CIRCLE_NODE(RESIZE_BILINEAR, CircleResizeBilinearGraphBuilder); // 23 CIRCLE_NODE(RESIZE_NEAREST_NEIGHBOR, CircleResizeNearestNeighborGraphBuilder); // 97 CIRCLE_NODE(REVERSE_SEQUENCE, CircleReverseSequenceGraphBuilder); // 112 CIRCLE_NODE(REVERSE_V2, CircleReverseV2GraphBuilder); // 105 CIRCLE_NODE(ROUND, CircleRoundGraphBuilder); // 116 CIRCLE_NODE(RSQRT, CircleRsqrtGraphBuilder); // 76 CIRCLE_NODE(SCATTER_ND, CircleScatterNdGraphBuilder); // 122 CIRCLE_NODE(SEGMENT_SUM, CircleSegmentSumGraphBuilder); // 125 CIRCLE_NODE(SELECT, CircleSelectGraphBuilder); // 64 CIRCLE_NODE(SELECT_V2, CircleSelectV2GraphBuilder); // 123 CIRCLE_NODE(SHAPE, CircleShapeGraphBuilder); // 77 CIRCLE_NODE(SIN, CircleSinGraphBuilder); // 66 CIRCLE_NODE(SLICE, CircleSliceGraphBuilder); // 65 CIRCLE_NODE(SOFTMAX, CircleSoftmaxGraphBuilder); // 25 CIRCLE_NODE(SPACE_TO_BATCH_ND, CircleSpaceToBatchNDGraphBuilder); // 38 CIRCLE_NODE(SPACE_TO_DEPTH, CircleSpaceToDepthGraphBuilder); // 26 CIRCLE_NODE(SPARSE_TO_DENSE, CircleSparseToDenseGraphBuilder); // 68 CIRCLE_NODE(SPLIT, CircleSplitGraphBuilder); // 49 CIRCLE_NODE(SPLIT_V, CircleSplitVGraphBuilder); // 102 CIRCLE_NODE(SQRT, CircleSqrtGraphBuilder); // 75 CIRCLE_NODE(SQUARE, CircleSquareGraphBuilder); // 92 CIRCLE_NODE(SQUARED_DIFFERENCE, CircleSquaredDifferenceGraphBuilder); // 99 CIRCLE_NODE(SQUEEZE, CircleSqueezeGraphBuilder); // 43 CIRCLE_NODE(STRIDED_SLICE, CircleStridedSliceGraphBuilder); // 45 CIRCLE_NODE(SUB, CircleSubGraphBuilder); // 41 CIRCLE_NODE(SUM, CircleSumGraphBuilder); // 74 CIRCLE_NODE(TANH, CircleTanhGraphBuilder); // 28 CIRCLE_NODE(TILE, CircleTileGraphBuilder); // 69 CIRCLE_NODE(TOPK_V2, CircleTopKV2GraphBuilder); // 48 CIRCLE_NODE(TRANSPOSE, CircleTransposeGraphBuilder); // 39 CIRCLE_NODE(TRANSPOSE_CONV, CircleTransposeConvGraphBuilder); // 67 CIRCLE_NODE(UNIQUE, CircleUniqueGraphBuilder); // 103 CIRCLE_NODE(UNPACK, CircleUnpackGraphBuilder); // 88 CIRCLE_NODE(WHERE, CircleWhereGraphBuilder); // 109 CIRCLE_NODE(WHILE, CircleWhileGraphBuilder); // 119 CIRCLE_NODE(ZEROS_LIKE, CircleZerosLikeGraphBuilder); // 93 #undef CIRCLE_NODE // BuiltinOperator_EMBEDDING_LOOKUP = 7, // BuiltinOperator_HASHTABLE_LOOKUP = 10, // BuiltinOperator_LSH_PROJECTION = 15, // BuiltinOperator_LSTM = 16, // BuiltinOperator_RNN = 24, // BuiltinOperator_SVDF = 27, // BuiltinOperator_CONCAT_EMBEDDINGS = 29, // BuiltinOperator_SKIP_GRAM = 30, // BuiltinOperator_CALL = 31, // BuiltinOperator_EMBEDDING_LOOKUP_SPARSE = 33, // BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_RNN = 35, // BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM = 44, // BuiltinOperator_BIDIRECTIONAL_SEQUENCE_RNN = 46, // BuiltinOperator_DELEGATE = 51, // BuiltinOperator_BIDIRECTIONAL_SEQUENCE_LSTM = 52, // BuiltinOperator_ARG_MAX = 56, // BuiltinOperator_FAKE_QUANT = 80, // BuiltinOperator_QUANTIZE = 114, // BuiltinOperator_HARD_SWISH = 117, // BuiltinOperator_DENSIFY = 124, } } // namespace luci
75.239521
100
0.52877
wateret
8d8f2ea8a7ecb7dfebcebb3f6227866647f7a0a7
44,222
hpp
C++
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_FLASH_MIB.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_FLASH_MIB.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_FLASH_MIB.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_FLASH_MIB_ #define _CISCO_FLASH_MIB_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> namespace cisco_ios_xe { namespace CISCO_FLASH_MIB { class CISCOFLASHMIB : public ydk::Entity { public: CISCOFLASHMIB(); ~CISCOFLASHMIB(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::shared_ptr<ydk::Entity> clone_ptr() const override; ydk::augment_capabilities_function get_augment_capabilities_function() const override; std::string get_bundle_yang_models_location() const override; std::string get_bundle_name() const override; std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override; class CiscoFlashDevice; //type: CISCOFLASHMIB::CiscoFlashDevice class CiscoFlashCfg; //type: CISCOFLASHMIB::CiscoFlashCfg class CiscoFlashDeviceTable; //type: CISCOFLASHMIB::CiscoFlashDeviceTable class CiscoFlashChipTable; //type: CISCOFLASHMIB::CiscoFlashChipTable class CiscoFlashPartitionTable; //type: CISCOFLASHMIB::CiscoFlashPartitionTable class CiscoFlashFileTable; //type: CISCOFLASHMIB::CiscoFlashFileTable class CiscoFlashFileByTypeTable; //type: CISCOFLASHMIB::CiscoFlashFileByTypeTable class CiscoFlashCopyTable; //type: CISCOFLASHMIB::CiscoFlashCopyTable class CiscoFlashPartitioningTable; //type: CISCOFLASHMIB::CiscoFlashPartitioningTable class CiscoFlashMiscOpTable; //type: CISCOFLASHMIB::CiscoFlashMiscOpTable std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashDevice> ciscoflashdevice; std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashCfg> ciscoflashcfg; std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashDeviceTable> ciscoflashdevicetable; std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashChipTable> ciscoflashchiptable; std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashPartitionTable> ciscoflashpartitiontable; std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashFileTable> ciscoflashfiletable; std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashFileByTypeTable> ciscoflashfilebytypetable; std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashCopyTable> ciscoflashcopytable; std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashPartitioningTable> ciscoflashpartitioningtable; std::shared_ptr<cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashMiscOpTable> ciscoflashmiscoptable; }; // CISCOFLASHMIB class CISCOFLASHMIB::CiscoFlashDevice : public ydk::Entity { public: CiscoFlashDevice(); ~CiscoFlashDevice(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ciscoflashdevicessupported; //type: uint32 }; // CISCOFLASHMIB::CiscoFlashDevice class CISCOFLASHMIB::CiscoFlashCfg : public ydk::Entity { public: CiscoFlashCfg(); ~CiscoFlashCfg(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ciscoflashcfgdevinsnotifenable; //type: boolean ydk::YLeaf ciscoflashcfgdevremnotifenable; //type: boolean ydk::YLeaf ciscoflashpartitionlowspacenotifenable; //type: boolean }; // CISCOFLASHMIB::CiscoFlashCfg class CISCOFLASHMIB::CiscoFlashDeviceTable : public ydk::Entity { public: CiscoFlashDeviceTable(); ~CiscoFlashDeviceTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class CiscoFlashDeviceEntry; //type: CISCOFLASHMIB::CiscoFlashDeviceTable::CiscoFlashDeviceEntry ydk::YList ciscoflashdeviceentry; }; // CISCOFLASHMIB::CiscoFlashDeviceTable class CISCOFLASHMIB::CiscoFlashDeviceTable::CiscoFlashDeviceEntry : public ydk::Entity { public: CiscoFlashDeviceEntry(); ~CiscoFlashDeviceEntry(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ciscoflashdeviceindex; //type: uint32 ydk::YLeaf ciscoflashdevicesize; //type: uint32 ydk::YLeaf ciscoflashdeviceminpartitionsize; //type: uint32 ydk::YLeaf ciscoflashdevicemaxpartitions; //type: uint32 ydk::YLeaf ciscoflashdevicepartitions; //type: uint32 ydk::YLeaf ciscoflashdevicechipcount; //type: int32 ydk::YLeaf ciscoflashdevicename; //type: string ydk::YLeaf ciscoflashdevicedescr; //type: string ydk::YLeaf ciscoflashdevicecontroller; //type: string ydk::YLeaf ciscoflashdevicecard; //type: string ydk::YLeaf ciscoflashdeviceprogrammingjumper; //type: CiscoFlashDeviceProgrammingJumper ydk::YLeaf ciscoflashdeviceinittime; //type: uint32 ydk::YLeaf ciscoflashdeviceremovable; //type: boolean ydk::YLeaf ciscoflashphyentindex; //type: int32 ydk::YLeaf ciscoflashdevicenameextended; //type: string ydk::YLeaf ciscoflashdevicesizeextended; //type: uint64 ydk::YLeaf ciscoflashdeviceminpartitionsizeextended; //type: uint64 class CiscoFlashDeviceProgrammingJumper; }; // CISCOFLASHMIB::CiscoFlashDeviceTable::CiscoFlashDeviceEntry class CISCOFLASHMIB::CiscoFlashChipTable : public ydk::Entity { public: CiscoFlashChipTable(); ~CiscoFlashChipTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class CiscoFlashChipEntry; //type: CISCOFLASHMIB::CiscoFlashChipTable::CiscoFlashChipEntry ydk::YList ciscoflashchipentry; }; // CISCOFLASHMIB::CiscoFlashChipTable class CISCOFLASHMIB::CiscoFlashChipTable::CiscoFlashChipEntry : public ydk::Entity { public: CiscoFlashChipEntry(); ~CiscoFlashChipEntry(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; //type: uint32 (refers to cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashDeviceTable::CiscoFlashDeviceEntry::ciscoflashdeviceindex) ydk::YLeaf ciscoflashdeviceindex; ydk::YLeaf ciscoflashchipindex; //type: int32 ydk::YLeaf ciscoflashchipcode; //type: string ydk::YLeaf ciscoflashchipdescr; //type: string ydk::YLeaf ciscoflashchipwriteretries; //type: uint32 ydk::YLeaf ciscoflashchiperaseretries; //type: uint32 ydk::YLeaf ciscoflashchipmaxwriteretries; //type: uint32 ydk::YLeaf ciscoflashchipmaxeraseretries; //type: uint32 }; // CISCOFLASHMIB::CiscoFlashChipTable::CiscoFlashChipEntry class CISCOFLASHMIB::CiscoFlashPartitionTable : public ydk::Entity { public: CiscoFlashPartitionTable(); ~CiscoFlashPartitionTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class CiscoFlashPartitionEntry; //type: CISCOFLASHMIB::CiscoFlashPartitionTable::CiscoFlashPartitionEntry ydk::YList ciscoflashpartitionentry; }; // CISCOFLASHMIB::CiscoFlashPartitionTable class CISCOFLASHMIB::CiscoFlashPartitionTable::CiscoFlashPartitionEntry : public ydk::Entity { public: CiscoFlashPartitionEntry(); ~CiscoFlashPartitionEntry(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; //type: uint32 (refers to cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashDeviceTable::CiscoFlashDeviceEntry::ciscoflashdeviceindex) ydk::YLeaf ciscoflashdeviceindex; ydk::YLeaf ciscoflashpartitionindex; //type: uint32 ydk::YLeaf ciscoflashpartitionstartchip; //type: int32 ydk::YLeaf ciscoflashpartitionendchip; //type: int32 ydk::YLeaf ciscoflashpartitionsize; //type: uint32 ydk::YLeaf ciscoflashpartitionfreespace; //type: uint32 ydk::YLeaf ciscoflashpartitionfilecount; //type: uint32 ydk::YLeaf ciscoflashpartitionchecksumalgorithm; //type: CiscoFlashPartitionChecksumAlgorithm ydk::YLeaf ciscoflashpartitionstatus; //type: CiscoFlashPartitionStatus ydk::YLeaf ciscoflashpartitionupgrademethod; //type: CiscoFlashPartitionUpgradeMethod ydk::YLeaf ciscoflashpartitionname; //type: string ydk::YLeaf ciscoflashpartitionneederasure; //type: boolean ydk::YLeaf ciscoflashpartitionfilenamelength; //type: int32 ydk::YLeaf ciscoflashpartitionsizeextended; //type: uint64 ydk::YLeaf ciscoflashpartitionfreespaceextended; //type: uint64 ydk::YLeaf ciscoflashpartitionlowspacenotifthreshold; //type: int32 class CiscoFlashPartitionChecksumAlgorithm; class CiscoFlashPartitionStatus; class CiscoFlashPartitionUpgradeMethod; }; // CISCOFLASHMIB::CiscoFlashPartitionTable::CiscoFlashPartitionEntry class CISCOFLASHMIB::CiscoFlashFileTable : public ydk::Entity { public: CiscoFlashFileTable(); ~CiscoFlashFileTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class CiscoFlashFileEntry; //type: CISCOFLASHMIB::CiscoFlashFileTable::CiscoFlashFileEntry ydk::YList ciscoflashfileentry; }; // CISCOFLASHMIB::CiscoFlashFileTable class CISCOFLASHMIB::CiscoFlashFileTable::CiscoFlashFileEntry : public ydk::Entity { public: CiscoFlashFileEntry(); ~CiscoFlashFileEntry(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; //type: uint32 (refers to cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashDeviceTable::CiscoFlashDeviceEntry::ciscoflashdeviceindex) ydk::YLeaf ciscoflashdeviceindex; //type: uint32 (refers to cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashPartitionTable::CiscoFlashPartitionEntry::ciscoflashpartitionindex) ydk::YLeaf ciscoflashpartitionindex; ydk::YLeaf ciscoflashfileindex; //type: uint32 ydk::YLeaf ciscoflashfilesize; //type: uint32 ydk::YLeaf ciscoflashfilechecksum; //type: binary ydk::YLeaf ciscoflashfilestatus; //type: CiscoFlashFileStatus ydk::YLeaf ciscoflashfilename; //type: string ydk::YLeaf ciscoflashfiletype; //type: FlashFileType ydk::YLeaf ciscoflashfiledate; //type: string class CiscoFlashFileStatus; }; // CISCOFLASHMIB::CiscoFlashFileTable::CiscoFlashFileEntry class CISCOFLASHMIB::CiscoFlashFileByTypeTable : public ydk::Entity { public: CiscoFlashFileByTypeTable(); ~CiscoFlashFileByTypeTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class CiscoFlashFileByTypeEntry; //type: CISCOFLASHMIB::CiscoFlashFileByTypeTable::CiscoFlashFileByTypeEntry ydk::YList ciscoflashfilebytypeentry; }; // CISCOFLASHMIB::CiscoFlashFileByTypeTable class CISCOFLASHMIB::CiscoFlashFileByTypeTable::CiscoFlashFileByTypeEntry : public ydk::Entity { public: CiscoFlashFileByTypeEntry(); ~CiscoFlashFileByTypeEntry(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ciscoflashfiletype; //type: FlashFileType //type: uint32 (refers to cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashDeviceTable::CiscoFlashDeviceEntry::ciscoflashdeviceindex) ydk::YLeaf ciscoflashdeviceindex; //type: uint32 (refers to cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashPartitionTable::CiscoFlashPartitionEntry::ciscoflashpartitionindex) ydk::YLeaf ciscoflashpartitionindex; //type: uint32 (refers to cisco_ios_xe::CISCO_FLASH_MIB::CISCOFLASHMIB::CiscoFlashFileTable::CiscoFlashFileEntry::ciscoflashfileindex) ydk::YLeaf ciscoflashfileindex; ydk::YLeaf ciscoflashfilebytypesize; //type: uint32 ydk::YLeaf ciscoflashfilebytypechecksum; //type: binary ydk::YLeaf ciscoflashfilebytypestatus; //type: CiscoFlashFileByTypeStatus ydk::YLeaf ciscoflashfilebytypename; //type: string ydk::YLeaf ciscoflashfilebytypedate; //type: string class CiscoFlashFileByTypeStatus; }; // CISCOFLASHMIB::CiscoFlashFileByTypeTable::CiscoFlashFileByTypeEntry class CISCOFLASHMIB::CiscoFlashCopyTable : public ydk::Entity { public: CiscoFlashCopyTable(); ~CiscoFlashCopyTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class CiscoFlashCopyEntry; //type: CISCOFLASHMIB::CiscoFlashCopyTable::CiscoFlashCopyEntry ydk::YList ciscoflashcopyentry; }; // CISCOFLASHMIB::CiscoFlashCopyTable class CISCOFLASHMIB::CiscoFlashCopyTable::CiscoFlashCopyEntry : public ydk::Entity { public: CiscoFlashCopyEntry(); ~CiscoFlashCopyEntry(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ciscoflashcopyserialnumber; //type: int32 ydk::YLeaf ciscoflashcopycommand; //type: CiscoFlashCopyCommand ydk::YLeaf ciscoflashcopyprotocol; //type: CiscoFlashCopyProtocol ydk::YLeaf ciscoflashcopyserveraddress; //type: string ydk::YLeaf ciscoflashcopysourcename; //type: string ydk::YLeaf ciscoflashcopydestinationname; //type: string ydk::YLeaf ciscoflashcopyremoteusername; //type: string ydk::YLeaf ciscoflashcopystatus; //type: CiscoFlashCopyStatus ydk::YLeaf ciscoflashcopynotifyoncompletion; //type: boolean ydk::YLeaf ciscoflashcopytime; //type: uint32 ydk::YLeaf ciscoflashcopyentrystatus; //type: RowStatus ydk::YLeaf ciscoflashcopyverify; //type: boolean ydk::YLeaf ciscoflashcopyserveraddrtype; //type: InetAddressType ydk::YLeaf ciscoflashcopyserveraddrrev1; //type: binary ydk::YLeaf ciscoflashcopyremotepassword; //type: string class CiscoFlashCopyCommand; class CiscoFlashCopyProtocol; class CiscoFlashCopyStatus; }; // CISCOFLASHMIB::CiscoFlashCopyTable::CiscoFlashCopyEntry class CISCOFLASHMIB::CiscoFlashPartitioningTable : public ydk::Entity { public: CiscoFlashPartitioningTable(); ~CiscoFlashPartitioningTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class CiscoFlashPartitioningEntry; //type: CISCOFLASHMIB::CiscoFlashPartitioningTable::CiscoFlashPartitioningEntry ydk::YList ciscoflashpartitioningentry; }; // CISCOFLASHMIB::CiscoFlashPartitioningTable class CISCOFLASHMIB::CiscoFlashPartitioningTable::CiscoFlashPartitioningEntry : public ydk::Entity { public: CiscoFlashPartitioningEntry(); ~CiscoFlashPartitioningEntry(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ciscoflashpartitioningserialnumber; //type: int32 ydk::YLeaf ciscoflashpartitioningcommand; //type: CiscoFlashPartitioningCommand ydk::YLeaf ciscoflashpartitioningdestinationname; //type: string ydk::YLeaf ciscoflashpartitioningpartitioncount; //type: uint32 ydk::YLeaf ciscoflashpartitioningpartitionsizes; //type: string ydk::YLeaf ciscoflashpartitioningstatus; //type: CiscoFlashPartitioningStatus ydk::YLeaf ciscoflashpartitioningnotifyoncompletion; //type: boolean ydk::YLeaf ciscoflashpartitioningtime; //type: uint32 ydk::YLeaf ciscoflashpartitioningentrystatus; //type: RowStatus class CiscoFlashPartitioningCommand; class CiscoFlashPartitioningStatus; }; // CISCOFLASHMIB::CiscoFlashPartitioningTable::CiscoFlashPartitioningEntry class CISCOFLASHMIB::CiscoFlashMiscOpTable : public ydk::Entity { public: CiscoFlashMiscOpTable(); ~CiscoFlashMiscOpTable(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class CiscoFlashMiscOpEntry; //type: CISCOFLASHMIB::CiscoFlashMiscOpTable::CiscoFlashMiscOpEntry ydk::YList ciscoflashmiscopentry; }; // CISCOFLASHMIB::CiscoFlashMiscOpTable class CISCOFLASHMIB::CiscoFlashMiscOpTable::CiscoFlashMiscOpEntry : public ydk::Entity { public: CiscoFlashMiscOpEntry(); ~CiscoFlashMiscOpEntry(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf ciscoflashmiscopserialnumber; //type: int32 ydk::YLeaf ciscoflashmiscopcommand; //type: CiscoFlashMiscOpCommand ydk::YLeaf ciscoflashmiscopdestinationname; //type: string ydk::YLeaf ciscoflashmiscopstatus; //type: CiscoFlashMiscOpStatus ydk::YLeaf ciscoflashmiscopnotifyoncompletion; //type: boolean ydk::YLeaf ciscoflashmiscoptime; //type: uint32 ydk::YLeaf ciscoflashmiscopentrystatus; //type: RowStatus class CiscoFlashMiscOpCommand; class CiscoFlashMiscOpStatus; }; // CISCOFLASHMIB::CiscoFlashMiscOpTable::CiscoFlashMiscOpEntry class FlashFileType : public ydk::Enum { public: static const ydk::Enum::YLeaf unknown; static const ydk::Enum::YLeaf config; static const ydk::Enum::YLeaf image; static const ydk::Enum::YLeaf directory; static const ydk::Enum::YLeaf crashinfo; static int get_enum_value(const std::string & name) { if (name == "unknown") return 1; if (name == "config") return 2; if (name == "image") return 3; if (name == "directory") return 4; if (name == "crashinfo") return 5; return -1; } }; class CISCOFLASHMIB::CiscoFlashDeviceTable::CiscoFlashDeviceEntry::CiscoFlashDeviceProgrammingJumper : public ydk::Enum { public: static const ydk::Enum::YLeaf installed; static const ydk::Enum::YLeaf notInstalled; static const ydk::Enum::YLeaf unknown; static int get_enum_value(const std::string & name) { if (name == "installed") return 1; if (name == "notInstalled") return 2; if (name == "unknown") return 3; return -1; } }; class CISCOFLASHMIB::CiscoFlashPartitionTable::CiscoFlashPartitionEntry::CiscoFlashPartitionChecksumAlgorithm : public ydk::Enum { public: static const ydk::Enum::YLeaf simpleChecksum; static const ydk::Enum::YLeaf undefined; static const ydk::Enum::YLeaf simpleCRC; static int get_enum_value(const std::string & name) { if (name == "simpleChecksum") return 1; if (name == "undefined") return 2; if (name == "simpleCRC") return 3; return -1; } }; class CISCOFLASHMIB::CiscoFlashPartitionTable::CiscoFlashPartitionEntry::CiscoFlashPartitionStatus : public ydk::Enum { public: static const ydk::Enum::YLeaf readOnly; static const ydk::Enum::YLeaf runFromFlash; static const ydk::Enum::YLeaf readWrite; static int get_enum_value(const std::string & name) { if (name == "readOnly") return 1; if (name == "runFromFlash") return 2; if (name == "readWrite") return 3; return -1; } }; class CISCOFLASHMIB::CiscoFlashPartitionTable::CiscoFlashPartitionEntry::CiscoFlashPartitionUpgradeMethod : public ydk::Enum { public: static const ydk::Enum::YLeaf unknown; static const ydk::Enum::YLeaf rxbootFLH; static const ydk::Enum::YLeaf direct; static int get_enum_value(const std::string & name) { if (name == "unknown") return 1; if (name == "rxbootFLH") return 2; if (name == "direct") return 3; return -1; } }; class CISCOFLASHMIB::CiscoFlashFileTable::CiscoFlashFileEntry::CiscoFlashFileStatus : public ydk::Enum { public: static const ydk::Enum::YLeaf deleted; static const ydk::Enum::YLeaf invalidChecksum; static const ydk::Enum::YLeaf valid; static int get_enum_value(const std::string & name) { if (name == "deleted") return 1; if (name == "invalidChecksum") return 2; if (name == "valid") return 3; return -1; } }; class CISCOFLASHMIB::CiscoFlashFileByTypeTable::CiscoFlashFileByTypeEntry::CiscoFlashFileByTypeStatus : public ydk::Enum { public: static const ydk::Enum::YLeaf deleted; static const ydk::Enum::YLeaf invalidChecksum; static const ydk::Enum::YLeaf valid; static int get_enum_value(const std::string & name) { if (name == "deleted") return 1; if (name == "invalidChecksum") return 2; if (name == "valid") return 3; return -1; } }; class CISCOFLASHMIB::CiscoFlashCopyTable::CiscoFlashCopyEntry::CiscoFlashCopyCommand : public ydk::Enum { public: static const ydk::Enum::YLeaf copyToFlashWithErase; static const ydk::Enum::YLeaf copyToFlashWithoutErase; static const ydk::Enum::YLeaf copyFromFlash; static const ydk::Enum::YLeaf copyFromFlhLog; static int get_enum_value(const std::string & name) { if (name == "copyToFlashWithErase") return 1; if (name == "copyToFlashWithoutErase") return 2; if (name == "copyFromFlash") return 3; if (name == "copyFromFlhLog") return 4; return -1; } }; class CISCOFLASHMIB::CiscoFlashCopyTable::CiscoFlashCopyEntry::CiscoFlashCopyProtocol : public ydk::Enum { public: static const ydk::Enum::YLeaf tftp; static const ydk::Enum::YLeaf rcp; static const ydk::Enum::YLeaf lex; static const ydk::Enum::YLeaf ftp; static const ydk::Enum::YLeaf scp; static const ydk::Enum::YLeaf sftp; static int get_enum_value(const std::string & name) { if (name == "tftp") return 1; if (name == "rcp") return 2; if (name == "lex") return 3; if (name == "ftp") return 4; if (name == "scp") return 5; if (name == "sftp") return 6; return -1; } }; class CISCOFLASHMIB::CiscoFlashCopyTable::CiscoFlashCopyEntry::CiscoFlashCopyStatus : public ydk::Enum { public: static const ydk::Enum::YLeaf copyOperationPending; static const ydk::Enum::YLeaf copyInProgress; static const ydk::Enum::YLeaf copyOperationSuccess; static const ydk::Enum::YLeaf copyInvalidOperation; static const ydk::Enum::YLeaf copyInvalidProtocol; static const ydk::Enum::YLeaf copyInvalidSourceName; static const ydk::Enum::YLeaf copyInvalidDestName; static const ydk::Enum::YLeaf copyInvalidServerAddress; static const ydk::Enum::YLeaf copyDeviceBusy; static const ydk::Enum::YLeaf copyDeviceOpenError; static const ydk::Enum::YLeaf copyDeviceError; static const ydk::Enum::YLeaf copyDeviceNotProgrammable; static const ydk::Enum::YLeaf copyDeviceFull; static const ydk::Enum::YLeaf copyFileOpenError; static const ydk::Enum::YLeaf copyFileTransferError; static const ydk::Enum::YLeaf copyFileChecksumError; static const ydk::Enum::YLeaf copyNoMemory; static const ydk::Enum::YLeaf copyUnknownFailure; static const ydk::Enum::YLeaf copyInvalidSignature; static const ydk::Enum::YLeaf copyProhibited; static int get_enum_value(const std::string & name) { if (name == "copyOperationPending") return 0; if (name == "copyInProgress") return 1; if (name == "copyOperationSuccess") return 2; if (name == "copyInvalidOperation") return 3; if (name == "copyInvalidProtocol") return 4; if (name == "copyInvalidSourceName") return 5; if (name == "copyInvalidDestName") return 6; if (name == "copyInvalidServerAddress") return 7; if (name == "copyDeviceBusy") return 8; if (name == "copyDeviceOpenError") return 9; if (name == "copyDeviceError") return 10; if (name == "copyDeviceNotProgrammable") return 11; if (name == "copyDeviceFull") return 12; if (name == "copyFileOpenError") return 13; if (name == "copyFileTransferError") return 14; if (name == "copyFileChecksumError") return 15; if (name == "copyNoMemory") return 16; if (name == "copyUnknownFailure") return 17; if (name == "copyInvalidSignature") return 18; if (name == "copyProhibited") return 19; return -1; } }; class CISCOFLASHMIB::CiscoFlashPartitioningTable::CiscoFlashPartitioningEntry::CiscoFlashPartitioningCommand : public ydk::Enum { public: static const ydk::Enum::YLeaf partition; static int get_enum_value(const std::string & name) { if (name == "partition") return 1; return -1; } }; class CISCOFLASHMIB::CiscoFlashPartitioningTable::CiscoFlashPartitioningEntry::CiscoFlashPartitioningStatus : public ydk::Enum { public: static const ydk::Enum::YLeaf partitioningInProgress; static const ydk::Enum::YLeaf partitioningOperationSuccess; static const ydk::Enum::YLeaf partitioningInvalidOperation; static const ydk::Enum::YLeaf partitioningInvalidDestName; static const ydk::Enum::YLeaf partitioningInvalidPartitionCount; static const ydk::Enum::YLeaf partitioningInvalidPartitionSizes; static const ydk::Enum::YLeaf partitioningDeviceBusy; static const ydk::Enum::YLeaf partitioningDeviceOpenError; static const ydk::Enum::YLeaf partitioningDeviceError; static const ydk::Enum::YLeaf partitioningNoMemory; static const ydk::Enum::YLeaf partitioningUnknownFailure; static int get_enum_value(const std::string & name) { if (name == "partitioningInProgress") return 1; if (name == "partitioningOperationSuccess") return 2; if (name == "partitioningInvalidOperation") return 3; if (name == "partitioningInvalidDestName") return 4; if (name == "partitioningInvalidPartitionCount") return 5; if (name == "partitioningInvalidPartitionSizes") return 6; if (name == "partitioningDeviceBusy") return 7; if (name == "partitioningDeviceOpenError") return 8; if (name == "partitioningDeviceError") return 9; if (name == "partitioningNoMemory") return 10; if (name == "partitioningUnknownFailure") return 11; return -1; } }; class CISCOFLASHMIB::CiscoFlashMiscOpTable::CiscoFlashMiscOpEntry::CiscoFlashMiscOpCommand : public ydk::Enum { public: static const ydk::Enum::YLeaf erase; static const ydk::Enum::YLeaf verify; static const ydk::Enum::YLeaf delete_; static const ydk::Enum::YLeaf undelete; static const ydk::Enum::YLeaf squeeze; static const ydk::Enum::YLeaf format; static int get_enum_value(const std::string & name) { if (name == "erase") return 1; if (name == "verify") return 2; if (name == "delete") return 3; if (name == "undelete") return 4; if (name == "squeeze") return 5; if (name == "format") return 6; return -1; } }; class CISCOFLASHMIB::CiscoFlashMiscOpTable::CiscoFlashMiscOpEntry::CiscoFlashMiscOpStatus : public ydk::Enum { public: static const ydk::Enum::YLeaf miscOpInProgress; static const ydk::Enum::YLeaf miscOpOperationSuccess; static const ydk::Enum::YLeaf miscOpInvalidOperation; static const ydk::Enum::YLeaf miscOpInvalidDestName; static const ydk::Enum::YLeaf miscOpDeviceBusy; static const ydk::Enum::YLeaf miscOpDeviceOpenError; static const ydk::Enum::YLeaf miscOpDeviceError; static const ydk::Enum::YLeaf miscOpDeviceNotProgrammable; static const ydk::Enum::YLeaf miscOpFileOpenError; static const ydk::Enum::YLeaf miscOpFileDeleteFailure; static const ydk::Enum::YLeaf miscOpFileUndeleteFailure; static const ydk::Enum::YLeaf miscOpFileChecksumError; static const ydk::Enum::YLeaf miscOpNoMemory; static const ydk::Enum::YLeaf miscOpUnknownFailure; static const ydk::Enum::YLeaf miscOpSqueezeFailure; static const ydk::Enum::YLeaf miscOpNoSuchFile; static const ydk::Enum::YLeaf miscOpFormatFailure; static int get_enum_value(const std::string & name) { if (name == "miscOpInProgress") return 1; if (name == "miscOpOperationSuccess") return 2; if (name == "miscOpInvalidOperation") return 3; if (name == "miscOpInvalidDestName") return 4; if (name == "miscOpDeviceBusy") return 5; if (name == "miscOpDeviceOpenError") return 6; if (name == "miscOpDeviceError") return 7; if (name == "miscOpDeviceNotProgrammable") return 8; if (name == "miscOpFileOpenError") return 9; if (name == "miscOpFileDeleteFailure") return 10; if (name == "miscOpFileUndeleteFailure") return 11; if (name == "miscOpFileChecksumError") return 12; if (name == "miscOpNoMemory") return 13; if (name == "miscOpUnknownFailure") return 14; if (name == "miscOpSqueezeFailure") return 18; if (name == "miscOpNoSuchFile") return 19; if (name == "miscOpFormatFailure") return 20; return -1; } }; } } #endif /* _CISCO_FLASH_MIB_ */
50.08154
162
0.696735
CiscoDevNet
8d944ad508ecbc8b3457f025a558c30d21065fea
2,273
cpp
C++
cheats/hooks/paintTraverse.cpp
DemonLoverHvH/csgo
f7ff0211fd843bbf00cac5aa62422e5588552b23
[ "MIT" ]
null
null
null
cheats/hooks/paintTraverse.cpp
DemonLoverHvH/csgo
f7ff0211fd843bbf00cac5aa62422e5588552b23
[ "MIT" ]
null
null
null
cheats/hooks/paintTraverse.cpp
DemonLoverHvH/csgo
f7ff0211fd843bbf00cac5aa62422e5588552b23
[ "MIT" ]
null
null
null
#include "hooks.hpp" #include "../menu/menuX88.hpp" #include "../features/visuals/player.hpp" #include "../features/aimbot/aimbot.hpp" #include "../features/visuals/world.hpp" #include "../features/visuals/radar.hpp" #include "../features/misc/misc.hpp" #include "../menu/GUI/drawing.hpp" #include "../globals.hpp" #pragma region "Paint Helpers" bool shouldReloadsFonts() { static int oldX, oldY, x, y; interfaces::engine->getScreenSize(x, y); if (x != oldX || y != oldY) { oldX = x; oldY = y; return true; } return false; } bool isValidWindow() { // sub window is better, for cs as they recently updated main window name #ifdef _DEBUG if (auto window = FindWindowA("Valve001", NULL); GetForegroundWindow() != window) return false; #else if (auto window = LF(FindWindowA).cached()(XOR("Valve001"), NULL); LF(GetForegroundWindow).cached()() != window) return false; #endif return true; } void guiStates() { #ifdef _DEBUG for (short i = 0; i < 256; i++) { globals::previousKeyState[i] = globals::keyState[i]; globals::keyState[i] = static_cast<bool>(GetAsyncKeyState(i)); } #else for (short i = 0; i < 256; i++) { globals::previousKeyState[i] = globals::keyState[i]; globals::keyState[i] = static_cast<bool>(LF(GetAsyncKeyState).cached()(i)); } #endif interfaces::surface->getCursor(globals::mouseX, globals::mouseY); } #pragma endregion void __stdcall hooks::paintTraverse::hooked(unsigned int panel, bool forceRepaint, bool allowForce) { if (!isValidWindow()) return; // will run first no matter what, you can edit the function a bit or add ghetto static counter if (shouldReloadsFonts()) render::init(); if (strstr(interfaces::panel->getName(panel), XOR("HudZoom"))) { if (interfaces::engine->isInGame()) return; } original(interfaces::panel, panel, forceRepaint, allowForce); if (strstr(interfaces::panel->getName(panel), XOR("MatSystemTopPanel"))) { guiStates(); //Menu::g().draw(); //Menu::g().handleKeys(); esp::run(); world::drawMisc(); radar::run(); misc::drawLocalInfo(); misc::drawFpsPlot(); misc::drawVelocityPlot(); misc::drawHitmarker(); world::drawZeusRange(); misc::drawNoScope(); misc::drawCrosshair(); // testing image, all good //test::run(); GUI::draw(); } }
23.677083
113
0.678839
DemonLoverHvH
8d94fb1a5d590c30fa82d32647ef6540e428086d
9,299
cpp
C++
ex_4/ex_4.cpp
davidjgmarques/Monte-Carlo-exercises
6c31d524ebfcb434799b86714a7209193729d2d7
[ "MIT" ]
null
null
null
ex_4/ex_4.cpp
davidjgmarques/Monte-Carlo-exercises
6c31d524ebfcb434799b86714a7209193729d2d7
[ "MIT" ]
null
null
null
ex_4/ex_4.cpp
davidjgmarques/Monte-Carlo-exercises
6c31d524ebfcb434799b86714a7209193729d2d7
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <math.h> #include <chrono> #include <ctime> #include <cstdlib> #include <time.h> #include <vector> #include <random> #include "TCanvas.h" #include "TStyle.h" #include "TGraph.h" #include "TEllipse.h" #include "TAxis.h" #include "TLine.h" #include "TH1F.h" #include "TF1.h" #include "TApplication.h" using namespace std; double f_rng (double min, double max) { double val = ( (double)rand() / RAND_MAX ) * ( max - min ) + min; return val; } int f_rng_int ( int min, int max ) { int val = rand() % max + min; return val; } vector <int> throw_n_dice ( int n ) { vector<int> val; int rgn; for(int i = 0; i < n; i++){ rgn = f_rng_int(1,6); val.push_back(rgn); } sort ( val.begin(), val.end(), greater<int>()); return val; } tuple < int , int > Single_round ( vector<int> attack, vector<int> def ) { int won = 0.; int lost = 0.; int diff = min ( attack.size(), def.size() ); for ( size_t i = 0; i < diff; ++i ) { if ( attack[i] > def[i] ) won++; else lost++; } return make_tuple ( won, lost ); } tuple < int , int > Complete_war ( int initial_attack, int initial_defence ) { int attack = initial_attack; int defence = initial_defence; int win_attack; int lose_attack; vector <int> dice_attack; vector <int> dice_defence; while ( ( attack > 1 ) && ( defence > 0 ) ) { dice_attack = throw_n_dice ( min ( 3, attack - 1 ) ); dice_defence = throw_n_dice ( min ( 3, defence ) ); tie ( win_attack, lose_attack ) = Single_round ( dice_attack, dice_defence ); defence -= win_attack; attack -= lose_attack; } return make_tuple(attack,defence); } int main() { TApplication *myapp=new TApplication("myapp",0,0); int nBins1 = 26; int nBins2 = 10; TH1F * hDistrNumb = new TH1F("","",6,0.5,6.5); TH1F * hQuickFight = new TH1F("","",6,-1.5,4.5); TH1F * hArmiesWon80 = new TH1F("","",nBins1,-0.5,25.5); TH1F * hLeftArmiesWon80 = new TH1F("","",nBins2,-0.5,9.5); TH1F * h6LeftArmiesWon80 = new TH1F("","",nBins1,-0.5,25.5); vector<int> quick_attack; vector<int> quick_defence; ////////////////// 4.0 ////////////////// double rolls = 1e5; for ( int k = 0; k < rolls; k++ ){ quick_attack = throw_n_dice(3); quick_defence = throw_n_dice(3); int quick_survivors; int quick_deseased; for ( size_t i = 0; i < quick_attack.size(); ++i ) hDistrNumb->Fill( quick_attack [i] ); tie ( quick_survivors, quick_deseased ) = Single_round ( quick_attack, quick_defence ); hQuickFight -> Fill( quick_survivors ); } double average_survivors = hQuickFight->GetMean()/3.; cout << "Average number of armies won by dice roll: " << average_survivors << endl; ////////////////// 4.1 ////////////////// int initial_def = 3; int attackers_left; int defencers_left; for ( int init_at = 0; init_at < nBins1; init_at++){ for ( int k = 0; k < rolls; k++ ){ tie ( attackers_left, defencers_left ) = Complete_war ( init_at, initial_def ); if ( attackers_left > defencers_left ) { hArmiesWon80 -> Fill ( init_at ); if ( attackers_left > 5 ) { h6LeftArmiesWon80 -> Fill ( init_at ); } } if ( init_at == 9){ hLeftArmiesWon80 -> Fill ( attackers_left ); } } } double ThreshProb = 80; TLine * L_ThreshProb = new TLine(-0.5,ThreshProb,25.5,ThreshProb); L_ThreshProb->SetLineColor(kRed); L_ThreshProb->SetLineWidth(2); L_ThreshProb->SetLineStyle(2); gStyle->SetOptStat(110); TCanvas * c2 = new TCanvas("c2","c2",1000,700); c2->cd(); double factor = (double) 100. / rolls; hQuickFight->Scale((double) factor); hQuickFight->SetLineColor(kAzure-5); hQuickFight->SetTitle(""); hQuickFight->SetLineWidth(2); hQuickFight->SetFillStyle(3003); hQuickFight->SetFillColor(kAzure+5); hQuickFight->GetYaxis()->SetTitle("Probability [%]"); hQuickFight->GetYaxis()->SetTitleOffset(1.0); hQuickFight->GetYaxis()->SetTitleSize(0.045); hQuickFight->GetXaxis()->SetTitleSize(0.045); hQuickFight->GetXaxis()->SetTitle("Number of surviving armies"); hQuickFight->GetYaxis()->SetRangeUser(0,50); hQuickFight->Draw("hist"); c2->SaveAs("Distr_won_armies_single_round.pdf"); gStyle->SetOptStat(0); TCanvas * c3 = new TCanvas("c3","c3",1000,700); c3->cd(); double factor1 = (double) 100. / rolls; hArmiesWon80->Scale((double) factor1); hArmiesWon80->SetLineColor(kAzure-5); hArmiesWon80->SetTitle(""); hArmiesWon80->SetLineWidth(2); hArmiesWon80->SetFillStyle(3003); hArmiesWon80->SetFillColor(kAzure+5); hArmiesWon80->GetYaxis()->SetTitle("Probability [%]"); hArmiesWon80->GetYaxis()->SetTitleOffset(1.0); hArmiesWon80->GetYaxis()->SetTitleSize(0.045); hArmiesWon80->GetXaxis()->SetTitleOffset(1.0); hArmiesWon80->GetXaxis()->SetTitleSize(0.045); hArmiesWon80->GetXaxis()->SetTitle("Number of initial armies"); hArmiesWon80->Draw("HIST"); L_ThreshProb->Draw("same"); c3->SaveAs("Distribution_80_percent.pdf"); // TCanvas * c4 = new TCanvas("c4","c4",1000,700); // c4->cd(); // hDistrNumb->SetLineColor(kAzure-5); // hDistrNumb->SetTitle(""); // hDistrNumb->SetLineWidth(2); // hDistrNumb->SetFillStyle(3003); // hDistrNumb->SetFillColor(kAzure+5); // hDistrNumb->GetYaxis()->SetTitle("Counts"); // hDistrNumb->GetYaxis()->SetTitleOffset(1.0); // hDistrNumb->GetYaxis()->SetTitleSize(0.045); // hDistrNumb->GetXaxis()->SetTitleOffset(1.0); // hDistrNumb->GetXaxis()->SetTitleSize(0.045); // hDistrNumb->GetXaxis()->SetTitle("Dice outcome"); // hDistrNumb->GetYaxis()->SetRangeUser(0,int((rolls*3/6)+rolls*0.2)); // hDistrNumb->Draw(); // c4->SaveAs("Distribution_numbers_per_die.pdf"); TCanvas * c5 = new TCanvas("c5","c5",1000,700); c5->cd(); double factor2 = (double) 100. / rolls; hLeftArmiesWon80->Scale((double) factor2); hLeftArmiesWon80->SetLineColor(kAzure-5); hLeftArmiesWon80->SetTitle(""); hLeftArmiesWon80->SetLineWidth(2); hLeftArmiesWon80->SetFillStyle(3003); hLeftArmiesWon80->SetFillColor(kAzure+5); hLeftArmiesWon80->GetYaxis()->SetTitle("Probability [%]"); hLeftArmiesWon80->GetYaxis()->SetTitleOffset(1.0); hLeftArmiesWon80->GetYaxis()->SetTitleSize(0.045); hLeftArmiesWon80->GetXaxis()->SetTitleOffset(1.0); hLeftArmiesWon80->GetXaxis()->SetTitleSize(0.045); hLeftArmiesWon80->GetXaxis()->SetTitle("Number of attacker surviving armies"); hLeftArmiesWon80->Draw("HIST"); c5->SaveAs("Distribution_of_armies_won2.pdf"); TCanvas * c6 = new TCanvas("c6","c6",1000,700); c6->cd(); double factor3 = (double) 100. / rolls; h6LeftArmiesWon80->Scale((double) factor3); h6LeftArmiesWon80->SetLineColor(kAzure-5); h6LeftArmiesWon80->SetTitle(""); h6LeftArmiesWon80->SetLineWidth(2); h6LeftArmiesWon80->SetFillStyle(3003); h6LeftArmiesWon80->SetFillColor(kAzure+5); h6LeftArmiesWon80->GetYaxis()->SetTitle("Probability [%]"); h6LeftArmiesWon80->GetYaxis()->SetTitleOffset(1.0); h6LeftArmiesWon80->GetYaxis()->SetTitleOffset(1.0); h6LeftArmiesWon80->GetYaxis()->SetTitleSize(0.045); h6LeftArmiesWon80->GetXaxis()->SetTitleOffset(1.0); h6LeftArmiesWon80->GetXaxis()->SetTitleSize(0.045); h6LeftArmiesWon80->GetXaxis()->SetTitle("Number of initial armies"); h6LeftArmiesWon80->Draw("HIST"); L_ThreshProb->Draw("same"); c6->SaveAs("Distribution_of_armies_won_6_80.pdf"); int minArmies; for ( int i = 0; i < nBins1 + 1; i++ ) { cout << "i: " << i << ", with prob: " << hArmiesWon80 -> GetBinContent( i + 1 ) << endl; if ( hArmiesWon80 -> GetBinContent( i + 1 ) >= 80){ minArmies = i; break; } } cout << "Minimum armies to win the war with probability superior to 80%: " << minArmies << "\n" << endl; int n_rem_min = 6; double prob_n_rem_min = 0.; for ( int i = 0; i < nBins2 + 1; i++ ) { cout << "i: " << i << ", with prob: " << hLeftArmiesWon80 -> GetBinContent ( i + 1 ) << endl; if ( i >= n_rem_min ) prob_n_rem_min += hLeftArmiesWon80 -> GetBinContent ( i + 1 ); } cout << "The prob. of finishing the attack with 6 or more armies is: " << prob_n_rem_min << "\n" << endl; int minArmiesAt80; for ( int i = 0; i < nBins1 + 1; i++ ) { cout << "i: " << i << ", with prob: " << h6LeftArmiesWon80 -> GetBinContent( i + 1 ) << endl; if ( h6LeftArmiesWon80 -> GetBinContent( i + 1 ) >= 80){ minArmiesAt80 = i; break; } } cout << "Minimum armies to finish the war with more than 6 armies in 80% of the cases: " << minArmiesAt80 << "\n" << endl; myapp->Run(); return 0; }
30.488525
126
0.600172
davidjgmarques
8d953c9d558715d34c2319378d578e180bb35e12
3,682
cpp
C++
src/VDF/Sources/Evaluateurs/Eval_Puiss_Neutr_VDF_Elem.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
1
2021-10-04T09:20:19.000Z
2021-10-04T09:20:19.000Z
src/VDF/Sources/Evaluateurs/Eval_Puiss_Neutr_VDF_Elem.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
null
null
null
src/VDF/Sources/Evaluateurs/Eval_Puiss_Neutr_VDF_Elem.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2015 - 2016, CEA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// // // File: Eval_Puiss_Neutr_VDF_Elem.cpp // Directory: $TRUST_ROOT/src/VDF/Sources/Evaluateurs // Version: /main/9 // ////////////////////////////////////////////////////////////////////////////// #include <Eval_Puiss_Neutr_VDF_Elem.h> #include <Champ_Don.h> #include <Zone_VDF.h> #include <Parser.h> #include <Sous_Zone.h> #include <Champ_Uniforme.h> void Eval_Puiss_Neutr_VDF_Elem::associer_champs(const Champ_Don& rho, const Champ_Don& capa, const Champ_Don& Q) { rho_ref = rho; rho_ref_ = rho(0,0); Cp = capa; Cp_ = capa(0,0); la_puissance = ref_cast(Champ_Uniforme,Q.valeur()); puissance = Q(0,0); } void Eval_Puiss_Neutr_VDF_Elem::associer_repartition(const Nom& n, const Nom& nom_ssz) { const int nb_elem = la_zone->nb_elem(); const DoubleTab& xp = la_zone->xp(); const Sous_Zone& ssz = la_zone->zone().domaine().ss_zone(nom_ssz); fxyz = n; String2 sfxyz(fxyz.getChar()); Parser p(sfxyz,3); p.addVar("x"); p.addVar("y"); p.addVar("z"); p.parseString(); rep.resize(nb_elem); rep = 0.; for(int i=0; i<ssz.nb_elem_tot(); i++) rep(ssz(i))=1.; for (int i=0; i<nb_elem; i++) { double x,y,z; x = xp(i,0); y = xp(i,1); if (Objet_U::dimension == 3) z = xp(i,2); else z=0.; p.setVar("x",x); p.setVar("y",y); p.setVar("z",z); rep(i) *= p.eval(); } } void Eval_Puiss_Neutr_VDF_Elem::mettre_a_jour( ) { puissance = la_puissance->valeurs()(0); // on met a jour le tableau de puissance } void Eval_Puiss_Neutr_VDF_Elem::completer() { Evaluateur_Source_VDF_Elem::completer(); /*volume_tot = 0.; const int nb_elem = la_zone->nb_elem(); for (int i=0;i<nb_elem;i++) volume_tot += volumes(i); */ //Cerr << "Volume total du domaine contenant les termes sources de neutronique " << volume_tot << finl; }
39.591398
260
0.63308
pledac
8d95b9dab635a3344095a5716af257b108db208f
43
hh
C++
Include/Luce/IsOriginalType.hh
kmc7468/luce
6f71407f250dbc0428ceba33aeef345cc601db34
[ "MIT" ]
23
2017-02-09T11:48:01.000Z
2017-04-08T10:19:21.000Z
Include/Luce/IsOriginalType.hh
kmc7468/luce
6f71407f250dbc0428ceba33aeef345cc601db34
[ "MIT" ]
null
null
null
Include/Luce/IsOriginalType.hh
kmc7468/luce
6f71407f250dbc0428ceba33aeef345cc601db34
[ "MIT" ]
null
null
null
#include <Luce/TypeTrait/IsOriginalType.hh>
43
43
0.837209
kmc7468
8d95dbe987289460d119fa679b03aa406d3fc39d
1,345
cpp
C++
201-300/279-Perfect_Squares-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
201-300/279-Perfect_Squares-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
201-300/279-Perfect_Squares-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// Given a positive integer n, find the least number of perfect square numbers // (for example, 1, 4, 9, 16, ...) which sum to n. // For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, // return 2 because 13 = 4 + 9. // Credits: // Special thanks to @jianchao.li.fighter for adding this problem and creating // all test cases. class Solution { public: int numSquares(int n) { vector<int> dp(n + 1, INT_MAX); dp[0] = 0; // for(int i = 1; i <= n; ++i) // for(int j = 1, j_squ; (j_squ = j * j) <= i; ++j) for (int j = 1, j_squ; (j_squ = j * j) <= n; ++j) for (int i = j_squ; i <= n; ++i) dp[i] = min(dp[i], dp[i - j_squ] + 1); return dp[n]; } }; // mathematical way // https://www.alpertron.com.ar/4SQUARES.HTM class Solution { public: int is_square(int n) { int t = sqrt(n); return t * t == n; } int numSquares(int n) { // case 1 if (is_square(n)) return 1; // case 4: 4^r(8k + 7) while (n % 4 == 0) n /= 4; if (n % 8 == 7) return 4; // case 2 for (int i = 1, i_squ; (i_squ = i * i) <= n; ++i) if (is_square(n - i_squ)) return 2; // case 3 return 3; } };
24.907407
79
0.466171
ysmiles
8d95fe88cdcb44732db0ad8b72a04e01decd8489
2,279
cpp
C++
libsrc/leddevice/dev_other/LedDeviceFile.cpp
Bosken85/hyperion.ng
55253b53224b2598b454e561127c23376ff73e2e
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
3
2017-01-11T07:03:13.000Z
2020-09-29T05:17:21.000Z
libsrc/leddevice/dev_other/LedDeviceFile.cpp
Bosken85/hyperion.ng
55253b53224b2598b454e561127c23376ff73e2e
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
4
2018-01-02T23:19:58.000Z
2019-08-31T10:02:52.000Z
libsrc/leddevice/dev_other/LedDeviceFile.cpp
Bosken85/hyperion.ng
55253b53224b2598b454e561127c23376ff73e2e
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
7
2018-01-02T21:30:25.000Z
2018-10-09T07:28:43.000Z
#include "LedDeviceFile.h" #include <chrono> #include <iomanip> #include <iostream> LedDeviceFile::LedDeviceFile(const QJsonObject &deviceConfig) : LedDevice() { _devConfig = deviceConfig; _deviceReady = false; _printTimeStamp = false; } LedDeviceFile::~LedDeviceFile() { } LedDevice* LedDeviceFile::construct(const QJsonObject &deviceConfig) { return new LedDeviceFile(deviceConfig); } bool LedDeviceFile::init(const QJsonObject &deviceConfig) { bool initOK = LedDevice::init(deviceConfig); _fileName = deviceConfig["output"].toString("/dev/null"); _printTimeStamp = deviceConfig["printTimeStamp"].toBool(false); return initOK; } int LedDeviceFile::open() { int retval = -1; QString errortext; _deviceReady = false; if ( init(_devConfig) ) { if ( _ofs.is_open() ) { _ofs.close(); } _ofs.open( QSTRING_CSTR(_fileName)); if ( _ofs.fail() ) { errortext = QString ("Failed to open file (%1). Error message: %2").arg(_fileName, strerror(errno)); } else { _deviceReady = true; setEnable(true); retval = 0; } if ( retval < 0 ) { this->setInError( errortext ); } } return retval; } void LedDeviceFile::close() { LedDevice::close(); // LedDevice specific closing activites if ( _ofs ) { _ofs.close(); if ( _ofs.fail() ) { Error( _log, "Failed to close device (%s). Error message: %s", QSTRING_CSTR(_fileName), strerror(errno) ); } } } int LedDeviceFile::write(const std::vector<ColorRgb> & ledValues) { //printLedValues (ledValues); if ( _printTimeStamp ) { // get a precise timestamp as a string const auto now = std::chrono::system_clock::now(); const auto nowAsTimeT = std::chrono::system_clock::to_time_t(now); const auto nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000; const auto elapsedTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastWriteTime); _ofs << std::put_time(std::localtime(&nowAsTimeT), "%Y-%m-%d %T") << '.' << std::setfill('0') << std::setw(3) << nowMs.count() << " | +" << std::setfill('0') << std::setw(4) << elapsedTimeMs.count(); lastWriteTime = now; } _ofs << " ["; for (const ColorRgb& color : ledValues) { _ofs << color; } _ofs << "]" << std::endl; return 0; }
20.531532
109
0.663888
Bosken85
8d9c85ff1a60c122b6d7310e71c7d92557198c02
2,245
cpp
C++
Engine/CherrySoda/Components/Logic/Wiggler.cpp
fountainment/cherry-soda
3dd0eb7d0b5503ba572ff2104990856ef7a87495
[ "MIT" ]
null
null
null
Engine/CherrySoda/Components/Logic/Wiggler.cpp
fountainment/cherry-soda
3dd0eb7d0b5503ba572ff2104990856ef7a87495
[ "MIT" ]
null
null
null
Engine/CherrySoda/Components/Logic/Wiggler.cpp
fountainment/cherry-soda
3dd0eb7d0b5503ba572ff2104990856ef7a87495
[ "MIT" ]
null
null
null
#include <CherrySoda/Components/Logic/Wiggler.h> #include <CherrySoda/Engine.h> #include <CherrySoda/Entity.h> #include <CherrySoda/Util/Math.h> #include <CherrySoda/Util/STL.h> namespace cherrysoda { Wiggler* Wiggler::Create(float duration, float frequency, STL::Action<float> onChange/* = nullptr*/, bool start/* = false*/, bool removeSelfOnFinish/* = false*/) { Wiggler* wiggler = nullptr; if (STL::IsEmpty(ms_cache)) { wiggler = new Wiggler(); } else { wiggler = STL::Pop(ms_cache); } wiggler->Init(duration, frequency, onChange, start, removeSelfOnFinish); return wiggler; } void Wiggler::Removed(Entity* entity) { CancleAutoDelete(); base::Removed(entity); STL::Push(ms_cache, this); } void Wiggler::Init(float duration, float frequency, STL::Action<float> onChange, bool start, bool removeSelfOnFinish) { m_counter = m_sineCounter = 0.f; m_startZero = false; m_useRawDeltaTime = false; m_increment = 1.f / duration; m_sineAdd = Math::Pi2 * frequency; m_onChange = onChange; m_removeSelfOnFinish = removeSelfOnFinish; if (start) { Start(); } else { Active(false); } } void Wiggler::Start() { m_counter = 1.f; if (m_startZero) { m_sineCounter = Math::PiHalf; m_value = 0.f; if (m_onChange != nullptr) { m_onChange(m_value); } } else { m_sineCounter = 0.f; m_value = 1.f; if (m_onChange != nullptr) { m_onChange(m_value); } } Active(true); } void Wiggler::Start(float duration, float frequency) { m_increment = 1.f / duration; m_sineAdd = Math::Pi2 * frequency; Start(); } void Wiggler::StopAndClear() { Stop(); m_value = 0.f; } void Wiggler::Update() { if (m_useRawDeltaTime) { m_sineCounter += m_sineAdd * Engine::Instance()->RawDeltaTime(); m_counter -= m_increment * Engine::Instance()->RawDeltaTime(); } else { m_sineCounter += m_sineAdd * Engine::Instance()->DeltaTime(); m_counter -= m_increment * Engine::Instance()->DeltaTime(); } if (m_counter <= 0.f) { m_counter = 0.f; Active(false); if (m_removeSelfOnFinish) { RemoveSelf(); } } m_value = static_cast<float>(Math_Cos(m_sineCounter)) * m_counter; if (m_onChange != nullptr) { m_onChange(m_value); } } STL::Stack<Wiggler*> Wiggler::ms_cache; } // namespace cherrysoda
19.692982
161
0.684633
fountainment
8d9d6cbf6a5b26984967a25eb16289f9d2a44baf
1,595
cpp
C++
zircon/system/utest/fidl-compiler/flat_ast_tests.cpp
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
1
2019-10-09T10:50:57.000Z
2019-10-09T10:50:57.000Z
zircon/system/utest/fidl-compiler/flat_ast_tests.cpp
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
zircon/system/utest/fidl-compiler/flat_ast_tests.cpp
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <regex> #include <unittest/unittest.h> #include <fidl/flat_ast.h> namespace { using fidl::flat::HandleType; using fidl::types::HandleSubtype; using fidl::types::Nullability; static bool implicit_assumptions() { // Preconditions to unit test cases: if these change, we need to rewrite the tests themselves. EXPECT_TRUE(HandleSubtype::kChannel < HandleSubtype::kEvent); EXPECT_TRUE(Nullability::kNullable < Nullability::kNonnullable); return true; } static bool compare_handles() { HandleType nonnullable_channel(HandleSubtype::kChannel, Nullability::kNonnullable); HandleType nullable_channel(HandleSubtype::kChannel, Nullability::kNullable); HandleType nonnullable_event(HandleSubtype::kEvent, Nullability::kNonnullable); HandleType nullable_event(HandleSubtype::kEvent, Nullability::kNullable); // Comparison is nullability, then type. EXPECT_TRUE(nullable_channel < nonnullable_channel); EXPECT_TRUE(nullable_event < nonnullable_event); EXPECT_TRUE(nonnullable_channel < nonnullable_event); EXPECT_TRUE(nullable_channel < nullable_event); return true; } } // namespace BEGIN_TEST_CASE(flat_ast_tests) RUN_TEST(implicit_assumptions) RUN_TEST(compare_handles) END_TEST_CASE(flat_ast_tests)
32.55102
98
0.775549
yanyushr
8d9ddecdf67249e20cdf8922b70bda0bb92f2f9e
7,037
cpp
C++
source/common/rendering/gles/gles_samplers.cpp
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
1
2022-03-30T15:53:09.000Z
2022-03-30T15:53:09.000Z
source/common/rendering/gles/gles_samplers.cpp
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
null
null
null
source/common/rendering/gles/gles_samplers.cpp
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
null
null
null
/* ** gl_samplers.cpp ** ** Texture sampler handling ** **--------------------------------------------------------------------------- ** Copyright 2015-2019 Christoph Oelckers ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** */ #include "gles_system.h" #include "c_cvars.h" #include "hw_cvars.h" #include "gles_renderer.h" #include "gles_samplers.h" #include "hw_material.h" #include "i_interface.h" namespace OpenGLESRenderer { extern TexFilter_s TexFilter[]; FSamplerManager::FSamplerManager() { SetTextureFilterMode(); } FSamplerManager::~FSamplerManager() { } void FSamplerManager::UnbindAll() { } uint8_t FSamplerManager::Bind(int texunit, int num, int lastval) { int filter = sysCallbacks.DisableTextureFilter && sysCallbacks.DisableTextureFilter() ? 0 : gl_texture_filter; glActiveTexture(GL_TEXTURE0 + texunit); switch (num) { case CLAMP_NONE: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); if (lastval >= CLAMP_XY_NOMIP) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); } break; case CLAMP_X: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); if (lastval >= CLAMP_XY_NOMIP) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); } break; case CLAMP_Y: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (lastval >= CLAMP_XY_NOMIP) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); } break; case CLAMP_XY: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (lastval >= CLAMP_XY_NOMIP) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); } break; case CLAMP_XY_NOMIP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].magfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); break; case CLAMP_NOFILTER: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case CLAMP_NOFILTER_X: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case CLAMP_NOFILTER_Y: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case CLAMP_NOFILTER_XY: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case CLAMP_CAMTEX: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].magfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); break; } glActiveTexture(GL_TEXTURE0); return 255; } void FSamplerManager::SetTextureFilterMode() { /* GLRenderer->FlushTextures(); GLint bounds[IHardwareTexture::MAX_TEXTURES]; // Unbind all for(int i = IHardwareTexture::MAX_TEXTURES-1; i >= 0; i--) { glActiveTexture(GL_TEXTURE0 + i); glGetIntegerv(GL_SAMPLER_BINDING, &bounds[i]); glBindSampler(i, 0); } int filter = sysCallbacks.DisableTextureFilter && sysCallbacks.DisableTextureFilter() ? 0 : gl_texture_filter; for (int i = 0; i < 4; i++) { glSamplerParameteri(mSamplers[i], GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glSamplerParameteri(mSamplers[i], GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); glSamplerParameterf(mSamplers[i], GL_TEXTURE_MAX_ANISOTROPY_EXT, filter > 0? gl_texture_filter_anisotropic : 1.0); } glSamplerParameteri(mSamplers[CLAMP_XY_NOMIP], GL_TEXTURE_MIN_FILTER, TexFilter[filter].magfilter); glSamplerParameteri(mSamplers[CLAMP_XY_NOMIP], GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); glSamplerParameteri(mSamplers[CLAMP_CAMTEX], GL_TEXTURE_MIN_FILTER, TexFilter[filter].magfilter); glSamplerParameteri(mSamplers[CLAMP_CAMTEX], GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); for(int i = 0; i < IHardwareTexture::MAX_TEXTURES; i++) { glBindSampler(i, bounds[i]); } */ } }
35.903061
116
0.77533
Quake-Backup
8d9f59e551cb8ff562e4f7744edbcd051282d481
2,193
hpp
C++
modules/boost/simd/base/include/boost/simd/swar/functions/splatted_minimum.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/swar/functions/splatted_minimum.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/swar/functions/splatted_minimum.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2012 - 2013 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_SWAR_FUNCTIONS_SPLATTED_MINIMUM_HPP_INCLUDED #define BOOST_SIMD_SWAR_FUNCTIONS_SPLATTED_MINIMUM_HPP_INCLUDED #include <boost/simd/include/functor.hpp> #include <boost/dispatch/include/functor.hpp> namespace boost { namespace simd { namespace tag { /*! @brief splatted_minimum generic tag Represents the splatted_minimum function in generic contexts. **/ struct splatted_minimum_ : ext::unspecified_<splatted_minimum_> { /// @brief Parent hierarchy typedef ext::unspecified_<splatted_minimum_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_splatted_minimum_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site, class... Ts> BOOST_FORCEINLINE generic_dispatcher<tag::splatted_minimum_, Site> dispatching_splatted_minimum_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...) { return generic_dispatcher<tag::splatted_minimum_, Site>(); } template<class... Args> struct impl_splatted_minimum_; } /*! @brief Splatted minimum Computes the splatted minimum of the element of its argument. @par Semantic @code Type r = splatted_minimum(v); @endcode @code for(int i=0;i<Type::static_size;++i) x[i] = minimum(v); @endcode @param a0 @return a value of the same type as the parameter */ BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::splatted_minimum_, splatted_minimum, 1) } } #endif
31.782609
191
0.639307
psiha
8d9fd53c1f599065cd136c0572321601d04fbf26
34,009
cpp
C++
Sources/ToolChains/Carl/ElCar/Carc/clsbase/create.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/ToolChains/Carl/ElCar/Carc/clsbase/create.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/ToolChains/Carl/ElCar/Carc/clsbase/create.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <clsbase.h> int IsValidCLS(CLSModule *pModule, int nSize, const char *pszName) { if (pModule->mCLSModuleVersion != CLSMODULE_VERSION) { ExtraMessage("CLSModule version is incompatable", pszName, "should be recompiled and relinked"); _ReturnError(CLSError_CLSModuleVersion); } if (memcmp(pModule->mMagic, MAGIC_STRING, MAGIC_STRING_LENGTH)) { _ReturnError(CLSError_FormatMagic); } if (nSize < (int)sizeof(CLSModule) || pModule->mSize < nSize) { _ReturnError (CLSError_FormatSize); } _ReturnError (CLS_NoError); } void DeleteFileDirEntry(FileDirEntry* pFileDir) { assert(pFileDir != NULL); if (pFileDir->mPath) delete pFileDir->mPath; delete pFileDir; } void DeleteKeyValuePair(KeyValuePair* pPair) { assert(pPair != NULL); if (pPair->mKey) delete pPair->mKey; if (pPair->mValue) delete pPair->mValue; delete pPair; } void DeleteAnnotation(AnnotationDescriptor* pDesc) { assert(pDesc != NULL); if (pDesc->mName) delete pDesc->mName; if (pDesc->mNameSpace) delete pDesc->mNameSpace; for (int n = 0; n < pDesc->mKeyValuePairCount; n++) { DeleteKeyValuePair(pDesc->mKeyValuePairs[n]); } delete [] pDesc->mKeyValuePairs; delete pDesc; } ClassInterface *NewClassInterface(USHORT index) { ClassInterface *pClassInterface; pClassInterface = new ClassInterface; if (!pClassInterface) return NULL; memset(pClassInterface, 0, sizeof(ClassInterface)); pClassInterface->mIndex = index; return pClassInterface; } void DeleteClassInterface(ClassInterface *pClassInterface) { assert(pClassInterface != NULL); delete pClassInterface; } FileDirEntry *NewFileDirEntry(const char *pszPath) { FileDirEntry *pFile; assert(pszPath != NULL); pFile = new FileDirEntry; if (!pFile) return NULL; pFile->mPath = new char[strlen(pszPath) + 1]; if (!pFile->mPath) goto ErrorExit; strcpy(pFile->mPath, pszPath); return pFile; ErrorExit: delete pFile; return NULL; } ClassDirEntry *NewClassDirEntry(const char *pszName, const char *pszNamespace) { ClassDirEntry *pClass; assert(pszName != NULL); pClass = new ClassDirEntry; if (!pClass) return NULL; memset(pClass, 0, sizeof(ClassDirEntry)); pClass->mDesc = new ClassDescriptor; if (!pClass->mDesc) goto ErrorExit; memset(pClass->mDesc, 0, sizeof(ClassDescriptor)); pClass->mDesc->mAnnotations = \ new AnnotationDescriptor *[MAX_ANNOTATION_NUMBER]; if (!pClass->mDesc->mAnnotations) goto ErrorExit; pClass->mDesc->mInterfaces = \ new ClassInterface *[MAX_CLASS_INTERFACE_NUMBER]; if (!pClass->mDesc->mInterfaces) goto ErrorExit; pClass->mDesc->mAggrIndexes = new USHORT[MAX_CLASS_ASPECT_NUMBER]; if (!pClass->mDesc->mAggrIndexes) goto ErrorExit; pClass->mDesc->mAspectIndexes = new USHORT[MAX_CLASS_ASPECT_NUMBER]; if (!pClass->mDesc->mAspectIndexes) goto ErrorExit; pClass->mDesc->mClassIndexes = new USHORT[MAX_AGGRCLASSE_OF_ASPECT_NUMBER]; if (!pClass->mDesc->mClassIndexes) goto ErrorExit; pClass->mName = new char[strlen(pszName) + 1]; if (!pClass->mName) goto ErrorExit; strcpy(pClass->mName, pszName); if (pszNamespace != NULL) { pClass->mNameSpace = new char[strlen(pszNamespace) + 1]; if (!pClass->mNameSpace) goto ErrorExit; strcpy(pClass->mNameSpace, pszNamespace); } return pClass; ErrorExit: if (pClass->mDesc) { if (pClass->mDesc->mClassIndexes) delete [] pClass->mDesc->mClassIndexes; if (pClass->mDesc->mAspectIndexes) delete [] pClass->mDesc->mAspectIndexes; if (pClass->mDesc->mAggrIndexes) delete [] pClass->mDesc->mAggrIndexes; if (pClass->mDesc->mInterfaces) delete [] pClass->mDesc->mInterfaces; if (pClass->mDesc->mAnnotations) delete [] pClass->mDesc->mAnnotations; delete pClass->mDesc; } delete pClass; return NULL; } void DeleteClassDirEntry(ClassDirEntry *pClass) { assert(pClass != NULL); assert(pClass->mDesc != NULL); assert(pClass->mDesc->mInterfaces != NULL); assert(pClass->mDesc->mAggrIndexes != NULL); assert(pClass->mDesc->mAspectIndexes != NULL); for (int n = 0; n < pClass->mDesc->mAnnotationCount; n++) { DeleteAnnotation(pClass->mDesc->mAnnotations[n]); } delete [] pClass->mDesc->mAnnotations; for (int n = 0; n < pClass->mDesc->mInterfaceCount; n++) { DeleteClassInterface(pClass->mDesc->mInterfaces[n]); } delete [] pClass->mDesc->mInterfaces; delete [] pClass->mDesc->mAggrIndexes; delete [] pClass->mDesc->mAspectIndexes; delete pClass->mDesc; if (pClass->mName) delete pClass->mName; if (pClass->mNameSpace) delete pClass->mNameSpace; delete pClass; } InterfaceConstDescriptor *NewInterfaceConstDirEntry(const char *pszName) { InterfaceConstDescriptor *pConst; assert(pszName != NULL); pConst = new InterfaceConstDescriptor; if (!pConst) return NULL; memset(pConst, 0, sizeof(InterfaceConstDescriptor)); pConst->mName = new char[strlen(pszName) + 1]; if (!pConst->mName) { delete pConst; return NULL; } strcpy(pConst->mName, pszName); return pConst; } void DeleteInterfaceConst(InterfaceConstDescriptor *pDesc) { assert(pDesc != NULL); if (pDesc->mName) delete pDesc->mName; delete pDesc; } ParamDescriptor *NewParam(const char *pszName) { ParamDescriptor *pParam; assert(pszName != NULL); pParam = new ParamDescriptor; if (!pParam) return NULL; memset(pParam, 0, sizeof(ParamDescriptor)); pParam->mName = new char[strlen(pszName) + 1]; if (!pParam->mName) { delete pParam; return NULL; } strcpy(pParam->mName, pszName); return pParam; } void DeleteParam(ParamDescriptor *pParam) { assert(pParam != NULL); assert(pParam->mName != NULL); if (pParam->mType.mNestedType) delete pParam->mType.mNestedType; delete pParam->mName; delete pParam; } MethodDescriptor *NewMethod(const char *pszName) { MethodDescriptor *pMethod; assert(pszName != NULL); pMethod = new MethodDescriptor; if (!pMethod) return NULL; memset(pMethod, 0, sizeof(MethodDescriptor)); pMethod->mAnnotations = \ new AnnotationDescriptor *[MAX_ANNOTATION_NUMBER]; if (!pMethod->mAnnotations) goto ErrorExit; pMethod->mParams = \ new ParamDescriptor *[MAX_PARAM_NUMBER]; if (!pMethod->mParams) goto ErrorExit; pMethod->mName = new char[strlen(pszName) + 1]; if (!pMethod->mName) goto ErrorExit; strcpy(pMethod->mName, pszName); return pMethod; ErrorExit: if (pMethod->mParams) delete [] pMethod->mParams; if (pMethod->mAnnotations) delete [] pMethod->mAnnotations; delete pMethod; return NULL; } void DeleteMethod(MethodDescriptor *pMethod) { assert(pMethod != NULL); assert(pMethod->mName != NULL); assert(pMethod->mParams != NULL); for (int n = 0; n < pMethod->mAnnotationCount; n++) { DeleteAnnotation(pMethod->mAnnotations[n]); } delete [] pMethod->mAnnotations; for (int n = 0; n < pMethod->mParamCount; n++) { DeleteParam(pMethod->mParams[n]); } delete [] pMethod->mParams; delete pMethod->mSignature; delete pMethod->mName; delete pMethod; } InterfaceDirEntry *NewInterfaceDirEntry(const char *pszName, const char *pszNamespace) { assert(pszName != NULL); InterfaceDirEntry *pInterface; pInterface = new InterfaceDirEntry; if (!pInterface) return NULL; memset(pInterface, 0, sizeof(InterfaceDirEntry)); pInterface->mDesc = new InterfaceDescriptor; if (!pInterface->mDesc) goto ErrorExit; memset(pInterface->mDesc, 0, sizeof(InterfaceDescriptor)); pInterface->mDesc->mAnnotations = \ new AnnotationDescriptor *[MAX_ANNOTATION_NUMBER]; if (!pInterface->mDesc->mAnnotations) goto ErrorExit; pInterface->mDesc->mConsts = \ new InterfaceConstDescriptor *[MAX_INTERFACE_CONST_NUMBER]; if (!pInterface->mDesc->mConsts) goto ErrorExit; pInterface->mDesc->mMethods = \ new MethodDescriptor *[MAX_METHOD_NUMBER]; if (!pInterface->mDesc->mMethods) goto ErrorExit; pInterface->mName = new char[strlen(pszName) + 1]; if (!pInterface->mName) goto ErrorExit; strcpy(pInterface->mName, pszName); if (pszNamespace != NULL) { pInterface->mNameSpace = new char[strlen(pszNamespace) + 1]; if (!pInterface->mNameSpace) goto ErrorExit; strcpy(pInterface->mNameSpace, pszNamespace); } return pInterface; ErrorExit: if (pInterface->mDesc) { if (pInterface->mDesc->mAnnotations) delete [] pInterface->mDesc->mAnnotations; if (pInterface->mDesc->mConsts) delete [] pInterface->mDesc->mConsts; if (pInterface->mDesc->mMethods) delete [] pInterface->mDesc->mMethods; delete pInterface->mDesc; } delete pInterface; return NULL; } void DeleteInterfaceDirEntry(InterfaceDirEntry *pInterface) { assert(pInterface != NULL); assert(pInterface->mName != NULL); assert(pInterface->mDesc != NULL); assert(pInterface->mDesc->mMethods != NULL); for (int n = 0; n < pInterface->mDesc->mAnnotationCount; n++) { DeleteAnnotation(pInterface->mDesc->mAnnotations[n]); } delete [] pInterface->mDesc->mAnnotations; for (int n = 0; n < pInterface->mDesc->mConstCount; n++) { DeleteInterfaceConst(pInterface->mDesc->mConsts[n]); } delete [] pInterface->mDesc->mConsts; for (int n = 0; n < pInterface->mDesc->mMethodCount; n++) { DeleteMethod(pInterface->mDesc->mMethods[n]); } delete [] pInterface->mDesc->mMethods; delete pInterface->mDesc; delete pInterface->mName; if (pInterface->mNameSpace) delete pInterface->mNameSpace; delete pInterface; } StructElement *NewStructElement(const char *pszName) { StructElement *pElement; assert(pszName != NULL); pElement = new StructElement; if (!pElement) return NULL; memset(pElement, 0, sizeof(StructElement)); pElement->mName = new char[strlen(pszName) + 1]; if (!pElement->mName) { delete pElement; return NULL; } strcpy(pElement->mName, pszName); return pElement; } void DeleteStructElement(StructElement *pElement) { assert(pElement != NULL); assert(pElement->mName != NULL); if (pElement->mType.mNestedType) delete pElement->mType.mNestedType; delete pElement->mName; delete pElement; } StructDirEntry *NewStructDirEntry(const char *pszName) { StructDirEntry *pStruct; assert(pszName != NULL); pStruct = new StructDirEntry; if (!pStruct) return NULL; memset(pStruct, 0, sizeof(StructDirEntry)); pStruct->mDesc = new StructDescriptor; if (!pStruct->mDesc) goto ErrorExit; memset(pStruct->mDesc, 0, sizeof(StructDescriptor)); pStruct->mDesc->mElements = new StructElement *[MAX_STRUCT_ELEMENT_NUMBER]; if (!pStruct->mDesc->mElements) goto ErrorExit; pStruct->mName = new char[strlen(pszName) + 1]; if (!pStruct->mName) goto ErrorExit; strcpy(pStruct->mName, pszName); return pStruct; ErrorExit: if (pStruct->mDesc) { if (pStruct->mDesc->mElements) delete [] pStruct->mDesc->mElements; delete pStruct->mDesc; } delete pStruct; return NULL; } void DeleteStructDirEntry(StructDirEntry *pStruct) { assert(pStruct != NULL); assert(pStruct->mName != NULL); assert(pStruct->mDesc != NULL); assert(pStruct->mDesc->mElements != NULL); for (int n = 0; n < pStruct->mDesc->mElementCount; n++) { DeleteStructElement(pStruct->mDesc->mElements[n]); } delete [] pStruct->mDesc->mElements; delete pStruct->mDesc; delete pStruct->mName; if (pStruct->mNameSpace) delete pStruct->mNameSpace; delete pStruct; } ArrayDirEntry *NewArrayDirEntry() { ArrayDirEntry *pArray = new ArrayDirEntry; if (NULL == pArray) return NULL; memset(pArray, 0, sizeof(ArrayDirEntry)); return pArray; } void DeleteArrayDirEntry(ArrayDirEntry *pArray) { assert(pArray); if (pArray->mNameSpace) { delete pArray->mNameSpace; pArray->mNameSpace = NULL; } if (pArray->mType.mNestedType) { delete pArray->mType.mNestedType; pArray->mType.mNestedType = NULL; } delete pArray; } ConstDirEntry *NewConstDirEntry(const char *pszName) { assert(pszName != NULL); ConstDirEntry *pConst = new ConstDirEntry; if (NULL == pConst) return NULL; memset(pConst, 0, sizeof(ConstDirEntry)); pConst->mName = new char[strlen(pszName) + 1]; if (!pConst->mName) goto ErrorExit; strcpy(pConst->mName, pszName); return pConst; ErrorExit: delete pConst; return NULL; } void DeleteConstDirEntry(ConstDirEntry *pConst) { assert(pConst != NULL); assert(pConst->mName != NULL); if (pConst->mNameSpace) { delete pConst->mNameSpace; pConst->mNameSpace = NULL; } delete pConst->mName; if (pConst->mType == TYPE_STRING && pConst->mV.mStrValue.mValue != NULL) { free(pConst->mV.mStrValue.mValue); } delete pConst; } EnumElement *NewEnumElement(const char *pszName) { EnumElement *pElement; assert(pszName != NULL); pElement = new EnumElement; if (!pElement) return NULL; memset(pElement, 0, sizeof(EnumElement)); pElement->mName = new char[strlen(pszName) + 1]; if (!pElement->mName) { delete pElement; return NULL; } strcpy(pElement->mName, pszName); return pElement; } void DeleteEnumElement(EnumElement *pElement) { assert(pElement != NULL); assert(pElement->mName != NULL); delete pElement->mName; delete pElement; } EnumDirEntry *NewEnumDirEntry(const char *pszName, const char *pszNamespace) { EnumDirEntry *pEnum; assert(pszName != NULL); pEnum = new EnumDirEntry; if (!pEnum) return NULL; memset(pEnum, 0, sizeof(EnumDirEntry)); pEnum->mDesc = new EnumDescriptor; if (!pEnum->mDesc) goto ErrorExit; memset(pEnum->mDesc, 0, sizeof(EnumDescriptor)); pEnum->mDesc->mElements = new EnumElement *[MAX_ENUM_ELEMENT_NUMBER]; if (!pEnum->mDesc->mElements) goto ErrorExit; pEnum->mName = new char[strlen(pszName) + 1]; if (!pEnum->mName) goto ErrorExit; strcpy(pEnum->mName, pszName); if (pszNamespace != NULL) { pEnum->mNameSpace = new char[strlen(pszNamespace) + 1]; if (!pEnum->mNameSpace) goto ErrorExit; strcpy(pEnum->mNameSpace, pszNamespace); } return pEnum; ErrorExit: if (pEnum->mDesc) { if (pEnum->mDesc->mElements) delete [] pEnum->mDesc->mElements; delete pEnum->mDesc; } delete pEnum; return NULL; } void DeleteEnumDirEntry(EnumDirEntry *pEnum) { assert(pEnum != NULL); assert(pEnum->mName != NULL); assert(pEnum->mDesc != NULL); assert(pEnum->mDesc->mElements != NULL); for (int n = 0; n < pEnum->mDesc->mElementCount; n++) { DeleteEnumElement(pEnum->mDesc->mElements[n]); } delete [] pEnum->mDesc->mElements; delete pEnum->mDesc; delete pEnum->mName; if (pEnum->mNameSpace) delete pEnum->mNameSpace; delete pEnum; } AliasDirEntry *NewAliasDirEntry(const char *pszName) { assert(pszName != NULL); AliasDirEntry *pAlias; pAlias = new AliasDirEntry; if (!pAlias) return NULL; memset(pAlias, 0, sizeof(AliasDirEntry)); pAlias->mName = new char[strlen(pszName) + 1]; if (!pAlias->mName) { delete pAlias; return NULL; } strcpy(pAlias->mName, pszName); return pAlias; } void DeleteAliasDirEntry(AliasDirEntry *pAlias) { assert(pAlias != NULL); assert(pAlias->mName != NULL); if (pAlias->mType.mNestedType) delete pAlias->mType.mNestedType; delete pAlias->mName; if (pAlias->mNameSpace) delete pAlias->mNameSpace; delete pAlias; } CLSModule *CreateCLS() { CLSModule *pModule; FileDirEntry *pFile; pModule = new CLSModule; if (!pModule) return NULL; memset(pModule, '\0', sizeof(CLSModule)); memcpy(pModule->mMagic, MAGIC_STRING, MAGIC_STRING_LENGTH); pModule->mCLSModuleVersion = CLSMODULE_VERSION; pModule->mFileDirs = new FileDirEntry *[MAX_FILE_NUMBER]; pModule->mClassDirs = new ClassDirEntry *[MAX_CLASS_NUMBER]; pModule->mInterfaceDirs = new InterfaceDirEntry *[MAX_INTERFACE_NUMBER]; pModule->mDefinedInterfaceIndexes = new int[MAX_DEFINED_INTERFACE_NUMBER]; pModule->mStructDirs = new StructDirEntry *[MAX_STRUCT_NUMBER]; pModule->mEnumDirs = new EnumDirEntry *[MAX_ENUM_NUMBER]; pModule->mAliasDirs = new AliasDirEntry *[MAX_ALIAS_NUMBER]; pModule->mLibraryNames = new char *[MAX_LIBRARY_NUMBER]; pModule->mArrayDirs = new ArrayDirEntry *[MAX_ARRAY_NUMBER]; pModule->mConstDirs = new ConstDirEntry *[MAX_CONST_NUMBER]; pFile = new FileDirEntry; if (!pModule->mClassDirs || !pModule->mInterfaceDirs || !pModule->mStructDirs || !pModule->mEnumDirs || !pModule->mAliasDirs || !pModule->mLibraryNames || !pModule->mArrayDirs || !pModule->mConstDirs || !pModule->mDefinedInterfaceIndexes || !pModule->mFileDirs || !pFile) { DestroyCLS(pModule); return NULL; } pFile->mPath = NULL; pModule->mFileDirs[pModule->mFileCount++] = pFile; return pModule; } void DestroyCLS(CLSModule *pModule) { int n; assert(pModule != NULL); if (pModule->mFileDirs) { for (n = 0; n < pModule->mFileCount; n++) { DeleteFileDirEntry(pModule->mFileDirs[n]); } delete [] pModule->mFileDirs; } if (pModule->mClassDirs) { for (n = 0; n < pModule->mClassCount; n++) { DeleteClassDirEntry(pModule->mClassDirs[n]); } delete [] pModule->mClassDirs; } if (pModule->mInterfaceDirs) { for (n = 0; n < pModule->mInterfaceCount; n++) { DeleteInterfaceDirEntry(pModule->mInterfaceDirs[n]); } delete [] pModule->mInterfaceDirs; } if (pModule->mDefinedInterfaceIndexes) { delete [] pModule->mDefinedInterfaceIndexes; } if (pModule->mArrayDirs) { for (n = 0; n < pModule->mArrayCount; n++) { DeleteArrayDirEntry(pModule->mArrayDirs[n]); } delete [] pModule->mArrayDirs; } if (pModule->mStructDirs) { for (n = 0; n < pModule->mStructCount; n++) { DeleteStructDirEntry(pModule->mStructDirs[n]); } delete [] pModule->mStructDirs; } if (pModule->mEnumDirs) { for (n = 0; n < pModule->mEnumCount; n++) { DeleteEnumDirEntry(pModule->mEnumDirs[n]); } delete [] pModule->mEnumDirs; } if (pModule->mAliasDirs) { for (n = 0; n < pModule->mAliasCount; n++) { DeleteAliasDirEntry(pModule->mAliasDirs[n]); } delete [] pModule->mAliasDirs; } if (pModule->mConstDirs) { for (n = 0; n < pModule->mConstCount; n++) { DeleteConstDirEntry(pModule->mConstDirs[n]); } delete [] pModule->mConstDirs; } if (pModule->mLibraryNames) { for (n = 0; n < pModule->mLibraryCount; n++) { delete pModule->mLibraryNames[n]; } delete [] pModule->mLibraryNames; } if (pModule->mUunm) delete pModule->mUunm; if (pModule->mName) delete pModule->mName; delete pModule; } int CreateFileDirEntry( const char *pszPath, CLSModule *pModule) { int n; FileDirEntry *pFile; if (!pszPath || pszPath[0] == '\0') return 0; n = SelectFileDirEntry(pszPath, pModule); if (n >= 1) { _ReturnOK (n); } assert(pModule->mFileCount < MAX_FILE_NUMBER); pFile = NewFileDirEntry(pszPath); pModule->mFileDirs[pModule->mFileCount] = pFile; _ReturnOK (pModule->mFileCount++); } int CreateClassDirEntry( const char *pszName, CLSModule *pModule, unsigned long attribs) { int n; ClassDirEntry *pClass; ClassDescriptor *pDesc; char *pszNamespace = NULL; const char *dot = strrchr(pszName, '.'); if (dot != NULL) { pszNamespace = (char*)malloc(dot - pszName + 1); memset(pszNamespace, 0, dot - pszName + 1); memcpy(pszNamespace, pszName, dot - pszName); pszName = dot + 1; } n = SelectClassDirEntry(pszName, pszNamespace, pModule); if (n >= 0) { pDesc = pModule->mClassDirs[n]->mDesc; if (pszNamespace != NULL) free(pszNamespace); if (CLASS_TYPE(attribs) != CLASS_TYPE(pDesc->mAttribs)) { ExtraMessage(pModule->mClassDirs[n]->mNameSpace, "class", pszName); _ReturnError (CLSError_NameConflict); } if (pDesc->mInterfaceCount > 0 || (pDesc->mAttribs & ClassAttrib_hasparent) > 0 || IsValidUUID(&pDesc->mClsid)) { ExtraMessage(pModule->mClassDirs[n]->mNameSpace, "class", pszName); _ReturnError (CLSError_DupEntry); } _ReturnOK (n); } n = GlobalSelectSymbol(pszName, pszNamespace, pModule, GType_Class, NULL); if (n >= 0) { if (pszNamespace != NULL) free(pszNamespace); _ReturnError (CLSError_NameConflict); } if (pModule->mClassCount >= MAX_CLASS_NUMBER) { if (pszNamespace != NULL) free(pszNamespace); _ReturnError (CLSError_FullEntry); } pClass = NewClassDirEntry(pszName, pszNamespace); if (pszNamespace != NULL) free(pszNamespace); if (!pClass) _ReturnError (CLSError_OutOfMemory); pModule->mClassDirs[pModule->mClassCount] = pClass; _ReturnOK (pModule->mClassCount++); } int CreateInterfaceDirEntry( const char *pszName, CLSModule *pModule, unsigned long attribs) { int n; InterfaceDirEntry *pInterface; InterfaceDescriptor *pDesc; char *pszNamespace = NULL; const char *dot = strrchr(pszName, '.'); if (dot != NULL) { pszNamespace = (char*)malloc(dot - pszName + 1); memset(pszNamespace, 0, dot - pszName + 1); memcpy(pszNamespace, pszName, dot - pszName); pszName = dot + 1; } n = SelectInterfaceDirEntry(pszName, pszNamespace, pModule); if (n >= 0) { pDesc = pModule->mInterfaceDirs[n]->mDesc; if (pszNamespace != NULL) free(pszNamespace); if (INTERFACE_TYPE(attribs) != \ INTERFACE_TYPE(pDesc->mAttribs)) { ExtraMessage(pModule->mInterfaceDirs[n]->mNameSpace, "interface", pModule->mInterfaceDirs[n]->mName); _ReturnError (CLSError_NameConflict); } if (pDesc->mMethodCount > 0 || pDesc->mParentIndex != 0 || IsValidUUID(&pDesc->mIID)) { ExtraMessage(pModule->mInterfaceDirs[n]->mNameSpace, "interface", pModule->mInterfaceDirs[n]->mName); _ReturnError (CLSError_DupEntry); } _ReturnOK (n); } n = GlobalSelectSymbol(pszName, pszNamespace, pModule, GType_Interface, NULL); if (n >= 0) { if (pszNamespace != NULL) free(pszNamespace); _ReturnError (CLSError_NameConflict); } if (pModule->mInterfaceCount >= MAX_INTERFACE_NUMBER) { if (pszNamespace != NULL) free(pszNamespace); _ReturnError (CLSError_FullEntry); } pInterface = NewInterfaceDirEntry(pszName, pszNamespace); if (pszNamespace != NULL) free(pszNamespace); if (!pInterface) _ReturnError (CLSError_OutOfMemory); pModule->mInterfaceDirs[pModule->mInterfaceCount] = pInterface; _ReturnOK (pModule->mInterfaceCount++); } int CreateArrayDirEntry(CLSModule *pModule) { ArrayDirEntry *pArray; pArray = NewArrayDirEntry(); if (!pArray) _ReturnError (CLSError_OutOfMemory); pModule->mArrayDirs[pModule->mArrayCount] = pArray; _ReturnOK (pModule->mArrayCount++); } int CreateStructDirEntry( const char *pszName, CLSModule *pModule) { int n; StructDirEntry *pStruct; n = SelectStructDirEntry(pszName, pModule); if (n >= 0) { if (pModule->mStructDirs[n]->mDesc->mElementCount > 0) { ExtraMessage(pModule->mStructDirs[n]->mNameSpace, "struct", pModule->mStructDirs[n]->mName); _ReturnError (CLSError_DupEntry); } _ReturnOK (n); } n = GlobalSelectSymbol(pszName, NULL, pModule, GType_Struct, NULL); if (n >= 0) _ReturnError (CLSError_NameConflict); if (pModule->mStructCount >= MAX_STRUCT_NUMBER) _ReturnError (CLSError_FullEntry); pStruct = NewStructDirEntry(pszName); if (!pStruct) _ReturnError (CLSError_OutOfMemory); pModule->mStructDirs[pModule->mStructCount] = pStruct; _ReturnOK (pModule->mStructCount++); } int CreateEnumDirEntry( const char *pszName, CLSModule *pModule) { int n; EnumDirEntry *pEnum; char *pszNamespace = NULL; const char *dot = strrchr(pszName, '.'); if (dot != NULL) { pszNamespace = (char*)malloc(dot - pszName + 1); memset(pszNamespace, 0, dot - pszName + 1); memcpy(pszNamespace, pszName, dot - pszName); pszName = dot + 1; } n = SelectEnumDirEntry(pszName, pszNamespace, pModule); if (n >= 0) { if (pszNamespace != NULL) free(pszNamespace); if (pModule->mEnumDirs[n]->mDesc->mElementCount > 0) { ExtraMessage(pModule->mEnumDirs[n]->mNameSpace, "enum", pModule->mEnumDirs[n]->mName); _ReturnError (CLSError_DupEntry); } _ReturnOK (n); } n = GlobalSelectSymbol(pszName, pszNamespace, pModule, GType_Enum, NULL); if (n >= 0) { if (pszNamespace != NULL) free(pszNamespace); _ReturnError (CLSError_NameConflict); } if (pModule->mEnumCount >= MAX_ENUM_NUMBER) { if (pszNamespace != NULL) free(pszNamespace); _ReturnError (CLSError_FullEntry); } pEnum = NewEnumDirEntry(pszName, pszNamespace); if (pszNamespace != NULL) free(pszNamespace); if (!pEnum) _ReturnError (CLSError_OutOfMemory); pModule->mEnumDirs[pModule->mEnumCount] = pEnum; _ReturnOK (pModule->mEnumCount++); } int CreateConstDirEntry( const char *pszName, CLSModule *pModule) { int n; ConstDirEntry *pConst; n = SelectConstDirEntry(pszName, pModule); if (n >= 0) { _ReturnError (CLSError_DupEntry); } n = GlobalSelectSymbol(pszName, NULL, pModule, GType_Const, NULL); if (n >= 0) _ReturnError (CLSError_NameConflict); if (pModule->mConstCount >= MAX_CONST_NUMBER) _ReturnError (CLSError_FullEntry); pConst = NewConstDirEntry(pszName); if (!pConst) _ReturnError (CLSError_OutOfMemory); pModule->mConstDirs[pModule->mConstCount] = pConst; _ReturnOK (pModule->mConstCount++); } int CreateAliasDirEntry( const char *pszName, CLSModule *pModule, TypeDescriptor *pType) { int n; AliasDirEntry *pAlias; GlobalSymbolType gType; TypeDescriptor type; n = GlobalSelectSymbol(pszName, NULL, pModule, GType_None, &gType); if (n >= 0) { if (gType == GType_Class) { _ReturnError (CLSError_NameConflict); } memset(&type, 0, sizeof(type)); type.mType = (CARDataType)gType; type.mIndex = n; if (!IsEqualType(pModule, &type, pType)) { _ReturnError (CLSError_NameConflict); } } if (pModule->mAliasCount >= MAX_ALIAS_NUMBER) _ReturnError (CLSError_FullEntry); pAlias = NewAliasDirEntry(pszName); if (!pAlias) _ReturnError (CLSError_OutOfMemory); memcpy(&pAlias->mType, pType, sizeof(TypeDescriptor)); pModule->mAliasDirs[pModule->mAliasCount] = pAlias; _ReturnOK (pModule->mAliasCount++); } int CreateClassInterface(USHORT index, ClassDescriptor *pDesc) { int n; ClassInterface *pClassInterface; assert(pDesc != NULL); n = SelectClassInterface(index, pDesc); if (n >= 0) _ReturnError (CLSError_DupEntry); if (pDesc->mInterfaceCount >= MAX_CLASS_INTERFACE_NUMBER) _ReturnError (CLSError_FullEntry); pClassInterface = NewClassInterface(index); if (!pClassInterface) _ReturnError (CLSError_OutOfMemory); pDesc->mInterfaces[pDesc->mInterfaceCount] = pClassInterface; _ReturnOK (pDesc->mInterfaceCount++); } int CreateInterfaceConstDirEntry( const char *pszName, InterfaceDescriptor *pInterface) { int n; InterfaceConstDescriptor *pConst; n = SelectInterfaceConstDirEntry(pszName, pInterface); if (n >= 0) { _ReturnError (CLSError_DupEntry); } n = SelectInterfaceMemberSymbol(pszName, pInterface); if (n >= 0) _ReturnError (CLSError_NameConflict); if (pInterface->mConstCount >= MAX_INTERFACE_CONST_NUMBER) _ReturnError (CLSError_FullEntry); pConst = NewInterfaceConstDirEntry(pszName); if (!pConst) _ReturnError (CLSError_OutOfMemory); pInterface->mConsts[pInterface->mConstCount] = pConst; _ReturnOK (pInterface->mConstCount++); } int CreateInterfaceMethod( const char *pszName, InterfaceDescriptor *pInterface) { MethodDescriptor *pMethod; assert(pInterface != NULL); assert(pszName != NULL); if (pInterface->mMethodCount >= MAX_METHOD_NUMBER) _ReturnError (CLSError_FullEntry); pMethod = NewMethod(pszName); if (!pMethod) _ReturnError (CLSError_OutOfMemory); pInterface->mMethods[pInterface->mMethodCount] = pMethod; _ReturnOK (pInterface->mMethodCount++); } int CreateMethodParam( const char *pszName, MethodDescriptor *pMethod) { int n; ParamDescriptor *pParam; assert(pMethod != NULL); assert(pszName != NULL); n = SelectMethodParam(pszName, pMethod); if (n >= 0) { ExtraMessage("method parameter", pszName); _ReturnError (CLSError_DupEntry); } if (pMethod->mParamCount >= MAX_PARAM_NUMBER) _ReturnError (CLSError_FullEntry); pParam = NewParam(pszName); if (!pParam) _ReturnError (CLSError_OutOfMemory); pMethod->mParams[pMethod->mParamCount] = pParam; _ReturnOK (pMethod->mParamCount++); } int CreateStructElement( const char *pszName, StructDescriptor *pStruct) { int n; StructElement *pElement; assert(pStruct != NULL); assert(pszName != NULL); n = SelectStructElement(pszName, pStruct); if (n >= 0) { ExtraMessage("struct member", pszName); _ReturnError (CLSError_DupEntry); } if (pStruct->mElementCount >= MAX_STRUCT_ELEMENT_NUMBER) _ReturnError (CLSError_FullEntry); pElement = NewStructElement(pszName); if (!pElement) _ReturnError (CLSError_OutOfMemory); pStruct->mElements[pStruct->mElementCount] = pElement; _ReturnOK (pStruct->mElementCount++); } int CreateEnumElement( const char *pszName, CLSModule *pModule, EnumDescriptor *pEnum) { int n; EnumElement *pElement; assert(pModule != NULL); assert(pEnum != NULL); assert(pszName != NULL); n = SelectEnumElement(pszName, pEnum); if (n >= 0) { ExtraMessage("enum member", pszName); _ReturnError (CLSError_DupEntry); } pElement = GlobalSelectEnumElement(pszName, pModule); if (pElement) _ReturnError (CLSError_NameConflict); if (pEnum->mElementCount >= MAX_ENUM_ELEMENT_NUMBER) _ReturnError (CLSError_FullEntry); pElement = NewEnumElement(pszName); if (!pElement) _ReturnError (CLSError_OutOfMemory); pEnum->mElements[pEnum->mElementCount] = pElement; _ReturnOK (pEnum->mElementCount++); } int MethodAppend( const MethodDescriptor *pSrc, InterfaceDescriptor *pDesc) { int n, m; MethodDescriptor *pDest; ParamDescriptor *pParam; n = CreateInterfaceMethod(pSrc->mName, pDesc); if (n < 0) _Return (n); pDest = pDesc->mMethods[n]; pDest->mSignature = new char[strlen(pSrc->mSignature) + 1]; strcpy(pDest->mSignature, pSrc->mSignature); TypeCopy(&pSrc->mType, &pDest->mType); for (n = 0; n < pSrc->mParamCount; n++) { m = CreateMethodParam(pSrc->mParams[n]->mName, pDest); if (m < 0) _Return (m); pParam = pDest->mParams[m]; pParam->mAttribs = pSrc->mParams[n]->mAttribs; TypeCopy(&pSrc->mParams[n]->mType, &pParam->mType); } _ReturnOK (CLS_NoError); } int InterfaceMethodsAppend(const CLSModule *pModule, const InterfaceDescriptor *pSrc, InterfaceDescriptor *pDest) { int n, m; if (0 != pSrc->mParentIndex) { n = InterfaceMethodsAppend(pModule, pModule->mInterfaceDirs[pSrc->mParentIndex]->mDesc, pDest); if (n < 0) _Return (n); } for (n = 0; n < pSrc->mMethodCount; n++) { m = MethodAppend(pSrc->mMethods[n], pDest); if (m < 0) _Return (m); } _ReturnOK (CLS_NoError); }
28.317236
104
0.648622
jingcao80
8da01051e45342f754ec1a84c61711a99458bbc5
40,282
ipp
C++
src/maral/mtl/matrix_ops.ipp
arminms/maral
72ac000aa5e37702beec3b3423db7ab2e43da01e
[ "BSL-1.0" ]
1
2022-03-01T19:00:17.000Z
2022-03-01T19:00:17.000Z
src/maral/mtl/matrix_ops.ipp
arminms/maral
72ac000aa5e37702beec3b3423db7ab2e43da01e
[ "BSL-1.0" ]
2
2016-04-28T18:51:08.000Z
2016-05-25T19:43:19.000Z
src/maral/mtl/matrix_ops.ipp
arminms/maral
72ac000aa5e37702beec3b3423db7ab2e43da01e
[ "BSL-1.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // MARAL // (Molecular Architectural Record & Assembly Library) // // Copyright (C) by Armin Madadkar-Sobhani arminms@gmail.com // // See the LICENSE file for terms of use // //------------------------------------------------------------------------------ // $Id$ //------------------------------------------------------------------------------ // Filename: // matrix_ops.ipp //------------------------------------------------------------------------------ // Remarks: // This file contains implementation for all operations related to matrices. //------------------------------------------------------------------------------ /// \ingroup mtx22ops /// \name matrix22 Operations /// @{ //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix22 objects to see if they are /// exactly the same . /// \see operator!=(const matrix22&, const matrix22&) template<typename T> inline bool operator== ( const matrix22<T>& m1, const matrix22<T>& m2) { return ( m1(0) == m2(0) && m1(1) == m2(1) && m1(2) == m2(2) && m1(3) == m2(3) ); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 does not equal \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix22 objects to see if they are /// NOT exactly the same with zero tolerance. /// \see operator==(const matrix22&, const matrix22&) template<typename T> inline bool operator!= ( const matrix22<T>& m1, const matrix22<T>& m2) { return ( m1(0) != m2(0) || m1(1) != m2(1) || m1(2) != m2(2) || m1(3) != m2(3) ); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2 within the tolerance; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \param eps The epsilon tolerance value. /// \pre eps must be >= 0 /// \remarks /// Compares \a m1 and \a m2 to see if they are the same within the given /// epsilon tolerance. /// \see operator==(const matrix22&, const matrix22&) template<typename T> inline bool is_equal( const matrix22<T>& m1, const matrix22<T>& m2, const T eps = T(0.0005) ) { BOOST_ASSERT_MSG(eps >= 0, "negative tolerance!"); return ( std::abs(m1(0) - m2(0)) <= eps && std::abs(m1(1) - m2(1)) <= eps && std::abs(m1(2) - m2(2)) <= eps && std::abs(m1(3) - m2(3)) <= eps ); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// You can safely pass either \a lhs or \a rhs as \a r. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This function puts results of the \a lhs and \a rhs matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a lhs * \a rhs (where \a rhs is applied first). /// \see operator*(const matrix22&, const matrix22&) template<typename T> inline matrix22<T>& mult( matrix22<T>& r, const matrix22<T>& lhs, const matrix22<T>& rhs) { matrix22<T> ret; // prevents aliasing ret.zero(); ret(0) += lhs(0) * rhs(0); ret(0) += lhs(2) * rhs(1); ret(1) += lhs(1) * rhs(0); ret(1) += lhs(3) * rhs(1); ret(2) += lhs(0) * rhs(2); ret(2) += lhs(2) * rhs(3); ret(3) += lhs(1) * rhs(2); ret(3) += lhs(3) * rhs(3); return r = ret; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a operand * \a r /// \remarks /// This function puts results of the \a operand and \a r matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a operand * \a r. /// \see mult(matrix22<T>&,const matrix22&, const matrix22&), /// postMult(matrix22<T>&,const matrix22<T>& operand) template<typename T> inline matrix22<T>& pre_mult( matrix22<T>& r, const matrix22<T>& operand) { return mult(r, operand, r); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This function puts results of the \a r and \a operand matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a r * \a operand. /// \see mult(matrix22<T>&,const matrix22&, const matrix22&), /// preMult(matrix22<T>&,const matrix22<T>& operand) template<typename T> inline matrix22<T>& post_mult( matrix22<T>& r, const matrix22<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This overloaded binary operator multiplies \a rhs by \a lhs then returns the /// result. This is equivalent to the expression \a r = \a lhs * \a rhs (where /// \a rhs is applied first). /// \see mult(matrix22<T>&,const matrix22&, const matrix22&) template<typename T> inline matrix22<T> operator* ( const matrix22<T>& lhs, const matrix22<T>& rhs) { matrix22<T> temp; return mult(temp, lhs, rhs); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This overloaded binary operator multiplies \a r by \a operand and then /// returns reference to \a r. In this way, it can be used as a parameter for /// another function. This is equivalent to the expression \a r = \a r * /// \a operand. /// \see postMult(matrix22<T>&,const matrix22<T>& operand) template<typename T> inline matrix22<T>& operator*= ( matrix22<T>& r, const matrix22<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix to be transposed. /// \remarks /// This function transposes the given matrix \a r in place and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix22&, const matrix22&) template<typename T> inline matrix22<T>& transpose( matrix22<T>& r) { std::swap(r(1), r(2)); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \remarks /// This function puts the result of transposing \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix22&) template<typename T> inline matrix22<T>& transpose( matrix22<T>& r, const matrix22<T>& s) { r(0) = s(0); r(1) = s(2); r(2) = s(1); r(3) = s(3); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return The determinant of the matrix. /// \param m Reference to the matrix used for the determinant calculation. /// \remarks /// This function computes the determinant of the \a m matrix. Determinant is /// used for the calculation of the inverse of a matrix. /// \see invert(matrix22&, const matrix22&) template<typename T> inline T determinant( const matrix22<T>& m) { return ( (m(0)*m(3)) - (m(1)*m(2)) ); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \pre Only works with float types (e.g. matrix22<int> is not acceptable). /// \remarks /// This function puts the result of inverting \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see invert(const matrix22&) template<typename T> inline matrix22<T>& invert( matrix22<T>& r, const matrix22<T>& s) { T det = ( (s(0)*s(3)) - (s(1)*s(2)) ); BOOST_ASSERT_MSG(std::abs(det) > SMALL, "not invertible!"); T one_over_det = T(1) / det; r(0) = s(3) * one_over_det; r(1) = -s(1) * one_over_det; r(2) = -s(2) * one_over_det; r(3) = s(0) * one_over_det; return r; } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param m Reference to the matrix to be inverted. /// \pre Only works with float types (e.g. matrix22<int> is not acceptable). /// \remarks /// This function inverts the given matrix \a m and then returns the result. In /// this way, it can be used as a parameter for another function. /// \see invert(matrix22&, const matrix22&) template<typename T> inline matrix22<T> invert( const matrix22<T>& m) { matrix22<T> r; return invert(r, m); } /// @} /// \ingroup mtx33ops /// \name matrix33 Operations /// @{ //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix33 objects to see if they are /// exactly the same . /// \see operator!=(const matrix33&, const matrix33&) template<typename T> inline bool operator== ( const matrix33<T>& m1, const matrix33<T>& m2) { return ( m1(0) == m2(0) && m1(1) == m2(1) && m1(2) == m2(2) && m1(3) == m2(3) && m1(4) == m2(4) && m1(5) == m2(5) && m1(6) == m2(6) && m1(7) == m2(7) && m1(8) == m2(8)); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 does not equal \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix33 objects to see if they are /// NOT exactly the same with zero tolerance. /// \see operator==(const matrix33&, const matrix33&) template<typename T> inline bool operator!= ( const matrix33<T>& m1, const matrix33<T>& m2) { return ( m1(0) != m2(0) || m1(1) != m2(1) || m1(2) != m2(2) || m1(3) != m2(3) || m1(4) != m2(4) || m1(5) != m2(5) || m1(6) != m2(6) || m1(7) != m2(7) || m1(8) != m2(8)); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2 within the tolerance; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \param eps The epsilon tolerance value. /// \pre eps must be >= 0 /// \remarks /// Compares \a m1 and \a m2 to see if they are the same within the given /// epsilon tolerance. /// \see operator==(const matrix33&, const matrix33&) template<typename T> inline bool is_equal( const matrix33<T>& m1, const matrix33<T>& m2, const T eps = T(0.0005) ) { BOOST_ASSERT_MSG(eps >= 0, "negative tolerance!"); return ( std::abs(m1(0) - m2(0)) <= eps && std::abs(m1(1) - m2(1)) <= eps && std::abs(m1(2) - m2(2)) <= eps && std::abs(m1(3) - m2(3)) <= eps && std::abs(m1(4) - m2(4)) <= eps && std::abs(m1(5) - m2(5)) <= eps && std::abs(m1(6) - m2(6)) <= eps && std::abs(m1(7) - m2(7)) <= eps && std::abs(m1(8) - m2(8)) <= eps); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// You can safely pass either \a lhs or \a rhs as \a r. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This function puts results of the \a lhs and \a rhs matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a lhs * \a rhs (where \a rhs is applied first). /// \see operator*(const matrix33&, const matrix33&) template<typename T> inline matrix33<T>& mult( matrix33<T>& r, const matrix33<T>& lhs, const matrix33<T>& rhs) { matrix33<T> ret; // prevents aliasing ret.zero(); ret(0) += lhs(0) * rhs(0); ret(0) += lhs(3) * rhs(1); ret(0) += lhs(6) * rhs(2); ret(1) += lhs(1) * rhs(0); ret(1) += lhs(4) * rhs(1); ret(1) += lhs(7) * rhs(2); ret(2) += lhs(2) * rhs(0); ret(2) += lhs(5) * rhs(1); ret(2) += lhs(8) * rhs(2); ret(3) += lhs(0) * rhs(3); ret(3) += lhs(3) * rhs(4); ret(3) += lhs(6) * rhs(5); ret(4) += lhs(1) * rhs(3); ret(4) += lhs(4) * rhs(4); ret(4) += lhs(7) * rhs(5); ret(5) += lhs(2) * rhs(3); ret(5) += lhs(5) * rhs(4); ret(5) += lhs(8) * rhs(5); ret(6) += lhs(0) * rhs(6); ret(6) += lhs(3) * rhs(7); ret(6) += lhs(6) * rhs(8); ret(7) += lhs(1) * rhs(6); ret(7) += lhs(4) * rhs(7); ret(7) += lhs(7) * rhs(8); ret(8) += lhs(2) * rhs(6); ret(8) += lhs(5) * rhs(7); ret(8) += lhs(8) * rhs(8); return r = ret; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a operand * \a r /// \remarks /// This function puts results of the \a operand and \a r matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a operand * \a r. /// \see mult(matrix33<T>&,const matrix33&, const matrix33&), /// postMult(matrix33<T>&,const matrix33<T>& operand) template<typename T> inline matrix33<T>& pre_mult( matrix33<T>& r, const matrix33<T>& operand) { return mult(r, operand, r); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This function puts results of the \a r and \a operand matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a r * \a operand. /// \see mult(matrix33<T>&,const matrix33&, const matrix33&), /// preMult(matrix33<T>&,const matrix33<T>& operand) template<typename T> inline matrix33<T>& post_mult( matrix33<T>& r, const matrix33<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This overloaded binary operator multiplies \a rhs by \a lhs then returns the /// result. This is equivalent to the expression \a r = \a lhs * \a rhs (where /// \a rhs is applied first). /// \see mult(matrix33<T>&,const matrix33&, const matrix33&) template<typename T> inline matrix33<T> operator* ( const matrix33<T>& lhs, const matrix33<T>& rhs) { matrix33<T> temp; return mult(temp, lhs, rhs); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This overloaded binary operator multiplies \a r by \a operand and then /// returns reference to \a r. In this way, it can be used as a parameter for /// another function. This is equivalent to the expression \a r = \a r * /// \a operand. /// \see postMult(matrix33<T>&,const matrix33<T>& operand) template<typename T> inline matrix33<T>& operator*= ( matrix33<T>& r, const matrix33<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix to be transposed. /// \remarks /// This function transposes the given matrix \a r in place and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix33&, const matrix33&) template<typename T> inline matrix33<T>& transpose( matrix33<T>& r) { std::swap(r(1), r(3)); std::swap(r(2), r(6)); std::swap(r(5), r(7)); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \remarks /// This function puts the result of transposing \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix33&) template<typename T> inline matrix33<T>& transpose( matrix33<T>& r, const matrix33<T>& s) { r(0) = s(0); r(1) = s(3); r(2) = s(6); r(3) = s(1); r(4) = s(4); r(5) = s(7); r(6) = s(2); r(7) = s(5); r(8) = s(8); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return The determinant of the matrix. /// \param m Reference to the matrix used for the determinant calculation. /// \remarks /// This function computes the determinant of the \a m matrix. Determinant is /// used for the calculation of the inverse of a matrix. /// \see invert(matrix33&, const matrix33&) template<typename T> inline T determinant( const matrix33<T>& m) { return ((((m(3)*m(7)) - (m(6)*m(4))) * m(2)) + (((m(6)*m(1)) - (m(0)*m(7))) * m(5)) + (((m(0)*m(4)) - (m(3)*m(1))) * m(8))); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \pre Only works with float types (e.g. matrix33<int> is not acceptable). /// \remarks /// This function puts the result of inverting \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. It uses the \a classical \a adjoint method to compute the inverse. /// \see invert(const matrix33&) template<typename T> inline matrix33<T>& invert( matrix33<T>& r, const matrix33<T>& s) { T det = determinant(s); BOOST_ASSERT_MSG(std::abs(det) > SMALL, "not invertible!"); T one_over_det = T(1) / det; r(0) = ((s(4)*s(8))-(s(7)*s(5)))*one_over_det; r(1) = ((s(7)*s(2))-(s(1)*s(8)))*one_over_det; r(2) = ((s(1)*s(5))-(s(4)*s(2)))*one_over_det; r(3) = ((s(6)*s(5))-(s(3)*s(8)))*one_over_det; r(4) = ((s(0)*s(8))-(s(6)*s(2)))*one_over_det; r(5) = ((s(3)*s(2))-(s(0)*s(5)))*one_over_det; r(6) = ((s(3)*s(7))-(s(6)*s(4)))*one_over_det; r(7) = ((s(6)*s(1))-(s(0)*s(7)))*one_over_det; r(8) = ((s(0)*s(4))-(s(3)*s(1)))*one_over_det; return r; } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param m Reference to the matrix to be inverted. /// \pre Only works with float types (e.g. matrix33<int> is not acceptable). /// \remarks /// This function inverts the given matrix \a m and then returns the result. In /// this way, it can be used as a parameter for another function. It uses the \a /// classical \a adjoint method to compute the inverse. /// \see invert(matrix33&, const matrix33&) template<typename T> inline matrix33<T> invert( const matrix33<T>& m) { matrix33<T> r; return invert(r, m); } /// @} /// \ingroup mtx44ops /// \name matrix44 Operations /// @{ //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix44 objects to see if they are /// exactly the same . /// \see operator!=(const matrix44&, const matrix44&) template<typename T> inline bool operator== ( const matrix44<T>& m1, const matrix44<T>& m2) { return ( m1 (0) == m2 (0) && m1 (1) == m2 (1) && m1 (2) == m2 (2) && m1 (3) == m2 (3) && m1 (4) == m2 (4) && m1 (5) == m2 (5) && m1 (6) == m2 (6) && m1 (7) == m2 (7) && m1 (8) == m2 (8) && m1 (9) == m2 (9) && m1(10) == m2(10) && m1(11) == m2(11) && m1(12) == m2(12) && m1(13) == m2(13) && m1(14) == m2(14) && m1(15) == m2(15)); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 does not equal \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix44 objects to see if they are /// NOT exactly the same with zero tolerance. /// \see operator==(const matrix44&, const matrix44&) template<typename T> inline bool operator!= ( const matrix44<T>& m1, const matrix44<T>& m2) { return ( m1 (0) != m2 (0) || m1 (1) != m2 (1) || m1 (2) != m2 (2) || m1 (3) != m2 (3) || m1 (4) != m2 (4) || m1 (5) != m2 (5) || m1 (6) != m2 (6) || m1 (7) != m2 (7) || m1 (8) != m2 (8) || m1 (9) != m2 (9) || m1(10) != m2(10) || m1(11) != m2(11) || m1(12) != m2(12) || m1(13) != m2(13) || m1(14) != m2(14) || m1(15) != m2(15)); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2 within the tolerance; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \param eps The epsilon tolerance value. /// \pre eps must be >= 0 /// \remarks /// Compares \a m1 and \a m2 to see if they are the same within the given /// epsilon tolerance. /// \see operator==(const matrix44&, const matrix44&) template<typename T> inline bool is_equal( const matrix44<T>& m1, const matrix44<T>& m2, const T eps = T(0.0005) ) { BOOST_ASSERT_MSG(eps >= 0, "negative tolerance!"); return ( std::abs(m1 (0) - m2 (0)) <= eps && std::abs(m1 (1) - m2 (1)) <= eps && std::abs(m1 (2) - m2 (2)) <= eps && std::abs(m1 (3) - m2 (3)) <= eps && std::abs(m1 (4) - m2 (4)) <= eps && std::abs(m1 (5) - m2 (5)) <= eps && std::abs(m1 (6) - m2 (6)) <= eps && std::abs(m1 (7) - m2 (7)) <= eps && std::abs(m1 (8) - m2 (8)) <= eps && std::abs(m1 (9) - m2 (9)) <= eps && std::abs(m1(10) - m2(10)) <= eps && std::abs(m1(11) - m2(11)) <= eps && std::abs(m1(12) - m2(12)) <= eps && std::abs(m1(13) - m2(13)) <= eps && std::abs(m1(14) - m2(14)) <= eps && std::abs(m1(15) - m2(15)) <= eps); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// You can safely pass either \a lhs or \a rhs as \a r. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This function puts results of the \a lhs and \a rhs matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a lhs * \a rhs (where \a rhs is applied first). /// \see operator*(const matrix44&, const matrix44&) template<typename T> inline matrix44<T>& mult( matrix44<T>& r, const matrix44<T>& lhs, const matrix44<T>& rhs) { matrix44<T> ret; // prevents aliasing ret.zero(); ret (0) += lhs (0) * rhs (0); ret (0) += lhs (4) * rhs (1); ret (0) += lhs (8) * rhs (2); ret (0) += lhs(12) * rhs (3); ret (1) += lhs (1) * rhs (0); ret (1) += lhs (5) * rhs (1); ret (1) += lhs (9) * rhs (2); ret (1) += lhs(13) * rhs (3); ret (2) += lhs (2) * rhs (0); ret (2) += lhs (6) * rhs (1); ret (2) += lhs(10) * rhs (2); ret (2) += lhs(14) * rhs (3); ret (3) += lhs (3) * rhs (0); ret (3) += lhs (7) * rhs (1); ret (3) += lhs(11) * rhs (2); ret (3) += lhs(15) * rhs (3); ret (4) += lhs (0) * rhs (4); ret (4) += lhs (4) * rhs (5); ret (4) += lhs (8) * rhs (6); ret (4) += lhs(12) * rhs (7); ret (5) += lhs (1) * rhs (4); ret (5) += lhs (5) * rhs (5); ret (5) += lhs (9) * rhs (6); ret (5) += lhs(13) * rhs (7); ret (6) += lhs (2) * rhs (4); ret (6) += lhs (6) * rhs (5); ret (6) += lhs(10) * rhs (6); ret (6) += lhs(14) * rhs (7); ret (7) += lhs (3) * rhs (4); ret (7) += lhs (7) * rhs (5); ret (7) += lhs(11) * rhs (6); ret (7) += lhs(15) * rhs (7); ret (8) += lhs (0) * rhs (8); ret (8) += lhs (4) * rhs (9); ret (8) += lhs (8) * rhs(10); ret (8) += lhs(12) * rhs(11); ret (9) += lhs (1) * rhs (8); ret (9) += lhs (5) * rhs (9); ret (9) += lhs (9) * rhs(10); ret (9) += lhs(13) * rhs(11); ret(10) += lhs (2) * rhs (8); ret(10) += lhs (6) * rhs (9); ret(10) += lhs(10) * rhs(10); ret(10) += lhs(14) * rhs(11); ret(11) += lhs (3) * rhs (8); ret(11) += lhs (7) * rhs (9); ret(11) += lhs(11) * rhs(10); ret(11) += lhs(15) * rhs(11); ret(12) += lhs (0) * rhs(12); ret(12) += lhs (4) * rhs(13); ret(12) += lhs (8) * rhs(14); ret(12) += lhs(12) * rhs(15); ret(13) += lhs (1) * rhs(12); ret(13) += lhs (5) * rhs(13); ret(13) += lhs (9) * rhs(14); ret(13) += lhs(13) * rhs(15); ret(14) += lhs (2) * rhs(12); ret(14) += lhs (6) * rhs(13); ret(14) += lhs(10) * rhs(14); ret(14) += lhs(14) * rhs(15); ret(15) += lhs (3) * rhs(12); ret(15) += lhs (7) * rhs(13); ret(15) += lhs(11) * rhs(14); ret(15) += lhs(15) * rhs(15); return r = ret; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a operand * \a r /// \remarks /// This function puts results of the \a operand and \a r matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a operand * \a r. /// \see mult(matrix44<T>&,const matrix44&, const matrix44&), /// postMult(matrix44<T>&,const matrix44<T>& operand) template<typename T> inline matrix44<T>& pre_mult( matrix44<T>& r, const matrix44<T>& operand) { return mult(r, operand, r); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This function puts results of the \a r and \a operand matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a r * \a operand. /// \see mult(matrix44<T>&,const matrix44&, const matrix44&), /// preMult(matrix44<T>&,const matrix44<T>& operand) template<typename T> inline matrix44<T>& post_mult( matrix44<T>& r, const matrix44<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This overloaded binary operator multiplies \a rhs by \a lhs then returns the /// result. This is equivalent to the expression \a r = \a lhs * \a rhs (where /// \a rhs is applied first). /// \see mult(matrix44<T>&,const matrix44&, const matrix44&) template<typename T> inline matrix44<T> operator* ( const matrix44<T>& lhs, const matrix44<T>& rhs) { matrix44<T> temp; return mult(temp, lhs, rhs); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This overloaded binary operator multiplies \a r by \a operand and then /// returns reference to \a r. In this way, it can be used as a parameter for /// another function. This is equivalent to the expression \a r = \a r * /// \a operand. /// \see postMult(matrix44<T>&,const matrix44<T>& operand) template<typename T> inline matrix44<T>& operator*= ( matrix44<T>& r, const matrix44<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix to be transposed. /// \remarks /// This function transposes the given matrix \a r in place and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix44&, const matrix44&) template<typename T> inline matrix44<T>& transpose( matrix44<T>& r) { std::swap(r (1), r (4)); std::swap(r (2), r (8)); std::swap(r (3), r(12)); std::swap(r (6), r (9)); std::swap(r (7), r(13)); std::swap(r(11), r(14)); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \remarks /// This function puts the result of transposing \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix44&) template<typename T> inline matrix44<T>& transpose( matrix44<T>& r, const matrix44<T>& s) { r (0) = s (0); r (1) = s (4); r (2) = s (8); r (3) = s(12); r (4) = s (1); r (5) = s (5); r (6) = s (9); r (7) = s(13); r (8) = s (2); r (9) = s (6); r(10) = s(10); r(11) = s(14); r(12) = s (3); r(13) = s (7); r(14) = s(11); r(15) = s(15); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return The determinant of the matrix. /// \param m Reference to the matrix used for the determinant calculation. /// \remarks /// This function computes the determinant of the \a m matrix. Determinant is /// used for the calculation of the inverse of a matrix. /// \see invert(matrix44&, const matrix44&) template<typename T> inline T determinant( const matrix44<T>& m) { return ((( (((m(10)*m(15))-(m(14)*m(11)))*m (5)) + (((m(14)*m (7))-(m (6)*m(15)))*m (9)) + (((m (6)*m(11))-(m(10)*m (7)))*m(13))) *m (0)) - (( (((m(10)*m(15))-(m(14)*m(11)))*m (1)) + (((m(14)*m (3))-(m (2)*m(15)))*m (9)) + (((m (2)*m(11))-(m(10)*m (3)))*m(13))) *m (4)) + (( (((m (6)*m(15))-(m(14)*m (7)))*m (1)) + (((m(14)*m (3))-(m (2)*m(15)))*m (5)) + (((m (2)*m (7))-(m (6)*m (3)))*m(13))) *m (8)) - (( (((m (6)*m(11))-(m(10)*m (7)))*m (1)) + (((m(10)*m (3))-(m (2)*m(11)))*m (5)) + (((m (2)*m (7))-(m (6)*m (3)))*m (9))) *m(12) )); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \pre Only works with float types (e.g. matrix44<int> is not acceptable). /// \remarks /// This function puts the result of inverting \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. It uses the \a classical \a adjoint method to compute the inverse. /// \see invert(const matrix44&) template<typename T> inline matrix44<T>& invert( matrix44<T>& r, const matrix44<T>& s) { T det = determinant(s); BOOST_ASSERT_MSG(std::abs(det) > SMALL, "not invertible!"); T one_over_det = T(1) / det; r (0) = ((s (5)*s(10)*s(15)) + (s (9)*s(14)*s (7)) + (s(13)*s (6)*s(11)) - (s (5)*s(14)*s(11)) - (s (9)*s (6)*s(15)) - (s(13)*s(10)*s (7))) * one_over_det; r (1) = ((s (1)*s(14)*s(11)) + (s (9)*s (2)*s(15)) + (s(13)*s(10)*s (3)) - (s (1)*s(10)*s(15)) - (s (9)*s(14)*s (3)) - (s(13)*s (2)*s(11))) * one_over_det; r (2) = ((s (1)*s (6)*s(15)) + (s (5)*s(14)*s (3)) + (s(13)*s (2)*s (7)) - (s (1)*s(14)*s (7)) - (s (5)*s (2)*s(15)) - (s(13)*s (6)*s (3))) * one_over_det; r (3) = ((s (1)*s(10)*s (7)) + (s (5)*s (2)*s(11)) + (s (9)*s (6)*s (3)) - (s (1)*s (6)*s(11)) - (s (5)*s(10)*s (3)) - (s (9)*s (2)*s (7))) * one_over_det; r (4) = ((s (4)*s(14)*s(11)) + (s (8)*s (6)*s(15)) + (s(12)*s(10)*s (7)) - (s (4)*s(10)*s(15)) - (s (8)*s(14)*s (7)) - (s(12)*s (6)*s(11))) * one_over_det; r (5) = ((s (0)*s(10)*s(15)) + (s (8)*s(14)*s (3)) + (s(12)*s (2)*s(11)) - (s (0)*s(14)*s(11)) - (s (8)*s (2)*s(15)) - (s(12)*s(10)*s (3))) * one_over_det; r (6) = ((s (0)*s(14)*s (7)) + (s (4)*s (2)*s(15)) + (s(12)*s (6)*s (3)) - (s (0)*s (6)*s(15)) - (s (4)*s(14)*s (3)) - (s(12)*s (2)*s (7))) * one_over_det; r (7) = ((s (0)*s (6)*s(11)) + (s (4)*s(10)*s (3)) + (s (8)*s (2)*s (7)) - (s (0)*s(10)*s (7)) - (s (4)*s (2)*s(11)) - (s (8)*s (6)*s (3))) * one_over_det; r (8) = ((s (4)*s (9)*s(15)) + (s (8)*s(13)*s (7)) + (s(12)*s (5)*s(11)) - (s (4)*s(13)*s(11)) - (s (8)*s (5)*s(15)) - (s(12)*s (9)*s (7))) * one_over_det; r (9) = ((s (0)*s(13)*s(11)) + (s (8)*s (1)*s(15)) + (s(12)*s (9)*s (3)) - (s (0)*s (9)*s(15)) - (s (8)*s(13)*s (3)) - (s(12)*s (1)*s(11))) * one_over_det; r(10) = ((s (0)*s (5)*s(15)) + (s (4)*s(13)*s (3)) + (s(12)*s (1)*s (7)) - (s (0)*s(13)*s (7)) - (s (4)*s (1)*s(15)) - (s(12)*s (5)*s (3))) * one_over_det; r(11) = ((s (0)*s (9)*s (7)) + (s (4)*s (1)*s(11)) + (s (8)*s (5)*s (3)) - (s (0)*s (5)*s(11)) - (s (4)*s (9)*s (3)) - (s (8)*s (1)*s (7))) * one_over_det; r(12) = ((s (4)*s(13)*s(10)) + (s (8)*s (5)*s(14)) + (s(12)*s (9)*s (6)) - (s (4)*s (9)*s(14)) - (s (8)*s(13)*s (6)) - (s(12)*s (5)*s(10))) * one_over_det; r(13) = ((s (0)*s (9)*s(14)) + (s (8)*s(13)*s (2)) + (s(12)*s (1)*s(10)) - (s (0)*s(13)*s(10)) - (s (8)*s (1)*s(14)) - (s(12)*s (9)*s (2))) * one_over_det; r(14) = ((s (0)*s(13)*s (6)) + (s (4)*s (1)*s(14)) + (s(12)*s (5)*s (2)) - (s (0)*s (5)*s(14)) - (s (4)*s(13)*s (2)) - (s(12)*s (1)*s (6))) * one_over_det; r(15) = ((s (0)*s (5)*s(10)) + (s (4)*s (9)*s (2)) + (s (8)*s (1)*s (6)) - (s (0)*s (9)*s (6)) - (s (4)*s (1)*s(10)) - (s (8)*s (5)*s (2))) * one_over_det; return r; } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param m Reference to the matrix to be inverted. /// \pre Only works with float types (e.g. matrix44<int> is not acceptable). /// \remarks /// This function inverts the given matrix \a m and then returns the result. In /// this way, it can be used as a parameter for another function. It uses the \a /// classical \a adjoint method to compute the inverse. /// \see invert(matrix44&, const matrix44&) template<typename T> inline matrix44<T> invert( const matrix44<T>& m) { matrix44<T> r; return invert(r, m); } /// @}
34.666093
80
0.502408
arminms
8da624b3256033a18175ddab6f7c33455e62be5a
8,689
cpp
C++
dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationLimitNode.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationLimitNode.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationLimitNode.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Serialization/EditContext.h> #include "BlendTreeRotationLimitNode.h" #include <MCore/Source/FastMath.h> #include <MCore/Source/Compare.h> #include <MCore/Source/AzCoreConversions.h> #include <EMotionFX/Source/ConstraintTransformRotationAngles.h> namespace EMotionFX { AZ_CLASS_ALLOCATOR_IMPL(BlendTreeRotationLimitNode, AnimGraphAllocator, 0) AZ_CLASS_ALLOCATOR_IMPL(BlendTreeRotationLimitNode::RotationLimit, AnimGraphAllocator, 0) const float BlendTreeRotationLimitNode::RotationLimit::s_rotationLimitRangeMin = -360.0f; const float BlendTreeRotationLimitNode::RotationLimit::s_rotationLimitRangeMax = 360.0f; BlendTreeRotationLimitNode::RotationLimit::RotationLimit(BlendTreeRotationLimitNode::RotationLimit::Axis axis) : m_axis(axis) {} void BlendTreeRotationLimitNode::RotationLimit::SetMin(float min) { m_min = min; } void BlendTreeRotationLimitNode::RotationLimit::SetMax(float max) { m_max = max; } const char* BlendTreeRotationLimitNode::RotationLimit::GetLabel() const { const char* label = nullptr; switch (m_axis) { case RotationLimit::Axis::AXIS_X: label = "<font color='red'>X</font>"; break; case RotationLimit::Axis::AXIS_Y: label = "<font color='green'>Y</font>"; break; case RotationLimit::Axis::AXIS_Z: label = "<font color='blue'>Z</font>"; break; default: AZ_Assert(false, "Unknown axis type for Rotation limit"); label = ""; break; } return label; } const BlendTreeRotationLimitNode::RotationLimit& BlendTreeRotationLimitNode::GetRotationLimitX() const { return m_rotationLimits[RotationLimit::Axis::AXIS_X]; } const BlendTreeRotationLimitNode::RotationLimit& BlendTreeRotationLimitNode::GetRotationLimitY() const { return m_rotationLimits[RotationLimit::Axis::AXIS_Y]; } const BlendTreeRotationLimitNode::RotationLimit& BlendTreeRotationLimitNode::GetRotationLimitZ() const { return m_rotationLimits[RotationLimit::Axis::AXIS_Z]; } float BlendTreeRotationLimitNode::RotationLimit::GetLimitMin() const { return m_min; } float BlendTreeRotationLimitNode::RotationLimit::GetLimitMax() const { return m_max; } void BlendTreeRotationLimitNode::RotationLimit::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context); if (!serializeContext) { return; } serializeContext->Class<RotationLimit>() ->Version(1) ->Field("min", &RotationLimit::m_min) ->Field("max", &RotationLimit::m_max) ->Field("axis", &RotationLimit::m_axis) ; AZ::EditContext* editContext = serializeContext->GetEditContext(); if (!editContext) { return; } editContext->Class<RotationLimit>("Rotation limit", "Rotation limit") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->ElementAttribute(AZ::Edit::Attributes::NameLabelOverride, &RotationLimit::GetLabel); } BlendTreeRotationLimitNode::BlendTreeRotationLimitNode() : AnimGraphNode() { InitInputPorts(1); SetupInputPort("Input Rotation", INPUTPORT_ROTATION, MCore::AttributeQuaternion::TYPE_ID, PORTID_INPUT); InitOutputPorts(1); SetupOutputPort("Rotation", OUTPUTPORT_RESULT_QUATERNION, MCore::AttributeQuaternion::TYPE_ID, PORTID_OUTPUT_QUATERNION); } bool BlendTreeRotationLimitNode::InitAfterLoading(AnimGraph* animGraph) { if (!AnimGraphNode::InitAfterLoading(animGraph)) { return false; } InitInternalAttributesForAllInstances(); Reinit(); return true; } const char* BlendTreeRotationLimitNode::GetPaletteName() const { return "Rotation Limit"; } AnimGraphObject::ECategory BlendTreeRotationLimitNode::GetPaletteCategory() const { return AnimGraphObject::CATEGORY_MATH; } void BlendTreeRotationLimitNode::Output(AnimGraphInstance* animGraphInstance) { AnimGraphNode::Output(animGraphInstance); ExecuteMathLogic(animGraphInstance); } void BlendTreeRotationLimitNode::ExecuteMathLogic(EMotionFX::AnimGraphInstance * animGraphInstance) { // If there are no incoming connections, there is nothing to do if (mConnections.empty()) { return; } m_constraintTransformRotationAngles.SetTwistAxis(m_twistAxis); m_constraintTransformRotationAngles.GetTransform().mRotation = GetInputQuaternion(animGraphInstance, INPUTPORT_ROTATION)->GetValue(); m_constraintTransformRotationAngles.SetMaxRotationAngles(AZ::Vector2(GetRotationLimitY().m_max, GetRotationLimitX().m_max)); m_constraintTransformRotationAngles.SetMinRotationAngles(AZ::Vector2(GetRotationLimitY().m_min, GetRotationLimitX().m_min)); m_constraintTransformRotationAngles.SetMinTwistAngle(GetRotationLimitZ().m_min); m_constraintTransformRotationAngles.SetMaxTwistAngle(GetRotationLimitZ().m_max); m_constraintTransformRotationAngles.Execute(); GetOutputQuaternion(animGraphInstance, OUTPUTPORT_RESULT_QUATERNION)->SetValue(m_constraintTransformRotationAngles.GetTransform().mRotation); } void BlendTreeRotationLimitNode::Reflect(AZ::ReflectContext* context) { RotationLimit::Reflect(context); AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context); if (!serializeContext) { return; } serializeContext->Class<BlendTreeRotationLimitNode, AnimGraphNode>() ->Version(1) ->Field("rotationLimits", &BlendTreeRotationLimitNode::m_rotationLimits) ->Field("twistAxis", &BlendTreeRotationLimitNode::m_twistAxis) ; AZ::EditContext* editContext = serializeContext->GetEditContext(); if (!editContext) { return; } editContext->Class<BlendTreeRotationLimitNode>("Rotation Math2", "Rotation Math2 attributes") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, "") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->DataElement(AZ::Edit::UIHandlers::ComboBox, &BlendTreeRotationLimitNode::m_twistAxis, "Twist axis", "The twist axis to calculate the rotation limits") ->DataElement(AZ_CRC("BlendTreeRotationLimitContainerHandler", 0xb2c775fb), &BlendTreeRotationLimitNode::m_rotationLimits, "Rotation limits", "Rotation limits") ->Attribute(AZ::Edit::Attributes::ContainerCanBeModified, false) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->ElementAttribute(AZ::Edit::UIHandlers::Handler, AZ_CRC("BlendTreeRotationLimitHandler", 0xc1af4ea8)) ; } void BlendTreeRotationLimitNode::SetRotationLimitsX(float min, float max) { m_rotationLimits[RotationLimit::Axis::AXIS_X].m_min = min; m_rotationLimits[RotationLimit::Axis::AXIS_X].m_max = max; } void BlendTreeRotationLimitNode::SetRotationLimitsY(float min, float max) { m_rotationLimits[RotationLimit::Axis::AXIS_Y].m_min = min; m_rotationLimits[RotationLimit::Axis::AXIS_Y].m_max = max; } void BlendTreeRotationLimitNode::SetRotationLimitsZ(float min, float max) { m_rotationLimits[RotationLimit::Axis::AXIS_Z].m_min = min; m_rotationLimits[RotationLimit::Axis::AXIS_Z].m_max = max; } void BlendTreeRotationLimitNode::SetTwistAxis(ConstraintTransformRotationAngles::EAxis twistAxis) { m_twistAxis = twistAxis; } } // namespace EMotionFX
36.508403
172
0.687421
jeikabu
8daa226990508d749b8fe10c744ea91111c11ad8
14,755
cpp
C++
tcp_client/imager/Image_viewer.cpp
v0d0m3r/testing_task
d5fbb01bf4b6736dce43101397247da725df9c65
[ "MIT" ]
null
null
null
tcp_client/imager/Image_viewer.cpp
v0d0m3r/testing_task
d5fbb01bf4b6736dce43101397247da725df9c65
[ "MIT" ]
null
null
null
tcp_client/imager/Image_viewer.cpp
v0d0m3r/testing_task
d5fbb01bf4b6736dce43101397247da725df9c65
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ // Qt #include <QtWidgets> #include <QAction> //------------------------------------------------------------------------------ // Local #include "Image_viewer.hpp" #include "imager_lib/Transmit_image_dialog.hpp" //------------------------------------------------------------------------------ namespace Imager { //------------------------------------------------------------------------------ Image_viewer::Image_viewer() : image_label(new QLabel), scroll_area(new QScrollArea), scale_factor(1) { image_label->setBackgroundRole(QPalette::Base); image_label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); image_label->setScaledContents(true); scroll_area->setBackgroundRole(QPalette::Dark); scroll_area->setWidget(image_label); scroll_area->setVisible(false); setCentralWidget(scroll_area); create_actions(); resize(QGuiApplication::primaryScreen()->availableSize() * 3 / 5); } //------------------------------------------------------------------------------ bool Image_viewer::load_file(const QString& file_name) { QImageReader reader(file_name); reader.setAutoTransform(true); const QImage new_image = reader.read(); if (new_image.isNull()) { QMessageBox::information(this, QGuiApplication::applicationDisplayName(), tr("Cannot load %1: %2") .arg(QDir::toNativeSeparators(file_name), reader.errorString())); return false; } curr_img_feat = Image_features(new_image.size(),reader.quality()); prev_img_feat = curr_img_feat; curr_name_image = file_name; set_image(new_image); setWindowFilePath(file_name); const QString message = tr("Opened \"%1\", %2x%3, Depth: %4") .arg(QDir::toNativeSeparators(file_name)).arg(image.width()).arg(image.height()).arg(image.depth()); statusBar()->showMessage(message); return true; } //------------------------------------------------------------------------------ void Image_viewer::set_image(const QImage& new_image) { image = new_image; image_label->setPixmap(QPixmap::fromImage(image)); scale_factor = 1.0; scroll_area->setVisible(true); fit_to_window_act->setEnabled(true); update_actions(); if (!fit_to_window_act->isChecked()) image_label->adjustSize(); } //------------------------------------------------------------------------------ bool Image_viewer::save_file(const QString& file_name) { QImageWriter writer(file_name); writer.setCompression(curr_img_feat.info.compression_level); writer.setQuality(curr_img_feat.info.quality); qDebug() << writer.compression(); qDebug() << writer.quality(); if (!writer.write(image)) { QMessageBox::information(this, QGuiApplication::applicationDisplayName(), tr("Cannot write %1: %2") .arg(QDir::toNativeSeparators(file_name)), writer.errorString()); return false; } const QString message = tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(file_name)); statusBar()->showMessage(message); return true; } //------------------------------------------------------------------------------ static void init_image_file_dialog(QFileDialog& dialog, QFileDialog::AcceptMode accept_mode) { static bool first_dialog = true; if (first_dialog) { first_dialog = false; const QStringList pictures_locations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation); dialog.setDirectory(pictures_locations.isEmpty() ? QDir::currentPath() : pictures_locations.last()); } QStringList mime_type_filters; const auto supported_mime_types = (accept_mode == QFileDialog::AcceptOpen) ? QImageReader::supportedMimeTypes() : QImageWriter::supportedMimeTypes(); foreach (const auto& mime_type_name, supported_mime_types) mime_type_filters.append(mime_type_name); mime_type_filters.sort(); dialog.setMimeTypeFilters(mime_type_filters); dialog.selectMimeTypeFilter("image/png"); if (accept_mode == QFileDialog::AcceptSave) dialog.setDefaultSuffix("png"); } //------------------------------------------------------------------------------ void Image_viewer::open_cb() { QFileDialog dialog(this, tr("Open File")); init_image_file_dialog(dialog, QFileDialog::AcceptOpen); while (dialog.exec() == QDialog::Accepted && !load_file(dialog.selectedFiles().first())) {} } //------------------------------------------------------------------------------ void Image_viewer::save_cb() { prev_img_feat = curr_img_feat; previous_state_act->setEnabled(false); save_file(curr_name_image); } //------------------------------------------------------------------------------ void Image_viewer::save_as_cb() { QFileDialog dialog(this, tr("Save File As")); init_image_file_dialog(dialog, QFileDialog::AcceptSave); while (dialog.exec() == QDialog::Accepted && !save_file(dialog.selectedFiles().first())) {} } //------------------------------------------------------------------------------ void Image_viewer::transmission_cb() { Q_ASSERT(image_label->pixmap()); Transmit_image_dialog d(image); d.exec(); } //------------------------------------------------------------------------------ void Image_viewer::copy_cb() { #ifndef QT_NO_CLIPBOARD QGuiApplication::clipboard()->setImage(image); #endif // !QT_NO_CLIPBOARD } //------------------------------------------------------------------------------ #ifndef QT_NO_CLIPBOARD static QImage clipboardImage() { if (const QMimeData* mime_data = QGuiApplication::clipboard()->mimeData()) { if (mime_data->hasImage()) { const QImage image = qvariant_cast<QImage>(mime_data->imageData()); if (!image.isNull()) return image; } } return QImage(); } #endif // !QT_NO_CLIPBOARD //------------------------------------------------------------------------------ void Image_viewer::paste_cb() { #ifndef QT_NO_CLIPBOARD const QImage new_image = clipboardImage(); if (new_image.isNull()) statusBar()->showMessage(tr("No image in clipboard")); else { curr_img_feat = Image_features(new_image.size()); prev_img_feat = curr_img_feat; set_image(new_image); setWindowFilePath(QString()); const QString message = tr("Obtained image from clipboard, %1x%2, Depth: %3") .arg(new_image.width()).arg(new_image.height()).arg(new_image.depth()); statusBar()->showMessage(message); } #endif // !QT_NO_CLIPBOARD } //------------------------------------------------------------------------------ void Image_viewer::resize_cb() { Q_ASSERT(image_label->pixmap()); Resize_image_dialog rid; rid.set_original_size(curr_img_feat.size); if (rid.exec() == QDialog::Accepted) { prev_img_feat.size = curr_img_feat.size; curr_img_feat.size = rid.size(); if (prev_img_feat.size == curr_img_feat.size) { previous_state_act->setEnabled(curr_img_feat.info != prev_img_feat.info); return; } set_image(image.scaled(curr_img_feat.size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); previous_state_act->setEnabled(true); save_act->setEnabled(true); } } //------------------------------------------------------------------------------ void Image_viewer::compress_cb() { Q_ASSERT(image_label->pixmap()); Compress_image_dialog cid; cid.set_original_info(curr_img_feat.info); if (cid.exec() == QDialog::Accepted) { prev_img_feat.info = curr_img_feat.info; curr_img_feat.info = cid.compression_info(); if (curr_img_feat.info == prev_img_feat.info) previous_state_act->setEnabled(prev_img_feat.size != curr_img_feat.size); else { previous_state_act->setEnabled(true); save_act->setEnabled(true); } } } //------------------------------------------------------------------------------ void Image_viewer::previous_cb() { Q_ASSERT(image_label->pixmap()); bool enabled = true; if (prev_img_feat.size != curr_img_feat.size) { set_image(image.scaled(prev_img_feat.size)); curr_img_feat.size = prev_img_feat.size; enabled = false; } if ( prev_img_feat.info.compression_level != curr_img_feat.info.compression_level || prev_img_feat.info.quality != curr_img_feat.info.quality) { curr_img_feat.info = prev_img_feat.info; enabled = false; } previous_state_act->setEnabled(enabled); } //------------------------------------------------------------------------------ void Image_viewer::zoom_in_cb() { scale_image(1.25); } //------------------------------------------------------------------------------ void Image_viewer::zoom_out_cb() { scale_image(0.8); } //------------------------------------------------------------------------------ void Image_viewer::normal_size_cb() { image_label->adjustSize(); scale_factor = 1.0; } //------------------------------------------------------------------------------ void Image_viewer::fit_to_window_cb() { bool fit_to_window = fit_to_window_act->isChecked(); scroll_area->setWidgetResizable(fit_to_window); if (!fit_to_window) normal_size_cb(); update_actions(); } //------------------------------------------------------------------------------ void Image_viewer::about_cb() { QMessageBox::about(this, tr("About Image Viewer"), tr("<p>The <b>Image Viewer</b> is first aplication of testing task." "For more information follow to " "https://github.com/v0d0m3r/testing_task</p>")); } //------------------------------------------------------------------------------ void Image_viewer::create_actions() { auto file_menu = menuBar()->addMenu(tr("&File")); auto open_act = file_menu->addAction(tr("&Open..."), this, &Image_viewer::open_cb); open_act->setShortcut(QKeySequence::Open); save_act = file_menu->addAction(tr("&Save"), this, &Image_viewer::save_cb); save_act->setShortcut(Qt::CTRL + Qt::Key_S); save_act->setEnabled(false); save_as_act = file_menu->addAction(tr("Save &As..."), this, &Image_viewer::save_as_cb); save_as_act->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_S); save_as_act->setEnabled(false); file_menu->addSeparator(); transmission_act = file_menu->addAction(tr("&Transmission"), this, &Image_viewer::transmission_cb); transmission_act->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_T); transmission_act->setEnabled(false); file_menu->addSeparator(); auto exit_act = file_menu->addAction(tr("E&xit"), this, &QWidget::close); exit_act->setShortcut(tr("Ctrl+Q")); auto edit_menu = menuBar()->addMenu(tr("&Edit")); copy_act = edit_menu->addAction(tr("&Copy"), this, &Image_viewer::copy_cb); copy_act->setShortcut(QKeySequence::Copy); copy_act->setEnabled(false); auto paste_act = edit_menu->addAction(tr("&Paste"), this, &Image_viewer::paste_cb); paste_act->setShortcut(QKeySequence::Paste); edit_menu->addSeparator(); resize_act = edit_menu->addAction(tr("&Resize"), this, &Image_viewer::resize_cb); resize_act->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_R)); resize_act->setEnabled(false); compress_act = edit_menu->addAction(tr("Co&mpress"), this, &Image_viewer::compress_cb); compress_act->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_M)); compress_act->setEnabled(false); previous_state_act = edit_menu->addAction(tr("Pr&evious"), this, &Image_viewer::previous_cb); previous_state_act->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_E)); previous_state_act->setEnabled(false); auto view_menu = menuBar()->addMenu(tr("&View")); zoom_in_act = view_menu->addAction(tr("Zoom &In (25%)"), this, &Image_viewer::zoom_in_cb); zoom_in_act->setShortcut(QKeySequence::ZoomIn); zoom_in_act->setEnabled(false); zoom_out_act = view_menu->addAction(tr("Zoom &Out (25%)"), this, &Image_viewer::zoom_out_cb); zoom_out_act->setShortcut(QKeySequence::ZoomOut); zoom_out_act->setEnabled(false); normal_size_act = view_menu->addAction(tr("&Normal Size"), this, &Image_viewer::normal_size_cb); normal_size_act->setShortcut(tr("Ctrl+S")); normal_size_act->setEnabled(false); view_menu->addSeparator(); fit_to_window_act = view_menu->addAction(tr("&Fit to Window"), this, &Image_viewer::fit_to_window_cb); fit_to_window_act->setEnabled(false); fit_to_window_act->setCheckable(true); fit_to_window_act->setShortcut(tr("Ctrl+F")); auto help_menu = menuBar()->addMenu(tr("&Help")); help_menu->addAction(tr("&About"), this, &Image_viewer::about_cb); } //------------------------------------------------------------------------------ void Image_viewer::update_actions() { save_as_act->setEnabled(!image.isNull()); transmission_act->setEnabled(!image.isNull()); copy_act->setEnabled(!image.isNull()); resize_act->setEnabled(!image.isNull()); compress_act->setEnabled(!image.isNull()); zoom_in_act->setEnabled(!fit_to_window_act->isChecked()); zoom_out_act->setEnabled(!fit_to_window_act->isChecked()); normal_size_act->setEnabled(!fit_to_window_act->isChecked()); } //------------------------------------------------------------------------------ void Image_viewer::scale_image(double factor) { Q_ASSERT(image_label->pixmap()); scale_factor *= factor; image_label->resize(scale_factor * image_label->pixmap()->size()); adjust_scroll_bar(scroll_area->horizontalScrollBar(), factor); adjust_scroll_bar(scroll_area->verticalScrollBar(), factor); zoom_in_act->setEnabled(scale_factor < 3.0); zoom_out_act->setEnabled(scale_factor > 0.333); } //------------------------------------------------------------------------------ void Image_viewer::adjust_scroll_bar(QScrollBar* scroll_bar, double factor) { if (scroll_bar == nullptr) return; scroll_bar->setValue(int(factor * scroll_bar->value() + ((factor - 1) * scroll_bar->pageStep()/2))); } //------------------------------------------------------------------------------ } // Imager //------------------------------------------------------------------------------
33.008949
115
0.564351
v0d0m3r
8daa6dd5b5470d4783705cc0136e8ddc06d4b50a
6,135
cc
C++
tests/unit/test_reconstruct.cc
PhilMiller/checkpoint
7d44a3b56057272fc492a3d7e882a568d1fd411b
[ "BSD-3-Clause" ]
null
null
null
tests/unit/test_reconstruct.cc
PhilMiller/checkpoint
7d44a3b56057272fc492a3d7e882a568d1fd411b
[ "BSD-3-Clause" ]
null
null
null
tests/unit/test_reconstruct.cc
PhilMiller/checkpoint
7d44a3b56057272fc492a3d7e882a568d1fd411b
[ "BSD-3-Clause" ]
null
null
null
/* //@HEADER // ***************************************************************************** // // test_reconstruct.cc // DARMA Toolkit v. 1.0.0 // DARMA/checkpoint => Serialization Library // // Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #include "test_harness.h" #include <serdes_headers.h> #include <serialization_library_headers.h> #include <gtest/gtest.h> #include <vector> #include <cstdio> namespace serdes { namespace tests { namespace unit { template <typename T> struct TestReconstruct : TestHarness { }; TYPED_TEST_CASE_P(TestReconstruct); static constexpr int const u_val = 43; /* * Unit test with `UserObjectA` with a default constructor for deserialization * purposes */ struct UserObjectA { UserObjectA() = default; explicit UserObjectA(int in_u) : u_(in_u) { } void check() { EXPECT_EQ(u_, u_val); } template <typename SerializerT> void serialize(SerializerT& s) { s | u_; } int u_; }; /* * Unit test with `UserObjectB` with non-intrusive reconstruct for * deserialization purposes */ struct UserObjectB { explicit UserObjectB(int in_u) : u_(in_u) { } void check() { EXPECT_EQ(u_, u_val); } template <typename SerializerT> void serialize(SerializerT& s) { s | u_; } int u_; }; template <typename SerializerT> void reconstruct(SerializerT& s, UserObjectB*& obj, void* buf) { obj = new (buf) UserObjectB(100); } }}} // end namespace serdes::tests::unit /* * Unit test with `UserObjectC` with non-intrusive reconstruct for * deserialization purposes in the serdes namespace (ADL check) */ // Forward-declare UserObjectC namespace serdes { namespace tests { namespace unit { struct UserObjectC; }}} // end namespace serdes::tests::unit // Forward-declare serialize/reconstruct methods namespace serdes { // This using declaration is only used for convenience using UserObjType = serdes::tests::unit::UserObjectC; template <typename SerializerT> void reconstruct(SerializerT& s, UserObjType*& obj, void* buf); template <typename SerializerT> void serialize(SerializerT& s, UserObjType& x); } /* end namespace serdes */ // Actually define the UserObjectC namespace serdes { namespace tests { namespace unit { struct UserObjectC { explicit UserObjectC(int in_u) : u_(std::to_string(in_u)) { } public: void check() { EXPECT_EQ(u_, std::to_string(u_val)); } template <typename SerializerT> friend void serdes::serialize(SerializerT&, UserObjectC&); template <typename SerializerT> friend void serdes::reconstruct(SerializerT&, UserObjectC*&, void*); private: std::string u_ = {}; }; }}} // end namespace serdes::tests::unit // Implement the serialize and reconstruct in `serdes` namespace namespace serdes { // This using declaration is only used for convenience using UserObjType = serdes::tests::unit::UserObjectC; template <typename SerializerT> void reconstruct(SerializerT& s, UserObjType*& obj, void* buf) { obj = new (buf) UserObjType(100); } template <typename SerializerT> void serialize(SerializerT& s, UserObjType& x) { s | x.u_; } } /* end namespace serdes */ namespace serdes { namespace tests { namespace unit { /* * Unit test with `UserObjectD` with intrusive reconstruct for deserialization * purposes */ struct UserObjectD { explicit UserObjectD(int in_u) : u_(in_u) { } static UserObjectD& reconstruct(void* buf) { auto t = new (buf) UserObjectD(100); return *t; } void check() { EXPECT_EQ(u_, u_val); } template <typename SerializerT> void serialize(SerializerT& s) { s | u_; } int u_; }; /* * General test of serialization/deserialization for input object types */ TYPED_TEST_P(TestReconstruct, test_reconstruct_multi_type) { namespace ser = serialization::interface; using TestType = TypeParam; TestType in(u_val); in.check(); auto ret = ser::serialize<TestType>(in); auto out = ser::deserialize<TestType>(std::move(ret)); out->check(); } using ConstructTypes = ::testing::Types< UserObjectA, UserObjectB, UserObjectC, UserObjectD >; REGISTER_TYPED_TEST_CASE_P(TestReconstruct, test_reconstruct_multi_type); INSTANTIATE_TYPED_TEST_CASE_P(Test_reconstruct, TestReconstruct, ConstructTypes); }}} // end namespace serdes::tests::unit
26.217949
81
0.704645
PhilMiller
8daac0cc288d290bcc9ddf7aac1a4b8862db03a9
1,403
cpp
C++
source/framework/benchmark/src/dummy_benchmark.cpp
OliverSchmitz/lue
da097e8c1de30724bfe7667cc04344b6535b40cd
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/benchmark/src/dummy_benchmark.cpp
OliverSchmitz/lue
da097e8c1de30724bfe7667cc04344b6535b40cd
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/benchmark/src/dummy_benchmark.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#include "lue/framework/benchmark/benchmark.hpp" #include "lue/framework/benchmark/main.hpp" #include <iostream> #include <random> #include <thread> static void dummy( lue::benchmark::Environment const& environment, lue::benchmark::Task const& task) { using namespace std::chrono_literals; auto const nr_workers{environment.nr_workers()}; auto const work_size = task.nr_elements(); std::random_device device; std::default_random_engine engine(device()); std::uniform_real_distribution<double> distribution(0.0, 2000.0); auto const noise = distribution(engine); auto const parallelization_overhead = nr_workers * noise; // in ms → 10s auto const duration_per_work_item = 10000.0 + parallelization_overhead; auto const duration_of_work_size = work_size * duration_per_work_item; auto const duration_in_case_of_perfect_scaling = duration_of_work_size / nr_workers; std::chrono::duration<double, std::milli> duration{ duration_in_case_of_perfect_scaling}; std::this_thread::sleep_for(duration); } auto setup_benchmark( int /* argc */, char* /* argv */[], lue::benchmark::Environment const& environment, lue::benchmark::Task const& task) { auto callable = dummy; return lue::benchmark::Benchmark{ std::move(callable), environment, task}; } LUE_CONFIGURE_BENCHMARK()
26.980769
75
0.709195
OliverSchmitz
8dada646277b764f546a21946958702c52f79cb9
337
cpp
C++
1. Algoritmi elementari/Prelucrarea cifrelor unui numar/mediaAritmetica.cpp
RegusAl/School
87deb27f241aab1a93fd1cab0de2c7d8ee93df71
[ "MIT" ]
2
2021-04-20T21:22:37.000Z
2021-04-20T21:23:09.000Z
1. Algoritmi elementari/Prelucrarea cifrelor unui numar/mediaAritmetica.cpp
RegusAl/School
87deb27f241aab1a93fd1cab0de2c7d8ee93df71
[ "MIT" ]
null
null
null
1. Algoritmi elementari/Prelucrarea cifrelor unui numar/mediaAritmetica.cpp
RegusAl/School
87deb27f241aab1a93fd1cab0de2c7d8ee93df71
[ "MIT" ]
null
null
null
// media aritmetica a cifrelor nenule #include <iostream> using namespace std; int main() { int sum = 0, nrcif = 0, medie = 0; int n; cin>>n; while(n) { int uc = n%10; if(uc > 0) { sum += uc; nrcif++; } n = n/10; } medie = sum/nrcif; cout<<"Media aritmetica este "<<medie; return 0; }
13.48
40
0.525223
RegusAl
8dae4a9315bd5bcae393e27e7d9e4a008b502a12
2,474
cpp
C++
Engine/Src/Runtime/Run/Implementations/Windows/RunWindows.cpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Run/Implementations/Windows/RunWindows.cpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Run/Implementations/Windows/RunWindows.cpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS 1 #include <Windows.h> #include <windowsx.h> #include <ApplicationBase//Application.hpp> #include <Application/ApplicationFactory.hpp> #include <PlatformCore/PlatformCore.hpp> #include <Core/Log.hpp> #include <Core/Containers/UniquePointer.hpp> #include <Core/Timer.hpp> #include <Core/Math/Vector2.hpp> #include <PlatformCore/Window/Window.hpp> #include <iostream> #include <Application/WindowsContext.hpp> int WINAPI WinMain( _In_ HINSTANCE a_InstanceHandle, _In_opt_ HINSTANCE a_PreviousInstanceHandle, _In_ LPSTR a_CommandLine, _In_ int a_CommandShow) { // Instantiate the logger on the stack, then save a static pointer for the public getter function Fade::CCompositeLogger CompositeLogger; CompositeLogger.RegisterLogger(new Fade::CFileLogger("./Intermediate/Logs/Log.txt")); // Temporary creation of console window #ifdef FADE_DEBUG if (!AllocConsole()) { DWORD ErrorID = ::GetLastError(); if (ErrorID == 0) { MessageBox(NULL, TEXT("Unable to allocate console"), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION); } else { MessageBox(nullptr, Fade::PlatformCore::GetLastErrorMessage(), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION); } return 1; } freopen("conin$","r",stdin); freopen("conout$","w",stdout); freopen("conout$","w",stderr); CompositeLogger.RegisterLogger(new Fade::CStreamLogger(&std::cout)); FADE_LOG(Info, Run, "Console created."); #endif Fade::PlatformCore::Windows::g_InstanceHandle = a_InstanceHandle; bool g_ShouldQuit = false; // Create an application Fade::TUniquePtr<Fade::IApplication> g_Application = Fade::GetApplication(); FADE_LOG(Info, Run, "Application created."); if (g_Application->Initialize() != Fade::EInitializationResult::SUCCESS || g_Application->PostInitialize() != Fade::EInitializationResult::SUCCESS) { return 1; } const Fade::u32 DesiredFPS = 120; const float FrameTime = 1.0f / (float)DesiredFPS; float CurrentTime = FrameTime; MSG Message; Fade::CTimer TickTimer; TickTimer.Start(); while (!g_ShouldQuit) { if (CurrentTime >= FrameTime) { TickTimer.Reset(); g_ShouldQuit = g_Application->Tick(CurrentTime) != Fade::ETickResult::CONTINUE || g_Application->PostTick(CurrentTime) != Fade::ETickResult::CONTINUE; } while (PeekMessage(&Message, NULL, 0, 0, PM_REMOVE) > 0) { TranslateMessage(&Message); DispatchMessage(&Message); } CurrentTime = TickTimer.Elapsed<float>(); } return 0; }
26.319149
109
0.731205
Septus10
8daeb8b490e76bb7e5ae3363951261a4bcd50e36
26,662
cpp
C++
samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp
fynv/Vulkan-Samples
bdb733ca258686668078de9026e11ca21580d6a7
[ "Apache-2.0" ]
null
null
null
samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp
fynv/Vulkan-Samples
bdb733ca258686668078de9026e11ca21580d6a7
[ "Apache-2.0" ]
null
null
null
samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp
fynv/Vulkan-Samples
bdb733ca258686668078de9026e11ca21580d6a7
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2019, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * * 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. */ /* * Runtime mip map generation */ #include "texture_mipmap_generation.h" TextureMipMapGeneration::TextureMipMapGeneration() { zoom = -2.5f; rotation = {0.0f, 15.0f, 0.0f}; title = "Texture MipMap generation"; } TextureMipMapGeneration::~TextureMipMapGeneration() { if (device) { vkDestroyPipeline(get_device().get_handle(), pipeline, nullptr); vkDestroyPipelineLayout(get_device().get_handle(), pipeline_layout, nullptr); vkDestroyDescriptorSetLayout(get_device().get_handle(), descriptor_set_layout, nullptr); for (auto sampler : samplers) { vkDestroySampler(get_device().get_handle(), sampler, nullptr); } } destroy_texture(texture); uniform_buffer.reset(); } // Enable physical device features required for this example void TextureMipMapGeneration::get_device_features() { // Enable anisotropic filtering if supported if (supported_device_features.samplerAnisotropy) { requested_device_features.samplerAnisotropy = VK_TRUE; }; } /* Load the base texture containing only the first mip level and generate the whole mip-chain at runtime */ void TextureMipMapGeneration::load_texture_generate_mipmaps(std::string file_name) { VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; ktxTexture * ktx_texture; KTX_error_code result; result = ktxTexture_CreateFromNamedFile(file_name.c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktx_texture); // @todo: get format from libktx if (ktx_texture == nullptr) { throw std::runtime_error("Couldn't load texture"); } texture.width = ktx_texture->baseWidth; texture.height = ktx_texture->baseHeight; // Calculate number of mip levels as per Vulkan specs: // numLevels = 1 + floor(log2(max(w, h, d))) texture.mip_levels = static_cast<uint32_t>(floor(log2(std::max(texture.width, texture.height))) + 1); // Get device properites for the requested texture format // Check if the selected format supports blit source and destination, which is required for generating the mip levels // If this is not supported you could implement a fallback via compute shader image writes and stores VkFormatProperties formatProperties; vkGetPhysicalDeviceFormatProperties(get_device().get_physical_device(), format, &formatProperties); if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT) || !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT)) { throw std::runtime_error("Selected image format does not support blit source and destination"); } VkMemoryAllocateInfo memory_allocate_info = vkb::initializers::memory_allocate_info(); VkMemoryRequirements memory_requirements = {}; ktx_uint8_t *ktx_image_data = ktxTexture_GetData(ktx_texture); ktx_size_t ktx_texture_size = ktxTexture_GetSize(ktx_texture); // Create a host-visible staging buffer that contains the raw image data VkBuffer staging_buffer; VkDeviceMemory staging_memory; VkBufferCreateInfo buffer_create_info = vkb::initializers::buffer_create_info(); buffer_create_info.size = ktx_texture_size; // This buffer is used as a transfer source for the buffer copy buffer_create_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; buffer_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VK_CHECK(vkCreateBuffer(get_device().get_handle(), &buffer_create_info, nullptr, &staging_buffer)); // Get memory requirements for the staging buffer (alignment, memory type bits) vkGetBufferMemoryRequirements(get_device().get_handle(), staging_buffer, &memory_requirements); memory_allocate_info.allocationSize = memory_requirements.size; // Get memory type index for a host visible buffer memory_allocate_info.memoryTypeIndex = get_device().get_memory_type(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VK_CHECK(vkAllocateMemory(get_device().get_handle(), &memory_allocate_info, nullptr, &staging_memory)); VK_CHECK(vkBindBufferMemory(get_device().get_handle(), staging_buffer, staging_memory, 0)); // Copy ktx image data into host local staging buffer uint8_t *data; VK_CHECK(vkMapMemory(get_device().get_handle(), staging_memory, 0, memory_requirements.size, 0, (void **) &data)); memcpy(data, ktx_image_data, ktx_texture_size); vkUnmapMemory(get_device().get_handle(), staging_memory); // Create optimal tiled target image on the device VkImageCreateInfo image_create_info = vkb::initializers::image_create_info(); image_create_info.imageType = VK_IMAGE_TYPE_2D; image_create_info.format = format; image_create_info.mipLevels = texture.mip_levels; image_create_info.arrayLayers = 1; image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_create_info.extent = {texture.width, texture.height, 1}; image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; VK_CHECK(vkCreateImage(get_device().get_handle(), &image_create_info, nullptr, &texture.image)); vkGetImageMemoryRequirements(get_device().get_handle(), texture.image, &memory_requirements); memory_allocate_info.allocationSize = memory_requirements.size; memory_allocate_info.memoryTypeIndex = get_device().get_memory_type(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK(vkAllocateMemory(get_device().get_handle(), &memory_allocate_info, nullptr, &texture.device_memory)); VK_CHECK(vkBindImageMemory(get_device().get_handle(), texture.image, texture.device_memory, 0)); VkCommandBuffer copy_command = device->create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); // Optimal image will be used as destination for the copy, so we must transfer from our initial undefined image layout to the transfer destination layout vkb::insert_image_memory_barrier( copy_command, texture.image, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); // Copy the first mip of the chain, remaining mips will be generated VkBufferImageCopy buffer_copy_region = {}; buffer_copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; buffer_copy_region.imageSubresource.mipLevel = 0; buffer_copy_region.imageSubresource.baseArrayLayer = 0; buffer_copy_region.imageSubresource.layerCount = 1; buffer_copy_region.imageExtent.width = texture.width; buffer_copy_region.imageExtent.height = texture.height; buffer_copy_region.imageExtent.depth = 1; vkCmdCopyBufferToImage(copy_command, staging_buffer, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); // Transition first mip level to transfer source so we can blit(read) from it vkb::insert_image_memory_barrier( copy_command, texture.image, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); device->flush_command_buffer(copy_command, queue, true); // Clean up staging resources vkFreeMemory(device->get_handle(), staging_memory, nullptr); vkDestroyBuffer(device->get_handle(), staging_buffer, nullptr); // Generate the mip chain // --------------------------------------------------------------- // We copy down the whole mip chain doing a blit from mip-1 to mip // An alternative way would be to always blit from the first mip level and sample that one down VkCommandBuffer blit_command = device->create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); // Copy down mips from n-1 to n for (uint32_t i = 1; i < texture.mip_levels; i++) { VkImageBlit image_blit{}; // Source image_blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; image_blit.srcSubresource.layerCount = 1; image_blit.srcSubresource.mipLevel = i - 1; image_blit.srcOffsets[1].x = int32_t(texture.width >> (i - 1)); image_blit.srcOffsets[1].y = int32_t(texture.height >> (i - 1)); image_blit.srcOffsets[1].z = 1; // Destination image_blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; image_blit.dstSubresource.layerCount = 1; image_blit.dstSubresource.mipLevel = i; image_blit.dstOffsets[1].x = int32_t(texture.width >> i); image_blit.dstOffsets[1].y = int32_t(texture.height >> i); image_blit.dstOffsets[1].z = 1; // Prepare current mip level as image blit destination vkb::insert_image_memory_barrier( blit_command, texture.image, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, i, 1, 0, 1}); // Blit from previous level vkCmdBlitImage( blit_command, texture.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_blit, VK_FILTER_LINEAR); // Prepare current mip level as image blit source for next level vkb::insert_image_memory_barrier( blit_command, texture.image, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, i, 1, 0, 1}); } // After the loop, all mip layers are in TRANSFER_SRC layout, so transition all to SHADER_READ vkb::insert_image_memory_barrier( blit_command, texture.image, VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, 0, texture.mip_levels, 0, 1}); device->flush_command_buffer(blit_command, queue, true); // --------------------------------------------------------------- // Create samplers for different mip map demonstration cases samplers.resize(3); VkSamplerCreateInfo sampler = vkb::initializers::sampler_create_info(); sampler.magFilter = VK_FILTER_LINEAR; sampler.minFilter = VK_FILTER_LINEAR; sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler.mipLodBias = 0.0f; sampler.compareOp = VK_COMPARE_OP_NEVER; sampler.minLod = 0.0f; sampler.maxLod = 0.0f; sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; sampler.maxAnisotropy = 1.0; sampler.anisotropyEnable = VK_FALSE; // Without mip mapping VK_CHECK(vkCreateSampler(device->get_handle(), &sampler, nullptr, &samplers[0])); // With mip mapping sampler.maxLod = static_cast<float>(texture.mip_levels); VK_CHECK(vkCreateSampler(device->get_handle(), &sampler, nullptr, &samplers[1])); // With mip mapping and anisotropic filtering (when supported) if (device->get_features().samplerAnisotropy) { sampler.maxAnisotropy = device->get_properties().limits.maxSamplerAnisotropy; sampler.anisotropyEnable = VK_TRUE; } VK_CHECK(vkCreateSampler(device->get_handle(), &sampler, nullptr, &samplers[2])); // Create image view VkImageViewCreateInfo view = vkb::initializers::image_view_create_info(); view.image = texture.image; view.viewType = VK_IMAGE_VIEW_TYPE_2D; view.format = format; view.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A}; view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view.subresourceRange.baseMipLevel = 0; view.subresourceRange.baseArrayLayer = 0; view.subresourceRange.layerCount = 1; view.subresourceRange.levelCount = texture.mip_levels; VK_CHECK(vkCreateImageView(device->get_handle(), &view, nullptr, &texture.view)); } // Free all Vulkan resources used by a texture object void TextureMipMapGeneration::destroy_texture(Texture texture) { vkDestroyImageView(get_device().get_handle(), texture.view, nullptr); vkDestroyImage(get_device().get_handle(), texture.image, nullptr); vkFreeMemory(get_device().get_handle(), texture.device_memory, nullptr); } void TextureMipMapGeneration::load_assets() { load_texture_generate_mipmaps(vkb::fs::path::get(vkb::fs::path::Assets, "textures/checkerboard_rgba.ktx")); scene = load_model("scenes/tunnel_cylinder.gltf"); } void TextureMipMapGeneration::build_command_buffers() { VkCommandBufferBeginInfo command_buffer_begin_info = vkb::initializers::command_buffer_begin_info(); VkClearValue clear_values[2]; clear_values[0].color = default_clear_color; clear_values[1].depthStencil = {1.0f, 0}; VkRenderPassBeginInfo render_pass_begin_info = vkb::initializers::render_pass_begin_info(); render_pass_begin_info.renderPass = render_pass; render_pass_begin_info.renderArea.offset.x = 0; render_pass_begin_info.renderArea.offset.y = 0; render_pass_begin_info.renderArea.extent.width = width; render_pass_begin_info.renderArea.extent.height = height; render_pass_begin_info.clearValueCount = 2; render_pass_begin_info.pClearValues = clear_values; for (int32_t i = 0; i < draw_cmd_buffers.size(); ++i) { render_pass_begin_info.framebuffer = framebuffers[i]; VK_CHECK(vkBeginCommandBuffer(draw_cmd_buffers[i], &command_buffer_begin_info)); vkCmdBeginRenderPass(draw_cmd_buffers[i], &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = vkb::initializers::viewport((float) width, (float) height, 0.0f, 1.0f); vkCmdSetViewport(draw_cmd_buffers[i], 0, 1, &viewport); VkRect2D scissor = vkb::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, NULL); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); draw_model(scene, draw_cmd_buffers[i]); draw_ui(draw_cmd_buffers[i]); vkCmdEndRenderPass(draw_cmd_buffers[i]); VK_CHECK(vkEndCommandBuffer(draw_cmd_buffers[i])); } } void TextureMipMapGeneration::draw() { ApiVulkanSample::prepare_frame(); // Command buffer to be sumitted to the queue submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &draw_cmd_buffers[current_buffer]; // Submit to queue VK_CHECK(vkQueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE)); ApiVulkanSample::submit_frame(); } void TextureMipMapGeneration::setup_descriptor_pool() { // Example uses one ubo and one image sampler std::vector<VkDescriptorPoolSize> pool_sizes = { vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1), vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLER, 3), }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info( static_cast<uint32_t>(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void TextureMipMapGeneration::setup_descriptor_set_layout() { std::vector<VkDescriptorSetLayoutBinding> set_layout_bindings = { // Binding 0 : Parameter uniform buffer vkb::initializers::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), // Binding 1 : Fragment shader image sampler vkb::initializers::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_SHADER_STAGE_FRAGMENT_BIT, 1), // Binding 2 : Sampler array (3 descriptors) vkb::initializers::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2, 3), }; VkDescriptorSetLayoutCreateInfo descriptor_layout = vkb::initializers::descriptor_set_layout_create_info( set_layout_bindings.data(), static_cast<uint32_t>(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info( &descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void TextureMipMapGeneration::setup_descriptor_set() { VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info( descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*uniform_buffer); VkDescriptorImageInfo image_descriptor; image_descriptor.imageView = texture.view; image_descriptor.sampler = VK_NULL_HANDLE; image_descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; std::vector<VkWriteDescriptorSet> write_descriptor_sets = { // Binding 0 : Vertex shader uniform buffer vkb::initializers::write_descriptor_set( descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), // Binding 1 : Fragment shader texture sampler vkb::initializers::write_descriptor_set( descriptor_set, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, &image_descriptor)}; // Binding 2: Sampler array std::vector<VkDescriptorImageInfo> sampler_descriptors; for (auto i = 0; i < samplers.size(); i++) { sampler_descriptors.push_back({samplers[i], VK_NULL_HANDLE, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}); } VkWriteDescriptorSet write_descriptor_set{}; write_descriptor_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write_descriptor_set.dstSet = descriptor_set; write_descriptor_set.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; write_descriptor_set.descriptorCount = static_cast<uint32_t>(sampler_descriptors.size()); write_descriptor_set.pImageInfo = sampler_descriptors.data(); write_descriptor_set.dstBinding = 2; write_descriptor_set.dstArrayElement = 0; write_descriptor_sets.push_back(write_descriptor_set); vkUpdateDescriptorSets(get_device().get_handle(), static_cast<uint32_t>(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); } void TextureMipMapGeneration::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info( 1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamic_state_enables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info( dynamic_state_enables.data(), static_cast<uint32_t>(dynamic_state_enables.size()), 0); // Load shaders std::array<VkPipelineShaderStageCreateInfo, 2> shader_stages; shader_stages[0] = load_shader("texture_mipmap_generation/texture.vert", VK_SHADER_STAGE_VERTEX_BIT); shader_stages[1] = load_shader("texture_mipmap_generation/texture.frag", VK_SHADER_STAGE_FRAGMENT_BIT); // Vertex bindings and attributes const std::vector<VkVertexInputBindingDescription> vertex_input_bindings = { vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX), }; const std::vector<VkVertexInputAttributeDescription> vertex_input_attributes = { vkb::initializers::vertex_input_attribute_description(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 0: Position vkb::initializers::vertex_input_attribute_description(0, 1, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 6), // Location 1: UV vkb::initializers::vertex_input_attribute_description(0, 2, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 8), // Location 2: Color }; VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); vertex_input_state.vertexBindingDescriptionCount = static_cast<uint32_t>(vertex_input_bindings.size()); vertex_input_state.pVertexBindingDescriptions = vertex_input_bindings.data(); vertex_input_state.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertex_input_attributes.size()); vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; pipeline_create_info.pRasterizationState = &rasterization_state; pipeline_create_info.pColorBlendState = &color_blend_state; pipeline_create_info.pMultisampleState = &multisample_state; pipeline_create_info.pViewportState = &viewport_state; pipeline_create_info.pDepthStencilState = &depth_stencil_state; pipeline_create_info.pDynamicState = &dynamic_state; pipeline_create_info.stageCount = static_cast<uint32_t>(shader_stages.size()); pipeline_create_info.pStages = shader_stages.data(); VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, nullptr, &pipeline)); } void TextureMipMapGeneration::prepare_uniform_buffers() { // Shared parameter uniform buffer block uniform_buffer = std::make_unique<vkb::core::Buffer>(get_device(), sizeof(ubo), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } void TextureMipMapGeneration::update_uniform_buffers(float delta_time) { ubo.projection = camera.matrices.perspective; ubo.model = camera.matrices.view; ubo.model = glm::rotate(ubo.model, glm::radians(90.0f + timer * 360.0f), glm::vec3(0.0f, 0.0f, 1.0f)); ubo.model = glm::scale(ubo.model, glm::vec3(0.5f)); timer += delta_time * 0.005f; if (timer > 1.0f) { timer -= 1.0f; } uniform_buffer->convert_and_update(ubo); } bool TextureMipMapGeneration::prepare(vkb::Platform &platform) { if (!ApiVulkanSample::prepare(platform)) { return false; } camera.type = vkb::CameraType::FirstPerson; camera.set_perspective(60.0f, (float) width / (float) height, 0.1f, 1024.0f); camera.set_translation(glm::vec3(0.0f, 0.0f, -12.5f)); load_assets(); prepare_uniform_buffers(); setup_descriptor_set_layout(); prepare_pipelines(); setup_descriptor_pool(); setup_descriptor_set(); build_command_buffers(); prepared = true; return true; } void TextureMipMapGeneration::render(float delta_time) { if (!prepared) return; draw(); if (rotate_scene) update_uniform_buffers(delta_time); } void TextureMipMapGeneration::view_changed() { update_uniform_buffers(); } void TextureMipMapGeneration::on_update_ui_overlay(vkb::Drawer &drawer) { if (drawer.header("Settings")) { drawer.checkbox("Rotate", &rotate_scene); if (drawer.slider_float("LOD bias", &ubo.lod_bias, 0.0f, (float) texture.mip_levels)) { update_uniform_buffers(); } if (drawer.combo_box("Sampler type", &ubo.sampler_index, sampler_names)) { update_uniform_buffers(); } } } std::unique_ptr<vkb::Application> create_texture_mipmap_generation() { return std::make_unique<TextureMipMapGeneration>(); }
40.830015
181
0.746231
fynv
8dafa14508f0b02ad248e15e43b72c3c6f628979
4,819
cpp
C++
Source/ShooterGame/Private/UI/Style/ShooterStyle.cpp
wangminzt/AI_FPS
f04c1d6202a92e362b86eaa60245f2e9f3c252d1
[ "MIT" ]
3
2020-07-19T22:44:25.000Z
2020-08-06T08:11:31.000Z
Source/ShooterGame/Private/UI/Style/ShooterStyle.cpp
wangminzt/AI_FPS
f04c1d6202a92e362b86eaa60245f2e9f3c252d1
[ "MIT" ]
null
null
null
Source/ShooterGame/Private/UI/Style/ShooterStyle.cpp
wangminzt/AI_FPS
f04c1d6202a92e362b86eaa60245f2e9f3c252d1
[ "MIT" ]
1
2021-04-15T05:56:04.000Z
2021-04-15T05:56:04.000Z
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "ShooterGame.h" #include "ShooterStyle.h" #include "SlateGameResources.h" TSharedPtr< FSlateStyleSet > FShooterStyle::ShooterStyleInstance = NULL; void FShooterStyle::Initialize() { if ( !ShooterStyleInstance.IsValid() ) { ShooterStyleInstance = Create(); FSlateStyleRegistry::RegisterSlateStyle( *ShooterStyleInstance ); } } void FShooterStyle::Shutdown() { FSlateStyleRegistry::UnRegisterSlateStyle( *ShooterStyleInstance ); ensure( ShooterStyleInstance.IsUnique() ); ShooterStyleInstance.Reset(); } FName FShooterStyle::GetStyleSetName() { static FName StyleSetName(TEXT("ShooterStyle")); return StyleSetName; } #define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".png"), __VA_ARGS__ ) #define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".png"), __VA_ARGS__ ) #define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".png"), __VA_ARGS__ ) #define TTF_FONT( RelativePath, ... ) FSlateFontInfo( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".ttf"), __VA_ARGS__ ) #define OTF_FONT( RelativePath, ... ) FSlateFontInfo( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".otf"), __VA_ARGS__ ) TSharedRef< FSlateStyleSet > FShooterStyle::Create() { TSharedRef<FSlateStyleSet> StyleRef = FSlateGameResources::New(FShooterStyle::GetStyleSetName(), "/Game/UI/Styles", "/Game/UI/Styles"); FSlateStyleSet& Style = StyleRef.Get(); // Load the speaker icon to be used for displaying when a user is talking Style.Set("ShooterGame.Speaker", new IMAGE_BRUSH("Images/SoundCue_SpeakerIcon", FVector2D(32, 32))); // The border image used to draw the replay timeline bar Style.Set("ShooterGame.ReplayTimelineBorder", new BOX_BRUSH("Images/ReplayTimeline", FMargin(3.0f / 8.0f))); // The border image used to draw the replay timeline bar Style.Set("ShooterGame.ReplayTimelineIndicator", new IMAGE_BRUSH("Images/ReplayTimelineIndicator", FVector2D(4.0f, 26.0f))); // The image used to draw the replay pause button Style.Set("ShooterGame.ReplayPauseIcon", new IMAGE_BRUSH("Images/ReplayPause", FVector2D(32.0f, 32.0f))); // Fonts still need to be specified in code for now Style.Set("ShooterGame.MenuServerListTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 14)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.ScoreboardListTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 14)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.MenuProfileNameStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 18)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.MenuTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 20)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.MenuHeaderTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 26)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.WelcomeScreen.WelcomeTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Medium", 32)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.DefaultScoreboard.Row.HeaderTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 24)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FVector2D(0,1)) ); Style.Set("ShooterGame.DefaultScoreboard.Row.StatTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Regular", 18)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FVector2D(0,1)) ); Style.Set("ShooterGame.SplitScreenLobby.StartMatchTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Regular", 16)) .SetColorAndOpacity(FLinearColor::Green) .SetShadowOffset(FVector2D(0,1)) ); Style.Set("ShooterGame.DemoListCheckboxTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 12)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); return StyleRef; } #undef IMAGE_BRUSH #undef BOX_BRUSH #undef BORDER_BRUSH #undef TTF_FONT #undef OTF_FONT void FShooterStyle::ReloadTextures() { FSlateApplication::Get().GetRenderer()->ReloadTextureResources(); } const ISlateStyle& FShooterStyle::Get() { return *ShooterStyleInstance; }
36.233083
140
0.736252
wangminzt
8db2b9ef1e6f924bd79aef48af618ffcb3626b49
49,803
cc
C++
GeneratorInterface/Hydjet2Interface/src/Hydjet2Hadronizer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
GeneratorInterface/Hydjet2Interface/src/Hydjet2Hadronizer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
GeneratorInterface/Hydjet2Interface/src/Hydjet2Hadronizer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
/* ########################## # Hydjet2 # # version: 2.2.0 patch1 # ########################## Interface to the HYDJET++ generator, produces HepMC events Author: Andrey Belyaev (Andrey.Belyaev@cern.ch) Hydjet2Hadronizer is the modified InitialStateHydjet HYDJET++ version 2.2: InitialStateHydjet is the modified InitialStateBjorken The high-pt part related with PYTHIA-PYQUEN is included InitialStateBjorken (FASTMC) was used. InitialStateBjorken version 2.0: Ludmila Malinina malinina@lav01.sinp.msu.ru, SINP MSU/Moscow and JINR/Dubna Ionut Arsene i.c.arsene@fys.uio.no, Oslo University June 2007 version 1.0: Nikolai Amelin, Ludmila Malinina, Timur Pocheptsov (C) JINR/Dubna amelin@sunhe.jinr.ru, malinina@sunhe.jinr.ru, pocheptsov@sunhe.jinr.ru November. 2, 2005 */ //expanding localy equilibated fireball with volume hadron radiation //thermal part: Blast wave model, Bjorken-like parametrization //high-pt: PYTHIA + jet quenching model PYQUEN #include <TLorentzVector.h> #include <TVector3.h> #include <TMath.h> #include "GeneratorInterface/Core/interface/FortranInstance.h" #include "GeneratorInterface/Hydjet2Interface/interface/Hydjet2Hadronizer.h" #include "GeneratorInterface/Hydjet2Interface/interface/RandArrayFunction.h" #include "GeneratorInterface/Hydjet2Interface/interface/HadronDecayer.h" #include "GeneratorInterface/Hydjet2Interface/interface/GrandCanonical.h" #include "GeneratorInterface/Hydjet2Interface/interface/StrangePotential.h" #include "GeneratorInterface/Hydjet2Interface/interface/EquationSolver.h" #include "GeneratorInterface/Hydjet2Interface/interface/Particle.h" #include "GeneratorInterface/Hydjet2Interface/interface/ParticlePDG.h" #include "GeneratorInterface/Hydjet2Interface/interface/UKUtility.h" #include <iostream> #include <fstream> #include <cmath> #include "boost/lexical_cast.hpp" #include "FWCore/Concurrency/interface/SharedResourceNames.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/EDMException.h" #include "GeneratorInterface/Pythia6Interface/interface/Pythia6Declarations.h" #include "GeneratorInterface/Pythia6Interface/interface/Pythia6Service.h" #include "HepMC/PythiaWrapper6_4.h" #include "HepMC/GenEvent.h" #include "HepMC/HeavyIon.h" #include "HepMC/SimpleVector.h" #include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h" #include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h" #include "SimDataFormats/GeneratorProducts/interface/GenRunInfoProduct.h" #include "SimDataFormats/HiGenData/interface/GenHIEvent.h" #include "GeneratorInterface/Hydjet2Interface/interface/HYJET_COMMONS.h" extern "C" void hyevnt_(); extern "C" void myini_(); extern HYIPARCommon HYIPAR; extern HYFPARCommon HYFPAR; extern HYJPARCommon HYJPAR; extern HYPARTCommon HYPART; using namespace edm; using namespace std; using namespace gen; TString RunInputHYDJETstr; // definition of the static member fLastIndex int Particle::fLastIndex; bool ev=false; namespace { int convertStatusForComponents(int sta, int typ){ if(sta== 1 && typ==0) return 6; if(sta== 1 && typ==1) return 7; if(sta== 2 && typ==0) return 16; if(sta== 2 && typ==1) return 17; else return sta; } int convertStatus(int st){ if(st<= 0) return 0; if(st<=10) return 1; if(st<=20) return 2; if(st<=30) return 3; else return st; } } const std::vector<std::string> Hydjet2Hadronizer::theSharedResources = { edm::SharedResourceNames::kPythia6, gen::FortranInstance::kFortranInstance }; //____________________________________________________________________________________________ Hydjet2Hadronizer::Hydjet2Hadronizer(const edm::ParameterSet& pset): BaseHadronizer(pset), fSqrtS(pset.getParameter<double>("fSqrtS")), // C.m.s. energy per nucleon pair fAw(pset.getParameter<double>("fAw")), // Atomic weigth of nuclei, fAw fIfb(pset.getParameter<int>("fIfb")), // Flag of type of centrality generation, fBfix (=0 is fixed by fBfix, >0 distributed [fBfmin, fBmax]) fBmin(pset.getParameter<double>("fBmin")), // Minimum impact parameter in units of nuclear radius, fBmin fBmax(pset.getParameter<double>("fBmax")), // Maximum impact parameter in units of nuclear radius, fBmax fBfix(pset.getParameter<double>("fBfix")), // Fixed impact parameter in units of nuclear radius, fBfix fT(pset.getParameter<double>("fT")), // Temperature at chemical freeze-out, fT [GeV] fMuB(pset.getParameter<double>("fMuB")), // Chemical baryon potential per unit charge, fMuB [GeV] fMuS(pset.getParameter<double>("fMuS")), // Chemical strangeness potential per unit charge, fMuS [GeV] fMuC(pset.getParameter<double>("fMuC")), // Chemical charm potential per unit charge, fMuC [GeV] (used if charm production is turned on) fMuI3(pset.getParameter<double>("fMuI3")), // Chemical isospin potential per unit charge, fMuI3 [GeV] fThFO(pset.getParameter<double>("fThFO")), // Temperature at thermal freeze-out, fThFO [GeV] fMu_th_pip(pset.getParameter<double>("fMu_th_pip")),// Chemical potential of pi+ at thermal freeze-out, fMu_th_pip [GeV] fTau(pset.getParameter<double>("fTau")), // Proper time proper at thermal freeze-out for central collisions, fTau [fm/c] fSigmaTau(pset.getParameter<double>("fSigmaTau")), // Duration of emission at thermal freeze-out for central collisions, fSigmaTau [fm/c] fR(pset.getParameter<double>("fR")), // Maximal transverse radius at thermal freeze-out for central collisions, fR [fm] fYlmax(pset.getParameter<double>("fYlmax")), // Maximal longitudinal flow rapidity at thermal freeze-out, fYlmax fUmax(pset.getParameter<double>("fUmax")), // Maximal transverse flow rapidity at thermal freeze-out for central collisions, fUmax fDelta(pset.getParameter<double>("fDelta")), // Momentum azimuthal anizotropy parameter at thermal freeze-out, fDelta fEpsilon(pset.getParameter<double>("fEpsilon")), // Spatial azimuthal anisotropy parameter at thermal freeze-out, fEpsilon fIfDeltaEpsilon(pset.getParameter<double>("fIfDeltaEpsilon")), // Flag to specify fDelta and fEpsilon values, fIfDeltaEpsilon (=0 user's ones, >=1 calculated) fDecay(pset.getParameter<int>("fDecay")), // Flag to switch on/off hadron decays, fDecay (=0 decays off, >=1 decays on) fWeakDecay(pset.getParameter<double>("fWeakDecay")),// Low decay width threshold fWeakDecay[GeV]: width<fWeakDecay decay off, width>=fDecayWidth decay on; can be used to switch off weak decays fEtaType(pset.getParameter<double>("fEtaType")), // Flag to choose longitudinal flow rapidity distribution, fEtaType (=0 uniform, >0 Gaussian with the dispersion Ylmax) fTMuType(pset.getParameter<double>("fTMuType")), // Flag to use calculated T_ch, mu_B and mu_S as a function of fSqrtS, fTMuType (=0 user's ones, >0 calculated) fCorrS(pset.getParameter<double>("fCorrS")), // Strangeness supression factor gamma_s with fCorrS value (0<fCorrS <=1, if fCorrS <= 0 then it is calculated) fCharmProd(pset.getParameter<int>("fCharmProd")), // Flag to include thermal charm production, fCharmProd (=0 no charm production, >=1 charm production) fCorrC(pset.getParameter<double>("fCorrC")), // Charmness enhancement factor gamma_c with fCorrC value (fCorrC >0, if fCorrC<0 then it is calculated) fNhsel(pset.getParameter<int>("fNhsel")), //Flag to include jet (J)/jet quenching (JQ) and hydro (H) state production, fNhsel (0 H on & J off, 1 H/J on & JQ off, 2 H/J/HQ on, 3 J on & H/JQ off, 4 H off & J/JQ on) fPyhist(pset.getParameter<int>("fPyhist")), // Flag to suppress the output of particle history from PYTHIA, fPyhist (=1 only final state particles; =0 full particle history from PYTHIA) fIshad(pset.getParameter<int>("fIshad")), // Flag to switch on/off nuclear shadowing, fIshad (0 shadowing off, 1 shadowing on) fPtmin(pset.getParameter<double>("fPtmin")), // Minimal pt of parton-parton scattering in PYTHIA event, fPtmin [GeV/c] fT0(pset.getParameter<double>("fT0")), // Initial QGP temperature for central Pb+Pb collisions in mid-rapidity, fT0 [GeV] fTau0(pset.getParameter<double>("fTau0")), // Proper QGP formation time in fm/c, fTau0 (0.01<fTau0<10) fNf(pset.getParameter<int>("fNf")), // Number of active quark flavours in QGP, fNf (0, 1, 2 or 3) fIenglu(pset.getParameter<int>("fIenglu")), // Flag to fix type of partonic energy loss, fIenglu (0 radiative and collisional loss, 1 radiative loss only, 2 collisional loss only) fIanglu(pset.getParameter<int>("fIanglu")), // Flag to fix type of angular distribution of in-medium emitted gluons, fIanglu (0 small-angular, 1 wide-angular, 2 collinear). embedding_(pset.getParameter<bool>("embeddingMode")), rotate_(pset.getParameter<bool>("rotateEventPlane")), evt(nullptr), nsub_(0), nhard_(0), nsoft_(0), phi0_(0.), sinphi0_(0.), cosphi0_(1.), pythia6Service_(new Pythia6Service(pset)) { // constructor // PYLIST Verbosity Level // Valid PYLIST arguments are: 1, 2, 3, 5, 7, 11, 12, 13 pythiaPylistVerbosity_ = pset.getUntrackedParameter<int>("pythiaPylistVerbosity",0); LogDebug("PYLISTverbosity") << "Pythia PYLIST verbosity level = " << pythiaPylistVerbosity_; //Max number of events printed on verbosity level maxEventsToPrint_ = pset.getUntrackedParameter<int>("maxEventsToPrint",0); LogDebug("Events2Print") << "Number of events to be printed = " << maxEventsToPrint_; if(embedding_) src_ = pset.getParameter<edm::InputTag>("backgroundLabel"); } //__________________________________________________________________________________________ Hydjet2Hadronizer::~Hydjet2Hadronizer(){ // destructor call_pystat(1); delete pythia6Service_; } //_____________________________________________________________________ void Hydjet2Hadronizer::doSetRandomEngine(CLHEP::HepRandomEngine* v) { pythia6Service_->setRandomEngine(v); hjRandomEngine = v; } //______________________________________________________________________________________________________ bool Hydjet2Hadronizer::readSettings( int ) { Pythia6Service::InstanceWrapper guard(pythia6Service_); pythia6Service_->setGeneralParams(); SERVICE.iseed_fromC=hjRandomEngine->CLHEP::HepRandomEngine::getSeed(); LogInfo("Hydjet2Hadronizer|GenSeed") << "Seed for random number generation: "<<hjRandomEngine->CLHEP::HepRandomEngine::getSeed(); fNPartTypes = 0; //counter of hadron species return kTRUE; } //______________________________________________________________________________________________________ bool Hydjet2Hadronizer::initializeForInternalPartons(){ Pythia6Service::InstanceWrapper guard(pythia6Service_); // the input impact parameter (bxx_) is in [fm]; transform in [fm/RA] for hydjet usage const float ra = nuclear_radius(); LogInfo("Hydjet2Hadronizer|RAScaling")<<"Nuclear radius(RA) = "<<ra; fBmin /= ra; fBmax /= ra; fBfix /= ra; //check and redefine input parameters if(fTMuType>0 && fSqrtS > 2.24) { if(fSqrtS < 2.24){ LogError("Hydjet2Hadronizer|sqrtS") << "SqrtS<2.24 not allowed with fTMuType>0"; return false; } //sqrt(s) = 2.24 ==> T_kin = 0.8 GeV //see J. Cleymans, H. Oeschler, K. Redlich,S. Wheaton, Phys Rev. C73 034905 (2006) fMuB = 1.308/(1. + fSqrtS*0.273); fT = 0.166 - 0.139*fMuB*fMuB - 0.053*fMuB*fMuB*fMuB*fMuB; fMuI3 = 0.; fMuS = 0.; //create strange potential object and set strangeness density 0 NAStrangePotential* psp = new NAStrangePotential(0., fDatabase); psp->SetBaryonPotential(fMuB); psp->SetTemperature(fT); //compute strangeness potential if(fMuB > 0.01) fMuS = psp->CalculateStrangePotential(); LogInfo("Hydjet2Hadronizer|Strange") << "fMuS = " << fMuS; //if user choose fYlmax larger then allowed by kinematics at the specified beam energy sqrt(s) if(fYlmax > TMath::Log(fSqrtS/0.94)){ LogError("Hydjet2Hadronizer|Ylmax") << "fYlmax more then TMath::Log(fSqrtS vs 0.94)!!! "; return false; } if(fCorrS <= 0.) { //see F. Becattini, J. Mannien, M. Gazdzicki, Phys Rev. C73 044905 (2006) fCorrS = 1. - 0.386* TMath::Exp(-1.23*fT/fMuB); LogInfo("Hydjet2Hadronizer|Strange") << "The phenomenological f-la F. Becattini et al. PRC73 044905 (2006) for CorrS was used."<<endl <<"Strangeness suppression parameter = "<<fCorrS; } LogInfo("Hydjet2Hadronizer|Strange") << "The phenomenological f-la J. Cleymans et al. PRC73 034905 (2006) for Tch mu_B was used." << endl <<"The simulation will be done with the calculated parameters:" << endl <<"Baryon chemical potential = "<<fMuB<< " [GeV]" << endl <<"Strangeness chemical potential = "<<fMuS<< " [GeV]" << endl <<"Isospin chemical potential = "<<fMuI3<< " [GeV]" << endl <<"Strangeness suppression parameter = "<<fCorrS << endl <<"Eta_max = "<<fYlmax; } LogInfo("Hydjet2Hadronizer|Param") << "Used eta_max = "<<fYlmax<< endl <<"maximal allowed eta_max TMath::Log(fSqrtS/0.94)= "<<TMath::Log(fSqrtS/0.94); //initialisation of high-pt part HYJPAR.nhsel = fNhsel; HYJPAR.ptmin = fPtmin; HYJPAR.ishad = fIshad; HYJPAR.iPyhist = fPyhist; HYIPAR.bminh = fBmin; HYIPAR.bmaxh = fBmax; HYIPAR.AW = fAw; HYPYIN.ifb = fIfb; HYPYIN.bfix = fBfix; HYPYIN.ene = fSqrtS; PYQPAR.T0 = fT0; PYQPAR.tau0 = fTau0; PYQPAR.nf = fNf; PYQPAR.ienglu = fIenglu; PYQPAR.ianglu = fIanglu; myini_(); // calculation of multiplicities of different particle species // according to the grand canonical approach GrandCanonical gc(15, fT, fMuB, fMuS, fMuI3, fMuC); GrandCanonical gc_ch(15, fT, fMuB, fMuS, fMuI3, fMuC); GrandCanonical gc_pi_th(15, fThFO, 0., 0., fMu_th_pip, fMuC); GrandCanonical gc_th_0(15, fThFO, 0., 0., 0., 0.); // std::ofstream outMult("densities.txt"); // outMult<<"encoding particle density chemical potential "<<std::endl; double Nocth=0; //open charm double NJPsith=0; //JPsi //effective volume for central double dYl= 2 * fYlmax; //uniform distr. [-Ylmax; Ylmax] if (fEtaType >0) dYl = TMath::Sqrt(2 * TMath::Pi()) * fYlmax ; //Gaussian distr. fVolEff = 2 * TMath::Pi() * fTau * dYl * (fR * fR)/TMath::Power((fUmax),2) * ((fUmax)*TMath::SinH((fUmax))-TMath::CosH((fUmax))+ 1); LogInfo("Hydjet2Hadronizer|Param") << "central Effective volume = " << fVolEff << " [fm^3]"; double particleDensity_pi_ch=0; double particleDensity_pi_th=0; // double particleDensity_th_0=0; if(fThFO != fT && fThFO > 0){ GrandCanonical gc_ch(15, fT, fMuB, fMuS, fMuI3, fMuC); GrandCanonical gc_pi_th(15, fThFO, 0., 0., fMu_th_pip, fMuC); GrandCanonical gc_th_0(15, fThFO, 0., 0., 0., 0.); particleDensity_pi_ch = gc_ch.ParticleNumberDensity(fDatabase->GetPDGParticle(211)); particleDensity_pi_th = gc_pi_th.ParticleNumberDensity(fDatabase->GetPDGParticle(211)); } for(int particleIndex = 0; particleIndex < fDatabase->GetNParticles(); particleIndex++) { ParticlePDG *currParticle = fDatabase->GetPDGParticleByIndex(particleIndex); int encoding = currParticle->GetPDG(); //strangeness supression double gammaS = 1; int S = int(currParticle->GetStrangeness()); if(encoding == 333)S = 2; if(fCorrS < 1. && S != 0)gammaS = TMath::Power(fCorrS,-TMath::Abs(S)); //average densities double particleDensity = gc.ParticleNumberDensity(currParticle)/gammaS; //compute chemical potential for single f.o. mu==mu_ch double mu = fMuB * int(currParticle->GetBaryonNumber()) + fMuS * int(currParticle->GetStrangeness()) + fMuI3 * int(currParticle->GetElectricCharge()) + fMuC * int(currParticle->GetCharmness()); //thermal f.o. if(fThFO != fT && fThFO > 0){ double particleDensity_ch = gc_ch.ParticleNumberDensity(currParticle); double particleDensity_th_0 = gc_th_0.ParticleNumberDensity(currParticle); double numb_dens_bolt = particleDensity_pi_th*particleDensity_ch/particleDensity_pi_ch; mu = fThFO*TMath::Log(numb_dens_bolt/particleDensity_th_0); if(abs(encoding)==211 || encoding==111)mu= fMu_th_pip; particleDensity = numb_dens_bolt; } // set particle densities to zero for some particle codes // pythia quark codes if(abs(encoding)<=9) { particleDensity=0; } // leptons if(abs(encoding)>10 && abs(encoding)<19) { particleDensity=0; } // exchange bosons if(abs(encoding)>20 && abs(encoding)<30) { particleDensity=0; } // pythia special codes (e.g. strings, clusters ...) if(abs(encoding)>80 && abs(encoding)<100) { particleDensity=0; } // pythia di-quark codes // Note: in PYTHIA all diquark codes have the tens digits equal to zero if(abs(encoding)>1000 && abs(encoding)<6000) { int tens = ((abs(encoding)-(abs(encoding)%10))/10)%10; if(tens==0) { // its a diquark; particleDensity=0; } } // K0S and K0L if(abs(encoding)==130 || abs(encoding)==310) { particleDensity=0; } // charmed particles if(encoding==443)NJPsith=particleDensity*fVolEff/dYl; // We generate thermo-statistically only J/psi(443), D_+(411), D_-(-411), D_0(421), //Dbar_0(-421), D1_+(413), D1_-(-413), D1_0(423), D1bar_0(-423) //Dcs(431) Lambdac(4122) if(currParticle->GetCharmQNumber()!=0 || currParticle->GetCharmAQNumber()!=0) { //ml if(abs(encoding)!=443 && //ml abs(encoding)!=411 && abs(encoding)!=421 && //ml abs(encoding)!=413 && abs(encoding)!=423 && abs(encoding)!=4122 && abs(encoding)!=431) { //ml particleDensity=0; } if(abs(encoding)==441 || abs(encoding)==10441 || abs(encoding)==10443 || abs(encoding)==20443 || abs(encoding)==445 || abs(encoding)==4232 || abs(encoding)==4322 || abs(encoding)==4132 || abs(encoding)==4312 || abs(encoding)==4324 || abs(encoding)==4314 || abs(encoding)==4332 || abs(encoding)==4334 ) { particleDensity=0; } else { if(abs(encoding)!=443){ //only open charm Nocth=Nocth+particleDensity*fVolEff/dYl; LogInfo("Hydjet2Hadronizer|Charam") << encoding<<" Nochth "<<Nocth; // particleDensity=particleDensity*fCorrC; // if(abs(encoding)==443)particleDensity=particleDensity*fCorrC; } } } // bottom mesons if((abs(encoding)>500 && abs(encoding)<600) || (abs(encoding)>10500 && abs(encoding)<10600) || (abs(encoding)>20500 && abs(encoding)<20600) || (abs(encoding)>100500 && abs(encoding)<100600)) { particleDensity=0; } // bottom baryons if(abs(encoding)>5000 && abs(encoding)<6000) { particleDensity=0; } //////////////////////////////////////////////////////////////////////////////////////// if(particleDensity > 0.) { fPartEnc[fNPartTypes] = encoding; fPartMult[2 * fNPartTypes] = particleDensity; fPartMu[2 * fNPartTypes] = mu; ++fNPartTypes; if(fNPartTypes > 1000) LogError("Hydjet2Hadronizer") << "fNPartTypes is too large" << fNPartTypes; //outMult<<encoding<<" "<<particleDensity*fVolEff/dYl <<" "<<mu<<std::endl; } } //put open charm number and cc number in Params fNocth = Nocth; fNccth = NJPsith; return kTRUE; } //__________________________________________________________________________________________ bool Hydjet2Hadronizer::generatePartonsAndHadronize(){ Pythia6Service::InstanceWrapper guard(pythia6Service_); // Initialize the static "last index variable" Particle::InitIndexing(); //----- high-pt part------------------------------ TLorentzVector partJMom, partJPos, zeroVec; // generate single event if(embedding_){ fIfb = 0; const edm::Event& e = getEDMEvent(); Handle<HepMCProduct> input; e.getByLabel(src_,input); const HepMC::GenEvent * inev = input->GetEvent(); const HepMC::HeavyIon* hi = inev->heavy_ion(); if(hi){ fBfix = hi->impact_parameter(); phi0_ = hi->event_plane_angle(); sinphi0_ = sin(phi0_); cosphi0_ = cos(phi0_); }else{ LogWarning("EventEmbedding")<<"Background event does not have heavy ion record!"; } }else if(rotate_) rotateEvtPlane(); nsoft_ = 0; nhard_ = 0; /* edm::LogInfo("HYDJET2mode") << "##### HYDJET2 fNhsel = " << fNhsel; edm::LogInfo("HYDJET2fpart") << "##### HYDJET2 fpart = " << hyflow.fpart;?? edm::LogInfo("HYDJET2tf") << "##### HYDJET2 hadron freez-out temp, Tf = " << hyflow.Tf;?? edm::LogInfo("HYDJET2tf") << "##### HYDJET2 hadron freez-out temp, Tf = " << hyflow.Tf;?? edm::LogInfo("HYDJET2inTemp") << "##### HYDJET2: QGP init temperature, fT0 ="<<fT0; edm::LogInfo("HYDJET2inTau") << "##### HYDJET2: QGP formation time, fTau0 ="<<fTau0; */ // generate a HYDJET event int ntry = 0; while(nsoft_ == 0 && nhard_ == 0){ if(ntry > 100){ LogError("Hydjet2EmptyEvent") << "##### HYDJET2: No Particles generated, Number of tries ="<<ntry; // Throw an exception. Use the EventCorruption exception since it maps onto SkipEvent // which is what we want to do here. std::ostringstream sstr; sstr << "Hydjet2HadronizerProducer: No particles generated after " << ntry << " tries.\n"; edm::Exception except(edm::errors::EventCorruption, sstr.str()); throw except; } else { //generate non-equilibrated part event hyevnt_(); ////////-------------HARD & SOFT particle list ----------begin------- //////////////// --->to separete func. if(fNhsel != 0){ //get number of particles in jets int numbJetPart = HYPART.njp; for(int i = 0; i <numbJetPart; ++i) { int pythiaStatus = int(HYPART.ppart[i][0]); // PYTHIA status code int pdg = int(HYPART.ppart[i][1]); // PYTHIA species code double px = HYPART.ppart[i][2]; // px double py = HYPART.ppart[i][3]; // py double pz = HYPART.ppart[i][4]; // pz double e = HYPART.ppart[i][5]; // E double vx = HYPART.ppart[i][6]; // x double vy = HYPART.ppart[i][7]; // y double vz = HYPART.ppart[i][8]; // z double vt = HYPART.ppart[i][9]; // t // particle line number in pythia are 1 based while we use a 0 based numbering int mother_index = int(HYPART.ppart[i][10])-1; //line number of parent particle int daughter_index1 = int(HYPART.ppart[i][11])-1; //line number of first daughter int daughter_index2 = int(HYPART.ppart[i][12])-1; //line number of last daughter // For status codes 3, 13, 14 the first and last daughter indexes have a different meaning // used for color flow in PYTHIA. So these indexes will be reset to zero. if(TMath::Abs(daughter_index1)>numbJetPart || TMath::Abs(daughter_index2)>numbJetPart || TMath::Abs(daughter_index1)>TMath::Abs(daughter_index2)) { daughter_index1 = -1; daughter_index2 = -1; } ParticlePDG *partDef = fDatabase->GetPDGParticle(pdg); int type=1; //from jet if(partDef) { int motherPdg = int(HYPART.ppart[mother_index][1]); if(motherPdg==0) motherPdg = -1; partJMom.SetXYZT(px, py, pz, e); partJPos.SetXYZT(vx, vy, vz, vt); Particle particle(partDef, partJPos, partJMom, 0, 0, type, motherPdg, zeroVec, zeroVec); int index = particle.SetIndex(); if(index!=i) { // LogWarning("Hydjet2Hadronizer") << " Allocated Hydjet2 index is not synchronized with the PYTHIA index !" << endl // << " Collision history information is destroyed! It happens when a PYTHIA code is not" << endl // << " implemented in Hydjet2 particle list particles.data! Check it out!"; } particle.SetPythiaStatusCode(pythiaStatus); particle.SetMother(mother_index); particle.SetFirstDaughterIndex(daughter_index1); particle.SetLastDaughterIndex(daughter_index2); if(pythiaStatus!=1) particle.SetDecayed(); allocator.AddParticle(particle, source); } else { LogWarning("Hydjet2Hadronizer") << " PYTHIA particle of specie " << pdg << " is not in Hydjet2 particle list" << endl <<" Please define it in particles.data, otherwise the history information will be de-synchronized and lost!"; } } } //nhsel !=0 not only hydro! //----------HYDRO part-------------------------------------- // get impact parameter double impactParameter = HYFPAR.bgen; // Sergey psiforv3 psiforv3 = 0.; //AS-ML Nov2012 epsilon3 // double e3 = (0.2/5.5)*TMath::Power(impactParameter,1./3.); psiforv3 = TMath::TwoPi() * (-0.5 + CLHEP::RandFlat::shoot(hjRandomEngine)) / 3.; SERVICEEV.psiv3 = -psiforv3; if(fNhsel < 3){ const double weightMax = 2*TMath::CosH(fUmax); const int nBins = 100; double probList[nBins]; RandArrayFunction arrayFunctDistE(nBins); RandArrayFunction arrayFunctDistR(nBins); TLorentzVector partPos, partMom, n1, p0; TVector3 vec3; const TLorentzVector zeroVec; //set maximal hadron energy const double eMax = 5.; //------------------------------------- // get impact parameter double Delta =fDelta; double Epsilon =fEpsilon; if(fIfDeltaEpsilon>0){ double Epsilon0 = 0.5*impactParameter; //e0=b/2Ra double coeff = (HYIPAR.RA/fR)/12.;//phenomenological coefficient Epsilon = Epsilon0 * coeff; double C=5.6; double A = C*Epsilon*(1-Epsilon*Epsilon); if(TMath::Abs(Epsilon)<0.0001 || TMath::Abs(A)<0.0001 )Delta=0.0; if(TMath::Abs(Epsilon)>0.0001 && TMath::Abs(A)>0.0001)Delta = 0.5*(TMath::Sqrt(1+4*A*(Epsilon+A))-1)/A; } //effective volume for central double dYl= 2 * fYlmax; //uniform distr. [-Ylmax; Ylmax] if (fEtaType >0) dYl = TMath::Sqrt(2 * TMath::Pi()) * fYlmax ; //Gaussian distr. double VolEffcent = 2 * TMath::Pi() * fTau * dYl * (fR * fR)/TMath::Power((fUmax),2) * ((fUmax)*TMath::SinH((fUmax))-TMath::CosH((fUmax))+ 1); //effective volume for non-central Simpson2 double VolEffnoncent = fTau * dYl * SimpsonIntegrator2(0., 2.*TMath::Pi(), Epsilon, Delta); fVolEff = VolEffcent * HYFPAR.npart/HYFPAR.npart0; double coeff_RB = TMath::Sqrt(VolEffcent * HYFPAR.npart/HYFPAR.npart0/VolEffnoncent); double coeff_R1 = HYFPAR.npart/HYFPAR.npart0; coeff_R1 = TMath::Power(coeff_R1, 0.333333); double Veff=fVolEff; //------------------------------------ //cycle on particles types double Nbcol = HYFPAR.nbcol; double NccNN = SERVICE.charm; double Ncc = Nbcol * NccNN/dYl; double Nocth = fNocth; double NJPsith = fNccth; double gammaC=1.0; if(fCorrC<=0){ gammaC=CharmEnhancementFactor(Ncc, Nocth, NJPsith, 0.001); }else{ gammaC=fCorrC; } LogInfo("Hydjet2Hadronizer|Param") <<" gammaC = " <<gammaC; for(int i = 0; i < fNPartTypes; ++i) { double Mparam = fPartMult[2 * i] * Veff; const int encoding = fPartEnc[i]; //ml if(abs(encoding)==443)Mparam = Mparam * gammaC * gammaC; //ml if(abs(encoding)==411 || abs(encoding)==421 ||abs(encoding)==413 || abs(encoding)==423 //ml || abs(encoding)==4122 || abs(encoding)==431) ParticlePDG *partDef0 = fDatabase->GetPDGParticle(encoding); if(partDef0->GetCharmQNumber()!=0 || partDef0->GetCharmAQNumber()!=0)Mparam = Mparam * gammaC; if(abs(encoding)==443)Mparam = Mparam * gammaC; LogInfo("Hydjet2Hadronizer|Param") <<encoding<<" "<<Mparam/dYl; int multiplicity = CLHEP::RandPoisson::shoot(hjRandomEngine, Mparam); LogInfo("Hydjet2Hadronizer|Param") <<"specie: " << encoding << "; average mult: = " << Mparam << "; multiplicity = " << multiplicity; if (multiplicity > 0) { ParticlePDG *partDef = fDatabase->GetPDGParticle(encoding); if(!partDef) { LogError("Hydjet2Hadronizer") << "No particle with encoding "<< encoding; continue; } if(fCharmProd<=0 && (partDef->GetCharmQNumber()!=0 || partDef->GetCharmAQNumber()!=0)){ LogInfo("Hydjet2Hadronizer|Param") <<"statistical charmed particle not allowed ! "<<encoding; continue; } if(partDef->GetCharmQNumber()!=0 || partDef->GetCharmAQNumber()!=0) LogInfo("Hydjet2Hadronizer|Param") <<" charm pdg generated "<< encoding; //compute chemical potential for single f.o. mu==mu_ch //compute chemical potential for thermal f.o. double mu = fPartMu[2 * i]; //choose Bose-Einstein or Fermi-Dirac statistics const double d = !(int(2*partDef->GetSpin()) & 1) ? -1 : 1; const double mass = partDef->GetMass(); //prepare histogram to sample hadron energy: double h = (eMax - mass) / nBins; double x = mass + 0.5 * h; int i; for(i = 0; i < nBins; ++i) { if(x>=mu && fThFO>0)probList[i] = x * TMath::Sqrt(x * x - mass * mass) / (TMath::Exp((x - mu) / (fThFO)) + d); if(x>=mu && fThFO<=0)probList[i] = x * TMath::Sqrt(x * x - mass * mass) / (TMath::Exp((x - mu) / (fT)) + d); if(x<mu)probList[i] = 0.; x += h; } arrayFunctDistE.PrepareTable(probList); //prepare histogram to sample hadron transverse radius: h = (fR) / nBins; x = 0.5 * h; double param = (fUmax) / (fR); for (i = 0; i < nBins; ++i) { probList[i] = x * TMath::CosH(param*x); x += h; } arrayFunctDistR.PrepareTable(probList); //loop over hadrons, assign hadron coordinates and momenta double weight = 0., yy = 0., px0 = 0., py0 = 0., pz0 = 0.; double e = 0., x0 = 0., y0 = 0., z0 = 0., t0 = 0., etaF = 0.; double r, RB, phiF; RB = fR * coeff_RB * coeff_R1 * TMath::Sqrt((1+e3)/(1-e3)); for(int j = 0; j < multiplicity; ++j) { do { fEtaType <=0 ? etaF = fYlmax * (2. * CLHEP::RandFlat::shoot(hjRandomEngine) - 1.) : etaF = (fYlmax) * (CLHEP::RandGauss::shoot(hjRandomEngine)); n1.SetXYZT(0.,0.,TMath::SinH(etaF),TMath::CosH(etaF)); if(TMath::Abs(etaF)>5.)continue; //old //double RBold = fR * TMath::Sqrt(1-fEpsilon); //RB = fR * coeff_RB * coeff_R1; //double impactParameter =HYFPAR.bgen; //double e0 = 0.5*impactParameter; //double RBold1 = fR * TMath::Sqrt(1-e0); double rho = TMath::Sqrt(CLHEP::RandFlat::shoot(hjRandomEngine)); double phi = TMath::TwoPi() * CLHEP::RandFlat::shoot(hjRandomEngine); double Rx = TMath::Sqrt(1-Epsilon)*RB; double Ry = TMath::Sqrt(1+Epsilon)*RB; x0 = Rx * rho * TMath::Cos(phi); y0 = Ry * rho * TMath::Sin(phi); r = TMath::Sqrt(x0*x0+y0*y0); phiF = TMath::Abs(TMath::ATan(y0/x0)); if(x0<0&&y0>0)phiF = TMath::Pi()-phiF; if(x0<0&&y0<0)phiF = TMath::Pi()+phiF; if(x0>0&&y0<0)phiF = 2.*TMath::Pi()-phiF; //new Nov2012 AS-ML if(r>RB*(1+e3*TMath::Cos(3*(phiF+psiforv3)))/(1+e3))continue; //proper time with emission duration double tau = coeff_R1 * fTau + sqrt(2.) * fSigmaTau * coeff_R1 * (CLHEP::RandGauss::shoot(hjRandomEngine)); z0 = tau * TMath::SinH(etaF); t0 = tau * TMath::CosH(etaF); double rhou = fUmax * r / RB; double rhou3 = 0.063*TMath::Sqrt((0.5*impactParameter)/0.67); double rhou4 = 0.023*((0.5*impactParameter)/0.67); double rrcoeff = 1./TMath::Sqrt(1. + Delta*TMath::Cos(2*phiF)); //AS-ML Nov.2012 rhou3=0.; //rhou4=0.; rhou = rhou * (1 + rrcoeff*rhou3*TMath::Cos(3*(phiF+psiforv3)) + rrcoeff*rhou4*TMath::Cos(4*phiF) ); //ML new suggestion of AS mar2012 double delta1 = 0.; Delta = Delta * (1.0 + delta1 * TMath::Cos(phiF) - delta1 * TMath::Cos(3*phiF)); double uxf = TMath::SinH(rhou)*TMath::Sqrt(1+Delta)*TMath::Cos(phiF); double uyf = TMath::SinH(rhou)*TMath::Sqrt(1-Delta)*TMath::Sin(phiF); double utf = TMath::CosH(etaF) * TMath::CosH(rhou) * TMath::Sqrt(1+Delta*TMath::Cos(2*phiF)*TMath::TanH(rhou)*TMath::TanH(rhou)); double uzf = TMath::SinH(etaF) * TMath::CosH(rhou) * TMath::Sqrt(1+Delta*TMath::Cos(2*phiF)*TMath::TanH(rhou)*TMath::TanH(rhou)); vec3.SetXYZ(uxf / utf, uyf / utf, uzf / utf); n1.Boost(-vec3); yy = weightMax * CLHEP::RandFlat::shoot(hjRandomEngine); double php0 = TMath::TwoPi() * CLHEP::RandFlat::shoot(hjRandomEngine); double ctp0 = 2. * CLHEP::RandFlat::shoot(hjRandomEngine) - 1.; double stp0 = TMath::Sqrt(1. - ctp0 * ctp0); e = mass + (eMax - mass) * arrayFunctDistE(); double pp0 = TMath::Sqrt(e * e - mass * mass); px0 = pp0 * stp0 * TMath::Sin(php0); py0 = pp0 * stp0 * TMath::Cos(php0); pz0 = pp0 * ctp0; p0.SetXYZT(px0, py0, pz0, e); //weight for rdr weight = (n1 * p0) /e; // weight for rdr gammar: weight = (n1 * p0) / n1[3] / e; } while(yy >= weight); if(abs(z0)>1000 || abs(x0)>1000) LogInfo("Hydjet2Hadronizer|Param") <<" etaF = "<<etaF<<std::endl; partMom.SetXYZT(px0, py0, pz0, e); partPos.SetXYZT(x0, y0, z0, t0); partMom.Boost(vec3); int type =0; //hydro Particle particle(partDef, partPos, partMom, 0., 0, type, -1, zeroVec, zeroVec); particle.SetIndex(); allocator.AddParticle(particle, source); } //nhsel==4 , no hydro part } } } ////////-------------HARD & SOFT particle list ----------end------- /////////////////////////// Npart = (int)HYFPAR.npart; Bgen = HYFPAR.bgen; Njet = (int)HYJPAR.njet; Nbcol = (int)HYFPAR.nbcol; //if(source.empty()) { // LogError("Hydjet2Hadronizer") << "Source is not initialized!! Trying again..."; //return ; //} //Run the decays if(RunDecays()) Evolve(source, allocator, GetWeakDecayLimit()); LPIT_t it; LPIT_t e; //Fill the decayed arrays Ntot = 0; Nhyd=0; Npyt=0; for(it = source.begin(), e = source.end(); it != e; ++it) { TVector3 pos(it->Pos().Vect()); TVector3 mom(it->Mom().Vect()); float m1 = it->TableMass(); pdg[Ntot] = it->Encoding(); Mpdg[Ntot] = it->GetLastMotherPdg(); Px[Ntot] = mom[0]; Py[Ntot] = mom[1]; Pz[Ntot] = mom[2]; E[Ntot] = TMath::Sqrt(mom.Mag2() + m1*m1); X[Ntot] = pos[0]; Y[Ntot] = pos[1]; Z[Ntot] = pos[2]; T[Ntot] = it->T(); type[Ntot] = it->GetType(); pythiaStatus[Ntot] = convertStatus(it->GetPythiaStatusCode()); Index[Ntot] = it->GetIndex(); MotherIndex[Ntot] = it->GetMother(); NDaughters[Ntot] = it->GetNDaughters(); FirstDaughterIndex[Ntot] = -1; LastDaughterIndex[Ntot] = -1; //index of first daughter FirstDaughterIndex[Ntot] = it->GetFirstDaughterIndex(); //index of last daughter LastDaughterIndex[Ntot] = it->GetLastDaughterIndex(); if(type[Ntot]==1) { // jets if(pythiaStatus[Ntot]==1 && NDaughters[Ntot]==0){ // code for final state particle in pythia final[Ntot]=1; }else{ final[Ntot]=pythiaStatus[Ntot]; } } if(type[Ntot]==0) { // hydro if(NDaughters[Ntot]==0) final[Ntot]=1; else final[Ntot]=2; } if(type[Ntot]==0)Nhyd++; if(type[Ntot]==1)Npyt++; Ntot++; if(Ntot > kMax) LogError("Hydjet2Hadronizer") << "Ntot is too large" << Ntot; } nsoft_ = Nhyd; nsub_ = Njet; nhard_ = Npyt; //100 trys ++ntry; } } if(ev==0) { Sigin=HYJPAR.sigin; Sigjet=HYJPAR.sigjet; } ev=1; if(fNhsel < 3) nsub_++; // event information HepMC::GenEvent *evt = new HepMC::GenEvent(); if(nhard_>0 || nsoft_>0) get_particles(evt); evt->set_signal_process_id(pypars.msti[0]); // type of the process evt->set_event_scale(pypars.pari[16]); // Q^2 add_heavy_ion_rec(evt); event().reset(evt); allocator.FreeList(source); return kTRUE; } //________________________________________________________________ bool Hydjet2Hadronizer::declareStableParticles(const std::vector<int>& _pdg ) { std::vector<int> pdg = _pdg; for ( size_t i=0; i < pdg.size(); i++ ) { int pyCode = pycomp_( pdg[i] ); std::ostringstream pyCard ; pyCard << "MDCY(" << pyCode << ",1)=0"; std::cout << pyCard.str() << std::endl; call_pygive( pyCard.str() ); } return true; } //________________________________________________________________ bool Hydjet2Hadronizer::hadronize() { return false; } bool Hydjet2Hadronizer::decay() { return true; } bool Hydjet2Hadronizer::residualDecay() { return true; } void Hydjet2Hadronizer::finalizeEvent() { } void Hydjet2Hadronizer::statistics() { } const char* Hydjet2Hadronizer::classname() const { return "gen::Hydjet2Hadronizer"; } //---------------------------------------------------------------------------------------------- //______________________________________________________________________________________________ //f2=f(phi,r) double Hydjet2Hadronizer::f2(double x, double y, double Delta) { LogDebug("f2") <<"in f2: "<<"delta"<<Delta; double RsB = fR; //test: podstavit' *coefff_RB double rhou = fUmax * y / RsB; double ff = y*TMath::CosH(rhou)* TMath::Sqrt(1+Delta*TMath::Cos(2*x)*TMath::TanH(rhou)*TMath::TanH(rhou)); //n_mu u^mu f-la 20 return ff; } //____________________________________________________________________________________________ double Hydjet2Hadronizer::SimpsonIntegrator(double a, double b, double phi, double Delta) { LogDebug("SimpsonIntegrator") <<"in SimpsonIntegrator"<<"delta - "<<Delta; int nsubIntervals=100; double h = (b - a)/nsubIntervals; double s = f2(phi,a + 0.5*h,Delta); double t = 0.5*(f2(phi,a,Delta) + f2(phi,b,Delta)); double x = a; double y = a + 0.5*h; for(int i = 1; i < nsubIntervals; i++) { x += h; y += h; s += f2(phi,y,Delta); t += f2(phi,x,Delta); } t += 2.0*s; return t*h/3.0; } //______________________________________________________________________________________________ double Hydjet2Hadronizer::SimpsonIntegrator2(double a, double b, double Epsilon, double Delta) { LogInfo("SimpsonIntegrator2") <<"in SimpsonIntegrator2: epsilon - "<<Epsilon<<" delta - "<<Delta; int nsubIntervals=10000; double h = (b - a)/nsubIntervals; //-1-pi, phi double s=0; // double h2 = (fR)/nsubIntervals; //0-R maximal RB ? double x = 0; //phi for(int j = 1; j < nsubIntervals; j++) { x += h; // phi double e = Epsilon; double RsB = fR; //test: podstavit' *coefff_RB double RB = RsB *(TMath::Sqrt(1-e*e)/TMath::Sqrt(1+e*TMath::Cos(2*x))); //f-la7 RB double sr = SimpsonIntegrator(0,RB,x,Delta); s += sr; } return s*h; } //___________________________________________________________________________________________________ double Hydjet2Hadronizer::MidpointIntegrator2(double a, double b, double Delta, double Epsilon) { int nsubIntervals=2000; int nsubIntervals2=1; double h = (b - a)/nsubIntervals; //0-pi , phi double h2 = (fR)/nsubIntervals; //0-R maximal RB ? double x = a + 0.5*h; double y = 0; double t = f2(x,y,Delta); double e = Epsilon; for(int j = 1; j < nsubIntervals; j++) { x += h; // integr phi double RsB = fR; //test: podstavit' *coefff_RB double RB = RsB *(TMath::Sqrt(1-e*e)/TMath::Sqrt(1+e*TMath::Cos(2*x))); //f-la7 RB nsubIntervals2 = int(RB / h2)+1; // integr R y=0; for(int i = 1; i < nsubIntervals2; i++) t += f2(x,(y += h2),Delta); } return t*h*h2; } //__________________________________________________________________________________________________________ double Hydjet2Hadronizer::CharmEnhancementFactor(double Ncc, double Ndth, double NJPsith, double Epsilon) { double gammaC=100.; double x1 = gammaC*Ndth; double var1 = Ncc-0.5*gammaC*Ndth*TMath::BesselI1(x1)/TMath::BesselI0(x1)-gammaC*gammaC*NJPsith; LogInfo("Charam") << "gammaC 20"<<" var "<<var1<<endl; gammaC=1.; double x0 = gammaC*Ndth; double var0 = Ncc-0.5*gammaC*Ndth*TMath::BesselI1(x0)/TMath::BesselI0(x0)-gammaC*gammaC*NJPsith; LogInfo("Charam") << "gammaC 1"<<" var "<<var0; for(int i=1; i<1000; i++){ if(var1 * var0<0){ gammaC=gammaC+0.01*i; double x = gammaC*Ndth; var0 = Ncc-0.5*gammaC*Ndth*TMath::BesselI1(x)/TMath::BesselI0(x)-gammaC*gammaC*NJPsith; } else { LogInfo("Charam") << "gammaC "<<gammaC<<" var0 "<<var0; return gammaC; } } LogInfo("Charam") << "gammaC not found ? "<<gammaC<<" var0 "<<var0; return -100; } //---------------------------------------------------------------------------------------------- //_____________________________________________________________________ //________________________________________________________________ void Hydjet2Hadronizer::rotateEvtPlane() { const double pi = 3.14159265358979; phi0_ = 2.*pi*gen::pyr_(nullptr) - pi; sinphi0_ = sin(phi0_); cosphi0_ = cos(phi0_); } //_____________________________________________________________________ bool Hydjet2Hadronizer::get_particles(HepMC::GenEvent *evt ) { // Hard particles. The first nhard_ lines from hyjets array. // Pythia/Pyquen sub-events (sub-collisions) for a given event // Return T/F if success/failure // Create particles from lujet entries, assign them into vertices and // put the vertices in the GenEvent, for each SubEvent // The SubEvent information is kept by storing indeces of main vertices // of subevents as a vector in GenHIEvent. LogDebug("SubEvent")<< "Number of sub events "<<nsub_; LogDebug("Hydjet2")<<"Number of hard events "<<Njet; LogDebug("Hydjet2")<<"Number of hard particles "<<nhard_; LogDebug("Hydjet2")<<"Number of soft particles "<<nsoft_; vector<HepMC::GenVertex*> sub_vertices(nsub_); int ihy = 0; for(int isub=0;isub<nsub_;isub++){ LogDebug("SubEvent") <<"Sub Event ID : "<<isub; int sub_up = (isub+1)*150000; // Upper limit in mother index, determining the range of Sub-Event vector<HepMC::GenParticle*> particles; vector<int> mother_ids; vector<HepMC::GenVertex*> prods; sub_vertices[isub] = new HepMC::GenVertex(HepMC::FourVector(0,0,0,0),isub); evt->add_vertex(sub_vertices[isub]); if(!evt->signal_process_vertex()) evt->set_signal_process_vertex(sub_vertices[isub]); while(ihy<nhard_+nsoft_ && (MotherIndex[ihy] < sub_up || ihy > nhard_ )){ particles.push_back(build_hyjet2(ihy,ihy+1)); prods.push_back(build_hyjet2_vertex(ihy,isub)); mother_ids.push_back(MotherIndex[ihy]); LogDebug("DecayChain")<<"Mother index : "<<MotherIndex[ihy]; ihy++; } //Produce Vertices and add them to the GenEvent. Remember that GenParticles are adopted by //GenVertex and GenVertex is adopted by GenEvent. LogDebug("Hydjet2")<<"Number of particles in vector "<<particles.size(); for (unsigned int i = 0; i<particles.size(); i++) { HepMC::GenParticle* part = particles[i]; //The Fortran code is modified to preserve mother id info, by seperating the beginning //mother indices of successive subevents by 5000 int mid = mother_ids[i]-isub*150000-1; LogDebug("DecayChain")<<"Particle "<<i; LogDebug("DecayChain")<<"Mother's ID "<<mid; LogDebug("DecayChain")<<"Particle's PDG ID "<<part->pdg_id(); if(mid <= 0){ sub_vertices[isub]->add_particle_out(part); continue; } if(mid > 0){ HepMC::GenParticle* mother = particles[mid]; LogDebug("DecayChain")<<"Mother's PDG ID "<<mother->pdg_id(); HepMC::GenVertex* prod_vertex = mother->end_vertex(); if(!prod_vertex){ prod_vertex = prods[i]; prod_vertex->add_particle_in(mother); evt->add_vertex(prod_vertex); prods[i]=nullptr; // mark to protect deletion } prod_vertex->add_particle_out(part); } } // cleanup vertices not assigned to evt for (unsigned int i = 0; i<prods.size(); i++) { if(prods[i]) delete prods[i]; } } return kTRUE; } //___________________________________________________________________ HepMC::GenParticle* Hydjet2Hadronizer::build_hyjet2(int index, int barcode) { // Build particle object corresponding to index in hyjets (soft+hard) double px0 = Px[index]; double py0 = Py[index]; double px = px0*cosphi0_-py0*sinphi0_; double py = py0*cosphi0_+px0*sinphi0_; // cout<< "status: "<<convertStatus(final[index], type[index])<<endl; HepMC::GenParticle* p = new HepMC::GenParticle( HepMC::FourVector( px, // px py, // py Pz[index], // pz E[index]), // E pdg[index], // id convertStatusForComponents(final[index], type[index])// status ); p->suggest_barcode(barcode); return p; } //___________________________________________________________________ HepMC::GenVertex* Hydjet2Hadronizer::build_hyjet2_vertex(int i,int id) { // build verteces for the hyjets stored events double x0=X[i]; double y0=Y[i]; double x = x0*cosphi0_-y0*sinphi0_; double y = y0*cosphi0_+x0*sinphi0_; double z=Z[i]; double t=T[i]; HepMC::GenVertex* vertex = new HepMC::GenVertex(HepMC::FourVector(x,y,z,t),id); return vertex; } //_____________________________________________________________________ void Hydjet2Hadronizer::add_heavy_ion_rec(HepMC::GenEvent *evt) { // heavy ion record in the final CMSSW Event double npart = Npart; int nproj = static_cast<int>(npart / 2); int ntarg = static_cast<int>(npart - nproj); HepMC::HeavyIon* hi = new HepMC::HeavyIon( nsub_, // Ncoll_hard/N of SubEvents nproj, // Npart_proj ntarg, // Npart_targ Nbcol, // Ncoll 0, // spectator_neutrons 0, // spectator_protons 0, // N_Nwounded_collisions 0, // Nwounded_N_collisions 0, // Nwounded_Nwounded_collisions Bgen * nuclear_radius(), // impact_parameter in [fm] phi0_, // event_plane_angle 0, // eccentricity Sigin // sigma_inel_NN ); evt->set_heavy_ion(*hi); delete hi; }
40.65551
231
0.608257
nistefan
8db2c34a04b97b0a5c4c04db0dddd9a87582e51a
14,334
cc
C++
chrome/browser/enterprise/reporting/report_request_queue_generator_unittest.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/enterprise/reporting/report_request_queue_generator_unittest.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-03-13T10:32:53.000Z
2019-03-13T11:05:30.000Z
chrome/browser/enterprise/reporting/report_request_queue_generator_unittest.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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/enterprise/browser/reporting/report_request_queue_generator.h" #include <vector> #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind.h" #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/enterprise/reporting/reporting_delegate_factory_desktop.h" #include "chrome/browser/profiles/profile_attributes_init_params.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile_manager.h" #include "components/account_id/account_id.h" #include "components/enterprise/browser/reporting/browser_report_generator.h" #include "components/enterprise/browser/reporting/report_request_definition.h" #include "components/policy/core/common/mock_policy_service.h" #include "components/policy/core/common/policy_map.h" #include "components/sync_preferences/pref_service_syncable.h" #include "content/public/test/browser_task_environment.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension_builder.h" #include "testing/gtest/include/gtest/gtest.h" #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif namespace em = enterprise_management; namespace enterprise_reporting { namespace { const char kIdleProfileName1[] = "idle_profile1"; const char kIdleProfileName2[] = "idle_profile2"; const char kActiveProfileName1[] = "active_profile1"; const char kActiveProfileName2[] = "active_profile2"; } // namespace // TODO(crbug.com/1103732): Get rid of chrome/browser dependencies and then // move this file to components/enterprise/browser. class ReportRequestQueueGeneratorTest : public ::testing::Test { public: using ReportRequest = definition::ReportRequest; ReportRequestQueueGeneratorTest() : profile_manager_(TestingBrowserProcess::GetGlobal()), browser_report_generator_(&reporting_delegate_factory_), report_request_queue_generator_(&reporting_delegate_factory_) { } ReportRequestQueueGeneratorTest(const ReportRequestQueueGeneratorTest&) = delete; ReportRequestQueueGeneratorTest& operator=( const ReportRequestQueueGeneratorTest&) = delete; ~ReportRequestQueueGeneratorTest() override = default; void SetUp() override { ASSERT_TRUE(profile_manager_.SetUp()); profile_manager_.CreateGuestProfile(); profile_manager_.CreateSystemProfile(); #if BUILDFLAG(ENABLE_PLUGINS) content::PluginService::GetInstance()->Init(); #endif // BUILDFLAG(ENABLE_PLUGINS) } std::set<std::string> CreateIdleProfiles() { CreateIdleProfile(kIdleProfileName1); CreateIdleProfile(kIdleProfileName2); return std::set<std::string>{kIdleProfileName1, kIdleProfileName2}; } std::set<std::string> CreateActiveProfiles() { CreateActiveProfile(kActiveProfileName1); CreateActiveProfile(kActiveProfileName2); return std::set<std::string>{kActiveProfileName1, kActiveProfileName2}; } std::set<std::string> CreateActiveProfilesWithContent() { CreateActiveProfileWithContent(kActiveProfileName1); CreateActiveProfileWithContent(kActiveProfileName2); return std::set<std::string>{kActiveProfileName1, kActiveProfileName2}; } void CreateIdleProfile(std::string profile_name) { ProfileAttributesInitParams params; params.profile_path = profile_manager()->profiles_dir().AppendASCII(profile_name); params.profile_name = base::ASCIIToUTF16(profile_name); profile_manager_.profile_attributes_storage()->AddProfile( std::move(params)); } TestingProfile* CreateActiveProfile(std::string profile_name) { return profile_manager_.CreateTestingProfile(profile_name); } TestingProfile* CreateActiveProfileWithPolicies( std::string profile_name, std::unique_ptr<policy::PolicyService> policy_service) { return profile_manager_.CreateTestingProfile( profile_name, {}, base::UTF8ToUTF16(profile_name), 0, {}, TestingProfile::TestingFactories(), absl::nullopt, std::move(policy_service)); } void CreateActiveProfileWithContent(std::string profile_name) { TestingProfile* active_profile = CreateActiveProfile(profile_name); extensions::ExtensionRegistry* extension_registry = extensions::ExtensionRegistry::Get(active_profile); std::string extension_name = "a super super super super super super super super super super super " "super super super super super super long extension name"; extension_registry->AddEnabled( extensions::ExtensionBuilder(extension_name) .SetID("abcdefghijklmnoabcdefghijklmnoab") .Build()); } std::unique_ptr<ReportRequest> GenerateBasicRequest() { auto request = std::make_unique<ReportRequest>(); base::RunLoop run_loop; browser_report_generator_.Generate( base::BindLambdaForTesting( [&run_loop, &request](std::unique_ptr<em::BrowserReport> report) { request->set_allocated_browser_report(report.release()), run_loop.Quit(); })); run_loop.Run(); return request; } std::vector<std::unique_ptr<ReportRequest>> GenerateRequests( const ReportRequest& request) { histogram_tester_ = std::make_unique<base::HistogramTester>(); std::queue<std::unique_ptr<ReportRequest>> requests = report_request_queue_generator_.Generate(request); std::vector<std::unique_ptr<ReportRequest>> result; while (!requests.empty()) { result.push_back(std::move(requests.front())); requests.pop(); } VerifyMetrics(result); return result; } void SetAndVerifyMaximumRequestSize(size_t size) { report_request_queue_generator_.SetMaximumReportSizeForTesting(size); EXPECT_EQ(size, report_request_queue_generator_.GetMaximumReportSizeForTesting()); } void VerifyProfiles(const em::BrowserReport& report, const std::set<std::string>& idle_profile_names, const std::set<std::string>& active_profile_names) { EXPECT_EQ((size_t)report.chrome_user_profile_infos_size(), idle_profile_names.size() + active_profile_names.size()); std::set<std::string> mutable_idle_profile_names(idle_profile_names); std::set<std::string> mutable_active_profile_names(active_profile_names); std::string profiles_dir = profile_manager_.profiles_dir().AsUTF8Unsafe(); for (auto profile : report.chrome_user_profile_infos()) { // Verify the generated profile id, whose mapping rule varies in // different cases. // - Idle: <profiles_dir>/<profile_name> // - Active: <profiles_dir>/u-<profile_name>-hash EXPECT_EQ(0u, profile.id().find(profiles_dir)); EXPECT_LE(0u, profile.id().find(profile.name())); if (profile.is_detail_available()) FindAndRemove(mutable_active_profile_names, profile.name()); else FindAndRemove(mutable_idle_profile_names, profile.name()); } EXPECT_TRUE(mutable_idle_profile_names.empty()); EXPECT_TRUE(mutable_active_profile_names.empty()); } void VerifyMetrics( const std::vector<std::unique_ptr<ReportRequest>>& requests) { histogram_tester_->ExpectUniqueSample( "Enterprise.CloudReportingRequestCount", requests.size(), 1); histogram_tester_->ExpectUniqueSample( "Enterprise.CloudReportingBasicRequestSize", /*basic request size floor to KB*/ 0, 1); } TestingProfileManager* profile_manager() { return &profile_manager_; } ReportRequestQueueGenerator* report_request_queue_generator() { return &report_request_queue_generator_; } base::HistogramTester* histogram_tester() { return histogram_tester_.get(); } private: void FindAndRemove(std::set<std::string>& names, const std::string& name) { auto it = names.find(name); EXPECT_NE(names.end(), it); names.erase(it); } content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_; ReportingDelegateFactoryDesktop reporting_delegate_factory_; BrowserReportGenerator browser_report_generator_; ReportRequestQueueGenerator report_request_queue_generator_; std::unique_ptr<base::HistogramTester> histogram_tester_; }; TEST_F(ReportRequestQueueGeneratorTest, GenerateReport) { auto idle_profile_names = CreateIdleProfiles(); auto basic_request = GenerateBasicRequest(); auto requests = GenerateRequests(*basic_request); EXPECT_EQ(1u, requests.size()); VerifyProfiles(requests[0]->browser_report(), idle_profile_names, {}); histogram_tester()->ExpectBucketCount("Enterprise.CloudReportingRequestSize", /*report size floor to KB*/ 0, 1); } TEST_F(ReportRequestQueueGeneratorTest, GenerateActiveProfiles) { auto idle_profile_names = CreateIdleProfiles(); auto active_profile_names = CreateActiveProfiles(); auto basic_request = GenerateBasicRequest(); auto requests = GenerateRequests(*basic_request); EXPECT_EQ(1u, requests.size()); VerifyProfiles(requests[0]->browser_report(), idle_profile_names, active_profile_names); histogram_tester()->ExpectBucketCount("Enterprise.CloudReportingRequestSize", /*report size floor to KB*/ 0, 1); } TEST_F(ReportRequestQueueGeneratorTest, BasicReportIsTooBig) { // Set a super small limitation. SetAndVerifyMaximumRequestSize(5); // Because the limitation is so small, no request can be created. CreateIdleProfiles(); auto basic_request = GenerateBasicRequest(); auto requests = GenerateRequests(*basic_request); EXPECT_EQ(0u, requests.size()); histogram_tester()->ExpectTotalCount("Enterprise.CloudReportingRequestSize", 0); } TEST_F(ReportRequestQueueGeneratorTest, ReportSeparation) { auto active_profiles = CreateActiveProfilesWithContent(); auto basic_request = GenerateBasicRequest(); auto requests = GenerateRequests(*basic_request); EXPECT_EQ(1u, requests.size()); // Set the limitation just below the size of the report so that it needs to be // separated into two requests later. SetAndVerifyMaximumRequestSize(requests[0]->ByteSizeLong() - 30); requests = GenerateRequests(*basic_request); EXPECT_EQ(2u, requests.size()); // The profile order in requests should match the return value of // GetAllProfilesAttributes(). std::vector<std::string> expected_active_profiles_in_requests; for (const auto* entry : profile_manager() ->profile_attributes_storage() ->GetAllProfilesAttributes()) { std::string profile_name = base::UTF16ToUTF8(entry->GetName()); if (active_profiles.find(profile_name) != active_profiles.end()) expected_active_profiles_in_requests.push_back(profile_name); } // The first profile is activated in the first request only while the second // profile is activated in the second request. VerifyProfiles( requests[0]->browser_report(), {/* idle_profile_names */ expected_active_profiles_in_requests[1]}, {/* active_profile_names */ expected_active_profiles_in_requests[0]}); VerifyProfiles( requests[1]->browser_report(), {/* idle_profile_names */ expected_active_profiles_in_requests[0]}, {/* active_profile_names */ expected_active_profiles_in_requests[1]}); histogram_tester()->ExpectBucketCount("Enterprise.CloudReportingRequestSize", /*report size floor to KB*/ 0, 2); } TEST_F(ReportRequestQueueGeneratorTest, ProfileReportIsTooBig) { CreateActiveProfileWithContent(kActiveProfileName1); auto basic_request = GenerateBasicRequest(); auto requests = GenerateRequests(*basic_request); EXPECT_EQ(1u, requests.size()); // Set the limitation just below the size of the report. SetAndVerifyMaximumRequestSize(requests[0]->ByteSizeLong() - 30); // Add a smaller Profile. CreateActiveProfile(kActiveProfileName2); basic_request = GenerateBasicRequest(); requests = GenerateRequests(*basic_request); EXPECT_EQ(1u, requests.size()); // Only the second Profile is activated while the first one is too big to be // reported. VerifyProfiles(requests[0]->browser_report(), {kActiveProfileName1}, {kActiveProfileName2}); histogram_tester()->ExpectBucketCount("Enterprise.CloudReportingRequestSize", /*report size floor to KB*/ 0, 2); } TEST_F(ReportRequestQueueGeneratorTest, ChromePoliciesCollection) { auto policy_service = std::make_unique<policy::MockPolicyService>(); policy::PolicyMap policy_map; ON_CALL(*policy_service.get(), GetPolicies(::testing::Eq(policy::PolicyNamespace( policy::POLICY_DOMAIN_CHROME, std::string())))) .WillByDefault(::testing::ReturnRef(policy_map)); policy_map.Set("kPolicyName1", policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, base::Value(std::vector<base::Value>()), nullptr); policy_map.Set("kPolicyName2", policy::POLICY_LEVEL_RECOMMENDED, policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_MERGED, base::Value(true), nullptr); CreateActiveProfileWithPolicies(kActiveProfileName1, std::move(policy_service)); auto basic_request = GenerateBasicRequest(); auto requests = GenerateRequests(*basic_request); EXPECT_EQ(1u, requests.size()); auto browser_report = requests[0]->browser_report(); EXPECT_EQ(1, browser_report.chrome_user_profile_infos_size()); auto profile_info = browser_report.chrome_user_profile_infos(0); #if BUILDFLAG(IS_CHROMEOS_ASH) // In Chrome OS, the collection of policies is disabled. EXPECT_EQ(0, profile_info.chrome_policies_size()); #else // In desktop Chrome, the collection of policies is enabled. EXPECT_EQ(2, profile_info.chrome_policies_size()); #endif } } // namespace enterprise_reporting
39.706371
83
0.73657
Yannic
8db3164e1e1928594f36744cdde0b2d221b8b750
509
cpp
C++
Searching & Sorting/Two number with sum closeset to zero.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
9
2020-10-01T09:29:10.000Z
2022-02-12T04:58:41.000Z
Searching & Sorting/Two number with sum closeset to zero.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
6
2020-10-03T16:08:58.000Z
2020-10-14T12:06:25.000Z
Searching & Sorting/Two number with sum closeset to zero.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
17
2020-10-01T09:17:27.000Z
2021-06-18T09:36:31.000Z
#include<bits/stdc++.h> using namespace std; int main() { int n;cin>>n; while(n--) { int m; cin>>m; vector<int>v(m); for(int i=0;i<m;i++) cin>>v[i]; sort(v.begin(),v.end()); int l=0,r=v.size()-1,sum=0; int m_sum=v[0]+v[r]; while(l<r) { sum=v[l]+v[r]; if(sum>0) r--; else l++; m_sum=abs(m_sum)<=abs(sum)?m_sum:sum; } cout<<m_sum<<endl; } return 0; }
14.138889
45
0.400786
vermagaurav8
8db563593207e9bd12dae2c1e3445a555a504a4c
10,922
cpp
C++
src/lib/tvgShape.cpp
Samsung/thorvg
906679cbeb62539e25fea1416b35e806c784e952
[ "MIT" ]
187
2020-08-24T04:45:30.000Z
2022-03-30T20:14:21.000Z
src/lib/tvgShape.cpp
Samsung/thorvg
906679cbeb62539e25fea1416b35e806c784e952
[ "MIT" ]
666
2020-09-10T06:45:14.000Z
2022-03-30T07:11:16.000Z
src/lib/tvgShape.cpp
Samsung/thorvg
906679cbeb62539e25fea1416b35e806c784e952
[ "MIT" ]
57
2020-08-24T05:15:41.000Z
2022-03-22T11:15:25.000Z
/* * Copyright (c) 2020-2021 Samsung Electronics Co., Ltd. All rights reserved. * 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 "tvgMath.h" #include "tvgShapeImpl.h" /************************************************************************/ /* Internal Class Implementation */ /************************************************************************/ constexpr auto PATH_KAPPA = 0.552284f; /************************************************************************/ /* External Class Implementation */ /************************************************************************/ Shape :: Shape() : pImpl(new Impl(this)) { Paint::pImpl->id = TVG_CLASS_ID_SHAPE; Paint::pImpl->method(new PaintMethod<Shape::Impl>(pImpl)); } Shape :: ~Shape() { delete(pImpl); } unique_ptr<Shape> Shape::gen() noexcept { return unique_ptr<Shape>(new Shape); } uint32_t Shape::identifier() noexcept { return TVG_CLASS_ID_SHAPE; } Result Shape::reset() noexcept { pImpl->path.reset(); pImpl->flag = RenderUpdateFlag::Path; return Result::Success; } uint32_t Shape::pathCommands(const PathCommand** cmds) const noexcept { if (!cmds) return 0; *cmds = pImpl->path.cmds; return pImpl->path.cmdCnt; } uint32_t Shape::pathCoords(const Point** pts) const noexcept { if (!pts) return 0; *pts = pImpl->path.pts; return pImpl->path.ptsCnt; } Result Shape::appendPath(const PathCommand *cmds, uint32_t cmdCnt, const Point* pts, uint32_t ptsCnt) noexcept { if (cmdCnt == 0 || ptsCnt == 0 || !cmds || !pts) return Result::InvalidArguments; pImpl->path.grow(cmdCnt, ptsCnt); pImpl->path.append(cmds, cmdCnt, pts, ptsCnt); pImpl->flag |= RenderUpdateFlag::Path; return Result::Success; } Result Shape::moveTo(float x, float y) noexcept { pImpl->path.moveTo(x, y); pImpl->flag |= RenderUpdateFlag::Path; return Result::Success; } Result Shape::lineTo(float x, float y) noexcept { pImpl->path.lineTo(x, y); pImpl->flag |= RenderUpdateFlag::Path; return Result::Success; } Result Shape::cubicTo(float cx1, float cy1, float cx2, float cy2, float x, float y) noexcept { pImpl->path.cubicTo(cx1, cy1, cx2, cy2, x, y); pImpl->flag |= RenderUpdateFlag::Path; return Result::Success; } Result Shape::close() noexcept { pImpl->path.close(); pImpl->flag |= RenderUpdateFlag::Path; return Result::Success; } Result Shape::appendCircle(float cx, float cy, float rx, float ry) noexcept { auto rxKappa = rx * PATH_KAPPA; auto ryKappa = ry * PATH_KAPPA; pImpl->path.grow(6, 13); pImpl->path.moveTo(cx, cy - ry); pImpl->path.cubicTo(cx + rxKappa, cy - ry, cx + rx, cy - ryKappa, cx + rx, cy); pImpl->path.cubicTo(cx + rx, cy + ryKappa, cx + rxKappa, cy + ry, cx, cy + ry); pImpl->path.cubicTo(cx - rxKappa, cy + ry, cx - rx, cy + ryKappa, cx - rx, cy); pImpl->path.cubicTo(cx - rx, cy - ryKappa, cx - rxKappa, cy - ry, cx, cy - ry); pImpl->path.close(); pImpl->flag |= RenderUpdateFlag::Path; return Result::Success; } Result Shape::appendArc(float cx, float cy, float radius, float startAngle, float sweep, bool pie) noexcept { //just circle if (sweep >= 360.0f || sweep <= -360.0f) return appendCircle(cx, cy, radius, radius); startAngle = (startAngle * M_PI) / 180.0f; sweep = sweep * M_PI / 180.0f; auto nCurves = ceil(fabsf(sweep / float(M_PI_2))); auto sweepSign = (sweep < 0 ? -1 : 1); auto fract = fmodf(sweep, float(M_PI_2)); fract = (mathZero(fract)) ? float(M_PI_2) * sweepSign : fract; //Start from here Point start = {radius * cosf(startAngle), radius * sinf(startAngle)}; if (pie) { pImpl->path.moveTo(cx, cy); pImpl->path.lineTo(start.x + cx, start.y + cy); } else { pImpl->path.moveTo(start.x + cx, start.y + cy); } for (int i = 0; i < nCurves; ++i) { auto endAngle = startAngle + ((i != nCurves - 1) ? float(M_PI_2) * sweepSign : fract); Point end = {radius * cosf(endAngle), radius * sinf(endAngle)}; //variables needed to calculate bezier control points //get bezier control points using article: //(http://itc.ktu.lt/index.php/ITC/article/view/11812/6479) auto ax = start.x; auto ay = start.y; auto bx = end.x; auto by = end.y; auto q1 = ax * ax + ay * ay; auto q2 = ax * bx + ay * by + q1; auto k2 = (4.0f/3.0f) * ((sqrtf(2 * q1 * q2) - q2) / (ax * by - ay * bx)); start = end; //Next start point is the current end point end.x += cx; end.y += cy; Point ctrl1 = {ax - k2 * ay + cx, ay + k2 * ax + cy}; Point ctrl2 = {bx + k2 * by + cx, by - k2 * bx + cy}; pImpl->path.cubicTo(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, end.x, end.y); startAngle = endAngle; } if (pie) pImpl->path.close(); pImpl->flag |= RenderUpdateFlag::Path; return Result::Success; } Result Shape::appendRect(float x, float y, float w, float h, float rx, float ry) noexcept { auto halfW = w * 0.5f; auto halfH = h * 0.5f; //clamping cornerRadius by minimum size if (rx > halfW) rx = halfW; if (ry > halfH) ry = halfH; //rectangle if (rx == 0 && ry == 0) { pImpl->path.grow(5, 4); pImpl->path.moveTo(x, y); pImpl->path.lineTo(x + w, y); pImpl->path.lineTo(x + w, y + h); pImpl->path.lineTo(x, y + h); pImpl->path.close(); //circle } else if (mathEqual(rx, halfW) && mathEqual(ry, halfH)) { return appendCircle(x + (w * 0.5f), y + (h * 0.5f), rx, ry); } else { auto hrx = rx * 0.5f; auto hry = ry * 0.5f; pImpl->path.grow(10, 17); pImpl->path.moveTo(x + rx, y); pImpl->path.lineTo(x + w - rx, y); pImpl->path.cubicTo(x + w - rx + hrx, y, x + w, y + ry - hry, x + w, y + ry); pImpl->path.lineTo(x + w, y + h - ry); pImpl->path.cubicTo(x + w, y + h - ry + hry, x + w - rx + hrx, y + h, x + w - rx, y + h); pImpl->path.lineTo(x + rx, y + h); pImpl->path.cubicTo(x + rx - hrx, y + h, x, y + h - ry + hry, x, y + h - ry); pImpl->path.lineTo(x, y + ry); pImpl->path.cubicTo(x, y + ry - hry, x + rx - hrx, y, x + rx, y); pImpl->path.close(); } pImpl->flag |= RenderUpdateFlag::Path; return Result::Success; } Result Shape::fill(uint8_t r, uint8_t g, uint8_t b, uint8_t a) noexcept { pImpl->color[0] = r; pImpl->color[1] = g; pImpl->color[2] = b; pImpl->color[3] = a; pImpl->flag |= RenderUpdateFlag::Color; if (pImpl->fill) { delete(pImpl->fill); pImpl->fill = nullptr; pImpl->flag |= RenderUpdateFlag::Gradient; } return Result::Success; } Result Shape::fill(unique_ptr<Fill> f) noexcept { auto p = f.release(); if (!p) return Result::MemoryCorruption; if (pImpl->fill && pImpl->fill != p) delete(pImpl->fill); pImpl->fill = p; pImpl->flag |= RenderUpdateFlag::Gradient; return Result::Success; } Result Shape::fillColor(uint8_t* r, uint8_t* g, uint8_t* b, uint8_t* a) const noexcept { if (r) *r = pImpl->color[0]; if (g) *g = pImpl->color[1]; if (b) *b = pImpl->color[2]; if (a) *a = pImpl->color[3]; return Result::Success; } const Fill* Shape::fill() const noexcept { return pImpl->fill; } Result Shape::stroke(float width) noexcept { if (!pImpl->strokeWidth(width)) return Result::FailedAllocation; return Result::Success; } float Shape::strokeWidth() const noexcept { if (!pImpl->stroke) return 0; return pImpl->stroke->width; } Result Shape::stroke(uint8_t r, uint8_t g, uint8_t b, uint8_t a) noexcept { if (!pImpl->strokeColor(r, g, b, a)) return Result::FailedAllocation; return Result::Success; } Result Shape::strokeColor(uint8_t* r, uint8_t* g, uint8_t* b, uint8_t* a) const noexcept { if (!pImpl->stroke) return Result::InsufficientCondition; if (r) *r = pImpl->stroke->color[0]; if (g) *g = pImpl->stroke->color[1]; if (b) *b = pImpl->stroke->color[2]; if (a) *a = pImpl->stroke->color[3]; return Result::Success; } Result Shape::stroke(unique_ptr<Fill> f) noexcept { return pImpl->strokeFill(move(f)); } const Fill* Shape::strokeFill() const noexcept { if (!pImpl->stroke) return nullptr; return pImpl->stroke->fill; } Result Shape::stroke(const float* dashPattern, uint32_t cnt) noexcept { if ((cnt == 1) || (!dashPattern && cnt > 0) || (dashPattern && cnt == 0)) { return Result::InvalidArguments; } for (uint32_t i = 0; i < cnt; i++) if (dashPattern[i] < FLT_EPSILON) return Result::InvalidArguments; if (!pImpl->strokeDash(dashPattern, cnt)) return Result::FailedAllocation; return Result::Success; } uint32_t Shape::strokeDash(const float** dashPattern) const noexcept { if (!pImpl->stroke) return 0; if (dashPattern) *dashPattern = pImpl->stroke->dashPattern; return pImpl->stroke->dashCnt; } Result Shape::stroke(StrokeCap cap) noexcept { if (!pImpl->strokeCap(cap)) return Result::FailedAllocation; return Result::Success; } Result Shape::stroke(StrokeJoin join) noexcept { if (!pImpl->strokeJoin(join)) return Result::FailedAllocation; return Result::Success; } StrokeCap Shape::strokeCap() const noexcept { if (!pImpl->stroke) return StrokeCap::Square; return pImpl->stroke->cap; } StrokeJoin Shape::strokeJoin() const noexcept { if (!pImpl->stroke) return StrokeJoin::Bevel; return pImpl->stroke->join; } Result Shape::fill(FillRule r) noexcept { pImpl->rule = r; return Result::Success; } FillRule Shape::fillRule() const noexcept { return pImpl->rule; }
25.578454
110
0.602088
Samsung
8dba60880f4e8f98eb53bb8235ed7a749ee3480c
2,758
cpp
C++
CMinus/CMinus/evaluator/class_evaluator.cpp
benbraide/CMinus
3b845e0bc22840b549f108bf6600f1f34d865e7b
[ "MIT" ]
null
null
null
CMinus/CMinus/evaluator/class_evaluator.cpp
benbraide/CMinus
3b845e0bc22840b549f108bf6600f1f34d865e7b
[ "MIT" ]
null
null
null
CMinus/CMinus/evaluator/class_evaluator.cpp
benbraide/CMinus
3b845e0bc22840b549f108bf6600f1f34d865e7b
[ "MIT" ]
null
null
null
#include "../type/class_type.h" #include "class_evaluator.h" cminus::evaluator::class_::~class_() = default; std::shared_ptr<cminus::memory::reference> cminus::evaluator::class_::evaluate_unary_left(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> target) const{ auto callable = find_operator_(runtime, op, target); if (callable == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); return callable->get_value()->call(runtime, callable->get_context(), std::vector<std::shared_ptr<memory::reference>>{target}); } std::shared_ptr<cminus::memory::reference> cminus::evaluator::class_::evaluate_unary_right(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> target) const{ auto callable = find_operator_(runtime, op, target); if (callable == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); std::vector<std::shared_ptr<memory::reference>> args{ target, runtime.global_storage->create_scalar(0) }; return callable->get_value()->call(runtime, callable->get_context(), args); } std::shared_ptr<cminus::memory::reference> cminus::evaluator::class_::evaluate_binary(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> left_value, const operand_type &right) const{ auto callable = find_operator_(runtime, op, left_value); if (callable == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); return callable->get_value()->call(runtime, callable->get_context(), std::vector<std::shared_ptr<memory::reference>>{ left_value, right->evaluate(runtime) }); } cminus::memory::function_reference *cminus::evaluator::class_::find_operator_(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> target) const{ std::shared_ptr<memory::reference> entry; if (std::holds_alternative<operator_id>(op)){ entry = dynamic_cast<type::class_ *>(target->get_type().get())->find_operator( runtime, std::get<operator_id>(op), logic::storage::object::namesless_search_options{ nullptr, target, false } ); } else//String value entry = dynamic_cast<type::class_ *>(target->get_type().get())->find(runtime, logic::storage::object::search_options{ nullptr, target, std::get<std::string>(op), false }); if (entry == nullptr) return nullptr; if (auto callable = dynamic_cast<memory::function_reference *>(entry->get_non_raw()); callable != nullptr) return callable; throw logic::exception("Bad operator definition", 0u, 0u); return nullptr; }
48.385965
216
0.741842
benbraide
8dbb81d0405ac9ac1d8493331358cd49c1650292
3,530
cc
C++
src/search_local/index_storage/common/plugin_dgram.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
3
2021-08-18T09:59:42.000Z
2021-09-07T03:11:28.000Z
src/search_local/index_storage/common/plugin_dgram.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
src/search_local/index_storage/common/plugin_dgram.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <sys/un.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <linux/sockios.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include "plugin_agent_mgr.h" #include "plugin_dgram.h" #include "plugin_unit.h" #include "poll_thread.h" #include "mem_check.h" #include "log.h" extern "C" { extern unsigned int get_local_ip(); } static int GetSocketFamily(int fd) { struct sockaddr addr; bzero(&addr, sizeof(addr)); socklen_t alen = sizeof(addr); getsockname(fd, &addr, &alen); return addr.sa_family; } PluginDgram::PluginDgram(PluginDecoderUnit *plugin_decoder, int fd) : PollerObject(plugin_decoder->owner_thread(), fd), mtu(0), _addr_len(0), _owner(plugin_decoder), _worker_notifier(NULL), _plugin_receiver(fd, PluginAgentManager::Instance()->get_dll()), _plugin_sender(fd, PluginAgentManager::Instance()->get_dll()), _local_ip(0) { } PluginDgram::~PluginDgram() { } int PluginDgram::Attach() { /* init local ip */ _local_ip = get_local_ip(); switch (GetSocketFamily(netfd)) { default: case AF_UNIX: mtu = 16 << 20; _addr_len = sizeof(struct sockaddr_un); break; case AF_INET: mtu = 65535; _addr_len = sizeof(struct sockaddr_in); break; case AF_INET6: mtu = 65535; _addr_len = sizeof(struct sockaddr_in6); break; } //get worker notifier _worker_notifier = PluginAgentManager::Instance()->get_worker_notifier(); if (NULL == _worker_notifier) { log_error("worker notifier is invalid."); return -1; } enable_input(); return attach_poller(); } //server peer int PluginDgram::recv_request(void) { //create dgram request PluginDatagram *dgram_request = NULL; NEW(PluginDatagram(this, PluginAgentManager::Instance()->get_dll()), dgram_request); if (NULL == dgram_request) { log_error("create PluginRequest for dgram failed, msg:%s", strerror(errno)); return -1; } //set request info dgram_request->_skinfo.sockfd = netfd; dgram_request->_skinfo.type = SOCK_DGRAM; dgram_request->_skinfo.local_ip = _local_ip; dgram_request->_skinfo.local_port = 0; dgram_request->_incoming_notifier = _owner->get_incoming_notifier(); dgram_request->_addr_len = _addr_len; dgram_request->_addr = MALLOC(_addr_len); if (NULL == dgram_request->_addr) { log_error("malloc failed, msg:%m"); DELETE(dgram_request); return -1; } if (_plugin_receiver.recvfrom(dgram_request, mtu) != 0) { DELETE(dgram_request); return -1; } dgram_request->set_time_info(); if (_worker_notifier->Push(dgram_request) != 0) { log_error("push plugin request failed, fd[%d]", netfd); DELETE(dgram_request); return -1; } return 0; } void PluginDgram::input_notify(void) { if (recv_request() < 0) /* */; }
26.541353
134
0.561473
jdisearch
8dbd09b2d4428c42a845c34d3c2d54bcf4c221e8
3,921
cpp
C++
lesson15/src/mainDijkstra.cpp
forsakenmap/CPPExercises2021
48b91b86aa0f02d462fd7fac3d08fed8468c1506
[ "MIT" ]
null
null
null
lesson15/src/mainDijkstra.cpp
forsakenmap/CPPExercises2021
48b91b86aa0f02d462fd7fac3d08fed8468c1506
[ "MIT" ]
null
null
null
lesson15/src/mainDijkstra.cpp
forsakenmap/CPPExercises2021
48b91b86aa0f02d462fd7fac3d08fed8468c1506
[ "MIT" ]
null
null
null
#include <vector> #include <sstream> #include <iostream> #include <stdexcept> // беда не работает дайте руки и мозг int debugPoint(int line) { if (line < 0) return 0; // You can put breakpoint at the following line to catch any rassert failure: return line; } #define rassert(condition, message) if (!(condition)) { std::stringstream ss; (ss << "Assertion \"" << message << "\" failed at line " << debugPoint(__LINE__) << "!"); throw std::runtime_error(ss.str()); } bool found(std::vector<int> a, int b) { for(int i = 0; i < a.size(); i++) { if(a.at(i) == b) { return true; } } return false; } struct Edge { int u, v; // номера вершин которые это ребро соединяет int w; // длина ребра (т.е. насколько длинный путь предстоит преодолеть переходя по этому ребру между вершинами) Edge(int u, int v, int w) : u(u), v(v), w(w) {} }; void run() { // https://codeforces.com/problemset/problem/20/C?locale=ru // Не требуется сделать оптимально быструю версию, поэтому если вы получили: // // Превышено ограничение времени на тесте 31 // // То все замечательно и вы молодец. int nvertices, medges; std::cin >> nvertices; std::cin >> medges; std::vector<std::vector<Edge>> edges_by_vertex(nvertices); std::vector<bool> edg_be(nvertices, false); for (int i = 0; i < medges; ++i) { int ai, bi, w; std::cin >> ai >> bi >> w; rassert(ai >= 1 && ai <= nvertices, 23472894792020); rassert(bi >= 1 && bi <= nvertices, 23472894792021); ai -= 1; bi -= 1; rassert(ai >= 0 && ai < nvertices, 3472897424024); rassert(bi >= 0 && bi < nvertices, 3472897424025); Edge edgeAB(ai, bi, w); edges_by_vertex[ai].push_back(edgeAB); edges_by_vertex[bi].push_back(Edge(bi, ai, w)); // а тут - обратное ребро, можно конструировать объект прямо в той же строчке где он и потребовался } int start = 0; const int finish = nvertices - 1; const int INF = std::numeric_limits<int>::max(); Edge a(0, 0, 0); int s = 0; std::vector<int> distances(nvertices, INF); distances.at(0) = 0; int min = INF; int num = 0; std::vector<std::string> put(nvertices, ""); std::vector<int> first_s; first_s.push_back(0); std::vector<int> second_s; // TODO ... while (true) { for (int i = 0; i < first_s.size(); i++) { for (int k = 0; k < edges_by_vertex[first_s.at(i)].size(); k++) { a = edges_by_vertex[first_s.at(i)].at(k); if ((!edg_be.at(first_s.at(i))) && (!found(second_s, a.v))) { second_s.push_back(a.v); } if (distances.at(a.v) > distances.at(a.u) + a.w) { if(!found(second_s, a.v)) { second_s.push_back(a.v); } distances.at(a.v) = distances.at(a.u) + a.w; put.at(a.v) = put.at(a.u) + " " + std::to_string(a.v + 1); } } edg_be.at(first_s.at(i)) = true; } if (second_s.empty()) { break; } first_s = second_s; second_s = std::vector<int>(); } if (put.at(nvertices-1) == "") { std::cout << "-1"; } else { std::cout << "1" + put.at(nvertices - 1); } // while (true) { // // } // if (...) { // ... // for (...) { // std::cout << (path[i] + 1) << " "; // } // std::cout << std::endl; // } else { // std::cout << -1 << std::endl; // } } using namespace std; int main() { try { run(); } catch (const std::exception &e) { std::cout << "Exception! " << e.what() << std::endl; } }
29.704545
205
0.502678
forsakenmap
8dbd74f8d6df869cf70a0e3d78d38b3a892d5fdd
4,711
cpp
C++
Test.cpp
shaiBonfil/CPP-Ex1
ec9a82b8de9b99e3dd4488781b363ec36c95509e
[ "MIT" ]
null
null
null
Test.cpp
shaiBonfil/CPP-Ex1
ec9a82b8de9b99e3dd4488781b363ec36c95509e
[ "MIT" ]
null
null
null
Test.cpp
shaiBonfil/CPP-Ex1
ec9a82b8de9b99e3dd4488781b363ec36c95509e
[ "MIT" ]
null
null
null
/** * * AUTHOR: <Shai Bonfil> * * This is a test that gets input of eight characters(less or more * is invalid input), and the purpose is to represent snowman in * a format like you can see in the link below - HNLRXYTB. * Each valid letter is number between 1 to 4 which presets * the following things: * * H - Hat * N - Nose * L - Left eye * R - Right eye * X - Left arm * Y - Right arm * T - Torso * B - Base * * https://codegolf.stackexchange.com/q/49671/12019 * * Date: 2021-03 */ #include "doctest.h" #include <iostream> #include <string> #include <algorithm> using namespace std; #include "snowman.hpp" using namespace ariel; string nospaces(string input) { std::erase(input, ' '); std::erase(input, '\t'); std::erase(input, '\n'); std::erase(input, '\r'); return input; } TEST_CASE("Good snowman code") { CHECK(nospaces(snowman(11114411)) == nospaces("_===_\n(.,.)\n( : )\n( : )")); } TEST_CASE("All Hats"){ // H CHECK(nospaces(snowman(12341234)) == nospaces("_===_ \n(...)\n(O:-)\n<(> <)/\n( )")); CHECK(nospaces(snowman(21341321)) == nospaces(" ___ \n ..... \n(O,-)\n<(] [)\\n( : )")); CHECK(nospaces(snowman(34324123)) == nospaces(" _ \n /_\\ \n(O o)\n( : )>\n(___)")); CHECK(nospaces(snowman(44123212)) == nospaces(" ___ \n (_*_) \n(. o)\n/(] [)/\n(\" \")")); } TEST_CASE("All Noses"){ // N CHECK(nospaces(snowman(11341234)) == nospaces("_===_ \n(...)\n(O,-)\n<(> <)/\n( )")); CHECK(nospaces(snowman(12341321)) == nospaces("_===_ \n(...)\n(O.-)\n<(] [)\\n( : )")); CHECK(nospaces(snowman(23324123)) == nospaces(" ___ \n ..... \n(O_o)\n( : )>\n(___)")); CHECK(nospaces(snowman(14123212)) == nospaces("_===_ \n(...)\n(. o)\n/(] [)/\n(\" \")")); } TEST_CASE("All Left Eyes"){ // L CHECK(nospaces(snowman(11141234)) == nospaces("_===_ \n(...)\n(.,-)\n<(> <)/\n( )")); CHECK(nospaces(snowman(12241321)) == nospaces("_===_ \n(...)\n(o.-)\n<(] [)\\n( : )")); CHECK(nospaces(snowman(23324123)) == nospaces(" ___ \n ..... \n(O_o)\n( : )>\n(___)")); CHECK(nospaces(snowman(14423212)) == nospaces("_===_ \n(...)\n(- o)\n/(] [)/\n(\" \")")); } TEST_CASE("All Right Eyes"){ // R CHECK(nospaces(snowman(11111234)) == nospaces("_===_ \n(...)\n(.,.)\n<(> <)/\n( )")); CHECK(nospaces(snowman(12221321)) == nospaces("_===_ \n(...)\n(o.o)\n<(] [)\\n( : )")); CHECK(nospaces(snowman(23334123)) == nospaces(" ___ \n ..... \n(O_O)\n( : )>\n(___)")); CHECK(nospaces(snowman(11443212)) == nospaces("_===_ \n(...)\n(-,-)\n/(] [)/\n(\" \")")); } TEST_CASE("All Left Arms"){ // X CHECK(nospaces(snowman(11111234)) == nospaces("_===_ \n(...)\n(.,.)\n<(> <)/\n( )")); CHECK(nospaces(snowman(12222321)) == nospaces("_===_ \n(...)\n(o.o)\n\\(] [)\\n( : )")); CHECK(nospaces(snowman(23333123)) == nospaces(" ___ \n ..... \n(O_O)\n/( : )>\n(___)")); CHECK(nospaces(snowman(11444212)) == nospaces("_===_ \n(...)\n(-,-)\n(] [)/\n(\" \")")); } TEST_CASE("All Right Arms"){ // Y CHECK(nospaces(snowman(11311134)) == nospaces("_===_ \n(...)\n(O,.)\n<(> <)>\n( )")); CHECK(nospaces(snowman(12221221)) == nospaces("_===_ \n(...)\n(o.o)\n<(] [)/\n( : )")); CHECK(nospaces(snowman(23133323)) == nospaces(" ___ \n ..... \n(._O)\n/( : )\\\n(___)")); CHECK(nospaces(snowman(11143412)) == nospaces("_===_ \n(...)\n(.,-)\n/(] [)\n(\" \")")); } TEST_CASE("All Torsos"){ // T CHECK(nospaces(snowman(11311114)) == nospaces("_===_ \n(...)\n(O,.)\n<( : )>\n( )")); CHECK(nospaces(snowman(12221221)) == nospaces("_===_ \n(...)\n(o.o)\n<(] [)/\n( : )")); CHECK(nospaces(snowman(23133333)) == nospaces(" ___ \n ..... \n(._O)\n/(> <)\\\n(___)")); CHECK(nospaces(snowman(11143442)) == nospaces("_===_ \n(...)\n(.,-)\n/( )\n(\" \")")); } TEST_CASE("All Bases"){ // B CHECK(nospaces(snowman(11311211)) == nospaces("_===_ \n(...)\n(O,.)\n<( : )/\n( : )")); CHECK(nospaces(snowman(12221222)) == nospaces("_===_ \n(...)\n(o.o)\n<(] [)/\n(\" \")")); CHECK(nospaces(snowman(23133233)) == nospaces(" ___ \n ..... \n(._O)\n/(> <)/\n(___)")); CHECK(nospaces(snowman(11143144)) == nospaces("_===_ \n(...)\n(.,-)\n/( )>\n( )")); } TEST_CASE("Bad snowman code: short or long input") { CHECK_THROWS(nospaces(snowman(1111))); CHECK_THROWS(nospaces(snowman(123456789))); CHECK_THROWS(nospaces(snowman(0))); CHECK_THROWS(nospaces(snowman(-123))); } TEST_CASE("Bad snowman code: invalid letter") { CHECK_THROWS(nospaces(snowman(11234353))); CHECK_THROWS(nospaces(snowman(56789005))); CHECK_THROWS(nospaces(snowman(14232319))); }
35.421053
96
0.525791
shaiBonfil
8dbda768e6214c57f275a3994a6e46cb9fb44ef4
393
cpp
C++
pbe/src/pbe/Core/Math/Common.cpp
pavilbezpravil/pbEngine
55c051bdb296f0960ad05447d385a554334c4b5c
[ "Apache-2.0" ]
null
null
null
pbe/src/pbe/Core/Math/Common.cpp
pavilbezpravil/pbEngine
55c051bdb296f0960ad05447d385a554334c4b5c
[ "Apache-2.0" ]
null
null
null
pbe/src/pbe/Core/Math/Common.cpp
pavilbezpravil/pbEngine
55c051bdb296f0960ad05447d385a554334c4b5c
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "Common.h" #include <glm/gtx/matrix_decompose.hpp> std::tuple<glm::vec3, glm::quat, glm::vec3> GetTransformDecomposition(const glm::mat4& transform) { glm::vec3 scale, translation, skew; glm::vec4 perspective; glm::quat orientation; glm::decompose(transform, scale, orientation, translation, skew, perspective); return { translation, orientation, scale }; }
24.5625
97
0.740458
pavilbezpravil
8dc01928c6b39a89fb33198e40721f77c62e262f
5,077
cpp
C++
Modules/Core/vaMemory.cpp
magcius/CMAA2
8ceb0daa2afa6b12804da62631494d2ed4b31b53
[ "Apache-2.0" ]
110
2018-09-04T20:33:59.000Z
2021-12-17T08:46:11.000Z
Modules/Core/vaMemory.cpp
magcius/CMAA2
8ceb0daa2afa6b12804da62631494d2ed4b31b53
[ "Apache-2.0" ]
5
2018-09-05T20:57:08.000Z
2021-02-24T09:02:31.000Z
Modules/Core/vaMemory.cpp
magcius/CMAA2
8ceb0daa2afa6b12804da62631494d2ed4b31b53
[ "Apache-2.0" ]
20
2018-09-05T00:41:13.000Z
2021-08-04T01:31:50.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016, Intel Corporation // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of // the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Author(s): Filip Strugar (filip.strugar@intel.com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "vaMemory.h" using namespace VertexAsylum; #include "IntegratedExternals/vaAssimpIntegration.h" _CrtMemState s_memStateStart; void vaMemory::Initialize( ) { // initialize some of the annoying globals so they appear before the s_memStateStart checkpoint { #ifdef VA_ASSIMP_INTEGRATION_ENABLED { Assimp::Importer importer; static unsigned char s_simpleObj [] = {35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,86,101,114,116,105,99,101,115,58,32,56,13,10,35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,80,111,105,110,116,115,58,32,48,13,10,35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,76,105,110,101,115,58,32,48,13,10,35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,70,97,99,101,115,58,32,54,13,10,35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,77,97,116,101,114,105,97,108,115,58,32,49,13,10,13,10,111,32,49,13,10,13,10,35,32,86,101,114,116,101,120,32,108,105,115,116,13,10,13,10,118,32,45,48,46,53,32,45,48,46,53,32,48,46,53,13,10,118,32,45,48,46,53,32,45,48,46,53,32,45,48,46,53,13,10,118,32,45,48,46,53,32,48,46,53,32,45,48,46,53,13,10,118,32,45,48,46,53,32,48,46,53,32,48,46,53,13,10,118,32,48,46,53,32,45,48,46,53,32,48,46,53,13,10,118,32,48,46,53,32,45,48,46,53,32,45,48,46,53,13,10,118,32,48,46,53,32,48,46,53,32,45,48,46,53,13,10,118,32,48,46,53,32,48,46,53,32,48,46,53,13,10,13,10,35,32,80,111,105,110,116,47,76,105,110,101,47,70,97,99,101,32,108,105,115,116,13,10,13,10,117,115,101,109,116,108,32,68,101,102,97,117,108,116,13,10,102,32,52,32,51,32,50,32,49,13,10,102,32,50,32,54,32,53,32,49,13,10,102,32,51,32,55,32,54,32,50,13,10,102,32,56,32,55,32,51,32,52,13,10,102,32,53,32,56,32,52,32,49,13,10,102,32,54,32,55,32,56,32,53,13,10,13,10,35,32,69,110,100,32,111,102,32,102,105,108,101,13,10,}; const aiScene * scene = importer.ReadFileFromMemory( s_simpleObj, _countof(s_simpleObj), 0, "obj" ); scene; //const aiScene * scene = importer.ReadFile( "C:\\Work\\Art\\crytek-sponza-other\\banner.obj", 0 ); } #endif // not needed // #ifdef VA_ENKITS_INTEGRATION_ENABLED // { // enki::TaskScheduler tempTS; // tempTS.Initialize(); // } // #endif } { #if defined(DEBUG) || defined(_DEBUG) // _CrtSetDbgFlag( 0 // | _CRTDBG_ALLOC_MEM_DF // | _CRTDBG_CHECK_CRT_DF // | _CRTDBG_CHECK_EVERY_128_DF // | _CRTDBG_LEAK_CHECK_DF // ); vaCore::DebugOutput( L"CRT memory checkpoint start" ); _CrtMemCheckpoint( &s_memStateStart ); //_CrtSetBreakAlloc( 291 ); // <- if this didn't work, the allocation probably happens before Initialize() or is a global variable #endif } } void vaMemory::Deinitialize() { #if defined(DEBUG) || defined(_DEBUG) _CrtMemState memStateStop, memStateDiff; _CrtMemCheckpoint( &memStateStop ); vaCore::DebugOutput( L"Checking for memory leaks...\n" ); if( _CrtMemDifference( &memStateDiff, &s_memStateStart, &memStateStop ) ) { _CrtMemDumpStatistics( &memStateDiff ); // doesn't play nice with .net runtime _CrtDumpMemoryLeaks(); VA_WARN( L"Memory leaks detected - check debug output; using _CrtSetBreakAlloc( allocationIndex ) in vaMemory::Initialize() might help to track it down. " ); // note: assimp sometimes leaks during importing - that's benign assert( false ); } else { vaCore::DebugOutput( L"No memory leaks detected!\n" ); } #endif }
52.340206
1,446
0.637187
magcius
8dc09ebb1c96844d37a252c065006eefe7b439ea
2,919
cpp
C++
A07_Supersampling&Anti_aliasing/source/raytracing_stats.cpp
satoshiSchubert/MIT_6.837_CG
df17d4daafbdf2350d44076205a06f87593bbc4a
[ "MIT" ]
null
null
null
A07_Supersampling&Anti_aliasing/source/raytracing_stats.cpp
satoshiSchubert/MIT_6.837_CG
df17d4daafbdf2350d44076205a06f87593bbc4a
[ "MIT" ]
null
null
null
A07_Supersampling&Anti_aliasing/source/raytracing_stats.cpp
satoshiSchubert/MIT_6.837_CG
df17d4daafbdf2350d44076205a06f87593bbc4a
[ "MIT" ]
null
null
null
#include <stdio.h> #include "raytracing_stats.h" int RayTracingStats::width; int RayTracingStats::height; BoundingBox *RayTracingStats::bbox; int RayTracingStats::num_x; int RayTracingStats::num_y; int RayTracingStats::num_z; unsigned long long RayTracingStats::start_time; unsigned long long RayTracingStats::num_nonshadow_rays; unsigned long long RayTracingStats::num_shadow_rays; unsigned long long RayTracingStats::num_intersections; unsigned long long RayTracingStats::num_grid_cells_traversed; // ==================================================================== // ==================================================================== void RayTracingStats::Initialize(int _width, int _height, BoundingBox *_bbox, int nx, int ny, int nz) { width = _width; height = _height; bbox = _bbox; num_x = nx; num_y = ny; num_z = nz; start_time = time(NULL); num_nonshadow_rays = 0; num_shadow_rays = 0; num_intersections = 0; num_grid_cells_traversed = 0; } // ==================================================================== // ==================================================================== void RayTracingStats::PrintStatistics() { int delta_time = time(NULL) - start_time; if (delta_time == 0) delta_time = 1; int secs = delta_time % 60; int min = (delta_time / 60) % 60; int hours = delta_time / (60 * 60); int num_rays = num_nonshadow_rays + num_shadow_rays; float rays_per_sec = float(num_rays) / float(delta_time); float rays_per_pixel = float(num_rays) / float(width * height); float intersections_per_ray = num_intersections / float(num_rays); float traversed_per_ray = num_grid_cells_traversed / float(num_rays); printf("********************************************\n"); printf("RAY TRACING STATISTICS\n"); printf(" total time %ld:%02d:%02d\n", hours, min, secs); printf(" num pixels %d (%dx%d)\n", width * height, width, height); printf(" scene bounds "); if (bbox == NULL) printf("NULL\n"); else bbox->Print(); printf(" num grid cells "); if (num_x == 0) printf("NULL\n"); else printf("%d (%dx%dx%d)\n", num_x * num_y * num_z, num_x, num_y, num_z); printf(" num non-shadow rays %lld\n", num_nonshadow_rays); printf(" num shadow rays %lld\n", num_shadow_rays); printf(" total intersections %lld\n", num_intersections); printf(" total cells traversed %lld\n", num_grid_cells_traversed); printf(" rays per second %0.1f\n", rays_per_sec); printf(" rays per pixel %0.1f\n", rays_per_pixel); printf(" intersections per ray %0.1f\n", intersections_per_ray); printf(" cells traversed per ray %0.1f\n", traversed_per_ray); printf("********************************************\n"); } // ==================================================================== // ====================================================================
39.986301
103
0.566975
satoshiSchubert
8dc1efe285244301c8bc86b56fd353a27ed544a3
10,193
cpp
C++
Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
null
null
null
Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
null
null
null
Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
1
2019-01-09T08:20:18.000Z
2019-01-09T08:20:18.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) 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 "QmitkVolumeVisualizationView.h" #include <QComboBox> #include <vtkVersionMacros.h> #include <vtkSmartVolumeMapper.h> #include <berryISelectionProvider.h> #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> //#include <berryISelectionService.h> #include <mitkDataNodeObject.h> #include <mitkProperties.h> #include <mitkNodePredicateDataType.h> #include <mitkTransferFunction.h> #include <mitkTransferFunctionProperty.h> #include <mitkTransferFunctionInitializer.h> #include "mitkHistogramGenerator.h" #include "QmitkPiecewiseFunctionCanvas.h" #include "QmitkColorTransferFunctionCanvas.h" #include "mitkBaseRenderer.h" #include "mitkVtkVolumeRenderingProperty.h" #include <mitkIRenderingManager.h> #include <QToolTip> const std::string QmitkVolumeVisualizationView::VIEW_ID = "org.mitk.views.volumevisualization"; enum {DEFAULT_RENDERMODE = 0, RAYCAST_RENDERMODE = 1, GPU_RENDERMODE = 2}; QmitkVolumeVisualizationView::QmitkVolumeVisualizationView() : QmitkAbstractView(), m_Controls(nullptr) { } QmitkVolumeVisualizationView::~QmitkVolumeVisualizationView() { } void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { m_Controls = new Ui::QmitkVolumeVisualizationViewControls; m_Controls->setupUi(parent); // Fill the tf presets in the generator widget std::vector<std::string> names; mitk::TransferFunctionInitializer::GetPresetNames(names); for (std::vector<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) { m_Controls->m_TransferFunctionGeneratorWidget->AddPreset(QString::fromStdString(*it)); } // see enum in vtkSmartVolumeMapper m_Controls->m_RenderMode->addItem("Default"); m_Controls->m_RenderMode->addItem("RayCast"); m_Controls->m_RenderMode->addItem("GPU"); // see vtkVolumeMapper::BlendModes m_Controls->m_BlendMode->addItem("Comp"); m_Controls->m_BlendMode->addItem("Max"); m_Controls->m_BlendMode->addItem("Min"); m_Controls->m_BlendMode->addItem("Avg"); m_Controls->m_BlendMode->addItem("Add"); connect( m_Controls->m_EnableRenderingCB, SIGNAL( toggled(bool) ),this, SLOT( OnEnableRendering(bool) )); connect(m_Controls->m_RenderMode, SIGNAL(activated(int)), this, SLOT(OnRenderMode(int))); connect(m_Controls->m_BlendMode, SIGNAL(activated(int)), this, SLOT(OnBlendMode(int))); connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL( SignalUpdateCanvas( ) ), m_Controls->m_TransferFunctionWidget, SLOT( OnUpdateCanvas( ) ) ); connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)), SLOT(OnMitkInternalPreset(int))); m_Controls->m_EnableRenderingCB->setEnabled(false); m_Controls->m_BlendMode->setEnabled(false); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); } } void QmitkVolumeVisualizationView::OnMitkInternalPreset( int mode ) { if (m_SelectedNode.IsNull()) return; mitk::DataNode::Pointer node(m_SelectedNode.GetPointer()); mitk::TransferFunctionProperty::Pointer transferFuncProp; if (node->GetProperty(transferFuncProp, "TransferFunction")) { //first item is only information if( --mode == -1 ) return; // -- Creat new TransferFunction mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue()); tfInit->SetTransferFunctionMode(mode); RequestRenderWindowUpdate(); m_Controls->m_TransferFunctionWidget->OnUpdateCanvas(); } } void QmitkVolumeVisualizationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList<mitk::DataNode::Pointer>& nodes) { bool weHadAnImageButItsNotThreeDeeOrFourDee = false; mitk::DataNode::Pointer node; for (mitk::DataNode::Pointer currentNode: nodes) { if( currentNode.IsNotNull() && dynamic_cast<mitk::Image*>(currentNode->GetData()) ) { if( dynamic_cast<mitk::Image*>(currentNode->GetData())->GetDimension()>=3 ) { if (node.IsNull()) { node = currentNode; } } else { weHadAnImageButItsNotThreeDeeOrFourDee = true; } } } if( node.IsNotNull() ) { m_Controls->m_NoSelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_SelectedImageLabel->show(); std::string infoText; if (node->GetName().empty()) infoText = std::string("Selected Image: [currently selected image has no name]"); else infoText = std::string("Selected Image: ") + node->GetName(); m_Controls->m_SelectedImageLabel->setText( QString( infoText.c_str() ) ); m_SelectedNode = node; } else { if(weHadAnImageButItsNotThreeDeeOrFourDee) { m_Controls->m_NoSelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->show(); std::string infoText; infoText = std::string("only 3D or 4D images are supported"); m_Controls->m_ErrorImageLabel->setText( QString( infoText.c_str() ) ); } else { m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_NoSelectedImageLabel->show(); } m_SelectedNode = 0; } UpdateInterface(); } void QmitkVolumeVisualizationView::UpdateInterface() { if(m_SelectedNode.IsNull()) { // turnoff all m_Controls->m_EnableRenderingCB->setChecked(false); m_Controls->m_EnableRenderingCB->setEnabled(false); m_Controls->m_BlendMode->setCurrentIndex(0); m_Controls->m_BlendMode->setEnabled(false); m_Controls->m_RenderMode->setCurrentIndex(0); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->SetDataNode(0); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); return; } bool enabled = false; m_SelectedNode->GetBoolProperty("volumerendering",enabled); m_Controls->m_EnableRenderingCB->setEnabled(true); m_Controls->m_EnableRenderingCB->setChecked(enabled); if(!enabled) { // turnoff all except volumerendering checkbox m_Controls->m_BlendMode->setCurrentIndex(0); m_Controls->m_BlendMode->setEnabled(false); m_Controls->m_RenderMode->setCurrentIndex(0); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->SetDataNode(0); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); return; } // otherwise we can activate em all m_Controls->m_BlendMode->setEnabled(true); m_Controls->m_RenderMode->setEnabled(true); // Determine Combo Box mode { bool usegpu=false; bool useray=false; bool usemip=false; m_SelectedNode->GetBoolProperty("volumerendering.usegpu",usegpu); m_SelectedNode->GetBoolProperty("volumerendering.useray",useray); m_SelectedNode->GetBoolProperty("volumerendering.usemip",usemip); int blendMode; if (m_SelectedNode->GetIntProperty("volumerendering.blendmode", blendMode)) m_Controls->m_BlendMode->setCurrentIndex(blendMode); if (usemip) m_Controls->m_BlendMode->setCurrentIndex(vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND); int mode = DEFAULT_RENDERMODE; if (useray) mode = RAYCAST_RENDERMODE; else if(usegpu) mode = GPU_RENDERMODE; m_Controls->m_RenderMode->setCurrentIndex(mode); } m_Controls->m_TransferFunctionWidget->SetDataNode(m_SelectedNode); m_Controls->m_TransferFunctionWidget->setEnabled(true); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(m_SelectedNode); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(true); } void QmitkVolumeVisualizationView::OnEnableRendering(bool state) { if(m_SelectedNode.IsNull()) return; m_SelectedNode->SetProperty("volumerendering",mitk::BoolProperty::New(state)); UpdateInterface(); RequestRenderWindowUpdate(); } void QmitkVolumeVisualizationView::OnBlendMode(int mode) { if (m_SelectedNode.IsNull()) return; bool usemip = false; if (mode == vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND) usemip = true; m_SelectedNode->SetProperty("volumerendering.usemip", mitk::BoolProperty::New(usemip)); m_SelectedNode->SetProperty("volumerendering.blendmode", mitk::IntProperty::New(mode)); RequestRenderWindowUpdate(); } void QmitkVolumeVisualizationView::OnRenderMode(int mode) { if(m_SelectedNode.IsNull()) return; bool usegpu = false; if (mode == GPU_RENDERMODE) usegpu = true; bool useray = false; if (mode == RAYCAST_RENDERMODE) useray = true; if (mode == DEFAULT_RENDERMODE) { useray = true; usegpu = true; } m_SelectedNode->SetProperty("volumerendering.usegpu",mitk::BoolProperty::New(usegpu)); m_SelectedNode->SetProperty("volumerendering.useray",mitk::BoolProperty::New(useray)); RequestRenderWindowUpdate(); } void QmitkVolumeVisualizationView::SetFocus() { } void QmitkVolumeVisualizationView::NodeRemoved(const mitk::DataNode* node) { if(m_SelectedNode == node) { m_SelectedNode=0; m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_NoSelectedImageLabel->show(); UpdateInterface(); } }
29.544928
161
0.725596
ZP-Hust
8dc461f2b0926fdcb082a53c68d6b1ab7f4e71fa
6,020
cc
C++
supersonic/cursor/core/aggregate_scalar_test.cc
ruccsbingo/parallel_supersonic
e21f866b46d00f606d2d0d472346bfb140fa3aba
[ "Apache-2.0" ]
null
null
null
supersonic/cursor/core/aggregate_scalar_test.cc
ruccsbingo/parallel_supersonic
e21f866b46d00f606d2d0d472346bfb140fa3aba
[ "Apache-2.0" ]
null
null
null
supersonic/cursor/core/aggregate_scalar_test.cc
ruccsbingo/parallel_supersonic
e21f866b46d00f606d2d0d472346bfb140fa3aba
[ "Apache-2.0" ]
null
null
null
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 "supersonic/utils/scoped_ptr.h" #include "supersonic/base/infrastructure/projector.h" #include "supersonic/cursor/base/cursor.h" #include "supersonic/cursor/base/cursor_transformer.h" #include "supersonic/cursor/core/aggregate.h" #include "supersonic/cursor/core/spy.h" #include "supersonic/proto/supersonic.pb.h" #include "supersonic/testing/block_builder.h" #include "supersonic/testing/comparators.h" #include "supersonic/testing/operation_testing.h" #include "gtest/gtest.h" namespace supersonic { class ScalarAggregateCursorTest : public testing::Test { protected: virtual void CreateSampleData() { sample_input_builder_.AddRow("f") .AddRow("c") .AddRow("a") .AddRow("b") .AddRow("g") .AddRow("a") .AddRow("d") .AddRow("a") .AddRow(__) .AddRow("e"); sample_output_builder_.AddRow("g", 10, 9, 7); } CompoundSingleSourceProjector empty_projector_; TestDataBuilder<STRING> sample_input_builder_; TestDataBuilder<STRING, UINT64, UINT64, UINT64> sample_output_builder_; }; TEST_F(ScalarAggregateCursorTest, AggregateIntegers) { OperationTest test; test.SetInput(TestDataBuilder<INT32>() .AddRow(13) .AddRow(3) .AddRow(3) .AddRow(__) .AddRow(7) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64, UINT64>() .AddRow(13, 26, 5, 4, 3) .Build()); scoped_ptr<AggregationSpecification> aggregator(new AggregationSpecification); aggregator->AddAggregation(MAX, "col0", "max"); aggregator->AddAggregation(SUM, "col0", "sum"); aggregator->AddAggregation(COUNT, "", "count(*)"); aggregator->AddAggregation(COUNT, "col0", "count"); aggregator->AddDistinctAggregation(COUNT, "col0", "count distinct"); test.Execute(ScalarAggregate(aggregator.release(), test.input())); } TEST_F(ScalarAggregateCursorTest, AggregateEmptyInput) { OperationTest test; test.SetInput(TestDataBuilder<INT32>().Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64, UINT64>() .AddRow(__, __, 0, 0, 0) .Build()); scoped_ptr<AggregationSpecification> aggregator(new AggregationSpecification); aggregator->AddAggregation(MAX, "col0", "max"); aggregator->AddAggregation(SUM, "col0", "sum"); aggregator->AddAggregation(COUNT, "", "count(*)"); aggregator->AddAggregation(COUNT, "col0", "count"); aggregator->AddDistinctAggregation(COUNT, "col0", "count distinct"); test.Execute(ScalarAggregate(aggregator.release(), test.input())); } TEST_F(ScalarAggregateCursorTest, AggregateStrings) { OperationTest test; CreateSampleData(); test.SetInput(sample_input_builder_.Build()); test.SetExpectedResult(sample_output_builder_.Build()); scoped_ptr<AggregationSpecification> aggregator(new AggregationSpecification); aggregator->AddAggregation(MAX, "col0", "max"); aggregator->AddAggregation(COUNT, "", "count(*)"); aggregator->AddAggregation(COUNT, "col0", "count"); aggregator->AddDistinctAggregation(COUNT, "col0", "count distinct"); test.Execute(ScalarAggregate(aggregator.release(), test.input())); } TEST_F(ScalarAggregateCursorTest, AggregateStringsWithSpyTransform) { CreateSampleData(); Cursor* input = sample_input_builder_.BuildCursor(); scoped_ptr<Cursor> expected_result(sample_output_builder_.BuildCursor()); scoped_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(MAX, "col0", "max"); aggregation->AddAggregation(COUNT, "", "count(*)"); aggregation->AddAggregation(COUNT, "col0", "count"); aggregation->AddDistinctAggregation(COUNT, "col0", "count distinct"); FailureOrOwned<Aggregator> aggregator = Aggregator::Create( *aggregation, input->schema(), HeapBufferAllocator::Get(), 1); ASSERT_TRUE(aggregator.is_success()); scoped_ptr<Cursor> aggregate(BoundScalarAggregate(aggregator.release(), input)); scoped_ptr<CursorTransformerWithSimpleHistory> spy_transformer( PrintingSpyTransformer()); aggregate->ApplyToChildren(spy_transformer.get()); aggregate.reset(spy_transformer->Transform(aggregate.release())); EXPECT_CURSORS_EQUAL(expected_result.release(), aggregate.release()); } TEST_F(ScalarAggregateCursorTest, TransformTest) { // Empty input cursor. Cursor* input = sample_input_builder_.BuildCursor(); scoped_ptr<AggregationSpecification> aggregation( new AggregationSpecification); FailureOrOwned<Aggregator> aggregator = Aggregator::Create( *aggregation, input->schema(), HeapBufferAllocator::Get(), 1); ASSERT_TRUE(aggregator.is_success()); scoped_ptr<Cursor> aggregate(BoundScalarAggregate(aggregator.release(), input)); scoped_ptr<CursorTransformerWithSimpleHistory> spy_transformer( PrintingSpyTransformer()); aggregate->ApplyToChildren(spy_transformer.get()); ASSERT_EQ(1, spy_transformer->GetHistoryLength()); EXPECT_EQ(input, spy_transformer->GetEntryAt(0)->original()); } } // namespace supersonic
40.133333
80
0.691694
ruccsbingo
8dc4be40baf57c5481b922d3345f37176d7c3963
1,937
cpp
C++
tests/Ontology/AddressTests.cpp
baophucct/wallet-core
9583b45d732fa442f73090c02903a97f09dff6a8
[ "MIT" ]
null
null
null
tests/Ontology/AddressTests.cpp
baophucct/wallet-core
9583b45d732fa442f73090c02903a97f09dff6a8
[ "MIT" ]
null
null
null
tests/Ontology/AddressTests.cpp
baophucct/wallet-core
9583b45d732fa442f73090c02903a97f09dff6a8
[ "MIT" ]
1
2019-03-11T08:54:14.000Z
2019-03-11T08:54:14.000Z
// Copyright © 2017-2019 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "PublicKey.h" #include "HexCoding.h" #include "Ontology/Signer.h" #include "Ontology/Address.h" #include <gtest/gtest.h> using namespace TW; using namespace TW::Ontology; TEST(OntologyAddress, validation) { ASSERT_FALSE(Address::isValid("abc")); ASSERT_FALSE(Address::isValid("abeb60f3e94c1b9a09f33669435e7ef12eacd")); ASSERT_FALSE(Address::isValid("abcb60f3e94c9b9a09f33669435e7ef1beaedads")); ASSERT_TRUE(Address::isValid("ANDfjwrUroaVtvBguDtrWKRMyxFwvVwnZD")); } TEST(OntologyAddress, fromPubKey) { auto address = Address(PublicKey(parse_hex("031bec1250aa8f78275f99a6663688f31085848d0ed92f1203e447125f927b7486"))); EXPECT_EQ("AeicEjZyiXKgUeSBbYQHxsU1X3V5Buori5", address.string()); } TEST(OntologyAddress, fromString) { auto b58Str = "AYTxeseHT5khTWhtWX1pFFP1mbQrd4q1zz"; auto address = Address(b58Str); EXPECT_EQ(b58Str, address.string()); auto errB58Str = "AATxeseHT5khTWhtWX1pFFP1mbQrd4q1zz"; ASSERT_THROW(new Address(errB58Str), std::runtime_error); } TEST(OntologyAddress, fromMultiPubKeys) { auto signer1 = Signer(PrivateKey(parse_hex("4646464646464646464646464646464646464646464646464646464646464646"))); auto signer2 = Signer(PrivateKey(parse_hex("4646464646464646464646464646464646464646464646464646464646464652"))); auto signer3 = Signer(PrivateKey(parse_hex("4646464646464646464646464646464646464646464646464646464646464658"))); std::vector<Data> pubKeys{signer1.getPublicKey().bytes, signer2.getPublicKey().bytes, signer3.getPublicKey().bytes}; uint8_t m = 2; auto multiAddress = Address(m, pubKeys); EXPECT_EQ("AYGWgijVZnrUa2tRoCcydsHUXR1111DgdW", multiAddress.string()); }
43.044444
120
0.782137
baophucct
8dc52cbb04c435ac9f0f19ca3807c7f4486c6c31
273
cpp
C++
Stack_DSA/Stack_DSA/main.cpp
AlexStoyanova/DSA-FMI
512c925665b63e1c0934954ff26c2b1b755c10a7
[ "MIT" ]
1
2019-12-22T23:37:32.000Z
2019-12-22T23:37:32.000Z
Stack_DSA/Stack_DSA/main.cpp
AlexStoyanova/DSA-FMI
512c925665b63e1c0934954ff26c2b1b755c10a7
[ "MIT" ]
null
null
null
Stack_DSA/Stack_DSA/main.cpp
AlexStoyanova/DSA-FMI
512c925665b63e1c0934954ff26c2b1b755c10a7
[ "MIT" ]
null
null
null
#include <iostream> #include "Stack.h" int main() { Stack<int> stack(6); stack.peek(); stack.push(1); stack.push(5); std::cout << stack.peek() << std::endl; stack.pop(); std::cout << stack.peek() << std::endl; std::cout << stack.size() << std::endl; return 0; }
16.058824
40
0.593407
AlexStoyanova
44ef77164d82668b870baabd6ceb74c9317b7813
3,902
cpp
C++
thirdparty/vesta/interaction/ObserverController.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
6
2018-09-05T12:41:59.000Z
2021-07-01T05:34:23.000Z
thirdparty/vesta/interaction/ObserverController.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-02-07T19:09:21.000Z
2015-08-14T03:15:42.000Z
thirdparty/vesta/interaction/ObserverController.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-03-25T15:50:31.000Z
2017-12-06T12:16:47.000Z
/* * $Revision: 223 $ $Date: 2010-03-30 05:44:44 -0700 (Tue, 30 Mar 2010) $ * * Copyright by Astos Solutions GmbH, Germany * * this file is published under the Astos Solutions Free Public License * For details on copyright and terms of use see * http://www.astos.de/Astos_Solutions_Free_Public_License.html */ #include "ObserverController.h" #include "../WorldGeometry.h" #include "../Debug.h" #include <cmath> using namespace vesta; using namespace Eigen; using namespace std; ObserverController::ObserverController() : m_orbitAngularVelocity(Vector3d::Zero()), m_panAngularVelocity(Vector3d::Zero()), m_dollyVelocity(1.0), m_rotationDampingFactor(5.0) { } ObserverController::~ObserverController() { } /** Update the position and orientation of the observer. * * \param dt the amount of real time in seconds elapsed since the last tick */ void ObserverController::tick(double dt) { double damping = exp(-dt * m_rotationDampingFactor); m_orbitAngularVelocity *= damping; m_panAngularVelocity *= damping; m_dollyVelocity = pow(m_dollyVelocity, damping); double w = m_orbitAngularVelocity.norm(); if (w > 1.0e-6) { m_observer->orbit(Quaterniond(AngleAxisd(w * dt, m_orbitAngularVelocity / w))); } w = m_panAngularVelocity.norm(); if (w > 1.0e-6) { m_observer->rotate(Quaterniond(AngleAxisd(w * dt, m_panAngularVelocity / w))); } if (abs(m_dollyVelocity - 1.0) > 1.0e-6) { Entity* center = m_observer->center(); double f = pow(m_dollyVelocity, dt * 1000.0); if (center) { // Special case for world geometry, where the distance is to the surface of the // planet, not the center. // TODO: It would be a better design to have a method that reports the appropriate // distance to use for any geometry. WorldGeometry* world = dynamic_cast<WorldGeometry*>(center->geometry()); if (world) { double distance = m_observer->position().norm() - world->maxRadius(); m_observer->setPosition(m_observer->position().normalized() * (world->maxRadius() + distance * f)); } else { m_observer->changeDistance(f); } } } } /** Apply a torque to the observer that causes it to rotate * about its center. */ void ObserverController::applyTorque(const Vector3d& torque) { m_panAngularVelocity += torque; } /** Apply a 'torque' that causes the observer to rotate about the * center object. */ void ObserverController::applyOrbitTorque(const Vector3d& torque) { m_orbitAngularVelocity += torque; } /** Rotate the observer about its local x axis (horizontal axis on * the screen. */ void ObserverController::pitch(double f) { applyTorque(Vector3d::UnitX() * f); } /** Rotate the observer about its local y axis (vertical axis on * the screen. */ void ObserverController::yaw(double f) { applyTorque(Vector3d::UnitY() * f); } /** Rotate the observer about its local z axis (which points out of * the screen back toward the user.) */ void ObserverController::roll(double f) { applyTorque(Vector3d::UnitZ() * f); } /** Move the camera along a line between the positions of the observer and * the object of interest. The rate of movement varies exponentially with * the distance to the object of interest. A factor of less than one moves * the observer toward the object of interest, and a factor greater than * one moves the observer away. */ void ObserverController::dolly(double factor) { m_dollyVelocity *= factor; } /** Stop all translational and rotational motion. */ void ObserverController::stop() { m_dollyVelocity = 1.0; m_panAngularVelocity = Vector3d::Zero(); m_orbitAngularVelocity = Vector3d::Zero(); }
25.337662
115
0.665812
hoehnp
44f4a9ce8b35aade21fe0e1c36d12bf44fc6deea
2,978
cpp
C++
Client/test/SCPort.cpp
ecmwf/ecflow
2498d0401d3d1133613d600d5c0e0a8a30b7b8eb
[ "Apache-2.0" ]
11
2020-08-07T14:42:45.000Z
2021-10-21T01:59:59.000Z
Client/test/SCPort.cpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
10
2020-08-07T14:36:27.000Z
2022-02-22T06:51:24.000Z
Client/test/SCPort.cpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
6
2020-08-07T14:34:38.000Z
2022-01-10T12:06:27.000Z
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // Name : // Author : Avi // Revision : $Revision: #8 $ // // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Description : /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 #include <iostream> #include "SCPort.hpp" #include "EcfPortLock.hpp" #include "ClientInvoker.hpp" #include "ClientEnvironment.hpp" #include "Str.hpp" namespace ecf { // init the globals. Note we dont use 3141, so that in the case where we already // have a remote/local server started external to the test, it does not clash // Also debug and release version use different port numbers to avoid clashes, if both tests run at same time #ifdef DEBUG int SCPort::thePort_ = 3161; #else int SCPort::thePort_ = 3144; #endif std::string SCPort::next() { bool debug = false; if ( getenv("ECF_DEBUG_TEST") ) debug = true; if (debug) std::cout << "\nSCPort::next() : "; // Allow parallel tests char* ECF_FREE_PORT = getenv("ECF_FREE_PORT"); if ( ECF_FREE_PORT ) { if (debug) std::cout << " seed_port=ECF_FREE_PORT=(" << ECF_FREE_PORT << ")"; std::string port = ECF_FREE_PORT; try { thePort_ = boost::lexical_cast<int>(port);} catch (...){ std::cout << "SCPort::next() ECF_FREE_PORT(" << ECF_FREE_PORT << ") not convertible to an integer\n";} } // This is used to test remote servers(or legacy server with new client). Here ECF_HOST=localhost in the test scripts std::string host = ClientEnvironment::hostSpecified(); if (debug) std::cout << " ECF_HOST('" << host << "')"; if ( host == Str::LOCALHOST() ) { char* ecf_port = getenv("ECF_PORT"); if ( ecf_port ) { std::string port = ecf_port; if (!port.empty()) { if (debug) std::cout << " ECF_PORT('" << ecf_port << "')\n"; return port; } } if (debug) std::cout << " !!!!!! ERROR when ECF_HOST=localhost EXPECTED ECF_PORT to be set !!!!!! "; } if (debug) std::cout << "\n"; std::string the_port = next_only(debug); if (debug) std::cout << " SCPort::next() returning free port=" << the_port << "\n"; return the_port; } std::string SCPort::next_only(bool debug) { if (debug) std::cout << " SCPort::next_only : starting seed_port(" << thePort_ << ")\n"; // Use a combination of local lock file, and pinging the server while (!EcfPortLock::is_free(thePort_,debug)) thePort_++; if (debug) std::cout << " SCPort::next_only() seed_port(" << thePort_ << ")\n"; return ClientInvoker::find_free_port(thePort_,debug); } }
33.840909
123
0.613163
ecmwf
44f5b7070c312aa09d95f6581dc550ece247e151
279
hpp
C++
src/pkao_util.hpp
SkyTemple/ppmdu
9731ea103affd66f2e8c1202c9acb2ebfd4c9924
[ "CC0-1.0" ]
37
2015-10-30T21:56:26.000Z
2021-11-30T15:33:26.000Z
src/pkao_util.hpp
SkyTemple/ppmdu
9731ea103affd66f2e8c1202c9acb2ebfd4c9924
[ "CC0-1.0" ]
27
2015-01-06T05:45:55.000Z
2020-01-29T21:40:22.000Z
src/pkao_util.hpp
SkyTemple/ppmdu
9731ea103affd66f2e8c1202c9acb2ebfd4c9924
[ "CC0-1.0" ]
8
2016-02-07T23:31:03.000Z
2020-07-12T08:51:41.000Z
#ifndef PKAO_UTIL_HPP #define PKAO_UTIL_HPP /* pkao_util.hpp 2014/11/02 psycommando@gmail.com Description: Function for running the kaomado utility command line tool! */ namespace pkao_util { //Runs the tool //int RunPKaoUtil( int argc, const char * argv[] ); }; #endif
17.4375
72
0.738351
SkyTemple
44f6c833a316625f1aec35de8f1722bfcaa615d8
922
hpp
C++
include/mizuiro/color/format/homogenous_ns/types/pointer.hpp
cpreh/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
1
2015-08-22T04:19:39.000Z
2015-08-22T04:19:39.000Z
include/mizuiro/color/format/homogenous_ns/types/pointer.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
include/mizuiro/color/format/homogenous_ns/types/pointer.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef MIZUIRO_COLOR_FORMAT_HOMOGENOUS_NS_TYPES_POINTER_HPP_INCLUDED #define MIZUIRO_COLOR_FORMAT_HOMOGENOUS_NS_TYPES_POINTER_HPP_INCLUDED #include <mizuiro/apply_const.hpp> #include <mizuiro/access/pointer.hpp> #include <mizuiro/color/format/homogenous_ns/tag.hpp> #include <mizuiro/color/types/pointer_ns/tag.hpp> namespace mizuiro::color::types::pointer_ns { template <typename Access, typename Format, typename Constness> mizuiro::apply_const<mizuiro::access::pointer<Access, typename Format::channel_type *>, Constness> pointer_adl( mizuiro::color::types::pointer_ns::tag, Access, mizuiro::color::format::homogenous_ns::tag<Format>, Constness); } #endif
32.928571
98
0.752711
cpreh
44f77fe752355062d0b3ad2abb6b9fb2d2e89117
4,910
cpp
C++
inference-engine/tests/functional/shared_test_classes/src/subgraph/reshape_permute_conv_permute_reshape_act.cpp
NikDemoShow/openvino
31907e51e96f1603753dc69811bdf738374ca5e6
[ "Apache-2.0" ]
1
2020-07-07T10:13:00.000Z
2020-07-07T10:13:00.000Z
inference-engine/tests/functional/shared_test_classes/src/subgraph/reshape_permute_conv_permute_reshape_act.cpp
NikDemoShow/openvino
31907e51e96f1603753dc69811bdf738374ca5e6
[ "Apache-2.0" ]
105
2020-06-04T00:23:29.000Z
2022-02-21T13:04:33.000Z
inference-engine/tests/functional/shared_test_classes/src/subgraph/reshape_permute_conv_permute_reshape_act.cpp
v-Golubev/openvino
26936d1fbb025c503ee43fe74593ee9d7862ab15
[ "Apache-2.0" ]
4
2021-04-02T08:48:38.000Z
2021-07-01T06:59:02.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "shared_test_classes/subgraph/reshape_permute_conv_permute_reshape_act.hpp" namespace SubgraphTestsDefinitions { std::string ConvReshapeAct::getTestCaseName(testing::TestParamInfo<ConvReshapeActParams> obj) { InferenceEngine::Precision netPrecision; std::string targetName; std::array<size_t, 4> input_shape; std::array<size_t, 2> kernel_shape; size_t output_channels; std::map<std::string, std::string> configuration; std::tie(netPrecision, targetName, input_shape, kernel_shape, output_channels, configuration) = obj.param; std::ostringstream results; results << "IS=" << CommonTestUtils::vec2str(std::vector<size_t>(input_shape.begin(), input_shape.end())) << "_"; results << "KS=" << CommonTestUtils::vec2str(std::vector<size_t>(kernel_shape.begin(), kernel_shape.end())) << "_"; results << "OC=" << output_channels << "_"; results << "netPRC=" << netPrecision.name() << "_"; results << "targetDevice=" << targetName; return results.str(); } void ConvReshapeAct::SetUp() { InferenceEngine::Precision netPrecision; std::array<size_t, 4> input_shape; std::array<size_t, 2> kernel_shape; size_t output_channels; std::map<std::string, std::string> additional_config; std::tie(netPrecision, targetDevice, input_shape, kernel_shape, output_channels, additional_config) = this->GetParam(); configuration.insert(additional_config.begin(), additional_config.end()); const std::size_t input_dim = std::accumulate(input_shape.begin(), input_shape.end(), 1, std::multiplies<size_t>()); auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision); std::vector<size_t> input_dims { 1, input_dim }; std::vector<size_t> reshape_in_dims = std::vector<size_t>(input_shape.begin(), input_shape.end()); std::vector<size_t> permute_in_order = { 0, 3, 1, 2 }; std::vector<size_t> permute_out_order = { 0, 2, 3, 1 }; std::vector<size_t> reshape_out_dims = { 1, input_shape[0] * input_shape[1] * (input_shape[2] - kernel_shape[1] + 1) * output_channels }; auto input_parameter = ngraph::builder::makeParams(ngPrc, {input_dims}); auto reshape_in_pattern = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{4}, reshape_in_dims); auto reshape_in = std::make_shared<ngraph::op::v1::Reshape>(input_parameter[0], reshape_in_pattern, false); auto permute_in_params = std::make_shared<ngraph::opset1::Constant>(ngraph::element::i64, ngraph::Shape{4}, ngraph::Shape{permute_in_order}); auto permute_in = std::make_shared<ngraph::opset1::Transpose>(reshape_in, permute_in_params); auto conv = ngraph::builder::makeConvolution(permute_in, ngPrc, {kernel_shape[0], kernel_shape[1]}, {1, 1}, {0, 0}, {0, 0}, {1, 1}, ngraph::op::PadType::VALID, output_channels); auto permute_out_params = std::make_shared<ngraph::opset1::Constant>(ngraph::element::i64, ngraph::Shape{4}, permute_out_order); auto permute_out = std::make_shared<ngraph::opset1::Transpose>(conv, permute_out_params); auto reshape_out_pattern = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{2}, std::vector<size_t>{reshape_out_dims}); auto reshape_out = std::make_shared<ngraph::op::v1::Reshape>(permute_out, reshape_out_pattern, false); auto tanh = std::make_shared<ngraph::op::Tanh>(reshape_out); function = std::make_shared<ngraph::Function>(tanh, input_parameter, "conv_reshape_act"); } void ConvReshapeAct::Run() { SKIP_IF_CURRENT_TEST_IS_DISABLED() LoadNetwork(); inferRequest = executableNetwork.CreateInferRequest(); inputs.clear(); for (const auto &input : cnnNetwork.getInputsInfo()) { const auto &info = input.second; auto tensorDesc = info->getTensorDesc(); auto blob = FuncTestUtils::createAndFillBlobFloat(tensorDesc, 2, -1, 100, 111); FuncTestUtils::fillInputsBySinValues(blob); inferRequest.SetBlob(info->name(), blob); inputs.push_back(blob); } if (configuration.count(InferenceEngine::PluginConfigParams::KEY_DYN_BATCH_ENABLED) && configuration.count(InferenceEngine::PluginConfigParams::YES)) { auto batchSize = cnnNetwork.getInputsInfo().begin()->second->getTensorDesc().getDims()[0] / 2; inferRequest.SetBatch(batchSize); } inferRequest.Infer(); threshold = 0.1; Validate(); } } // namespace SubgraphTestsDefinitions
45.462963
145
0.658656
NikDemoShow
44f99489ab1e36fc67b8b82f4daf4bf263a0c57a
55,164
cpp
C++
src/slam/Debug.cpp
meitiever/SLAM-BA
57ee2af8508300e818feb67f7adbe026eee3ada7
[ "MIT" ]
null
null
null
src/slam/Debug.cpp
meitiever/SLAM-BA
57ee2af8508300e818feb67f7adbe026eee3ada7
[ "MIT" ]
null
null
null
src/slam/Debug.cpp
meitiever/SLAM-BA
57ee2af8508300e818feb67f7adbe026eee3ada7
[ "MIT" ]
null
null
null
/* +-----------------------------------+ | | | *** Debugging functionality *** | | | | Copyright (c) -tHE SWINe- 2015 | | | | Debug.cpp | | | +-----------------------------------+ */ /** * @file src/slam/Debug.cpp * @brief basic debugging functionality * @author -tHE SWINe- * @date 2015-10-07 */ #include "slam/Debug.h" #include <csparse/cs.hpp> #include "slam/Tga.h" #include "slam/Parser.h" #include "slam/BlockMatrix.h" #include <math.h> #include <cmath> /* * === globals === */ #if !defined(_WIN32) && !defined(_WIN64) #include <stdio.h> #include <ctype.h> #include <string.h> // sprintf bool _finite(double x) { #ifdef __FAST_MATH__ // handle https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25975 char p_s_str[256]; size_t l = sprintf(p_s_str, "%f", x); // total number of characters written is returned, this count does not include the additional null //size_t l = strlen(p_s_str); std::transform(p_s_str, p_s_str + l, p_s_str, tolower); return !strstr(p_s_str, "nan") && !strstr(p_s_str, "ind") && !strstr(p_s_str, "inf"); // https://en.wikipedia.org/wiki/NaN#Display #else // __FAST_MATH__ //return isfinite(x); // math.h, did not work in some later versions of g++ return std::isfinite(x); // cmath, should work #endif // __FAST_MATH__ } bool _isnan(double x) { #ifdef __FAST_MATH__ // handle https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25975 char p_s_str[256]; size_t l = sprintf(p_s_str, "%f", x); // total number of characters written is returned, this count does not include the additional null //size_t l = strlen(p_s_str); std::transform(p_s_str, p_s_str + l, p_s_str, tolower); return strstr(p_s_str, "nan") != 0 || strstr(p_s_str, "ind") != 0; // https://en.wikipedia.org/wiki/NaN#Display #else // __FAST_MATH__ //return isnan(x); // math.h, should work return std::isnan(x); // cmath, should work #endif // __FAST_MATH__ } #endif // !_WIN32 && !_WIN64 /* * === ~globals === */ /* * === CDebug::CSparseMatrixShapedIterator === */ CDebug::CSparseMatrixShapedIterator::CSparseMatrixShapedIterator(const cs *p_matrix) :m_p_matrix(p_matrix), m_n_rows(p_matrix->m), m_n_columns(p_matrix->n), m_n_column(0), m_n_row(0), m_n_row_pointer(p_matrix->p[0]), m_n_row_pointer_column_end(p_matrix->p[1]), m_n_row_pointer_end(p_matrix->p[p_matrix->n]) { if(m_n_row_pointer <= m_n_row_pointer_column_end) { size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { size_t p = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column] : m_n_row_pointer_end, e = (m_n_column + 1 < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } } CDebug::CSparseMatrixShapedIterator::CSparseMatrixShapedIterator(const cs *p_matrix, size_t n_rows, size_t n_cols) :m_p_matrix(p_matrix), m_n_rows(n_rows), m_n_columns(n_cols), m_n_column(0), m_n_row(0), m_n_row_pointer(p_matrix->p[0]), m_n_row_pointer_column_end(p_matrix->p[1]), m_n_row_pointer_end(p_matrix->p[p_matrix->n]) { if(m_n_row_pointer <= m_n_row_pointer_column_end) { size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { size_t p = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column] : m_n_row_pointer_end, e = (m_n_column + 1 < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } } double CDebug::CSparseMatrixShapedIterator::operator *() const { _ASSERTE(m_n_column < m_n_columns && m_n_row < m_n_rows); // make sure the iterator is dereferencable if(m_n_row_pointer < m_n_row_pointer_column_end) { _ASSERTE(unsigned(m_p_matrix->i[m_n_row_pointer]) >= m_n_row); if(size_t(m_p_matrix->i[m_n_row_pointer]) == m_n_row) return (m_p_matrix->x)? m_p_matrix->x[m_n_row_pointer] : 1; } return 0; // no data (outside the matrix or being in "sparse area") } double CDebug::CSparseMatrixShapedIterator::f_Get(bool &r_b_value) const { _ASSERTE(m_n_column < m_n_columns && m_n_row < m_n_rows); // make sure the iterator is dereferencable if(m_n_row_pointer < m_n_row_pointer_column_end) { _ASSERTE(unsigned(m_p_matrix->i[m_n_row_pointer]) >= m_n_row); if(size_t(m_p_matrix->i[m_n_row_pointer]) == m_n_row) { r_b_value = true; return (m_p_matrix->x)? m_p_matrix->x[m_n_row_pointer] : 1; } } r_b_value = false; return 0; // no data (outside the matrix or being in "sparse area") } void CDebug::CSparseMatrixShapedIterator::operator ++() { _ASSERTE(m_n_column < m_n_columns); _ASSERTE(m_n_row < m_n_rows); // make sure we're not iterating too far if(m_n_column >= unsigned(m_p_matrix->n)) { if(++ m_n_row == m_n_rows) { m_n_row = 0; ++ m_n_column; } // we are below the matrix data, just iterating zeroes } else if(m_n_row >= unsigned(m_p_matrix->m)) { if(++ m_n_row == m_n_rows) { m_n_row = 0; ++ m_n_column; _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); /*if(m_n_column <= m_p_matrix->n) */ { // always true // m_p_matrix->n is a valid index in p (sets m_n_row_pointer_offset equal to m_n_row_pointer_end) m_n_row_pointer = m_p_matrix->p[m_n_column]; m_n_row_pointer_column_end = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; } } // we are right of the matrix data, just iterating zeroes (the same code) } else { if(++ m_n_row == m_n_rows) { m_n_row = 0; ++ m_n_column; _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); /*if(m_n_column <= m_p_matrix->n) */ { // always true // m_p_matrix->n is a valid index in p (sets m_n_row_pointer_offset equal to m_n_row_pointer_end) m_n_row_pointer = m_p_matrix->p[m_n_column]; m_n_row_pointer_column_end = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; } } // shift to the next row / column size_t p = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column] : m_n_row_pointer_end, e = (m_n_column + 1 < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; _ASSERTE(e >= p); _ASSERTE(m_n_row_pointer_column_end == e); _ASSERTE(m_n_row_pointer >= p && m_n_row_pointer <= e); // note that m_n_row_pointer == e is a valid state in case there is not enough data on the row // we are inside the matrix data; just need to find row in the CSC array if(m_n_row_pointer <= m_n_row_pointer_column_end) { // have to check if we hit the last nonzero row in the column size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; while(n_data_row < m_n_row && m_n_row_pointer < m_n_row_pointer_column_end) n_data_row = m_p_matrix->i[++ m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } // makes sure that m_n_row_pointer points to an element at the current or greater } _ASSERTE((m_n_column < m_n_columns && m_n_row < m_n_rows) || (m_n_column == m_n_columns && !m_n_row)); // make sure we are still inside, or just outside if(m_n_column < unsigned(m_p_matrix->n)) { #ifdef _DEBUG size_t p = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column] : m_n_row_pointer_end, e = (m_n_column + 1 < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; #endif // _DEBUG _ASSERTE(m_n_row_pointer_column_end == e); if(m_n_row < unsigned(m_p_matrix->m)) { _ASSERTE(m_n_row_pointer == e || m_n_row <= unsigned(m_p_matrix->i[m_n_row_pointer])); // either we are at the end of data, or m_n_row_pointer points at or after current row } else { _ASSERTE(m_n_row_pointer == e); // we are at the end of the row for sure } } else { _ASSERTE(m_n_row_pointer == m_n_row_pointer_end); _ASSERTE(m_n_row_pointer_column_end == m_n_row_pointer_end); // we are at the end } // iterator integrity check } /* * === ~CDebug::CSparseMatrixShapedIterator === */ /* * === CDebug::CSparseMatrixIterator === */ CDebug::CSparseMatrixIterator::CSparseMatrixIterator(const cs *p_matrix) :m_p_matrix(p_matrix), m_n_column(0), m_n_row(0), m_n_row_pointer(p_matrix->p[0]), m_n_row_pointer_column_end(p_matrix->p[1]) { if(m_n_row_pointer <= m_n_row_pointer_column_end) { size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { size_t p = m_p_matrix->p[m_n_column], e = (m_n_column + 1 <= size_t(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : p; for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } } double CDebug::CSparseMatrixIterator::operator *() const { _ASSERTE(m_n_column < unsigned(m_p_matrix->n) && m_n_row < unsigned(m_p_matrix->m)); // make sure the iterator is dereferencable if(m_n_row_pointer < m_n_row_pointer_column_end) { _ASSERTE(unsigned(m_p_matrix->i[m_n_row_pointer]) >= m_n_row); if(size_t(m_p_matrix->i[m_n_row_pointer]) == m_n_row) return (m_p_matrix->x)? m_p_matrix->x[m_n_row_pointer] : 1; } return 0; // no data (being in "sparse area") } void CDebug::CSparseMatrixIterator::operator ++() { _ASSERTE(m_n_column < unsigned(m_p_matrix->n)); _ASSERTE(m_n_row < unsigned(m_p_matrix->m)); // make sure we're not iterating too far { if(++ m_n_row == size_t(m_p_matrix->m)) { m_n_row = 0; ++ m_n_column; _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); /*if(m_n_column <= m_p_matrix->n) */ { // always true // m_p_matrix->n is a valid index in p (sets m_n_row_pointer_offset equal to the ebd) m_n_row_pointer = m_p_matrix->p[m_n_column]; m_n_row_pointer_column_end = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer; // m_n_row_pointer == p_matrix->p[p_matrix->n] by then _ASSERTE(m_n_column < unsigned(m_p_matrix->n) || m_n_row_pointer == m_p_matrix->p[m_p_matrix->n]); // just to make sure } } // shift to the next row / column _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); size_t p = m_p_matrix->p[m_n_column], e = (m_n_column + 1 <= unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : p; _ASSERTE(e >= p); _ASSERTE(m_n_row_pointer_column_end == e); _ASSERTE(m_n_row_pointer >= p && m_n_row_pointer <= e); // note that m_n_row_pointer == e is a valid state in case there is not enough data on the row // we are inside the matrix data; just need to find row in the CSC array if(m_n_row_pointer <= m_n_row_pointer_column_end) { // have to check if we hit the last nonzero row in the column size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; while(n_data_row < m_n_row && m_n_row_pointer < m_n_row_pointer_column_end) n_data_row = m_p_matrix->i[++ m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } // makes sure that m_n_row_pointer points to an element at the current or greater } _ASSERTE((m_n_column < unsigned(m_p_matrix->n) && m_n_row < unsigned(m_p_matrix->m)) || (m_n_column == m_p_matrix->n && !m_n_row)); // make sure we are still inside, or just outside if(m_n_column < unsigned(m_p_matrix->n)) { _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); #ifdef _DEBUG size_t p = m_p_matrix->p[m_n_column], e = (m_n_column + 1 <= size_t(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : p; #endif // _DEBUG _ASSERTE(m_n_row_pointer_column_end == e); if(m_n_row < unsigned(m_p_matrix->m)) { _ASSERTE(m_n_row_pointer == e || m_n_row <= unsigned(m_p_matrix->i[m_n_row_pointer])); // either we are at the end of data, or m_n_row_pointer points at or after current row } else { _ASSERTE(m_n_row_pointer == e); // we are at the end of the row for sure } } else { _ASSERTE(m_n_row_pointer == m_n_row_pointer_column_end); _ASSERTE(m_n_row_pointer_column_end == m_p_matrix->p[m_p_matrix->n]); // we are at the end } // iterator integrity check } /* * === ~CDebug::CSparseMatrixIterator === */ /* * === CDebug === */ bool CDebug::Dump_SparseMatrix(const char *p_s_filename, const cs *A, const cs *A_prev /*= 0*/, int n_scalar_size /*= 5*/) { _ASSERTE(CS_CSC(A)); _ASSERTE(!A_prev || CS_CSC(A_prev)); // the matrices need to be in compressed column form const uint32_t n_background = 0xffffffffU, n_nonzero = 0xff8080ffU, n_nonzero_new = 0xffff0000U, n_zero_new = 0xff00ff00U; // colors of the individual areas const uint32_t n_nonzero_border = 0x80000000U | ((n_nonzero >> 1) & 0x7f7f7f7fU), n_nonzero_new_border = 0x80000000U | ((n_nonzero_new >> 1) & 0x7f7f7f7fU), n_zero_new_border = 0x80000000U | ((n_zero_new >> 1) & 0x7f7f7f7fU); // colors of borders (just darker) size_t m = (A_prev)? std::max(A->m, A_prev->m) : A->m; size_t n = (A_prev)? std::max(A->n, A_prev->n) : A->n; if(m == SIZE_MAX || n == SIZE_MAX || m > INT_MAX || n > INT_MAX || m * (n_scalar_size - 1) + 1 > INT_MAX || n * (n_scalar_size - 1) + 1 > INT_MAX || uint64_t(m * (n_scalar_size - 1) + 1) * (m * (n_scalar_size - 1) + 1) > INT_MAX) return false; TBmp *p_bitmap; if(!(p_bitmap = TBmp::p_Alloc(int(n * (n_scalar_size - 1) + 1), int(m * (n_scalar_size - 1) + 1)))) return false; p_bitmap->Clear(n_background); if(A_prev) { CSparseMatrixShapedIterator p_a_it(A, m, n); CSparseMatrixShapedIterator p_a_prev_it(A_prev, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it, ++ p_a_prev_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); _ASSERTE(n_row == p_a_prev_it.n_Row() && n_col == p_a_prev_it.n_Column()); // make sure it iterates to the right position bool b_is; double f_value = p_a_it.f_Get(b_is);// = *p_a_it; double f_prev_value = *p_a_prev_it; // read the value double f_value_thr = (fabs(f_value) < 1e-10)? 0 : f_value; double f_prev_value_thr = (fabs(f_prev_value) < 1e-10)? 0 : f_prev_value; // threshold if(b_is || f_value != 0 || f_prev_value != 0) { uint32_t n_fill_color = (f_value_thr != 0 && f_prev_value_thr != 0)? n_nonzero : (f_value_thr != 0 && f_prev_value_thr == 0)? n_nonzero_new : (f_value != 0 && f_prev_value != 0)? n_nonzero : n_zero_new; uint32_t n_line_color = (f_value_thr != 0 && f_prev_value_thr != 0)? n_nonzero_border : (f_value_thr != 0 && f_prev_value_thr == 0)? n_nonzero_new_border : (f_value != 0 && f_prev_value != 0)? n_nonzero_border : n_zero_new_border; size_t n_x = n_col * (n_scalar_size - 1); size_t n_y = n_row * (n_scalar_size - 1); for(int dy = 1; dy < n_scalar_size - 1; ++ dy) for(int dx = 1; dx < n_scalar_size - 1; ++ dx) p_bitmap->PutPixel(int(n_x + dx), int(n_y + dy), n_fill_color); p_bitmap->DrawLine_SP(float(n_x), float(n_y), float(n_x + n_scalar_size - 1), float(n_y), n_line_color); p_bitmap->DrawLine_SP(float(n_x), float(n_y + n_scalar_size - 1), float(n_x + n_scalar_size - 1), float(n_y + n_scalar_size - 1), n_line_color); p_bitmap->DrawLine_SP(float(n_x), float(n_y), float(n_x), float(n_y + n_scalar_size - 1), n_line_color); p_bitmap->DrawLine_SP(float(n_x + n_scalar_size - 1), float(n_y), float(n_x + n_scalar_size - 1), float(n_y + n_scalar_size - 1), n_line_color); } // draw a square into the bitmap } } } else { CSparseMatrixShapedIterator p_a_it(A, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); // make sure it iterates to the right position double f_value = *p_a_it; // read the value if(f_value != 0) { size_t n_x = n_col * (n_scalar_size - 1); size_t n_y = n_row * (n_scalar_size - 1); for(int dy = 1; dy < n_scalar_size - 1; ++ dy) for(int dx = 1; dx < n_scalar_size - 1; ++ dx) p_bitmap->PutPixel(int(n_x + dx), int(n_y + dy), n_nonzero); p_bitmap->DrawLine_SP(float(n_x), float(n_y), float(n_x + n_scalar_size - 1), float(n_y), n_nonzero_border); p_bitmap->DrawLine_SP(float(n_x), float(n_y + n_scalar_size - 1), float(n_x + n_scalar_size - 1), float(n_y + n_scalar_size - 1), n_nonzero_border); p_bitmap->DrawLine_SP(float(n_x), float(n_y), float(n_x), float(n_y + n_scalar_size - 1), n_nonzero_border); p_bitmap->DrawLine_SP(float(n_x + n_scalar_size - 1), float(n_y), float(n_x + n_scalar_size - 1), float(n_y + n_scalar_size - 1), n_nonzero_border); } // draw a square into the bitmap } } } // iterate the matrix, draw small tiles bool b_result = CTgaCodec::Save_TGA(p_s_filename, *p_bitmap, false); p_bitmap->Delete(); /*for(int j = 0; j < n; ++ j) { //printf(" col %d\n", j); int y = 0; if(j < A->n) { for(int p = A->p[j]; p < A->p[j + 1]; ++ p, ++ y) { int n_cur_y = A->i[p]; for(; y < n_cur_y; ++ y) ;//printf(" %f, ", .0f); // zero entries double f_value = (A->x)? A->x[p] : 1; // nonzero entry } for(; y < m; ++ y) ;//printf(" %f%s", .0f, (x + 1 == m)? "\n" : ", "); // zero entries } }*/ // t_odo - make this an iterator anyway // t_odo - rasterize the matrix (A_prev is used to mark difference areas) // todo - implement libPNG image writing return b_result; } static inline void PutPixel_Max(TBmp *p_bitmap, int x, int y, uint32_t n_color) { uint32_t *p_buffer = p_bitmap->p_buffer; const int n_width = p_bitmap->n_width; const int n_height = p_bitmap->n_height; if(x >= 0 && x < n_width && y >= 0 && y < n_height) { uint32_t &r_n_pixel = p_buffer[int(x) + n_width * int(y)]; if((r_n_pixel & 0xffffff) < (n_color & 0xffffff)) r_n_pixel = n_color; } } #define BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS // optimize bitmap write routines to access the bitmaps row-wise for better cache reuse #define BITMAP_SUBSAMPLE_DUMP_PARALLELIZE // parallelize Dump_SparseMatrix_Subsample() and Dump_SparseMatrix_Subsample_AA() (only if BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS is defined) bool CDebug::Dump_SparseMatrix_Subsample(const char *p_s_filename, const cs *A, const cs *A_prev /*= 0*/, size_t n_max_bitmap_size /*= 640*/, bool b_symmetric /*= false*/) { _ASSERTE(CS_CSC(A)); _ASSERTE(!A_prev || CS_CSC(A_prev)); // the matrices need to be in compressed column form const uint32_t n_background = 0xffffffffU, n_nonzero = 0xff8080ffU, n_nonzero_new = 0xffff0000U, n_zero_new = 0xff00ff00U; // colors of the individual areas size_t m = (A_prev)? std::max(A->m, A_prev->m) : A->m; size_t n = (A_prev)? std::max(A->n, A_prev->n) : A->n; size_t mb = m, nb = n; double f_scale = double(n_max_bitmap_size) / std::max(m, n); if(f_scale < 1) { mb = std::max(size_t(1), size_t(m * f_scale)); nb = std::max(size_t(1), size_t(n * f_scale)); } else f_scale = 1; // scale the bitmap down if needed if(mb == SIZE_MAX || nb == SIZE_MAX || mb > INT_MAX || nb > INT_MAX || uint64_t(mb) * nb > INT_MAX) return false; TBmp *p_bitmap; #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(!(p_bitmap = TBmp::p_Alloc(int(mb), int(nb)))) // transposed return false; #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(!(p_bitmap = TBmp::p_Alloc(int(nb), int(mb)))) return false; #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(A_prev) { p_bitmap->Clear(0/*n_background*/); CSparseMatrixShapedIterator p_a_it(A, m, n); CSparseMatrixShapedIterator p_a_prev_it(A_prev, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it, ++ p_a_prev_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); _ASSERTE(n_row == p_a_prev_it.n_Row() && n_col == p_a_prev_it.n_Column()); // make sure it iterates to the right position bool b_is; double f_value = p_a_it.f_Get(b_is);// = *p_a_it; double f_prev_value = *p_a_prev_it; // read the value double f_value_thr = (fabs(f_value) < 1e-10)? 0 : f_value; double f_prev_value_thr = (fabs(f_prev_value) < 1e-10)? 0 : f_prev_value; // threshold if(b_is || f_value != 0 || f_prev_value != 0) { uint32_t n_fill_color = (f_value_thr != 0 && f_prev_value_thr != 0)? 1/*n_nonzero*/ : (f_value_thr != 0 && f_prev_value_thr == 0)? 3/*n_nonzero_new*/ : (f_value != 0 && f_prev_value != 0)? 1/*n_nonzero*/ : 2/*n_zero_new*/; #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS size_t n_y = size_t(n_col * f_scale); size_t n_x = size_t(n_row * f_scale); // transposed #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS size_t n_x = size_t(n_col * f_scale); size_t n_y = size_t(n_row * f_scale); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS PutPixel_Max(p_bitmap, /*->PutPixel(*/int(n_x), int(n_y), n_fill_color); //if(b_symmetric && n_x != n_y) // PutPixel_Max(p_bitmap, /*->PutPixel(*/int(n_y), int(n_x), n_fill_color); // use PutPixel_Max() to get some deterministic precedences of the colors } // draw a dot into the bitmap } } if(b_symmetric) { uint32_t *p_buff = p_bitmap->p_buffer; for(size_t x = 0, w = p_bitmap->n_width, h = p_bitmap->n_height, s = std::min(w, h); x < s; ++ x) { for(size_t y = 0; y < x; ++ y) { // only the upper triangle _ASSERTE(x < w && y < h); uint32_t *p_up = p_buff + (x + w * y); _ASSERTE(y < w && x < h); uint32_t *p_lo = p_buff + (y + x * w); *p_up = std::max(*p_up, *p_lo); // choose the "color" with higher priority *p_lo = *p_up; // duplicate the result to the other triangle as well } } } // if symmetric, transpose the raster to save half the time on very large matrices uint32_t p_color_table[] = {n_background, n_nonzero, n_zero_new, n_nonzero_new}; for(uint32_t *p_buffer = p_bitmap->p_buffer, *p_end = p_bitmap->p_buffer + nb * mb; p_buffer != p_end; ++ p_buffer) { _ASSERTE(*p_buffer < sizeof(p_color_table) / sizeof(p_color_table[0])); *p_buffer = p_color_table[*p_buffer]; } // look the color table up } else { p_bitmap->Clear(n_background); /*CSparseMatrixShapedIterator p_a_it(A, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); // make sure it iterates to the right position*/ #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS #ifdef BITMAP_SUBSAMPLE_DUMP_PARALLELIZE if(n < INT_MAX && A->p[n] >= 10000) { const int _n = int(n); #pragma omp parallel for schedule(dynamic, 1) for(int n_col = 0; n_col < _n; ++ n_col) { for(size_t n_p0 = A->p[n_col], n_p1 = A->p[n_col + 1]; n_p0 != n_p1; ++ n_p0) { size_t n_row = A->i[n_p0]; double f_value = (A->x)? A->x[n_p0] : 1; // read the value if(f_value != 0) p_bitmap->PutPixel(int(n_row * f_scale), int(n_col * f_scale), n_nonzero); // draw a dot into the bitmap } } } else #endif // BITMAP_SUBSAMPLE_DUMP_PARALLELIZE { for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_p0 = A->p[n_col], n_p1 = A->p[n_col + 1]; n_p0 != n_p1; ++ n_p0) { size_t n_row = A->i[n_p0]; const double f_one = 1, *p_a_it = (A->x)? A->x + n_p0 : &f_one; #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS { CSparseMatrixIterator p_a_it(A); // can use the simple iterator here for(; p_a_it.n_Column() < n; ++ p_a_it) { size_t n_col = p_a_it.n_Column(); size_t n_row = p_a_it.n_Row(); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS double f_value = *p_a_it; // read the value if(f_value != 0) { #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS size_t n_y = size_t(n_col * f_scale); size_t n_x = size_t(n_row * f_scale); // transposed #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS size_t n_x = size_t(n_col * f_scale); size_t n_y = size_t(n_row * f_scale); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS p_bitmap->PutPixel(int(n_x), int(n_y), n_nonzero); //if(b_symmetric && n_x != n_y) // p_bitmap->PutPixel(int(n_y), int(n_x), n_nonzero); } // draw a square into the bitmap } } } if(b_symmetric) { uint32_t *p_buff = p_bitmap->p_buffer; for(size_t x = 0, w = p_bitmap->n_width, h = p_bitmap->n_height, s = std::min(w, h); x < s; ++ x) { for(size_t y = 0; y < x; ++ y) { // only the upper triangle _ASSERTE(x < w && y < h); uint32_t *p_up = p_buff + (x + w * y); _ASSERTE(y < w && x < h); uint32_t *p_lo = p_buff + (y + x * w); *p_up = std::min(*p_up, *p_lo); // choose the darker color *p_lo = *p_up; // duplicate the result to the other triangle as well } } } // if symmetric, transpose the raster to save half the time on very large matrices } // iterate the matrix, draw small tiles #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if((m != n || !b_symmetric) && !p_bitmap->Transpose()) { p_bitmap->Delete(); return false; } #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS bool b_result = CTgaCodec::Save_TGA(p_s_filename, *p_bitmap, false); p_bitmap->Delete(); return b_result; } static inline void AlphaBlend_RGBA_HQ(uint32_t &r_n_dest, uint32_t n_src, float f_alpha) { int n_dest_a = (r_n_dest >> 24) & 0xff; int n_dest_r = (r_n_dest >> 16) & 0xff; int n_dest_g = (r_n_dest >> 8) & 0xff; int n_dest_b = (r_n_dest) & 0xff; int n_src_a = (n_src >> 24) & 0xff; int n_src_r = (n_src >> 16) & 0xff; int n_src_g = (n_src >> 8) & 0xff; int n_src_b = (n_src) & 0xff; n_dest_a = std::max(0, std::min(255, int(n_dest_a + f_alpha * (n_src_a - n_dest_a) + .5f))); n_dest_r = std::max(0, std::min(255, int(n_dest_r + f_alpha * (n_src_r - n_dest_r) + .5f))); n_dest_g = std::max(0, std::min(255, int(n_dest_g + f_alpha * (n_src_g - n_dest_g) + .5f))); n_dest_b = std::max(0, std::min(255, int(n_dest_b + f_alpha * (n_src_b - n_dest_b) + .5f))); r_n_dest = (n_dest_a << 24) | (n_dest_r << 16) | (n_dest_g << 8) | n_dest_b; } static inline void PutPixel_AA_RGBA_HQ(TBmp *p_bitmap, float f_x, float f_y, uint32_t n_color) { uint32_t *p_buffer = p_bitmap->p_buffer; const int n_width = p_bitmap->n_width; const int n_height = p_bitmap->n_height; int x = int(floor(f_x)), y = int(floor(f_y)); float f_frac_x = f_x - x; float f_frac_y = f_y - y; const float f_alpha = ((n_color >> 24) & 0xff) / 255.0f; // alpha of the incoming pixel float f_weight_00 = (f_alpha * (1 - f_frac_x) * (1 - f_frac_y)); float f_weight_10 = (f_alpha * f_frac_x * (1 - f_frac_y)); float f_weight_01 = (f_alpha * (1 - f_frac_x) * f_frac_y); float f_weight_11 = (f_alpha * f_frac_x * f_frac_y); if(x >= 0 && x < n_width && y >= 0 && y < n_height) AlphaBlend_RGBA_HQ(p_buffer[x + n_width * y], n_color, f_weight_00); if(x + 1 >= 0 && x + 1 < n_width && y >= 0 && y < n_height) AlphaBlend_RGBA_HQ(p_buffer[(x + 1) + n_width * y], n_color, f_weight_10); if(x >= 0 && x < n_width && y + 1 >= 0 && y + 1 < n_height) AlphaBlend_RGBA_HQ(p_buffer[x + n_width * (y + 1)], n_color, f_weight_01); if(x + 1 >= 0 && x + 1 < n_width && y + 1 >= 0 && y + 1 < n_height) AlphaBlend_RGBA_HQ(p_buffer[(x + 1) + n_width * (y + 1)], n_color, f_weight_11); } static inline void AlphaBlend_Float(float &r_f_dest, float f_src, float f_alpha) { //r_f_dest = (r_f_dest * (1 - f_alpha)) + f_src * f_alpha; //r_f_dest = r_f_dest * 1 + f_src * f_alpha - r_f_dest * f_alpha; //r_f_dest = r_f_dest + (f_src - r_f_dest) * f_alpha; r_f_dest = r_f_dest + f_alpha * (f_src - r_f_dest); } static inline void PutPixel_AA_Float(TBmp *p_bitmap, float f_x, float f_y) // this is likely quite slow { _ASSERTE(sizeof(float) == sizeof(uint32_t)); float *p_buffer = (float*)p_bitmap->p_buffer; const int n_width = p_bitmap->n_width; const int n_height = p_bitmap->n_height; int x = int(floor(f_x)), y = int(floor(f_y)); float f_frac_x = f_x - x; float f_frac_y = f_y - y; const float f_alpha = 1; // alpha of the incoming pixel float f_weight_00 = (f_alpha * (1 - f_frac_x) * (1 - f_frac_y)); float f_weight_10 = (f_alpha * f_frac_x * (1 - f_frac_y)); float f_weight_01 = (f_alpha * (1 - f_frac_x) * f_frac_y); float f_weight_11 = (f_alpha * f_frac_x * f_frac_y); if(x >= 0 && x < n_width && y >= 0 && y < n_height) AlphaBlend_Float(p_buffer[x + n_width * y], 1, f_weight_00); if(x + 1 >= 0 && x + 1 < n_width && y >= 0 && y < n_height) AlphaBlend_Float(p_buffer[(x + 1) + n_width * y], 1, f_weight_10); if(x >= 0 && x < n_width && y + 1 >= 0 && y + 1 < n_height) AlphaBlend_Float(p_buffer[x + n_width * (y + 1)], 1, f_weight_01); if(x + 1 >= 0 && x + 1 < n_width && y + 1 >= 0 && y + 1 < n_height) AlphaBlend_Float(p_buffer[(x + 1) + n_width * (y + 1)], 1, f_weight_11); } bool CDebug::Dump_SparseMatrix_Subsample_AA(const char *p_s_filename, const cs *A, const cs *A_prev /*= 0*/, size_t n_max_bitmap_size /*= 640*/, bool b_symmetric /*= false*/) { _ASSERTE(CS_CSC(A)); _ASSERTE(!A_prev || CS_CSC(A_prev)); // the matrices need to be in compressed column form const uint32_t n_background = 0x00ffffffU, n_nonzero = 0xff8080ffU, n_nonzero_new = 0xffff0000U, n_zero_new = 0xff00ff00U; // colors of the individual areas size_t m = (A_prev)? std::max(A->m, A_prev->m) : A->m; size_t n = (A_prev)? std::max(A->n, A_prev->n) : A->n; size_t mb = m, nb = n; double f_scale = double(n_max_bitmap_size) / std::max(m, n); if(f_scale < 1) { mb = std::max(size_t(1), size_t(m * f_scale)); nb = std::max(size_t(1), size_t(n * f_scale)); } else f_scale = 1; // scale the bitmap down if needed if(mb == SIZE_MAX || nb == SIZE_MAX || mb > INT_MAX || nb > INT_MAX || uint64_t(mb) * nb > INT_MAX) return false; TBmp *p_bitmap; #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(!(p_bitmap = TBmp::p_Alloc(int(mb), int(nb)))) // transposed return false; #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(!(p_bitmap = TBmp::p_Alloc(int(nb), int(mb)))) return false; #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS // t_odo - dont use p_bitmap->PutPixel_AA(), the division of 0-255 by 256 diminishes // the color, yielding black pixels in cases of extreme overdraw. use a float // buffer or a fraction buffer instead if(A_prev) { p_bitmap->Clear(n_background); CSparseMatrixShapedIterator p_a_it(A, m, n); CSparseMatrixShapedIterator p_a_prev_it(A_prev, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it, ++ p_a_prev_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); _ASSERTE(n_row == p_a_prev_it.n_Row() && n_col == p_a_prev_it.n_Column()); // make sure it iterates to the right position bool b_is; double f_value = p_a_it.f_Get(b_is);// = *p_a_it; double f_prev_value = *p_a_prev_it; // read the value double f_value_thr = (fabs(f_value) < 1e-10)? 0 : f_value; double f_prev_value_thr = (fabs(f_prev_value) < 1e-10)? 0 : f_prev_value; // threshold if(b_is || f_value != 0 || f_prev_value != 0) { uint32_t n_fill_color = (f_value_thr != 0 && f_prev_value_thr != 0)? n_nonzero : (f_value_thr != 0 && f_prev_value_thr == 0)? n_nonzero_new : (f_value != 0 && f_prev_value != 0)? n_nonzero : n_zero_new; #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS float f_y = float(n_col * f_scale); float f_x = float(n_row * f_scale); // transposed #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS float f_x = float(n_col * f_scale); float f_y = float(n_row * f_scale); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS PutPixel_AA_RGBA_HQ(p_bitmap, /*->PutPixel_AA(*/f_x, f_y, n_fill_color); //if(b_symmetric && f_x != f_y) // PutPixel_AA_RGBA_HQ(p_bitmap, /*->PutPixel_AA(*/f_y, f_x, n_fill_color); // t_odo - float rgba? some more elaborate reweighting? } // draw a dot into the bitmap } } if(b_symmetric) { uint32_t *p_buff = p_bitmap->p_buffer; for(size_t x = 0, w = p_bitmap->n_width, h = p_bitmap->n_height, s = std::min(w, h); x < s; ++ x) { for(size_t y = 0; y < x; ++ y) { // only the upper triangle _ASSERTE(x < w && y < h); uint32_t *p_up = p_buff + (x + w * y); _ASSERTE(y < w && x < h); uint32_t *p_lo = p_buff + (y + x * w); AlphaBlend_RGBA_HQ(*p_up, *p_lo, ((*p_lo >> 24) & 0xff) / 255.0f); // blend the two colors *p_lo = *p_up; // duplicate the result in the other triangle as well } } } // if symmetric, transpose the raster to save half the time on very large matrices } else { _ASSERTE(sizeof(float) == sizeof(uint32_t)); std::fill((float*)p_bitmap->p_buffer, ((float*)p_bitmap->p_buffer) + nb * mb, .0f); // use as a float buffer /*CSparseMatrixShapedIterator p_a_it(A, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); // make sure it iterates to the right position*/ #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS #ifdef BITMAP_SUBSAMPLE_DUMP_PARALLELIZE if(n > 16 && n < INT_MAX && A->p[n] >= 10000) { size_t n_half_stripe_num = nb / 8 - 1; // want four-pixel stripes with at least four pixel clearance (the blend will overflow up to two pixels - one on the left, one on the right from each stripe), want the last one to be wider than the others _ASSERTE(n_half_stripe_num < INT_MAX); const int _n_half_stripe_num = int(n_half_stripe_num); for(int n_pass = 0; n_pass < 2; ++ n_pass) { // draw even stripes in one pass, odd stripes in the next, this guarantees that two threads never blend over each other's area #pragma omp parallel for schedule(dynamic, 1) for(int n_stripe = 0; n_stripe < _n_half_stripe_num; ++ n_stripe) { // each thread processes a single stripe size_t n_stripe_b = (n / n_half_stripe_num) * n_stripe; size_t n_stripe_e = (n_stripe + 1 == _n_half_stripe_num)? n : n_stripe_b + n / n_half_stripe_num; _ASSERTE(n_stripe_e >= n_stripe_b + 8); if(n_pass) n_stripe_b = (n_stripe_b + n_stripe_e) / 2; else n_stripe_e = (n_stripe_b + n_stripe_e) / 2; _ASSERTE(n_stripe_e >= n_stripe_b + 2); // begin and end of a stripe for(size_t n_col = n_stripe_b; n_col < n_stripe_e; ++ n_col) { for(size_t n_p0 = A->p[n_col], n_p1 = A->p[n_col + 1]; n_p0 != n_p1; ++ n_p0) { size_t n_row = A->i[n_p0]; double f_value = (A->x)? A->x[n_p0] : 1; // read the value if(f_value != 0) PutPixel_AA_Float(p_bitmap, float(n_row * f_scale), float(n_col * f_scale)); // draw a dot into the bitmap } } } // implicit thread synchronization here } } else #endif // BITMAP_SUBSAMPLE_DUMP_PARALLELIZE { for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_p0 = A->p[n_col], n_p1 = A->p[n_col + 1]; n_p0 != n_p1; ++ n_p0) { size_t n_row = A->i[n_p0]; const double f_one = 1, *p_a_it = (A->x)? A->x + n_p0 : &f_one; #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS { CSparseMatrixIterator p_a_it(A); // can use the simple iterator here for(; p_a_it.n_Column() < n; ++ p_a_it) { size_t n_col = p_a_it.n_Column(); size_t n_row = p_a_it.n_Row(); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS double f_value = *p_a_it; // read the value if(f_value != 0) { #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS float f_y = float(n_col * f_scale); float f_x = float(n_row * f_scale); // transposed #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS float f_x = float(n_col * f_scale); float f_y = float(n_row * f_scale); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS PutPixel_AA_Float(p_bitmap, /*->PutPixel_AA(*/f_x, f_y/*, n_nonzero*/); //if(b_symmetric && f_x != f_y) // PutPixel_AA_Float(p_bitmap, /*->PutPixel_AA(*/f_y, f_x/*, n_nonzero*/); } // draw a square into the bitmap } } } // alpha = 0 // alpha = 0 + a1 * (1 - 0) = a1 // alpha = a1 + a2 * (1 - a1) = a1 + a2 - a1a2 // // alpha = 0 // alpha = 0 + a2 * (1 - 0) = a2 // alpha = a2 + a1 * (1 - a2) = a2 + a1 - a1a2 // the order of blending does not make a difference if(b_symmetric) { float *p_buff = (float*)p_bitmap->p_buffer; for(size_t x = 0, w = p_bitmap->n_width, h = p_bitmap->n_height, s = std::min(w, h); x < s; ++ x) { for(size_t y = 0; y < x; ++ y) { // only the upper triangle _ASSERTE(x < w && y < h); float *p_up = p_buff + (x + w * y); _ASSERTE(y < w && x < h); float *p_lo = p_buff + (y + x * w); AlphaBlend_Float(*p_up, 1, *p_lo); // blend the two alphas *p_lo = *p_up; // duplicate the result in the other triangle as well } } } // if symmetric, transpose the raster to save half the time on very large matrices for(float *p_buffer = (float*)p_bitmap->p_buffer, *p_end = p_buffer + nb * mb; p_buffer != p_end; ++ p_buffer) { float f_alpha = *p_buffer; int n_alpha = std::min(255, std::max(0, int(255 * f_alpha))); *(uint32_t*)p_buffer = TBmp::n_Modulate(n_background, 255 - n_alpha) + TBmp::n_Modulate(n_nonzero, n_alpha); // integer blend should be enough now, only once per pixel } // convert float buffer to RGBA } // iterate the matrix, draw small tiles #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if((m != n || !b_symmetric) && !p_bitmap->Transpose()) { p_bitmap->Delete(); return false; } #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS bool b_result = CTgaCodec::Save_TGA(p_s_filename, *p_bitmap, false); p_bitmap->Delete(); return b_result; } void CDebug::Print_SparseMatrix(const cs *A, const char *p_s_label /*= 0*/) { if(p_s_label) printf("matrix \'%s\' = ", p_s_label); csi m, n, nzmax, /*nz,*/ *Ap, *Ai; double *Ax; if(!A) { printf("(null)\n"); return; } cs *Ac = 0; if(CS_TRIPLET(A) && !(Ac = cs_compress(A))) { printf("[not enough memory]\n"); return; } cs *At; if(!(At = cs_transpose((Ac)? Ac : A, 1))) { if(Ac) cs_spfree(Ac); printf("[not enough memory]\n"); return; } m = At->m; n = At->n; Ap = At->p; Ai = At->i; Ax = At->x; nzmax = At->nzmax; //nz = At->nz; // unused _ASSERTE(CS_CSC(At)); { _ASSERTE(n <= INT_MAX); _ASSERTE(m <= INT_MAX); _ASSERTE(nzmax <= INT_MAX); _ASSERTE(Ap[n] <= INT_MAX); printf("%d-by-%d, nzmax: %d nnz: %d, 1-norm: %g\n", int(n), int(m), int(nzmax), int(Ap[n]), cs_norm(A)); for(csi j = 0; j < n; ++ j) { printf(" row %d\n", int(j)); int x = 0; for(csi p = Ap[j]; p < Ap[j + 1]; ++ p, ++ x) { csi n_cur_x = Ai[p]; for(; x < n_cur_x; ++ x) printf(" %f, ", .0f); printf("%s%f%s", (Ax && Ax[p] < 0)? "" : " ", (Ax)? Ax[p] : 1, (n_cur_x + 1 == m)? "\n" : ", "); } for(; x < m; ++ x) printf(" %f%s", .0f, (x + 1 == m)? "\n" : ", "); } } cs_spfree(At); if(Ac) cs_spfree(Ac); } void CDebug::Print_SparseMatrix_in_MatlabFormat(const cs *A, const char *p_s_label /*= 0*/) { if(p_s_label) printf("matrix \'%s\' = ", p_s_label); csi m, n, /*nzmax, nz,*/ *Ap, *Ai; double *Ax; if(!A) { printf("(null)\n"); return; } cs *Ac = 0; if(CS_TRIPLET(A) && !(Ac = cs_compress(A))) { printf("[not enough memory]\n"); return; } cs *At; if(!(At = cs_transpose((Ac)? Ac : A, 1))) { if(Ac) cs_spfree(Ac); printf("[not enough memory]\n"); return; } m = At->m; n = At->n; Ap = At->p; Ai = At->i; Ax = At->x; //nzmax = At->nzmax; nz = At->nz; _ASSERTE(CS_CSC(At)); { printf("["); for(csi j = 0; j < n; ++ j) { csi x = 0; for(csi p = Ap[j]; p < Ap[j + 1]; ++ p, ++ x) { csi n_cur_x = Ai[p]; for(; x < n_cur_x; ++ x) printf("%f ", .0f); printf("%f%s", (Ax)? Ax[p] : 1, (n_cur_x + 1 == m)? ((j + 1 == n)? "" : "; ") : " "); } for(; x < m; ++ x) printf("%f%s", .0f, (x + 1 == m)? ((j + 1 == n)? "" : "; ") : " "); } printf("]\n"); } cs_spfree(At); if(Ac) cs_spfree(Ac); } bool CDebug::Print_SparseMatrix_in_MatlabFormat(FILE *p_fw, const cs *A, const char *p_s_prefix /*= 0*/, const char *p_s_suffix /*= ";\n"*/) { if(p_s_prefix) fprintf(p_fw, "%s", p_s_prefix); { fprintf(p_fw, "["); CSparseMatrixShapedIterator it(A); // @todo - replace this by a simple iterator as soon as it's tested for(size_t i = 0, m = A->m; i < m; ++ i) { // iterate rows in the outer loop for(size_t j = 0, n = A->n; j < n; ++ j, ++ it) { // iterate columns in the inner loop double f_value = *it; fprintf(p_fw, " %f", f_value); } if(i + 1 != m) fprintf(p_fw, "; "); } fprintf(p_fw, "]"); } // "to define a matrix, you can treat it like a column of row vectors" /* * >> A = [ 1 2 3; 3 4 5; 6 7 8] * * A = * * 1 2 3 * 3 4 5 * 6 7 8 */ if(p_s_suffix) fprintf(p_fw, "%s", p_s_suffix); return true; } bool CDebug::Print_SparseMatrix_in_MatlabFormat2(FILE *p_fw, const cs *A, const char *p_s_label, const char *p_s_prefix /*= 0*/, const char *p_s_suffix /*= 0*/) { if(p_s_prefix) fprintf(p_fw, "%s", p_s_prefix); fprintf(p_fw, "%s = sparse(" PRIdiff ", " PRIdiff ");\n", p_s_label, A->m, A->n); for(csi i = 0; i < A->n; ++ i) { for(csi p = A->p[i], e = A->p[i + 1]; p < e; ++ p) { csi j = A->i[p]; double x = (A->x)? A->x[p] : 1; if(x != 0) { // hard comparison here, try to avoid zero lines introduced by conversion from block matrices fprintf(p_fw, (fabs(x) > 1)? "%s(" PRIdiff ", " PRIdiff ") = %f;\n" : "%s(" PRIdiff ", " PRIdiff ") = %g;\n", p_s_label, j + 1, i + 1, x); } } } // to make sparse unit matrix, one writes: /* * >> A = sparse(2, 2); * >> A(1, 1) = 1 * >> A(2, 2) = 1 * * A = * (1, 1) 1 * (2, 2) 1 */ if(p_s_suffix) fprintf(p_fw, "%s", p_s_suffix); return true; } void CDebug::Print_DenseVector(const double *b, size_t n_vector_length, const char *p_s_label /*= 0*/) { //_ASSERTE(n_vector_length > 0); // doesn't work for empties double f_min_abs = (n_vector_length)? fabs(b[0]) : 0; for(size_t i = 1; i < n_vector_length; ++ i) f_min_abs = (fabs(b[i]) > 0 && (!f_min_abs || f_min_abs > fabs(b[i])))? fabs(b[i]) : f_min_abs; int n_log10 = (f_min_abs > 0)? int(ceil(log(f_min_abs) / log(10.0))) : 0; // calculate log10 to display the smallest nonzero value as 0 to 1 number if(n_log10 < -1) n_log10 += 2; else if(n_log10 < 0) ++ n_log10; // it's ok to have two first places 0 (in matlab it is, apparently) double f_scale = pow(10.0, -n_log10); // calculatze scale if(p_s_label) printf("%s = ", p_s_label); if(n_vector_length) { printf("vec(" PRIsize ") = 1e%+d * [%.4f", n_vector_length, n_log10, f_scale * b[0]); for(size_t i = 1; i < n_vector_length; ++ i) printf(", %.4f", f_scale * b[i]); printf("]\n"); } else printf("[ ]\n"); // print with scale } void CDebug::Print_DenseVector_in_MatlabFormat(FILE *p_fw, const double *b, size_t n_vector_length, const char *p_s_prefix /*= 0*/, const char *p_s_suffix /*= ";\n"*/) { //_ASSERTE(n_vector_length > 0); // doesn't work for empties double f_min_abs = (n_vector_length)? fabs(b[0]) : 0; for(size_t i = 1; i < n_vector_length; ++ i) f_min_abs = (fabs(b[i]) > 0 && (!f_min_abs || f_min_abs > fabs(b[i])))? fabs(b[i]) : f_min_abs; int n_log10 = (f_min_abs > 0)? int(ceil(log(f_min_abs) / log(10.0))) : 0; // calculate log10 to display the smallest nonzero value as 0 to 1 number if(n_log10 < -1) n_log10 += 2; else if(n_log10 < 0) ++ n_log10; // it's ok to have two first places 0 (in matlab it is, apparently) double f_scale = pow(10.0, -n_log10); // calculatze scale if(p_s_prefix) fprintf(p_fw, "%s", p_s_prefix); if(n_vector_length) { if(fabs(f_scale * b[0]) > 1) fprintf(p_fw, "1e%+d * [%.15f", n_log10, f_scale * b[0]); else fprintf(p_fw, "1e%+d * [%.15g", n_log10, f_scale * b[0]); for(size_t i = 1; i < n_vector_length; ++ i) fprintf(p_fw, (fabs(f_scale * b[i]) > 1)? " %.15f" : " %.15g", f_scale * b[i]); fprintf(p_fw, "]"); } else fprintf(p_fw, "[ ]"); if(p_s_suffix) fprintf(p_fw, "%s", p_s_suffix); // print with scale } #if (defined(_M_X64) || defined(_M_AMD64) || defined(_M_IA64) || defined(__x86_64) || defined(__amd64) || defined(__ia64) || \ defined(_M_I86) || defined(_M_IX86) || defined(__X86__) || defined(_X86_) || defined(__IA32__) || defined(__i386)) && \ 1 // in case the below include is not found or _mm_clflush() or _mm_mfence() are undefined, switch to 0. this will only affect some debugging / performance profiling functionality #include <emmintrin.h> void CDebug::Evict_Buffer(const void *p_begin, size_t n_size) { if(!p_begin) return; for(intptr_t n_addr = intptr_t(p_begin), n_end = intptr_t(p_begin) + n_size; n_addr != n_end; ++ n_addr) { _mm_clflush((const void*)n_addr); // flush the corresponding cache line } _mm_mfence(); // memory fence; force all operations to complete before going on } #else // (x86 || x64) && 1 //#pragma message "warning: emmintrin.h likely not present, evict semantics will not be available" void CDebug::Evict_Buffer(const void *UNUSED(p_begin), size_t UNUSED(n_size)) { // we're not on x86, can't use _mm_*() intrinsics // this is needed if building e.g. for ARM } #endif // (x86 || x64) && 1 void CDebug::Evict(const cs *p_mat) { if(CS_TRIPLET(p_mat)) Evict_Buffer(p_mat->p, sizeof(csi) * p_mat->nzmax); else Evict_Buffer(p_mat->p, sizeof(csi) * (p_mat->n + 1)); Evict_Buffer(p_mat->i, sizeof(csi) * p_mat->nzmax); Evict_Buffer(p_mat->x, sizeof(double) * p_mat->nzmax); // evict the internal buffers Evict_Buffer(p_mat, sizeof(cs)); // evict the structure } void CDebug::Evict(const CUberBlockMatrix &r_mat) { CUBM_EvictUtil<blockmatrix_detail::CUberBlockMatrix_Base>::EvictMembers(r_mat); // evict the internal vectors Evict_Buffer(&r_mat, sizeof(r_mat)); // evict the structure } void CDebug::Swamp_Cache(size_t n_buffer_size /*= 100 * 1048576*/) // throw(std::bad_alloc) { std::vector<uint8_t> buffer(n_buffer_size); for(size_t i = 0; i < n_buffer_size; ++ i) buffer[i] = uint8_t(n_SetBit_Num(i)); // alloc a large buffer and fill it using nontrivial // ops, so that cache would not be bypassed by DMA as // e.g. for memset or memcpy } /* * === ~CDebug === */ /* * === CSparseMatrixMemInfo === */ uint64_t CSparseMatrixMemInfo::n_Allocation_Size(const cs *p_matrix) { if(!p_matrix) return 0; if(p_matrix->nz <= 0) { return sizeof(cs) + (p_matrix->n + 1) * sizeof(csi) + p_matrix->p[p_matrix->n] * ((p_matrix->x)? sizeof(double) + sizeof(csi) : sizeof(csi)); } else { return sizeof(cs) + p_matrix->nzmax * ((p_matrix->x)? sizeof(double) + 2 * sizeof(csi) : 2 * sizeof(csi)); } } bool CSparseMatrixMemInfo::Peek_MatrixMarket_Header(const char *p_s_filename, CSparseMatrixMemInfo::TMMHeader &r_t_header) { bool b_symmetric = false, b_binary = false; bool b_had_specifier = false; bool b_had_header = false; size_t n_rows, n_cols, n_nnz = -1, n_read_nnz = 0, n_full_nnz = 0; FILE *p_fr; if(!(p_fr = fopen(p_s_filename, "r"))) return false; // open the matrix market file try { std::string s_line; while(!feof(p_fr)) { if(!CParserBase::ReadLine(s_line, p_fr)) { fclose(p_fr); return false; } // read a single line size_t n_pos; if(!b_had_specifier && (n_pos = s_line.find("%%MatrixMarket")) != std::string::npos) { s_line.erase(0, n_pos + strlen("%%MatrixMarket")); // get rid of header b_binary = s_line.find("pattern") != std::string::npos; if(s_line.find("matrix") == std::string::npos || s_line.find("coordinate") == std::string::npos || (s_line.find("real") == std::string::npos && s_line.find("integer") == std::string::npos && !b_binary)) // integer matrices are not real, but have values and are loadable return false; // must be matrix coordinate real if(s_line.find("general") != std::string::npos) b_symmetric = false; else if(s_line.find("symmetric") != std::string::npos) b_symmetric = true; else { b_symmetric = false; /*//fclose(p_fr); return false;*/ // or assume general } // either general or symmetric b_had_specifier = true; continue; } if((n_pos = s_line.find('%')) != std::string::npos) s_line.erase(n_pos); CParserBase::TrimSpace(s_line); if(s_line.empty()) continue; // trim comments, skip empty lines if(!b_had_header) { if(!b_had_specifier) { fclose(p_fr); return false; } // specifier must come before header #if defined(_MSC_VER) && !defined(__MWERKS__) && _MSC_VER >= 1400 if(sscanf_s(s_line.c_str(), PRIsize " " PRIsize " " PRIsize, &n_rows, &n_cols, &n_nnz) != 3) { #else //_MSC_VER && !__MWERKS__ && _MSC_VER >= 1400 if(sscanf(s_line.c_str(), PRIsize " " PRIsize " " PRIsize, &n_rows, &n_cols, &n_nnz) != 3) { #endif //_MSC_VER && !__MWERKS__ && _MSC_VER >= 1400 fclose(p_fr); return false; } // read header if(n_rows <= SIZE_MAX / std::max(size_t(1), n_cols) && n_nnz > n_rows * n_cols) { fclose(p_fr); return false; } // sanity check (may also fail on big matrices) b_had_header = true; break; } } if(!b_had_header) { fclose(p_fr); return false; } if(b_symmetric) { _ASSERTE(b_had_header && b_had_specifier); while(!feof(p_fr)) { // only elements follow if(!CParserBase::ReadLine(s_line, p_fr)) { fclose(p_fr); return false; } // read a single line CParserBase::TrimSpace(s_line); if(s_line.empty() || s_line[0] == '%') // only handles comments at the beginning of the line; comments at the end will simply be ignored continue; // trim comments, skip empty lines double f_value; size_t n_rowi, n_coli; do { const char *b = s_line.c_str(); _ASSERTE(*b && !isspace(uint8_t(*b))); // not empty and not space for(n_rowi = 0; *b && isdigit(uint8_t(*b)); ++ b) // ignores overflows n_rowi = 10 * n_rowi + *b - '0'; // parse the first number if(!*b || !isspace(uint8_t(*b))) { fclose(p_fr); return false; } ++ b; // skip the first space while(*b && isspace(uint8_t(*b))) ++ b; if(!*b || !isdigit(uint8_t(*b))) { fclose(p_fr); return false; } // skip space to the second number for(n_coli = 0; *b && isdigit(uint8_t(*b)); ++ b) // ignores overflows n_coli = 10 * n_coli + *b - '0'; // parse the second number if(!*b) { f_value = 1; // a binary matrix? break; } if(!isspace(uint8_t(*b))) { fclose(p_fr); return false; // bad character } ++ b; // skip the first space while(*b && isspace(uint8_t(*b))) ++ b; _ASSERTE(*b); // there must be something since the string sure does not end with space (called TrimSpace() above) // skip space to the value f_value = 1;//atof(b); // don't care about the values here } while(0); // read a triplet -- n_rowi; -- n_coli; // indices are 1-based, i.e. a(1,1) is the first element if(n_rowi >= n_rows || n_coli >= n_cols || n_read_nnz >= n_nnz) { fclose(p_fr); return false; } // make sure it figures _ASSERTE(b_symmetric); n_full_nnz += (n_rowi != n_coli)? 2 : 1; ++ n_read_nnz; // append the nonzero } // read the file line by line if(ferror(p_fr) || !b_had_header || n_read_nnz != n_nnz) { fclose(p_fr); return false; } // make sure no i/o errors occurred, and that the entire matrix was read } // in case the matrix is symmetric, need to read the indices to see which ones are at the // diagonal; does not actually store them, just goes through them quickly; the floats are // not parsed fclose(p_fr); } catch(std::bad_alloc&) { fclose(p_fr); return false; } r_t_header.b_binary = b_binary; r_t_header.b_symmetric = b_symmetric; r_t_header.n_nnz = n_nnz; r_t_header.n_rows = n_rows; r_t_header.n_cols = n_cols; if(!b_symmetric) r_t_header.n_full_nnz = n_nnz; else r_t_header.n_full_nnz = n_full_nnz; return true; } uint64_t CSparseMatrixMemInfo::n_Peek_MatrixMarket_SizeInMemory(const char *p_s_filename) { TMMHeader t_header; if(!Peek_MatrixMarket_Header(p_s_filename, t_header)) return uint64_t(-1); cs spmat = {0, 0, 0, 0, 0, 0, 0}; // put all to avoid -Wmissing-field-initializers return t_header.n_AllocationSize_CSC(sizeof(*spmat.p), sizeof(*spmat.x)); } /* * === ~CSparseMatrixMemInfo === */
36.339921
247
0.619335
meitiever
44fd3f6002bdfc3d75dcd08eb50bd0e6657ed9ec
31,190
cxx
C++
VTKExtensions/IOGeneral/vtkPhastaReader.cxx
xj361685640/ParaView
0a27eef5abc5a0c0472ab0bc806c4db881156e64
[ "Apache-2.0", "BSD-3-Clause" ]
815
2015-01-03T02:14:04.000Z
2022-03-26T07:48:07.000Z
VTKExtensions/IOGeneral/vtkPhastaReader.cxx
xj361685640/ParaView
0a27eef5abc5a0c0472ab0bc806c4db881156e64
[ "Apache-2.0", "BSD-3-Clause" ]
9
2015-04-28T20:10:37.000Z
2021-08-20T18:19:01.000Z
VTKExtensions/IOGeneral/vtkPhastaReader.cxx
xj361685640/ParaView
0a27eef5abc5a0c0472ab0bc806c4db881156e64
[ "Apache-2.0", "BSD-3-Clause" ]
328
2015-01-22T23:11:46.000Z
2022-03-14T06:07:52.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkPhastaReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPhastaReader.h" #include "vtkByteSwap.h" #include "vtkCellData.h" #include "vtkCellType.h" //added for constants such as VTK_TETRA etc... #include "vtkDataArray.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkIntArray.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPointSet.h" #include "vtkSmartPointer.h" #include "vtkUnstructuredGrid.h" vtkStandardNewMacro(vtkPhastaReader); vtkCxxSetObjectMacro(vtkPhastaReader, CachedGrid, vtkUnstructuredGrid); #include <map> #include <sstream> #include <string> #include <utility> #include <vector> struct vtkPhastaReaderInternal { struct FieldInfo { int StartIndexInPhastaArray; int NumberOfComponents; int DataDependency; // 0-nodal, 1-elemental std::string DataType; // "int" or "double" std::string PhastaFieldTag; FieldInfo() : StartIndexInPhastaArray(-1) , NumberOfComponents(-1) , DataDependency(-1) { } }; typedef std::map<std::string, FieldInfo> FieldInfoMapType; FieldInfoMapType FieldInfoMap; }; // Begin of copy from phastaIO std::map<int, char*> LastHeaderKey; std::vector<FILE*> fileArray; std::vector<int> byte_order; std::vector<int> header_type; int DataSize = 0; int LastHeaderNotFound = 0; int Wrong_Endian = 0; int Strict_Error = 0; int binary_format = 0; // the caller has the responsibility to delete the returned string char* vtkPhastaReader::StringStripper(const char istring[]) { size_t length = strlen(istring); char* dest = new char[length + 1]; strcpy(dest, istring); dest[length] = '\0'; if (char* p = strpbrk(dest, " ")) { *p = '\0'; } return dest; } int vtkPhastaReader::cscompare(const char teststring[], const char targetstring[]) { char* s1 = const_cast<char*>(teststring); char* s2 = const_cast<char*>(targetstring); while (*s1 == ' ') { s1++; } while (*s2 == ' ') { s2++; } while ((*s1) && (*s2) && (*s2 != '?') && (tolower(*s1) == tolower(*s2))) { s1++; s2++; while (*s1 == ' ') { s1++; } while (*s2 == ' ') { s2++; } } if (!(*s1) || (*s1 == '?')) { return 1; } else { return 0; } } void vtkPhastaReader::isBinary(const char iotype[]) { char* fname = StringStripper(iotype); if (cscompare(fname, "binary")) { binary_format = 1; } else { binary_format = 0; } delete[] fname; } size_t vtkPhastaReader::typeSize(const char typestring[]) { char* ts1 = StringStripper(typestring); if (cscompare("integer", ts1)) { delete[] ts1; return sizeof(int); } else if (cscompare("double", ts1)) { delete[] ts1; return sizeof(double); } else if (cscompare("float", ts1)) { delete[] ts1; return sizeof(float); } else { vtkGenericWarningMacro(<< "unknown type : " << ts1 << endl); delete[] ts1; return 0; } } namespace { void xfgets(char* str, int num, FILE* stream) { if (fgets(str, num, stream) == nullptr) { vtkGenericWarningMacro(<< "Could not read or end of file" << endl); } } void xfread(void* ptr, size_t size, size_t count, FILE* stream) { if (fread(ptr, size, count, stream) != count) { vtkGenericWarningMacro(<< "Could not read or end of file" << endl); } } template <typename... Args> void xfscanf(FILE* stream, const char* format, Args... args) { int ret = fscanf(stream, format, args...); (void)ret; } } int vtkPhastaReader::readHeader(FILE* fileObject, const char phrase[], int* params, int expect) { char* text_header; char* token; char Line[1024]; char junk; int FOUND = 0; size_t real_length; int skip_size, integer_value; int rewind_count = 0; if (!fgets(Line, 1024, fileObject) && feof(fileObject)) { rewind(fileObject); clearerr(fileObject); rewind_count++; xfgets(Line, 1024, fileObject); } while (!FOUND && (rewind_count < 2)) { if ((Line[0] != '\n') && (real_length = strcspn(Line, "#"))) { text_header = new char[real_length + 1]; strncpy(text_header, Line, real_length); text_header[real_length] = static_cast<char>(0); token = strtok(text_header, ":"); if (cscompare(phrase, token)) { FOUND = 1; token = strtok(nullptr, " ,;<>"); skip_size = atoi(token); int i; for (i = 0; i < expect && (token = strtok(nullptr, " ,;<>")); i++) { params[i] = atoi(token); } if (i < expect) { vtkGenericWarningMacro(<< "Expected # of ints not found for: " << phrase << endl); } } else if (cscompare(token, "byteorder magic number")) { if (binary_format) { xfread((void*)&integer_value, sizeof(int), 1, fileObject); xfread(&junk, sizeof(char), 1, fileObject); if (362436 != integer_value) { Wrong_Endian = 1; } } else { xfscanf(fileObject, "%d\n", &integer_value); } } else { /* some other header, so just skip over */ token = strtok(nullptr, " ,;<>"); skip_size = atoi(token); if (binary_format) { fseek(fileObject, skip_size, SEEK_CUR); } else { for (int gama = 0; gama < skip_size; gama++) { xfgets(Line, 1024, fileObject); } } } delete[] text_header; } if (!FOUND) { if (!fgets(Line, 1024, fileObject) && feof(fileObject)) { rewind(fileObject); clearerr(fileObject); rewind_count++; xfgets(Line, 1024, fileObject); } } } if (!FOUND) { vtkGenericWarningMacro(<< "Could not find: " << phrase << endl); return 1; } return 0; } void vtkPhastaReader::SwapArrayByteOrder(void* array, int nbytes, int nItems) { /* This swaps the byte order for the array of nItems each of size nbytes , This will be called only locally */ int i, j; unsigned char* ucDst = (unsigned char*)array; for (i = 0; i < nItems; i++) { for (j = 0; j < (nbytes / 2); j++) { std::swap(ucDst[j], ucDst[(nbytes - 1) - j]); } ucDst += nbytes; } } void vtkPhastaReader::openfile(const char filename[], const char mode[], int* fileDescriptor) { FILE* file = nullptr; *fileDescriptor = 0; // Stripping a filename is not correct, since // filenames can certainly have spaces. // char* fname = StringStripper( filename ); const char* fname = filename; char* imode = StringStripper(mode); if (cscompare("read", imode)) { file = fopen(fname, "rb"); } else if (cscompare("write", imode)) { file = fopen(fname, "wb"); } else if (cscompare("append", imode)) { file = fopen(fname, "ab"); } if (!file) { vtkGenericWarningMacro(<< "unable to open file : " << fname << endl); } else { fileArray.push_back(file); byte_order.push_back(0); header_type.push_back(sizeof(int)); *fileDescriptor = static_cast<int>(fileArray.size()); } delete[] imode; } void vtkPhastaReader::closefile(int* fileDescriptor, const char mode[]) { char* imode = StringStripper(mode); if (cscompare("write", imode) || cscompare("append", imode)) { fflush(fileArray[*fileDescriptor - 1]); } fclose(fileArray[*fileDescriptor - 1]); delete[] imode; } void vtkPhastaReader::readheader(int* fileDescriptor, const char keyphrase[], void* valueArray, int* nItems, const char datatype[], const char iotype[]) { int filePtr = *fileDescriptor - 1; FILE* fileObject; int* valueListInt; if (*fileDescriptor < 1 || *fileDescriptor > (int)fileArray.size()) { vtkGenericWarningMacro(<< "No file associated with Descriptor " << *fileDescriptor << "\n" << "openfile function has to be called before \n" << "accessing the file\n " << "fatal error: cannot continue, returning out of call\n"); return; } LastHeaderKey[filePtr] = const_cast<char*>(keyphrase); LastHeaderNotFound = 0; fileObject = fileArray[filePtr]; Wrong_Endian = byte_order[filePtr]; isBinary(iotype); typeSize(datatype); // redundant call, just avoid a compiler warning. // right now we are making the assumption that we will only write integers // on the header line. valueListInt = static_cast<int*>(valueArray); int ierr = readHeader(fileObject, keyphrase, valueListInt, *nItems); byte_order[filePtr] = Wrong_Endian; if (ierr) { LastHeaderNotFound = 1; } } void vtkPhastaReader::readdatablock(int* fileDescriptor, const char keyphrase[], void* valueArray, int* nItems, const char datatype[], const char iotype[]) { int filePtr = *fileDescriptor - 1; FILE* fileObject; char junk; if (*fileDescriptor < 1 || *fileDescriptor > (int)fileArray.size()) { vtkGenericWarningMacro(<< "No file associated with Descriptor " << *fileDescriptor << "\n" << "openfile function has to be called before \n" << "accessing the file\n " << "fatal error: cannot continue, returning out of call\n"); return; } // error check.. // since we require that a consistent header always precede the data block // let us check to see that it is actually the case. if (!cscompare(LastHeaderKey[filePtr], keyphrase)) { vtkGenericWarningMacro(<< "Header not consistent with data block\n" << "Header: " << LastHeaderKey[filePtr] << "\n" << "DataBlock: " << keyphrase << "\n" << "Please recheck read sequence \n"); if (Strict_Error) { vtkGenericWarningMacro(<< "fatal error: cannot continue, returning out of call\n"); return; } } if (LastHeaderNotFound) { return; } fileObject = fileArray[filePtr]; Wrong_Endian = byte_order[filePtr]; size_t type_size = typeSize(datatype); int nUnits = *nItems; isBinary(iotype); if (binary_format) { xfread(valueArray, type_size, nUnits, fileObject); xfread(&junk, sizeof(char), 1, fileObject); if (Wrong_Endian) { SwapArrayByteOrder(valueArray, static_cast<int>(type_size), nUnits); } } else { char* ts1 = StringStripper(datatype); if (cscompare("integer", ts1)) { for (int n = 0; n < nUnits; n++) { xfscanf(fileObject, "%d\n", (int*)((int*)valueArray + n)); } } else if (cscompare("double", ts1)) { for (int n = 0; n < nUnits; n++) { xfscanf(fileObject, "%lf\n", (double*)((double*)valueArray + n)); } } delete[] ts1; } } // End of copy from phastaIO vtkPhastaReader::vtkPhastaReader() { this->GeometryFileName = nullptr; this->FieldFileName = nullptr; this->SetNumberOfInputPorts(0); this->Internal = new vtkPhastaReaderInternal; this->CachedGrid = nullptr; } vtkPhastaReader::~vtkPhastaReader() { delete[] this->GeometryFileName; delete[] this->FieldFileName; delete this->Internal; this->SetCachedGrid(nullptr); } void vtkPhastaReader::ClearFieldInfo() { this->Internal->FieldInfoMap.clear(); } void vtkPhastaReader::SetFieldInfo(const char* paraviewFieldTag, const char* phastaFieldTag, int index, int numOfComps, int dataDependency, const char* dataType) { vtkPhastaReaderInternal::FieldInfo& info = this->Internal->FieldInfoMap[paraviewFieldTag]; info.PhastaFieldTag = phastaFieldTag; info.StartIndexInPhastaArray = index; info.NumberOfComponents = numOfComps; info.DataDependency = dataDependency; info.DataType = dataType; } int vtkPhastaReader::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { int firstVertexNo = 0; int fvn = 0; int noOfNodes, noOfCells, noOfDatas; // get the data object vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkUnstructuredGrid* output = vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); if (this->GetCachedGrid()) { // shallow the cached grid that was previously set... vtkDebugMacro("Using a cached copy of the grid."); output->ShallowCopy(this->GetCachedGrid()); } else { vtkPoints* points; output->Allocate(10000, 2100); points = vtkPoints::New(); vtkDebugMacro(<< "Reading Phasta file..."); if (!this->GeometryFileName || !this->FieldFileName) { vtkErrorMacro(<< "All input parameters not set."); return 0; } vtkDebugMacro(<< "Updating ensa with ...."); vtkDebugMacro(<< "Geom File : " << this->GeometryFileName); vtkDebugMacro(<< "Field File : " << this->FieldFileName); fvn = firstVertexNo; this->ReadGeomFile(this->GeometryFileName, firstVertexNo, points, noOfNodes, noOfCells); /* set the points over here, this is because vtkUnStructuredGrid only insert points once, next insertion overwrites the previous one */ // acbauer is not sure why the above comment is about... output->SetPoints(points); points->Delete(); } if (this->Internal->FieldInfoMap.empty()) { vtkDataSetAttributes* field = output->GetPointData(); this->ReadFieldFile(this->FieldFileName, fvn, field, noOfNodes); } else { this->ReadFieldFile(this->FieldFileName, fvn, output, noOfDatas); } // if there exists point arrays called coordsX, coordsY and coordsZ, // create another array of point data and set the output to use this vtkPointData* pointData = output->GetPointData(); vtkDoubleArray* coordsX = vtkDoubleArray::SafeDownCast(pointData->GetArray("coordsX")); vtkDoubleArray* coordsY = vtkDoubleArray::SafeDownCast(pointData->GetArray("coordsY")); vtkDoubleArray* coordsZ = vtkDoubleArray::SafeDownCast(pointData->GetArray("coordsZ")); if (coordsX && coordsY && coordsZ) { vtkIdType numPoints = output->GetPoints()->GetNumberOfPoints(); if (numPoints != coordsX->GetNumberOfTuples() || numPoints != coordsY->GetNumberOfTuples() || numPoints != coordsZ->GetNumberOfTuples()) { vtkWarningMacro("Wrong number of points for moving mesh. Using original points."); return 0; } vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->DeepCopy(output->GetPoints()); for (vtkIdType i = 0; i < numPoints; i++) { points->SetPoint(i, coordsX->GetValue(i), coordsY->GetValue(i), coordsZ->GetValue(i)); } output->SetPoints(points); } return 1; } /* firstVertexNo is useful when reading multiple geom files and coalescing them into one, ReadGeomfile can then be called repeatedly from Execute with firstVertexNo forming consecutive series of vertex numbers */ void vtkPhastaReader::ReadGeomFile( char* geomFileName, int& firstVertexNo, vtkPoints* points, int& num_nodes, int& num_cells) { /* variables for vtk */ vtkUnstructuredGrid* output = this->GetOutput(); double* coordinates; vtkIdType* nodes; int cell_type; // int num_tpblocks; /* variables for the geom data file */ /* nodal information */ // int byte_order; // int data[11], data1[7]; int dim; int num_int_blocks; double* pos; // int *nlworkdata; /* element information */ int num_elems, num_vertices, num_per_line; int* connectivity = nullptr; /* misc variables*/ int i, j, k, item; int geomfile; openfile(geomFileName, "read", &geomfile); // geomfile = fopen(GeometryFileName,"rb"); if (!geomfile) { vtkErrorMacro(<< "Cannot open file " << geomFileName); return; } int expect; int array[10]; expect = 1; /* read number of nodes */ readheader(&geomfile, "number of nodes", array, &expect, "integer", "binary"); num_nodes = array[0]; /* read number of elements */ readheader(&geomfile, "number of interior elements", array, &expect, "integer", "binary"); num_elems = array[0]; num_cells = array[0]; /* read number of interior */ readheader(&geomfile, "number of interior tpblocks", array, &expect, "integer", "binary"); num_int_blocks = array[0]; vtkDebugMacro(<< "Nodes: " << num_nodes << "Elements: " << num_elems << "tpblocks: " << num_int_blocks); /* read coordinates */ expect = 2; readheader(&geomfile, "co-ordinates", array, &expect, "double", "binary"); // TEST ******************* num_nodes = array[0]; // TEST ******************* if (num_nodes != array[0]) { vtkErrorMacro(<< "Ambiguous information in geom.data file, number of nodes does not match the " "co-ordinates size. Nodes: " << num_nodes << " Coordinates: " << array[0]); return; } dim = array[1]; /* read the coordinates */ coordinates = new double[dim]; if (coordinates == nullptr) { vtkErrorMacro(<< "Unable to allocate memory for nodal info"); return; } pos = new double[num_nodes * dim]; if (pos == nullptr) { vtkErrorMacro(<< "Unable to allocate memory for nodal info"); delete[] coordinates; return; } item = num_nodes * dim; readdatablock(&geomfile, "co-ordinates", pos, &item, "double", "binary"); for (i = 0; i < num_nodes; i++) { for (j = 0; j < dim; j++) { coordinates[j] = pos[j * num_nodes + i]; } switch (dim) { case 1: points->InsertPoint(i + firstVertexNo, coordinates[0], 0, 0); break; case 2: points->InsertPoint(i + firstVertexNo, coordinates[0], coordinates[1], 0); break; case 3: points->InsertNextPoint(coordinates); break; default: vtkErrorMacro(<< "Unrecognized dimension in " << geomFileName); return; } } /* read the connectivity information */ expect = 7; for (k = 0; k < num_int_blocks; k++) { readheader(&geomfile, "connectivity interior", array, &expect, "integer", "binary"); /* read information about the block*/ num_elems = array[0]; num_vertices = array[1]; num_per_line = array[3]; connectivity = new int[num_elems * num_per_line]; if (connectivity == nullptr) { vtkErrorMacro(<< "Unable to allocate memory for connectivity info"); return; } item = num_elems * num_per_line; readdatablock(&geomfile, "connectivity interior", connectivity, &item, "integer", "binary"); /* insert cells */ for (i = 0; i < num_elems; i++) { nodes = new vtkIdType[num_vertices]; // connectivity starts from 1 so node[j] will never be -ve for (j = 0; j < num_vertices; j++) { nodes[j] = connectivity[i + num_elems * j] + firstVertexNo - 1; } /* 1 is subtracted from the connectivity info to reflect that in vtk vertex numbering start from 0 as opposed to 1 in geomfile */ // find out element type switch (num_vertices) { case 4: cell_type = VTK_TETRA; break; case 5: cell_type = VTK_PYRAMID; break; case 6: cell_type = VTK_WEDGE; break; case 8: cell_type = VTK_HEXAHEDRON; break; default: delete[] nodes; vtkErrorMacro(<< "Unrecognized CELL_TYPE in " << geomFileName); return; } /* insert the element */ output->InsertNextCell(cell_type, num_vertices, nodes); delete[] nodes; } } // update the firstVertexNo so that next slice/partition can be read firstVertexNo = firstVertexNo + num_nodes; // clean up closefile(&geomfile, "read"); delete[] coordinates; delete[] pos; delete[] connectivity; } void vtkPhastaReader::ReadFieldFile( char* fieldFileName, int, vtkDataSetAttributes* field, int& noOfNodes) { int i, j; int item; double* data; int fieldfile; openfile(fieldFileName, "read", &fieldfile); // fieldfile = fopen(FieldFileName,"rb"); if (!fieldfile) { vtkErrorMacro(<< "Cannot open file " << FieldFileName); return; } int array[10], expect; /* read the solution */ vtkDoubleArray* pressure = vtkDoubleArray::New(); pressure->SetName("pressure"); vtkDoubleArray* velocity = vtkDoubleArray::New(); velocity->SetName("velocity"); velocity->SetNumberOfComponents(3); vtkDoubleArray* temperature = vtkDoubleArray::New(); temperature->SetName("temperature"); expect = 3; readheader(&fieldfile, "solution", array, &expect, "double", "binary"); noOfNodes = array[0]; this->NumberOfVariables = array[1]; vtkDoubleArray* sArrays[4]; for (i = 0; i < 4; i++) { sArrays[i] = nullptr; } item = noOfNodes * this->NumberOfVariables; data = new double[item]; if (data == nullptr) { vtkErrorMacro(<< "Unable to allocate memory for field info"); return; } readdatablock(&fieldfile, "solution", data, &item, "double", "binary"); for (i = 5; i < this->NumberOfVariables; i++) { int idx = i - 5; sArrays[idx] = vtkDoubleArray::New(); std::ostringstream aName; aName << "s" << idx + 1 << ends; sArrays[idx]->SetName(aName.str().c_str()); sArrays[idx]->SetNumberOfTuples(noOfNodes); } pressure->SetNumberOfTuples(noOfNodes); velocity->SetNumberOfTuples(noOfNodes); temperature->SetNumberOfTuples(noOfNodes); for (i = 0; i < noOfNodes; i++) { pressure->SetTuple1(i, data[i]); velocity->SetTuple3(i, data[noOfNodes + i], data[2 * noOfNodes + i], data[3 * noOfNodes + i]); temperature->SetTuple1(i, data[4 * noOfNodes + i]); for (j = 5; j < this->NumberOfVariables; j++) { sArrays[j - 5]->SetTuple1(i, data[j * noOfNodes + i]); } } field->AddArray(pressure); field->SetActiveScalars("pressure"); pressure->Delete(); field->AddArray(velocity); field->SetActiveVectors("velocity"); velocity->Delete(); field->AddArray(temperature); temperature->Delete(); for (i = 5; i < this->NumberOfVariables; i++) { int idx = i - 5; field->AddArray(sArrays[idx]); sArrays[idx]->Delete(); } // clean up closefile(&fieldfile, "read"); delete[] data; } // closes ReadFieldFile void vtkPhastaReader::ReadFieldFile( char* fieldFileName, int, vtkUnstructuredGrid* output, int& noOfDatas) { int i, j, numOfVars; int item; int fieldfile; openfile(fieldFileName, "read", &fieldfile); // fieldfile = fopen(FieldFileName,"rb"); if (!fieldfile) { vtkErrorMacro(<< "Cannot open file " << FieldFileName); return; } int array[10], expect; int activeScalars = 0, activeTensors = 0; vtkPhastaReaderInternal::FieldInfoMapType::iterator it = this->Internal->FieldInfoMap.begin(); vtkPhastaReaderInternal::FieldInfoMapType::iterator itend = this->Internal->FieldInfoMap.end(); for (; it != itend; it++) { const char* paraviewFieldTag = it->first.c_str(); const char* phastaFieldTag = it->second.PhastaFieldTag.c_str(); int index = it->second.StartIndexInPhastaArray; int numOfComps = it->second.NumberOfComponents; int dataDependency = it->second.DataDependency; const char* dataType = it->second.DataType.c_str(); vtkDataSetAttributes* field; if (dataDependency) field = output->GetCellData(); else field = output->GetPointData(); // void *data; int dtype; // (0=double, 1=float) vtkDataArray* dataArray; /* read the field data */ if (strcmp(dataType, "double") == 0) { dataArray = vtkDoubleArray::New(); dtype = 0; } else if (strcmp(dataType, "float") == 0) { dataArray = vtkFloatArray::New(); dtype = 1; } else { vtkErrorMacro("Data type [" << dataType << "] NOT supported"); continue; } dataArray->SetName(paraviewFieldTag); dataArray->SetNumberOfComponents(numOfComps); expect = 3; readheader(&fieldfile, phastaFieldTag, array, &expect, dataType, "binary"); noOfDatas = array[0]; this->NumberOfVariables = array[1]; numOfVars = array[1]; dataArray->SetNumberOfTuples(noOfDatas); if (index < 0 || index > numOfVars - 1) { vtkErrorMacro("index [" << index << "] is out of range [num. of vars.:" << numOfVars << "] for field [paraview field tag:" << paraviewFieldTag << ", phasta field tag:" << phastaFieldTag << "]"); dataArray->Delete(); continue; } if (numOfComps < 0 || index + numOfComps > numOfVars) { vtkErrorMacro("index [" << index << "] with num. of comps. [" << numOfComps << "] is out of range [num. of vars.:" << numOfVars << "] for field [paraview field tag:" << paraviewFieldTag << ", phasta field tag:" << phastaFieldTag << "]"); dataArray->Delete(); continue; } item = numOfVars * noOfDatas; if (dtype == 0) { // data is type double double* data; data = new double[item]; if (data == nullptr) { vtkErrorMacro(<< "Unable to allocate memory for field info"); dataArray->Delete(); continue; } readdatablock(&fieldfile, phastaFieldTag, data, &item, dataType, "binary"); switch (numOfComps) { case 1: { int offset = index * noOfDatas; if (!activeScalars) field->SetActiveScalars(paraviewFieldTag); else activeScalars = 1; for (i = 0; i < noOfDatas; i++) { dataArray->SetTuple1(i, data[offset + i]); } } break; case 3: { int offset[3]; for (j = 0; j < 3; j++) offset[j] = (index + j) * noOfDatas; if (!activeScalars) field->SetActiveVectors(paraviewFieldTag); else activeScalars = 1; for (i = 0; i < noOfDatas; i++) { dataArray->SetTuple3(i, data[offset[0] + i], data[offset[1] + i], data[offset[2] + i]); } } break; case 9: { int offset[9]; for (j = 0; j < 9; j++) offset[j] = (index + j) * noOfDatas; if (!activeTensors) field->SetActiveTensors(paraviewFieldTag); else activeTensors = 1; for (i = 0; i < noOfDatas; i++) { dataArray->SetTuple9(i, data[offset[0] + i], data[offset[1] + i], data[offset[2] + i], data[offset[3] + i], data[offset[4] + i], data[offset[5] + i], data[offset[6] + i], data[offset[7] + i], data[offset[8] + i]); } } break; default: vtkErrorMacro("number of components [" << numOfComps << "] NOT supported"); dataArray->Delete(); delete[] data; continue; } // clean up delete[] data; } else if (dtype == 1) { // data is type float float* data; data = new float[item]; if (data == nullptr) { vtkErrorMacro(<< "Unable to allocate memory for field info"); dataArray->Delete(); continue; } readdatablock(&fieldfile, phastaFieldTag, data, &item, dataType, "binary"); switch (numOfComps) { case 1: { int offset = index * noOfDatas; if (!activeScalars) field->SetActiveScalars(paraviewFieldTag); else activeScalars = 1; for (i = 0; i < noOfDatas; i++) { // double tmpval = (double) data[offset+i]; // dataArray->SetTuple1(i, tmpval); dataArray->SetTuple1(i, data[offset + i]); } } break; case 3: { int offset[3]; for (j = 0; j < 3; j++) offset[j] = (index + j) * noOfDatas; if (!activeScalars) field->SetActiveVectors(paraviewFieldTag); else activeScalars = 1; for (i = 0; i < noOfDatas; i++) { // double tmpval[3]; // for(j=0;j<3;j++) // tmpval[j] = (double) data[offset[j]+i]; // dataArray->SetTuple3(i, // tmpval[0], tmpval[1], tmpval[3]); dataArray->SetTuple3(i, data[offset[0] + i], data[offset[1] + i], data[offset[2] + i]); } } break; case 9: { int offset[9]; for (j = 0; j < 9; j++) offset[j] = (index + j) * noOfDatas; if (!activeTensors) field->SetActiveTensors(paraviewFieldTag); else activeTensors = 1; for (i = 0; i < noOfDatas; i++) { // double tmpval[9]; // for(j=0;j<9;j++) // tmpval[j] = (double) data[offset[j]+i]; // dataArray->SetTuple9(i, // tmpval[0], // tmpval[1], // tmpval[2], // tmpval[3], // tmpval[4], // tmpval[5], // tmpval[6], // tmpval[7], // tmpval[8]); dataArray->SetTuple9(i, data[offset[0] + i], data[offset[1] + i], data[offset[2] + i], data[offset[3] + i], data[offset[4] + i], data[offset[5] + i], data[offset[6] + i], data[offset[7] + i], data[offset[8] + i]); } } break; default: vtkErrorMacro("number of components [" << numOfComps << "] NOT supported"); dataArray->Delete(); delete[] data; continue; } // clean up delete[] data; } else { vtkErrorMacro("Data type [" << dataType << "] NOT supported"); continue; } field->AddArray(dataArray); // clean up dataArray->Delete(); // delete [] data; } // close up closefile(&fieldfile, "read"); } // closes ReadFieldFile void vtkPhastaReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "GeometryFileName: " << (this->GeometryFileName ? this->GeometryFileName : "(none)") << endl; os << indent << "FieldFileName: " << (this->FieldFileName ? this->FieldFileName : "(none)") << endl; os << indent << "CachedGrid: " << this->CachedGrid << endl; }
26.567291
99
0.588746
xj361685640
44fe008bb5333b2a4a1f2349611e7fb18b6c7013
4,022
hpp
C++
pythran/pythonic/numpy/fft/ihfft.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,647
2015-01-13T01:45:38.000Z
2022-03-28T01:23:41.000Z
pythran/pythonic/numpy/fft/ihfft.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,116
2015-01-01T09:52:05.000Z
2022-03-18T21:06:40.000Z
pythran/pythonic/numpy/fft/ihfft.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
180
2015-02-12T02:47:28.000Z
2022-03-14T10:28:18.000Z
#ifndef PYTHONIC_NUMPY_FFT_IHFFT_HPP #define PYTHONIC_NUMPY_FFT_IHFFT_HPP #include "pythonic/include/numpy/fft/ihfft.hpp" #include "pythonic/utils/functor.hpp" #include "pythonic/include/utils/array_helper.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/builtins/None.hpp" #include "pythonic/numpy/fft/c2c.hpp" PYTHONIC_NS_BEGIN namespace numpy { namespace fft { template <class T, class pS> types::ndarray<typename std::enable_if<std::is_floating_point<T>::value, std::complex<T>>::type, types::array<long, std::tuple_size<pS>::value>> ihfft(types::ndarray<T, pS> const &in_array, types::none_type n, long axis, types::str const &norm) { return r2c(in_array, -1, axis, norm, false, false); } template <class T, class pS> types::ndarray<typename std::enable_if<std::is_floating_point<T>::value, std::complex<T>>::type, types::array<long, std::tuple_size<pS>::value>> ihfft(types::ndarray<T, pS> const &in_array, types::none_type n, long axis, types::none_type norm) { return r2c(in_array, -1, axis, "", false, false); } template <class T, class pS> types::ndarray<typename std::enable_if<std::is_floating_point<T>::value, std::complex<T>>::type, types::array<long, std::tuple_size<pS>::value>> ihfft(types::ndarray<T, pS> const &in_array, long n, long axis, types::none_type norm) { return r2c(in_array, n, axis, "", false, false); } template <class T, class pS> types::ndarray<typename std::enable_if<std::is_floating_point<T>::value, std::complex<T>>::type, types::array<long, std::tuple_size<pS>::value>> ihfft(types::ndarray<T, pS> const &in_array, long n, long axis, types::str const &norm) { return r2c(in_array, n, axis, norm, false, false); } template <class T, class pS> types::ndarray<typename std::enable_if<std::is_integral<T>::value, std::complex<double>>::type, types::array<long, std::tuple_size<pS>::value>> ihfft(types::ndarray<T, pS> const &in_array, types::none_type n, long axis, types::str const &norm) { auto tmp_array = _copy_to_double(in_array); return r2c(tmp_array, -1, axis, norm, false, false); } template <class T, class pS> types::ndarray<typename std::enable_if<std::is_integral<T>::value, std::complex<double>>::type, types::array<long, std::tuple_size<pS>::value>> ihfft(types::ndarray<T, pS> const &in_array, types::none_type n, long axis, types::none_type norm) { auto tmp_array = _copy_to_double(in_array); return r2c(tmp_array, -1, axis, "", false, false); } template <class T, class pS> types::ndarray<typename std::enable_if<std::is_integral<T>::value, std::complex<double>>::type, types::array<long, std::tuple_size<pS>::value>> ihfft(types::ndarray<T, pS> const &in_array, long n, long axis, types::none_type norm) { auto tmp_array = _copy_to_double(in_array); return r2c(tmp_array, n, axis, "", false, false); } template <class T, class pS> types::ndarray<typename std::enable_if<std::is_integral<T>::value, std::complex<double>>::type, types::array<long, std::tuple_size<pS>::value>> ihfft(types::ndarray<T, pS> const &in_array, long n, long axis, types::str const &norm) { auto tmp_array = _copy_to_double(in_array); return r2c(tmp_array, n, axis, norm, false, false); } NUMPY_EXPR_TO_NDARRAY0_IMPL(ihfft); } } PYTHONIC_NS_END #endif
37.588785
79
0.584286
davidbrochart
44feed8c45f1dcf885a76fabaf3620aecb80c7bc
4,294
hpp
C++
plugin/augmented_reality_plugin_wikitude/ios/Frameworks/WikitudeSDK.xcframework/ios-x86_64-simulator/WikitudeSDK.framework/Headers/Plane.hpp
Wikitude/wikitude-flutter-plugin-examples
8ed5e18e8f32e7570328e89df5c69000fda13153
[ "Apache-2.0" ]
9
2019-12-22T09:03:13.000Z
2021-08-20T00:46:05.000Z
plugin/augmented_reality_plugin_wikitude/ios/Frameworks/WikitudeSDK.framework/Headers/Plane.hpp
Wikitude/wikitude-flutter-plugin-examples
8ed5e18e8f32e7570328e89df5c69000fda13153
[ "Apache-2.0" ]
11
2019-09-03T15:45:44.000Z
2022-03-30T11:20:44.000Z
plugin/augmented_reality_plugin_wikitude/ios/Frameworks/WikitudeSDK.xcframework/ios-arm64/WikitudeSDK.framework/Headers/Plane.hpp
Wikitude/wikitude-flutter-plugin-examples
8ed5e18e8f32e7570328e89df5c69000fda13153
[ "Apache-2.0" ]
3
2021-09-01T13:02:11.000Z
2021-11-26T12:02:26.000Z
// // Plane.hpp // WikitudeUniversalSDK // // Created by Alexandru Florea on 01.08.18. // Copyright © 2018 Wikitude. All rights reserved. // #ifndef Plane_hpp #define Plane_hpp #ifdef __cplusplus #include <vector> #include "PlaneType.hpp" #include "Geometry.hpp" #include "CompilerAttributes.hpp" namespace wikitude::sdk { /** @addtogroup InstantTracking * @{ */ /** @class Plane * @brief A class that represents a plane found by an instant tracker. */ class Matrix4; class Vector3; class WT_EXPORT_API Plane { public: virtual ~Plane() = default; /** @brief Gets the combined modelview matrix that should be applied to augmentations when rendering. * In cases where the orientation of the rendering surface and orientation of the camera do not match, and a correct cameraToRenderSurfaceRotation is passed to the SDK, * this matrix will also be rotate to account for the mismatch. * * For example, on mobile devices running in portrait mode, that have a camera sensor is landscape right position, the cameraToRenderSurfaceRotation should be 90 degrees. * The matrix will be rotated by 90 degrees around the Z axis. * * @return The matrix that should be applied to the target augmentation when rendering. */ virtual const Matrix4& getMatrix() const = 0; /** @brief Gets the transformation from local space to world space. * When the CameraFrame doesn't contain a valid device pose, world space and camera space are the same. * When combined with the viewMatrix, this results in the modelViewMatrix that should be applied to the target augmentation when rendering. * * @return The matrix that transforms the target from local space to world space. */ virtual const Matrix4& getModelMatrix() const = 0; /** @brief Gets the transformation from world space to camera space. * When the CameraFrame doesn't contain a valid device pose, world space and camera space are the same. * When combined with the modelMatrix, this results in the modelViewMatrix that should be applied to the target augmentation when rendering. * * @return The matrix that transform the target from world space to camera space. */ virtual const Matrix4& getViewMatrix() const = 0; /** @brief Gets the unique id of the Plane. * * @return The unique id of the plane. */ virtual long getUniqueId() const = 0; /** @brief Gets the type for this plane. * * Please refer to the PlaneType documentation for more details. * * @return The plane type. */ virtual PlaneType getPlaneType() const = 0; /** @brief Returns the confidence level for the plane. * * The confidence level is mapped between 0 and 1. * * @return The confidence level for the plane. */ virtual float getConfidence() const = 0; /** @brief Gets the extents of the plane in the X axis. * * @return The extents of the plane in the X axis. */ virtual const Extent<float>& getExtentX() const = 0; /** @brief Gets the extents of the plane in the Y axis. * * @return The extents of the plane in the Y axis. */ virtual const Extent<float>& getExtentY() const = 0; /** @brief Gets the convex hull of the plane. * * The convex hull can be used to render the plane mesh as a triangle fan. * All the points are relative to the plane coordinate system and can also be used as texture coordinates. * * @return The convex hull of the plane. */ virtual const std::vector<Point<float>>& getConvexHull() const = 0; }; } #endif /* __cplusplus */ #endif /* Plane_hpp */
38.684685
183
0.591057
Wikitude
44ff9431bee60cd6197bd404e35abce7d38e993a
15,303
cpp
C++
cc/vision/vision.cpp
PEQUI-VSSS/VSSS-EMC
0c2b61e308f754ca91df52e46ba48828168223df
[ "MIT" ]
9
2017-07-18T12:37:09.000Z
2018-05-01T14:41:48.000Z
cc/vision/vision.cpp
PEQUI-MEC/VSSS-EMC
0c2b61e308f754ca91df52e46ba48828168223df
[ "MIT" ]
31
2018-07-31T13:10:01.000Z
2022-03-26T16:00:25.000Z
cc/vision/vision.cpp
PEQUI-MEC/VSSS-EMC
0c2b61e308f754ca91df52e46ba48828168223df
[ "MIT" ]
2
2017-10-01T16:09:20.000Z
2018-05-01T17:39:59.000Z
#include <Geometry/Geometry.h> #include <Strategy2/Field.h> #include "vision.hpp" using namespace vision; std::map<unsigned int, Vision::RecognizedTag> Vision::run(cv::Mat raw_frame) { in_frame = raw_frame.clone(); preProcessing(); findTags(); //findElements(); return pick_a_tag(); } void Vision::preProcessing() { cv::cvtColor(in_frame, lab_frame, cv::COLOR_RGB2Lab); } void Vision::findTags() { for (unsigned int color = 0; color < MAX_COLORS; color++) { threshold_threads.add_thread(new boost::thread(&Vision::segmentAndSearch, this, color)); } threshold_threads.join_all(); } void Vision::segmentAndSearch(const unsigned long color) { cv::Mat frame = lab_frame.clone(); inRange(frame, cv::Scalar(cieL[color][Limit::Min], cieA[color][Limit::Min], cieB[color][Limit::Min]), cv::Scalar(cieL[color][Limit::Max], cieA[color][Limit::Max], cieB[color][Limit::Max]), threshold_frame.at(color)); posProcessing(color); searchTags(color); } void Vision::posProcessing(const unsigned long color) { int morphShape; cv::Size size; if (color == Color::Ball) { morphShape = cv::MORPH_ELLIPSE; size = cv::Size(15, 15); } else { morphShape = cv::MORPH_RECT; size = cv::Size(3, 3); } cv::Mat erodeElement = cv::getStructuringElement(morphShape, size); cv::Mat dilateElement = cv::getStructuringElement(morphShape, size); if (blur[color] > 0) { cv::medianBlur(threshold_frame.at(color), threshold_frame.at(color), blur[color]); } cv::erode(threshold_frame.at(color), threshold_frame.at(color), erodeElement, cv::Point(-1, -1), erode[color]); cv::dilate(threshold_frame.at(color), threshold_frame.at(color), dilateElement, cv::Point(-1, -1), dilate[color]); } void Vision::searchTags(const unsigned long color) { std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; tags.at(color).clear(); cv::findContours(threshold_frame.at(color), contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_NONE); for (const auto &contour : contours) { double area = contourArea(contour); if (area >= areaMin[color]) { cv::Moments moment = moments((cv::Mat) contour); auto moment_x = static_cast<int>(moment.m10 / area); auto moment_y = static_cast<int>(moment.m01 / area); // seta as linhas para as tags principais do pick-a-tag if (color == Color::Main) { tags.at(color).emplace_back(cv::Point(moment_x, moment_y), area); // tem que ter jogado a tag no vetor antes de mexer nos valores dela cv::Vec4f line; cv::fitLine(cv::Mat(contour), line, 2, 0, 0.01, 0.01); unsigned long tagsInVec = tags.at(color).size() - 1; tags.at(color).at(tagsInVec).setLine(line); } else if (color == Color::Adv) { if (tags.at(color).size() >= 3) { // pega o menor índice unsigned long smaller = 0; for (unsigned long j = 1; j < 3; j++) { if (tags.at(color).at(j).area < tags.at(color).at(smaller).area) smaller = j; } if (smaller < tags.at(color).size() && area > tags.at(color).at(smaller).area) tags.at(color).at(smaller) = Tag(cv::Point(moment_x, moment_y), area); } else { tags.at(color).emplace_back(cv::Point(moment_x, moment_y), area); } } else { tags.at(color).emplace_back(cv::Point(moment_x, moment_y), area); } } } } /// <summary> /// Seleciona um conjunto de tags para representar cada robô /// </summary> /// <description> /// P.S.: Aqui eu uso a flag 'isOdd' para representar quando um robô tem as duas bolas laterais. /// </description> std::map<unsigned int, Vision::RecognizedTag> Vision::pick_a_tag() { std::map<unsigned int, RecognizedTag> found_tags; advRobots.clear(); // OUR ROBOTS for (unsigned int i = 0; i < tags.at(Color::Main).size() && i < 3; i++) { std::vector<Tag> secondary_tags; Tag main_tag = tags.at(Color::Main).at(i); // Posição do robô cv::Point position = main_tag.position; // Cálculo da orientação de acordo com os pontos rear e front double orientation = atan2((main_tag.frontPoint.y - position.y) * field::field_height / height, (main_tag.frontPoint.x - position.x) * field::field_width / width); // Para cada tag principal, verifica quais são as secundárias correspondentes for (Tag &secondary_tag : tags.at(Color::Green)) { // Altera a orientação caso esteja errada int tag_side = in_sphere(secondary_tag.position, main_tag, orientation); if (tag_side != 0) { secondary_tag.left = tag_side > 0; // calculos feitos, joga tag no vetor secondary_tags.push_back(secondary_tag); } } if (secondary_tags.size() > 1) { // tag 3 tem duas tags secundárias RecognizedTag tag = {position, orientation, main_tag.frontPoint, main_tag.rearPoint}; found_tags.insert(std::make_pair(2, tag)); } else if (!secondary_tags.empty()) { RecognizedTag tag = {position, orientation, main_tag.frontPoint, main_tag.rearPoint}; if (secondary_tags[0].left) { found_tags.insert(std::make_pair(0, tag)); } else { found_tags.insert(std::make_pair(1, tag)); } } } // OUR ROBOTS // ADV ROBOTS for (unsigned long i = 0; i < MAX_ADV; i++) { if (i < tags.at(Color::Adv).size()) advRobots.push_back(tags.at(Color::Adv).at(i).position); } // BALL POSITION if (!tags[Color::Ball].empty()) { ball.position = tags.at(Color::Ball).at(0).position; ball.isFound = true; } else { // É importante que a posição da bola permaneça sendo a última encontrada // para que os robôs funcionem corretamente em caso de oclusão da bola na imagem // portanto, a posição da bola não deve ser alterada aqui ball.isFound = false; } return found_tags; } /// <summary> /// Verifica se uma tag secundária pertence a esta pick-a e calcula seu delta. /// </summary> /// <param name="position">Posição central do robô</param> /// <param name="secondary">O suposto ponto que marca uma bola da tag</param> /// <param name="orientation">A orientação do robô</param> /// <returns> /// 0, se esta não é uma tag secundária; /// -1, caso a secundária esteja à esquerda; /// 1, caso a secundária esteja à direita /// </returns> int Vision::in_sphere(cv::Point secondary, Tag &main_tag, double &orientation) { // se esta secundária faz parte do robô if (calcDistance(main_tag.position, secondary) <= ROBOT_RADIUS) { if (calcDistance(main_tag.frontPoint, secondary) < calcDistance(main_tag.rearPoint, secondary)) { main_tag.switchPoints(); // calcula a orientação do robô orientation = atan2((main_tag.frontPoint.y - main_tag.position.y) * field::field_height / height, (main_tag.frontPoint.x - main_tag.position.x) * field::field_width / width); } double secSide = atan2((secondary.y - main_tag.position.y) * field::field_height / height, (secondary.x - main_tag.position.x) * field::field_width / width); // Cálculo do ângulo de orientação para diferenciar robôs de mesma cor return (atan2(sin(secSide - orientation + 3.1415), cos(secSide - orientation + 3.1415))) > 0 ? 1 : -1; } return 0; } double Vision::calcDistance(const cv::Point p1, const cv::Point p2) const { return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2)); } void Vision::switchMainWithAdv() { int tmp; for (int i = Limit::Min; i <= Limit::Max; i++) { tmp = cieL[Color::Main][i]; cieL[Color::Main][i] = cieL[Color::Adv][i]; cieL[Color::Adv][i] = tmp; tmp = cieA[Color::Main][i]; cieA[Color::Main][i] = cieA[Color::Adv][i]; cieA[Color::Adv][i] = tmp; tmp = cieB[Color::Main][i]; cieB[Color::Main][i] = cieB[Color::Adv][i]; cieB[Color::Adv][i] = tmp; } tmp = areaMin[Color::Main]; areaMin[Color::Main] = areaMin[Color::Adv]; areaMin[Color::Adv] = tmp; tmp = erode[Color::Main]; erode[Color::Main] = erode[Color::Adv]; erode[Color::Adv] = tmp; tmp = dilate[Color::Main]; dilate[Color::Main] = dilate[Color::Adv]; dilate[Color::Adv] = tmp; tmp = blur[Color::Main]; blur[Color::Main] = blur[Color::Adv]; blur[Color::Adv] = tmp; } cv::Mat Vision::getSplitFrame() { cv::Mat horizontal[2], vertical[2]; for (unsigned long index = 0; index < 3; index++) { cv::cvtColor(threshold_frame.at(index), threshold_frame.at(index), cv::COLOR_GRAY2RGB); } cv::pyrDown(in_frame, vertical[0]); cv::pyrDown(threshold_frame.at(0), vertical[1]); cv::hconcat(vertical, 2, horizontal[0]); cv::pyrDown(threshold_frame.at(1), vertical[0]); cv::pyrDown(threshold_frame.at(2), vertical[1]); cv::hconcat(vertical, 2, horizontal[1]); cv::vconcat(horizontal, 2, splitFrame); return splitFrame; } void Vision::saveCamCalibFrame() { // cv::Mat temp = rawFrameCamcalib.clone(); cv::Mat temp = in_frame.clone(); savedCamCalibFrames.push_back(temp); std::string text = "CamCalib_" + std::to_string(getCamCalibFrames().size()); saveCameraCalibPicture(text, "media/pictures/camCalib/"); std::cout << "Saving picture " << std::endl; } void Vision::collectImagesForCalibration() { std::cout << "Collecting pictures " << std::endl; cv::String path("media/pictures/camCalib/*.png"); //select only png std::vector<cv::String> fn; std::vector<cv::Mat> data; try{ cv::glob(path, fn, true); // recurse for (auto &index : fn) { cv::Mat im = cv::imread(index); if (im.empty()) continue; //only proceed if sucsessful // you probably want to do some preprocessing savedCamCalibFrames.push_back(im); } std::cout << "Pictures collected: " << savedCamCalibFrames.size() << std::endl; cameraCalibration(); }catch (...){ std::cout << "An exception occurred. No images for calibration. \n"; } } void Vision::cameraCalibration() { std::vector<std::vector<cv::Point2f>> checkerBoardImageSpacePoints; std::vector<std::vector<cv::Point3f>> worldSpaceCornersPoints; getChessBoardCorners(savedCamCalibFrames, worldSpaceCornersPoints, checkerBoardImageSpacePoints); std::cout << "Image Space Points " << checkerBoardImageSpacePoints.size() << std::endl; std::cout << "world SpaceCorners Points " << worldSpaceCornersPoints.size() << std::endl; std::vector<cv::Mat> rVectors, tVectors; distanceCoeficents = cv::Mat::zeros(8, 1, CV_64F); int flag = 0; flag |= cv::CALIB_FIX_K4; flag |= cv::CALIB_FIX_K5; //root mean square (RMS) reprojection error and should be between 0.1 and 1.0 pixels in a good calibration. double rms = cv::calibrateCamera(worldSpaceCornersPoints, checkerBoardImageSpacePoints, in_frame.size(), cameraMatrix, distanceCoeficents, rVectors, tVectors, flag); savedCamCalibFrames.clear(); flag_cam_calibrated = true; std::cout << "Camera parameters matrix." << std::endl; std::cout << cameraMatrix << std::endl; std::cout << "Camera distortion coefficients" << std::endl; std::cout << distanceCoeficents << std::endl; std::cout << "RMS" << std::endl; std::cout << rms << std::endl; std::cout << "End of calibration" << std::endl; } void Vision::getChessBoardCorners(std::vector<cv::Mat> images, std::vector<std::vector<cv::Point3f>>& pts3d,std::vector<std::vector<cv::Point2f>>& pts2d) const { cv::TermCriteria termCriteria = cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::MAX_ITER, 40, 0.001); cv::Mat grayFrame; //std::vector<std::vector<cv::Point2f>> allFoundCorners; for (auto &image : images) { std::vector<cv::Point2f> pointBuf; std::vector<cv::Point3f> corners; bool found = cv::findChessboardCorners(image, CHESSBOARD_DIMENSION, pointBuf, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE); for (int i = 0; i < CHESSBOARD_DIMENSION.height; i++) { for (int j = 0; j < CHESSBOARD_DIMENSION.width; ++j) { corners.emplace_back(j * CALIBRATION_SQUARE_DIMENSION, i * CALIBRATION_SQUARE_DIMENSION, 0.0f); } } if (found) { cv::cvtColor(image, grayFrame, cv::COLOR_RGB2GRAY); cv::cornerSubPix(grayFrame, pointBuf, cv::Size(5, 5), cv::Size(-1, -1), termCriteria); pts2d.push_back(pointBuf); pts3d.push_back(corners); } } } bool Vision::foundChessBoardCorners() const { std::vector<cv::Vec2f> foundPoints; cv::Mat temp; temp = in_frame.clone(); return cv::findChessboardCorners(temp, CHESSBOARD_DIMENSION, foundPoints, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE); } void Vision::saveCameraCalibPicture(const std::string in_name, const std::string directory) { cv::Mat frame = in_frame.clone(); std::string picName = directory + in_name + ".png"; cv::cvtColor(frame, frame, cv::COLOR_RGB2BGR); cv::imwrite(picName, frame); } cv::Mat Vision::getThreshold(const unsigned long index) { cv::cvtColor(threshold_frame.at(index), threshold_frame.at(index), cv::COLOR_GRAY2RGB); return threshold_frame.at(index); } void Vision::setFlagCamCalibrated(const bool value) { this->flag_cam_calibrated = value; } void Vision::popCamCalibFrames() { savedCamCalibFrames.pop_back(); } void Vision::setCIE_L(const unsigned long index0, const int index1, const int inValue) { if (index0 < MAX_COLORS && (index1 == Limit::Min || index1 == Limit::Max)) cieL[index0][index1] = inValue; else std::cout << "Vision:setCIE_L: could not set (invalid index)" << std::endl; } void Vision::setCIE_A(const unsigned long index0, const int index1, const int inValue) { if (index0 < MAX_COLORS && (index1 == Limit::Min || index1 == Limit::Max)) cieA[index0][index1] = inValue; else std::cout << "Vision:setCIE_A: could not set (invalid index)" << std::endl; } void Vision::setCIE_B(const unsigned long index0, const int index1, const int inValue) { if (index0 < MAX_COLORS && (index1 == Limit::Min || index1 == Limit::Max)) cieB[index0][index1] = inValue; else std::cout << "Vision:setCIE_B: could not set (invalid index)" << std::endl; } void Vision::setErode(const unsigned long index, const int inValue) { if (index < MAX_COLORS) erode[index] = inValue; else std::cout << "Vision:setErode: could not set (invalid index or convert type)" << std::endl; } void Vision::setDilate(const unsigned long index, const int inValue) { if (index < MAX_COLORS) dilate[index] = inValue; else std::cout << "Vision:setDilate: could not set (invalid index or convert type)" << std::endl; } void Vision::setBlur(const unsigned long index, int inValue) { if (index < MAX_COLORS) { if (inValue == 0 || inValue % 2 == 1) blur[index] = inValue; else blur[index] = inValue+1; } else { std::cout << "Vision:setBlur: could not set (invalid index or convert type)" << std::endl; } } void Vision::setAmin(const unsigned long index, const int inValue) { if (index < MAX_COLORS) areaMin[index] = inValue; else std::cout << "Vision:setAmin: could not set (invalid index or convert type)" << std::endl; } void Vision::setFrameSize(const int inWidth, const int inHeight) { if (inWidth >= 0) width = inWidth; if (inHeight >= 0) height = inHeight; } Vision::Vision(int w, int h) : width(w), height(h), threshold_frame(MAX_COLORS), tags(MAX_COLORS), cieL{{0, 255}, {0, 255}, {0, 255}, {0, 255}}, cieA{{0, 255}, {0, 255}, {0, 255}, {0, 255}}, cieB{{0, 255}, {0, 255}, {0, 255}, {0, 255}}, dilate{0, 0, 0, 0}, erode{0, 0, 0, 0}, blur{3, 3, 3, 3}, areaMin{50, 20, 30, 30} { } Vision::~Vision() = default;
33.632967
161
0.673071
PEQUI-VSSS
7800d16778bc873e2a6022ce7c163fe5bd3223cf
464
hh
C++
TrkFitter/TrkLineMaker.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkFitter/TrkLineMaker.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkFitter/TrkLineMaker.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
//-------------------------------------------------------------------------- // File and Version Information: // $Id: TrkLineMaker.hh 104 2010-01-15 12:13:14Z stroili $ // // Author(s): Gerhard Raven // //------------------------------------------------------------------------ #ifndef TRKLINEMAKER_HH #define TRKLINEMAKER_HH #include "TrkFitter/TrkSimpleMaker.hh" #include "TrkFitter/TrkLineRep.hh" typedef TrkSimpleMaker<TrkLineRep> TrkLineMaker; #endif
27.294118
76
0.506466
brownd1978
78019d43eaf3bd8f6b49eaf96e4ec72b9aa73015
4,238
cpp
C++
src/Base/View.cpp
geenux/choreonoid
25e534dd4dbf1ac890cdfe80b51add9c4f81e505
[ "MIT" ]
null
null
null
src/Base/View.cpp
geenux/choreonoid
25e534dd4dbf1ac890cdfe80b51add9c4f81e505
[ "MIT" ]
null
null
null
src/Base/View.cpp
geenux/choreonoid
25e534dd4dbf1ac890cdfe80b51add9c4f81e505
[ "MIT" ]
null
null
null
/** @author Shin'ichiro Nakaoka */ #include "View.h" #include "ViewArea.h" #include "ViewManager.h" #include "App.h" #include "AppConfig.h" #include <QLayout> #include <QKeyEvent> #include <QTabWidget> using namespace std; using namespace cnoid; View::View() { isActive_ = false; viewArea_ = 0; defaultLayoutArea_ = CENTER; isFontSizeZoomKeysEnabled = false; fontZoom = 0; } View::~View() { if(isActive_){ onDeactivated(); } if(viewArea_){ viewArea_->removeView(this); } View* focusView = lastFocusView(); if(this == focusView){ App::clearFocusView(); } } bool View::isActive() const { return isActive_; } void View::showEvent(QShowEvent* event) { if(!isActive_){ isActive_ = true; onActivated(); sigActivated_(); } } void View::hideEvent(QHideEvent* event) { if(isActive_){ isActive_ = false; onDeactivated(); sigDeactivated_(); } } /** Virtual function which is called when the view becomes visible on the main window. @note In the current implementation, this function may be continuously called two or three times when the perspective changes, and the number of calles does not necessarily corresponds to the number of 'onDeactivated()' calles. @todo improve the behavior written as note */ void View::onActivated() { } void View::onDeactivated() { if(isFontSizeZoomKeysEnabled){ AppConfig::archive()->openMapping(viewClass()->className())->write("fontZoom", fontZoom); } } void View::setName(const std::string& name) { setObjectName(name.c_str()); setWindowTitle(name.c_str()); } ViewClass* View::viewClass() const { return ViewManager::viewClass(typeid(*this)); } void View::bringToFront() { if(viewArea_){ QTabWidget* tab = 0; for(QWidget* widget = parentWidget(); widget; widget = widget->parentWidget()){ if(tab = dynamic_cast<QTabWidget*>(widget)){ tab->setCurrentWidget(this); } } } } void View::setDefaultLayoutArea(LayoutArea area) { defaultLayoutArea_ = area; } View::LayoutArea View::defaultLayoutArea() const { return defaultLayoutArea_; } void View::setLayout(QLayout* layout) { const int margin = 0; layout->setContentsMargins(margin, margin, margin, margin); QWidget::setLayout(layout); } QWidget* View::indicatorOnInfoBar() { return 0; } void View::enableFontSizeZoomKeys(bool on) { isFontSizeZoomKeysEnabled = on; if(on){ MappingPtr config = AppConfig::archive()->openMapping(viewClass()->className()); int storedZoom; if(config->read("fontZoom", storedZoom)){ zoomFontSize(storedZoom); } } } void View::keyPressEvent(QKeyEvent* event) { bool processed = false; if(isFontSizeZoomKeysEnabled){ if(event->modifiers() & Qt::ControlModifier){ switch(event->key()){ case Qt::Key_Plus: case Qt::Key_Semicolon: zoomFontSize(1); processed = true; break; case Qt::Key_Minus: zoomFontSize(-1); processed = true; break; defaut: break; } } } if(!processed){ QWidget::keyPressEvent(event); } } void View::zoomFontSize(int zoom) { zoomFontSizeSub(zoom, findChildren<QWidget*>()); fontZoom += zoom; } void View::zoomFontSizeSub(int zoom, const QList<QWidget*>& widgets) { int n = widgets.size(); for(int i=0; i < n; ++i){ QWidget* widget = widgets[i]; QFont font = widget->font(); font.setPointSize(font.pointSize() + zoom); widget->setFont(font); // The following recursive iteration is disabled because // it makes doubled zooming for some composite widgets // zoomFontSizeSub(zoom, widget->findChildren<QWidget*>()); } } void View::onAttachedMenuRequest(MenuManager& menuManager) { } bool View::storeState(Archive& archive) { return true; } bool View::restoreState(const Archive& archive) { return true; }
18.752212
97
0.614205
geenux
780233af3e04cbfb664be3e2a14ea4353dcf9761
6,218
cpp
C++
fboss/agent/hw/test/HwCpuFb303StatsTests.cpp
TomMD/fboss
30654277076e1f1f50c9b756e9690737dc1476e0
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/test/HwCpuFb303StatsTests.cpp
TomMD/fboss
30654277076e1f1f50c9b756e9690737dc1476e0
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/test/HwCpuFb303StatsTests.cpp
TomMD/fboss
30654277076e1f1f50c9b756e9690737dc1476e0
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2004-present, Facebook, Inc. * 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. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/hw/HwCpuFb303Stats.h" #include "fboss/agent/hw/StatsConstants.h" #include <fb303/ServiceData.h> #include <folly/logging/xlog.h> #include <gtest/gtest.h> using namespace facebook::fboss; using namespace facebook::fb303; using namespace std::chrono; namespace { HwCpuFb303Stats::QueueId2Name kQueue2Name = { {1, "high"}, {2, "low"}, }; HwPortStats getInitedStats() { return { apache::thrift::FragileConstructor(), 0, // inBytes 0, // inUcastPackets 0, // inMulticastPkts 0, // inBroadcastPkts 0, // inDiscards 0, // inErrors 0, // inPause 0, // inIpv4HdrErrors 0, // inIpv6HdrErrors 0, // inDstNullDiscards 0, // inDiscardsRaw 0, // outBytes 0, // outUnicastPkts 0, // outMulticastPkts 0, // outBroadcastPkts 0, // outDiscards 0, // outErrors 0, // outPause 0, // outCongestionDiscardPkts 0, // wredDroppedPackets {{1, 0}, {2, 0}}, // queueOutDiscards {{1, 0}, {2, 0}}, // queueOutBytes 0, // outEcnCounter {{1, 1}, {2, 1}}, // queueOutPackets {{1, 2}, {2, 2}}, // queueOutDiscardPackets {{0, 0}, {0, 0}}, // queueWatermarkBytes 0, // fecCorrectableErrors 0, // fecUncorrectableErrors 0, // timestamp "test", // portName }; } void updateStats(HwCpuFb303Stats& cpuStats) { auto now = duration_cast<seconds>(system_clock::now().time_since_epoch()); // To get last increment from monotonic counter we need to update it twice HwPortStats empty{}; // Need to populate queue stats, since by default these // maps are empty *empty.queueOutDiscardPackets__ref() = *empty.queueOutPackets__ref() = *empty.queueOutPackets__ref() = {{1, 0}, {2, 0}}; cpuStats.updateStats(empty, now); cpuStats.updateStats(getInitedStats(), now); } void verifyUpdatedStats(const HwCpuFb303Stats& cpuStats) { auto curValue{1}; curValue = 1; for (auto counterName : HwCpuFb303Stats::kQueueStatKeys()) { for (const auto& queueIdAndName : kQueue2Name) { EXPECT_EQ( cpuStats.getCounterLastIncrement(HwCpuFb303Stats::statName( counterName, queueIdAndName.first, queueIdAndName.second)), curValue); } ++curValue; } } } // namespace TEST(HwCpuFb303StatsTest, StatName) { for (auto statKey : HwCpuFb303Stats::kQueueStatKeys()) { EXPECT_EQ( HwCpuFb303Stats::statName(statKey, 1, "high"), folly::to<std::string>("cpu.queue1.cpuQueue-high.", statKey)); } } TEST(HwCpuFb303StatsTest, StatsInit) { HwCpuFb303Stats stats(kQueue2Name); for (auto statKey : HwCpuFb303Stats::kQueueStatKeys()) { for (const auto& queueIdAndName : kQueue2Name) { EXPECT_TRUE(fbData->getStatMap()->contains(HwCpuFb303Stats::statName( statKey, queueIdAndName.first, queueIdAndName.second))); } } } TEST(HwCpuFb303StatsTest, StatsDeInit) { { HwCpuFb303Stats stats(kQueue2Name); } for (auto statKey : HwCpuFb303Stats::kQueueStatKeys()) { for (const auto& queueIdAndName : kQueue2Name) { EXPECT_FALSE(fbData->getStatMap()->contains(HwCpuFb303Stats::statName( statKey, queueIdAndName.first, queueIdAndName.second))); } } } TEST(HwCpuFb303Stats, UpdateStats) { HwCpuFb303Stats cpuStats(kQueue2Name); updateStats(cpuStats); verifyUpdatedStats(cpuStats); } TEST(HwCpuFb303StatsTest, RenameQueue) { HwCpuFb303Stats stats(kQueue2Name); stats.queueChanged(1, "very_high"); auto newQueueMapping = kQueue2Name; for (auto statKey : HwCpuFb303Stats::kQueueStatKeys()) { EXPECT_TRUE(fbData->getStatMap()->contains( HwCpuFb303Stats::statName(statKey, 1, "very_high"))); EXPECT_FALSE(fbData->getStatMap()->contains( HwCpuFb303Stats::statName(statKey, 1, "high"))); // No impact on low EXPECT_TRUE(fbData->getStatMap()->contains( HwCpuFb303Stats::statName(statKey, 2, "low"))); } } TEST(HwCpuFb303StatsTest, AddQueue) { HwCpuFb303Stats stats(kQueue2Name); stats.queueChanged(3, "very_high"); auto newQueueMapping = kQueue2Name; for (auto statKey : HwCpuFb303Stats::kQueueStatKeys()) { EXPECT_TRUE(fbData->getStatMap()->contains( HwCpuFb303Stats::statName(statKey, 1, "high"))); EXPECT_TRUE(fbData->getStatMap()->contains( HwCpuFb303Stats::statName(statKey, 2, "low"))); EXPECT_TRUE(fbData->getStatMap()->contains( HwCpuFb303Stats::statName(statKey, 3, "very_high"))); } } TEST(HwCpuFb303StatsTest, RemoveQueue) { HwCpuFb303Stats stats(kQueue2Name); stats.queueRemoved(1); auto newQueueMapping = kQueue2Name; for (auto statKey : HwCpuFb303Stats::kQueueStatKeys()) { EXPECT_FALSE(fbData->getStatMap()->contains( HwCpuFb303Stats::statName(statKey, 1, "high"))); EXPECT_TRUE(fbData->getStatMap()->contains( HwCpuFb303Stats::statName(statKey, 2, "low"))); } } TEST(HwCpuFb303Stats, queueNameChangeResetsValue) { HwCpuFb303Stats cpuStats(kQueue2Name); updateStats(cpuStats); cpuStats.queueChanged(1, "very_high"); cpuStats.queueChanged(2, "very_low"); HwCpuFb303Stats::QueueId2Name newQueues = {{1, "very_high"}, {2, "very_low"}}; for (auto counterName : HwCpuFb303Stats::kQueueStatKeys()) { for (const auto& queueIdAndName : newQueues) { EXPECT_TRUE(fbData->getStatMap()->contains(HwCpuFb303Stats::statName( counterName, queueIdAndName.first, queueIdAndName.second))); EXPECT_EQ( cpuStats.getCounterLastIncrement(HwCpuFb303Stats::statName( counterName, queueIdAndName.first, queueIdAndName.second)), 0); } } for (auto counterName : HwCpuFb303Stats::kQueueStatKeys()) { for (const auto& queueIdAndName : kQueue2Name) { EXPECT_FALSE(fbData->getStatMap()->contains(HwCpuFb303Stats::statName( counterName, queueIdAndName.first, queueIdAndName.second))); } } }
33.430108
80
0.680444
TomMD
78029370fa5c23f92c6e5694ed03dcd806a2a202
3,091
cc
C++
srcs/lox/passes/pass_runner.cc
edimetia3d/cppLox
394bb0855c2a9d9b53f179330c2daa341786a04d
[ "MIT" ]
2
2021-12-25T01:45:26.000Z
2022-02-10T00:50:25.000Z
srcs/lox/passes/pass_runner.cc
edimetia3d/cppLox
394bb0855c2a9d9b53f179330c2daa341786a04d
[ "MIT" ]
null
null
null
srcs/lox/passes/pass_runner.cc
edimetia3d/cppLox
394bb0855c2a9d9b53f179330c2daa341786a04d
[ "MIT" ]
null
null
null
// // LICENSE: MIT // #include "pass_runner.h" #define RUNPASS_AND_UPDATE(KEY_NAME) \ { \ auto old_value = (KEY_NAME)(); \ auto new_value = RunPass(old_value); \ if (new_value != old_value) { \ (KEY_NAME)(new_value); \ } \ } #define RUNPASS_ON_VEC_AND_UPDATE(KEY_NAME) \ { \ auto cpy = (KEY_NAME)(); \ for (auto &node : cpy) { \ { \ auto new_value = RunPass(node); \ node = new_value; \ }; \ } \ if ((KEY_NAME)() != cpy) { \ (KEY_NAME)(cpy); \ } \ } namespace lox { void PassRunner::Visit(BlockStmt *state) { RUNPASS_ON_VEC_AND_UPDATE(state->statements) } void PassRunner::Visit(VarDeclStmt *state) { if (IsValid(state->initializer())) { RUNPASS_AND_UPDATE(state->initializer); } } void PassRunner::Visit(VariableExpr *state) {} void PassRunner::Visit(AssignExpr *state) { RUNPASS_AND_UPDATE(state->value); } void PassRunner::Visit(FunctionStmt *state) { RUNPASS_ON_VEC_AND_UPDATE(state->body); } void PassRunner::Visit(LogicalExpr *state) { RUNPASS_AND_UPDATE(state->left); RUNPASS_AND_UPDATE(state->right); } void PassRunner::Visit(BinaryExpr *state) { RUNPASS_AND_UPDATE(state->left); RUNPASS_AND_UPDATE(state->right); } void PassRunner::Visit(GroupingExpr *state) { RUNPASS_AND_UPDATE(state->expression); } void PassRunner::Visit(LiteralExpr *state) {} void PassRunner::Visit(UnaryExpr *state) { RUNPASS_AND_UPDATE(state->right); } void PassRunner::Visit(CallExpr *state) { RUNPASS_AND_UPDATE(state->callee); RUNPASS_ON_VEC_AND_UPDATE(state->arguments) } void PassRunner::Visit(PrintStmt *state) { RUNPASS_AND_UPDATE(state->expression); } void PassRunner::Visit(ReturnStmt *state) { if (IsValid(state->value())) { RUNPASS_AND_UPDATE(state->value); } } void PassRunner::Visit(WhileStmt *state) { RUNPASS_AND_UPDATE(state->condition); RUNPASS_AND_UPDATE(state->body); } void PassRunner::Visit(BreakStmt *state) {} void PassRunner::Visit(ExprStmt *state) { RUNPASS_AND_UPDATE(state->expression); } void PassRunner::Visit(IfStmt *state) { RUNPASS_AND_UPDATE(state->condition); RUNPASS_AND_UPDATE(state->thenBranch); if (IsValid(state->elseBranch())) { RUNPASS_AND_UPDATE(state->elseBranch); } } void PassRunner::Visit(ClassStmt *state) { if (IsValid(state->superclass())) { RUNPASS_AND_UPDATE(state->superclass); } RUNPASS_ON_VEC_AND_UPDATE(state->methods) } void PassRunner::Visit(GetAttrExpr *state) { RUNPASS_AND_UPDATE(state->src_object); } void PassRunner::Visit(SetAttrExpr *state) { RUNPASS_AND_UPDATE(state->src_object); RUNPASS_AND_UPDATE(state->value); } } // namespace lox
36.364706
89
0.601747
edimetia3d
780320aabb11830497141760c1a02e49bf06a584
3,401
hh
C++
src/parser/gen_parser.hh
ShreyasKhandekar/IEGenLib
93bce46a3fe0b829c3cb957746a53b7cfc4373b5
[ "BSD-2-Clause" ]
5
2019-05-20T03:35:41.000Z
2021-09-16T22:22:13.000Z
src/parser/gen_parser.hh
ShreyasKhandekar/IEGenLib
93bce46a3fe0b829c3cb957746a53b7cfc4373b5
[ "BSD-2-Clause" ]
160
2021-01-05T18:34:10.000Z
2022-03-03T01:27:49.000Z
src/parser/gen_parser.hh
ShreyasKhandekar/IEGenLib
93bce46a3fe0b829c3cb957746a53b7cfc4373b5
[ "BSD-2-Clause" ]
10
2015-11-04T17:45:04.000Z
2022-01-15T08:43:18.000Z
/* A Bison parser, made by GNU Bison 3.0.2. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. 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 3 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, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ #ifndef YY_YY_HOME_KING_TOOLS_BRANCH_ISLUPDATE_SRC_PARSER_GEN_PARSER_HH_INCLUDED # define YY_YY_HOME_KING_TOOLS_BRANCH_ISLUPDATE_SRC_PARSER_GEN_PARSER_HH_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { LBRACE = 258, RBRACE = 259, LBRACKET = 260, RBRACKET = 261, LPAREN = 262, RPAREN = 263, COMMA = 264, COLON = 265, LT = 266, LTE = 267, GT = 268, GTE = 269, SEMI = 270, OR = 271, UNION = 272, INVERSE = 273, EXISTS = 274, EQ = 275, ARROW = 276, ID = 277, INT = 278, INVALID_ID = 279, PLUS = 280, DASH = 281, STAR = 282, UMINUS = 283, AND = 284, WAND = 285 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE YYSTYPE; union YYSTYPE { #line 36 "parser/parser.y" /* yacc.c:1909 */ std::string* sval; int ival; iegenlib::TupleDecl* tdecl; iegenlib::Environment* env; iegenlib::Set* set; iegenlib::Relation* relation; iegenlib::Conjunction* conj; std::list<iegenlib::Conjunction*>* conjlist; iegenlib::Exp* exp; std::list<iegenlib::Exp*>* explist; std::list<std::string>* symlist; std::list<std::string>* existslist; #line 100 "/home/king/tools/branch/islUpdate/src/parser/gen_parser.hh" /* yacc.c:1909 */ }; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif extern YYSTYPE yylval; int yyparse (void); #endif /* !YY_YY_HOME_KING_TOOLS_BRANCH_ISLUPDATE_SRC_PARSER_GEN_PARSER_HH_INCLUDED */
30.63964
89
0.658924
ShreyasKhandekar
78040db4c3e0ec693440e0ac4157139790b53a35
3,112
cc
C++
server/db.cc
proprietary/prv.ec
0cc763ca1f27eff53780781d987da1e93455704c
[ "Apache-2.0" ]
1
2022-01-12T18:37:38.000Z
2022-01-12T18:37:38.000Z
server/db.cc
proprietary/prv.ec
0cc763ca1f27eff53780781d987da1e93455704c
[ "Apache-2.0" ]
null
null
null
server/db.cc
proprietary/prv.ec
0cc763ca1f27eff53780781d987da1e93455704c
[ "Apache-2.0" ]
null
null
null
#include "server/db.h" #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <span> #include <exception> namespace ec_prv { namespace db { auto KVStore::open_default() -> KVStore { const char* EC_PRV_ROCKSDB_DATADIR_PATH = std::getenv("EC_PRV_ROCKSDB_DATADIR_PATH"); if (nullptr == EC_PRV_ROCKSDB_DATADIR_PATH || strlen(EC_PRV_ROCKSDB_DATADIR_PATH) == 0) { throw std::runtime_error{"Environment variable EC_PRV_ROCKSDB_DATADIR_PATH is missing"}; } return KVStore{EC_PRV_ROCKSDB_DATADIR_PATH}; } KVStore::KVStore(std::string_view path) { rocksdb::Options options; options.create_if_missing = true; options.IncreaseParallelism(); options.OptimizeLevelStyleCompaction(); std::string datadir_path {path}; auto status = rocksdb::DB::Open(options, datadir_path, &db_); if (!status.ok()) { throw RocksDBError{status.ToString()}; } } KVStore::~KVStore() noexcept { delete db_; } KVStore::KVStore(KVStore&& other) noexcept { delete this->db_; this->db_ = other.db_; other.db_ = nullptr; other.~KVStore(); } KVStore& KVStore::operator=(KVStore&& other) noexcept { if (this->db_ != nullptr) { delete this->db_; } this->db_ = other.db_; other.db_ = nullptr; other.~KVStore(); return *this; } bool KVStore::put(std::vector<uint8_t>& key, std::vector<uint8_t>& value) { rocksdb::Slice k{reinterpret_cast<char*>(key.data()), key.size()}; rocksdb::Slice v{reinterpret_cast<char*>(value.data()), value.size()}; auto s = db_->Put(rocksdb::WriteOptions(), k, v); return s.ok(); } bool KVStore::put(std::span<uint8_t> key, std::span<uint8_t> value) { rocksdb::Slice k{reinterpret_cast<char*>(key.data()), key.size()}; rocksdb::Slice v{reinterpret_cast<char*>(value.data()), value.size()}; auto s = db_->Put(rocksdb::WriteOptions(), k, v); return s.ok(); } auto KVStore::get(std::vector<uint8_t>& key) -> std::vector<uint8_t> { rocksdb::Slice k{reinterpret_cast<char*>(key.data()), key.size()}; std::string v; auto s = db_->Get(rocksdb::ReadOptions(), k, &v); assert(s.ok()); if (!s.ok()) { // TODO: think about how to handle this in context of its use return {}; } std::vector<uint8_t> out(v.size()); std::copy(v.begin(), v.end(), out.begin()); return out; } void KVStore::get(std::string& dst, std::span<uint8_t> const key) { rocksdb::Slice k{reinterpret_cast<char const*>(key.data()), key.size()}; auto s = db_->Get(rocksdb::ReadOptions(), k, &dst); if (!s.ok()) { assert(false); // TODO } } auto KVStore::put(url_index::URLIndex key, std::span<uint8_t> value) -> bool { auto b = key.as_bytes(); rocksdb::Slice k {reinterpret_cast<char*>(b.data()), b.size()}; rocksdb::Slice v {reinterpret_cast<char*>(value.data()), value.size()}; auto s = db_->Put(rocksdb::WriteOptions(), k, v); return s.ok(); } auto KVStore::get(rocksdb::PinnableSlice& dst, url_index::URLIndex key) -> rocksdb::Status { auto b = key.as_bytes(); rocksdb::Slice k {reinterpret_cast<char*>(b.data()), b.size()}; auto s = db_->Get(rocksdb::ReadOptions(), db_->DefaultColumnFamily(), k, &dst); return s; } } // namespace db } // namespace ec_prv
29.084112
92
0.684769
proprietary
78056c583afccd8a1339aff0304be824bd66ecc4
26
cpp
C++
components/core/src/streaming_compression/Compressor.cpp
kirkrodrigues/clp
bb81eec43da218a5fa3f3a367e0a24c144bdf0c8
[ "Apache-2.0" ]
28
2021-07-18T02:21:14.000Z
2021-09-30T22:46:24.000Z
components/core/src/streaming_compression/Compressor.cpp
kirkrodrigues/clp
bb81eec43da218a5fa3f3a367e0a24c144bdf0c8
[ "Apache-2.0" ]
15
2021-10-12T03:55:07.000Z
2022-03-24T09:04:35.000Z
components/core/src/streaming_compression/Compressor.cpp
kirkrodrigues/clp
bb81eec43da218a5fa3f3a367e0a24c144bdf0c8
[ "Apache-2.0" ]
11
2021-10-06T11:35:47.000Z
2022-03-20T11:40:49.000Z
#include "Compressor.hpp"
13
25
0.769231
kirkrodrigues
7806073556f48b53e9f81b5b30dd04733b5ab553
515
hpp
C++
src/KawaiiEngine/include/graphics/deps.hpp
Mathieu-Lala/Cute_Solar_System_-3
0bfe496991344709481995af348da2be37a19cac
[ "MIT" ]
4
2021-06-03T11:20:09.000Z
2022-02-11T06:52:54.000Z
src/KawaiiEngine/include/graphics/deps.hpp
Mathieu-Lala/Cute_Solar_System_-3
0bfe496991344709481995af348da2be37a19cac
[ "MIT" ]
35
2021-05-29T09:25:57.000Z
2021-06-28T04:49:22.000Z
src/KawaiiEngine/include/graphics/deps.hpp
Mathieu-Lala/Kawaii_Engine
0bfe496991344709481995af348da2be37a19cac
[ "MIT" ]
null
null
null
#pragma once #include "helpers/warnings.hpp" DISABLE_WARNING_PUSH DISABLE_WARNING_OLD_CAST #include <imgui.h> DISABLE_WARNING_POP #include <imgui_impl_glfw.h> #include <imgui_impl_opengl3.h> #include <GL/glew.h> #include <GLFW/glfw3.h> namespace kawe { namespace ImGuiHelper { template<typename... Args> inline auto Text(const std::string_view format, Args &&... args) { ::ImGui::TextUnformatted(fmt::format(format, std::forward<Args>(args)...).c_str()); } } // namespace ImGuiHelper } // namespace kawe
19.074074
87
0.741748
Mathieu-Lala
780657d535958102269a41c81530e3dbe2f5352d
1,131
cpp
C++
src/main/util/backtrace.cpp
aaronwald/coypu
9371736309d3d205a43bd7e8972ea4a5621c176f
[ "Apache-2.0" ]
null
null
null
src/main/util/backtrace.cpp
aaronwald/coypu
9371736309d3d205a43bd7e8972ea4a5621c176f
[ "Apache-2.0" ]
null
null
null
src/main/util/backtrace.cpp
aaronwald/coypu
9371736309d3d205a43bd7e8972ea4a5621c176f
[ "Apache-2.0" ]
null
null
null
// http://eli.thegreenplace.net/2015/programmatic-access-to-the-call-stack-in-c #define UNW_LOCAL_ONLY #include <cxxabi.h> #include <libunwind.h> #include <cstdio> #include <cstdlib> #include "backtrace.h" using namespace coypu::backtrace; void BackTrace::bt() { unw_cursor_t cursor; unw_context_t context; // Initialize cursor to current frame for local unwinding. unw_getcontext(&context); unw_init_local(&cursor, &context); // Unwind frames one by one, going up the frame stack. while (unw_step(&cursor) > 0) { unw_word_t offset, pc; unw_get_reg(&cursor, UNW_REG_IP, &pc); if (pc == 0) { break; } std::printf("0x%lx:", pc); char sym[256]; if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) { char* nameptr = sym; int status; char* demangled = abi::__cxa_demangle(sym, nullptr, nullptr, &status); if (status == 0) { nameptr = demangled; } std::printf(" (%s+0x%lx)\n", nameptr, offset); std::free(demangled); } else { std::printf(" -- error: unable to obtain symbol name for this frame\n"); } } }
25.704545
79
0.635721
aaronwald
7808eb640a7731eb8e80fc180d245ebebb8d74f0
7,658
cpp
C++
libcaf_core/test/typed_response_promise.cpp
v2nero/actor-framework
c2f811809143d32c598471a20363238b0882a761
[ "BSL-1.0", "BSD-3-Clause" ]
1
2020-07-16T19:01:52.000Z
2020-07-16T19:01:52.000Z
libcaf_core/test/typed_response_promise.cpp
Boubou818/actor-framework
da90ef78b26da5d225f039072e616da415c48494
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/test/typed_response_promise.cpp
Boubou818/actor-framework
da90ef78b26da5d225f039072e616da415c48494
[ "BSL-1.0", "BSD-3-Clause" ]
1
2021-02-19T11:25:15.000Z
2021-02-19T11:25:15.000Z
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <map> #include "caf/config.hpp" #define CAF_SUITE typed_response_promise #include "caf/test/unit_test.hpp" #include "caf/all.hpp" using namespace caf; namespace { using foo_actor = typed_actor<replies_to<int>::with<int>, replies_to<get_atom, int>::with<int>, replies_to<get_atom, int, int>::with<int, int>, replies_to<get_atom, double>::with<double>, replies_to<get_atom, double, double> ::with<double, double>, reacts_to<put_atom, int, int>, reacts_to<put_atom, int, int, int>>; using foo_promise = typed_response_promise<int>; using foo2_promise = typed_response_promise<int, int>; using foo3_promise = typed_response_promise<double>; using get1_helper = typed_actor<replies_to<int, int>::with<put_atom, int, int>>; using get2_helper = typed_actor<replies_to<int, int, int>::with<put_atom, int, int, int>>; class foo_actor_impl : public foo_actor::base { public: foo_actor_impl(actor_config& cfg) : foo_actor::base(cfg) { // nop } behavior_type make_behavior() override { return { [=](int x) -> foo_promise { auto resp = response(x * 2); CAF_CHECK(!resp.pending()); return resp.deliver(x * 4); // has no effect }, [=](get_atom, int x) -> foo_promise { auto calculator = spawn([]() -> get1_helper::behavior_type { return { [](int promise_id, int value) -> result<put_atom, int, int> { return {put_atom::value, promise_id, value * 2}; } }; }); send(calculator, next_id_, x); auto& entry = promises_[next_id_++]; entry = make_response_promise<foo_promise>(); return entry; }, [=](get_atom, int x, int y) -> foo2_promise { auto calculator = spawn([]() -> get2_helper::behavior_type { return { [](int promise_id, int v0, int v1) -> result<put_atom, int, int, int> { return {put_atom::value, promise_id, v0 * 2, v1 * 2}; } }; }); send(calculator, next_id_, x, y); auto& entry = promises2_[next_id_++]; entry = make_response_promise<foo2_promise>(); // verify move semantics CAF_CHECK(entry.pending()); foo2_promise tmp(std::move(entry)); CAF_CHECK(!entry.pending()); CAF_CHECK(tmp.pending()); entry = std::move(tmp); CAF_CHECK(entry.pending()); CAF_CHECK(!tmp.pending()); return entry; }, [=](get_atom, double) -> foo3_promise { auto resp = make_response_promise<double>(); return resp.deliver(make_error(sec::unexpected_message)); }, [=](get_atom, double x, double y) { return response(x * 2, y * 2); }, [=](put_atom, int promise_id, int x) { auto i = promises_.find(promise_id); if (i == promises_.end()) return; i->second.deliver(x); promises_.erase(i); }, [=](put_atom, int promise_id, int x, int y) { auto i = promises2_.find(promise_id); if (i == promises2_.end()) return; i->second.deliver(x, y); promises2_.erase(i); } }; } private: int next_id_ = 0; std::map<int, foo_promise> promises_; std::map<int, foo2_promise> promises2_; }; struct fixture { fixture() : system(cfg), self(system, true), foo(system.spawn<foo_actor_impl>()) { // nop } actor_system_config cfg; actor_system system; scoped_actor self; foo_actor foo; }; } // namespace <anonymous> CAF_TEST_FIXTURE_SCOPE(typed_spawn_tests, fixture) CAF_TEST(typed_response_promise) { typed_response_promise<int> resp; CAF_MESSAGE("trigger 'invalid response promise' error"); resp.deliver(1); // delivers on an invalid promise has no effect auto f = make_function_view(foo); CAF_CHECK_EQUAL(f(get_atom::value, 42), 84); CAF_CHECK_EQUAL(f(get_atom::value, 42, 52), std::make_tuple(84, 104)); CAF_CHECK_EQUAL(f(get_atom::value, 3.14, 3.14), std::make_tuple(6.28, 6.28)); } CAF_TEST(typed_response_promise_chained) { auto f = make_function_view(foo * foo * foo); CAF_CHECK_EQUAL(f(1), 8); } // verify that only requests get an error response message CAF_TEST(error_response_message) { auto f = make_function_view(foo); CAF_CHECK_EQUAL(f(get_atom::value, 3.14), sec::unexpected_message); self->send(foo, get_atom::value, 42); self->receive( [](int x) { CAF_CHECK_EQUAL(x, 84); }, [](double x) { CAF_ERROR("unexpected ordinary response message received: " << x); } ); self->send(foo, get_atom::value, 3.14); self->receive( [&](error& err) { CAF_CHECK_EQUAL(err, sec::unexpected_message); self->send(self, message{}); } ); } // verify that delivering to a satisfied promise has no effect CAF_TEST(satisfied_promise) { self->send(foo, 1); self->send(foo, get_atom::value, 3.14, 3.14); int i = 0; self->receive_for(i, 2) ( [](int x) { CAF_CHECK_EQUAL(x, 1 * 2); }, [](double x, double y) { CAF_CHECK_EQUAL(x, 3.14 * 2); CAF_CHECK_EQUAL(y, 3.14 * 2); } ); } CAF_TEST(delegating_promises) { using task = std::pair<typed_response_promise<int>, int>; struct state { std::vector<task> tasks; }; using bar_actor = typed_actor<replies_to<int>::with<int>, reacts_to<ok_atom>>; auto bar_fun = [](bar_actor::stateful_pointer<state> self, foo_actor worker) -> bar_actor::behavior_type { return { [=](int x) -> typed_response_promise<int> { auto& tasks = self->state.tasks; tasks.emplace_back(self->make_response_promise<int>(), x); self->send(self, ok_atom::value); return tasks.back().first; }, [=](ok_atom) { auto& tasks = self->state.tasks; if (!tasks.empty()) { auto& task = tasks.back(); task.first.delegate(worker, task.second); tasks.pop_back(); } } }; }; auto f = make_function_view(system.spawn(bar_fun, foo)); CAF_CHECK_EQUAL(f(42), 84); } CAF_TEST_FIXTURE_SCOPE_END()
33.884956
90
0.536432
v2nero
780983d251b485f9e963bd8bf9de538eec72a7d9
310
cpp
C++
657. Judge Route Circle.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
657. Judge Route Circle.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
657. Judge Route Circle.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
class Solution { public: bool judgeCircle(string moves) { int v = 0, h = 0; unordered_map<char, int>m{{'R', 1}, {'L', -1}, {'U', -1}, {'D', 1}}; for(auto x: moves) if(x == 'L' || x == 'R') h += m[x]; else v += m[x]; return v == 0 && h == 0; } };
25.833333
76
0.387097
rajeev-ranjan-au6
780affb20c07c1bf973ccc3754fdbdd3ba7993cb
1,451
cpp
C++
CSC-210/Chapter 8/IC6_P3.cpp
FrancesCoronel/cs-hu
ecd103a525fd312146d3b6c69ee7c1452548c5e2
[ "MIT" ]
2
2016-12-05T06:15:34.000Z
2016-12-15T10:56:50.000Z
CSC-210/Chapter 8/IC6_P3.cpp
fvcproductions/CS-HU
ecd103a525fd312146d3b6c69ee7c1452548c5e2
[ "MIT" ]
null
null
null
CSC-210/Chapter 8/IC6_P3.cpp
fvcproductions/CS-HU
ecd103a525fd312146d3b6c69ee7c1452548c5e2
[ "MIT" ]
3
2019-04-06T01:45:54.000Z
2020-04-24T16:55:32.000Z
/* - Read a set of integers that the user enters until they type -1 (keep max at 50) - Create a function called statisticsValue which pass in 6 parameters: an array, a size, and then 4 variables for sum, average, min, and max which will pass them by reference. - The values will be calculated in the function and the variables passed by reference will be returned to the main method - Finally, print all #s in array and all stat values */ #include <iostream> using namespace std; void statisticsValue(int anArray[], int aSize, int &aSum, int &aAverage, int &amin, int &amax) { amax = anArray[0]; amin = anArray[0]; aSum = 0; cout << "Values In Array: "; for (int i = 0; i < aSize; i++) { if (amax < anArray[i]) { amax = anArray[i]; } else if (amin > anArray[i]) { amin = anArray[i]; } aSum += anArray[i]; cout << anArray[i] << ", "; } cout << "\nMin = " << amin << endl; cout << "Max = " << amax << endl; cout << "Sum = " << aSum << endl; cout << "Average = " << (double)aSum/aSize << endl; } int main() { int theArray [50] = {}; int count = 0; int num = 0; int aSum = 0; int aAverage = 0; int amin = 0; int amax = 0; while (num != -1) { cout << "Enter a number: "; cin >> num; if (num != -1) { theArray[count] = num; count++; } } int SIZE = sizeof(theArray[0]); cout << endl; statisticsValue(theArray, SIZE, aSum, aAverage, amin, amax); return 0; }
18.602564
175
0.597519
FrancesCoronel
780db0f16d2e1f4dbcef4b9c6a10b024a52df3b9
10,225
cpp
C++
unittests/unit/test_CollisionGroups.cpp
alinen/dart
e84d236f40238654779a2c1541534906a8ad8b93
[ "BSD-2-Clause" ]
6
2020-10-08T10:09:53.000Z
2021-10-01T05:59:33.000Z
unittests/unit/test_CollisionGroups.cpp
alinen/dart
e84d236f40238654779a2c1541534906a8ad8b93
[ "BSD-2-Clause" ]
null
null
null
unittests/unit/test_CollisionGroups.cpp
alinen/dart
e84d236f40238654779a2c1541534906a8ad8b93
[ "BSD-2-Clause" ]
2
2021-07-26T15:13:59.000Z
2021-10-04T07:01:56.000Z
/* * Copyright (c) 2011-2019, The DART development contributors * All rights reserved. * * The list of contributors can be found at: * https://github.com/dartsim/dart/blob/master/LICENSE * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <gtest/gtest.h> #include <dart/dynamics/SphereShape.hpp> #include "dart/dynamics/BoxShape.hpp" #include "dart/dynamics/FreeJoint.hpp" #include "dart/dynamics/Skeleton.hpp" #include "dart/constraint/ConstraintSolver.hpp" #include "dart/simulation/World.hpp" class CollisionGroupsTest : public testing::Test, public testing::WithParamInterface<const char*> { }; TEST_P(CollisionGroupsTest, SkeletonSubscription) { if (!dart::collision::CollisionDetector::getFactory()->canCreate(GetParam())) { std::cout << "Skipping test for [" << GetParam() << "], because it is not " << "available" << std::endl; return; } else { std::cout << "Running CollisionGroups test for [" << GetParam() << "]" << std::endl; } // Note: When skeletons are added to a world, the constraint solver will // subscribe to them. dart::simulation::WorldPtr world = dart::simulation::World::create(); world->getConstraintSolver()->setCollisionDetector( dart::collision::CollisionDetector::getFactory()->create(GetParam())); dart::dynamics::SkeletonPtr skel_A = dart::dynamics::Skeleton::create("A"); dart::dynamics::SkeletonPtr skel_B = dart::dynamics::Skeleton::create("B"); world->addSkeleton(skel_A); world->addSkeleton(skel_B); // There should be no collisions because there are no shapes in the world. EXPECT_FALSE(world->checkCollision()); // We will now add some BodyNodes and collision shapes *after* the Skeletons // have been added to the world, to see that the collision geometries get // updated automatically. Eigen::Isometry3d tf = Eigen::Isometry3d::Identity(); tf.translation() = (1.0 + 0.25) * Eigen::Vector3d::UnitX(); auto boxShape = std::make_shared<dart::dynamics::BoxShape>( Eigen::Vector3d::Constant(1.0)); auto pair = skel_A->createJointAndBodyNodePair<dart::dynamics::FreeJoint>(); pair.first->setTransform(tf); auto sn1 = pair.second->createShapeNodeWith<dart::dynamics::CollisionAspect>( boxShape); tf.translation() = (1.0 - 0.25) * Eigen::Vector3d::UnitX(); pair = skel_B->createJointAndBodyNodePair<dart::dynamics::FreeJoint>(); pair.first->setTransform(tf); auto sn2 = pair.second->createShapeNodeWith<dart::dynamics::CollisionAspect>( boxShape); EXPECT_TRUE(world->checkCollision()); // Now we'll change the properties of one the box shape so that there should // no longer be any collisions. boxShape->setSize(Eigen::Vector3d::Constant(0.2)); dart::collision::CollisionResult result2; EXPECT_FALSE(world->checkCollision()); // Now we'll replace one of the boxes with a large one, so that a collision // will occur again. auto largeBox = std::make_shared<dart::dynamics::BoxShape>( Eigen::Vector3d::Constant(0.95)); sn1->setShape(largeBox); EXPECT_TRUE(world->checkCollision()); // After this, both shapes will have been replaced with new shape instances. // If the shape map of the collision detector is empty upon destruction, then // the internal collision shapes are being managed correctly. Otherwise, if // they are not being managed correctly, then an assertion will fail when // testing in debug mode. auto sphereShape = std::make_shared<dart::dynamics::SphereShape>(0.01); sn2->setShape(sphereShape); EXPECT_FALSE(world->checkCollision()); // Resize the sphere so that there is a collision again. sphereShape->setRadius(0.5); EXPECT_TRUE(world->checkCollision()); // Remove the shape node so that there should no longer be a collision sn2->remove(); EXPECT_FALSE(world->checkCollision()); // Create a new shape node so that there should be a collision again pair.second->createShapeNodeWith<dart::dynamics::CollisionAspect>( sphereShape); EXPECT_TRUE(world->checkCollision()); // Remove the BodyNode so that there should no longer be a collision pair.second->remove(); EXPECT_FALSE(world->checkCollision()); // Add a new BodyNode and Shape Node so that there is a collision again pair = skel_B->createJointAndBodyNodePair<dart::dynamics::FreeJoint>(); pair.first->setTransform(tf); pair.second->createShapeNodeWith<dart::dynamics::CollisionAspect>( sphereShape); EXPECT_TRUE(world->checkCollision()); // Remove a skeleton so that there are no longer collisions world->removeSkeleton(skel_B); EXPECT_FALSE(world->checkCollision()); } TEST_P(CollisionGroupsTest, BodyNodeSubscription) { if (!dart::collision::CollisionDetector::getFactory()->canCreate(GetParam())) { std::cout << "Skipping test for [" << GetParam() << "], because it is not " << "available" << std::endl; return; } else { std::cout << "Running CollisionGroups test for [" << GetParam() << "]" << std::endl; } auto cd = dart::collision::CollisionDetector::getFactory()->create(GetParam()); auto group = cd->createCollisionGroup(); auto skel1 = dart::dynamics::Skeleton::create("skel1"); auto skel2 = dart::dynamics::Skeleton::create("skel2"); auto pair_1a = skel1->createJointAndBodyNodePair<dart::dynamics::FreeJoint>(); auto pair_2a = skel2->createJointAndBodyNodePair<dart::dynamics::FreeJoint>(); group->subscribeTo(pair_1a.second, pair_2a.second); // The BodyNodes currently have no collision geometries, so we expect there to // be no collisions. EXPECT_FALSE(group->collide()); Eigen::Isometry3d tf{Eigen::Translation3d(0.5, 0.0, 0.0)}; pair_1a.first->setTransform(tf); pair_1a.first->setName("1a"); pair_1a.second->setName("1a"); tf.translation()[0] = -0.5; pair_2a.first->setTransform(tf); pair_2a.first->setName("2a"); pair_2a.second->setName("2a"); auto sphere = std::make_shared<dart::dynamics::SphereShape>(0.75); auto sn_1a = pair_1a.second->createShapeNodeWith<dart::dynamics::CollisionAspect>( sphere); auto sn_2a = pair_2a.second->createShapeNodeWith<dart::dynamics::CollisionAspect>( sphere); // The BodyNodes have been given overlapping shapes, so now we expect the // collision information to automatically update and identify a collision. EXPECT_TRUE(group->collide()); tf.translation()[0] = 1.0; pair_1a.first->setTransform(tf); tf.translation()[0] = -1.0; pair_2a.first->setTransform(tf); // The collision geometries have been moved far enough from each other that // there should no longer be any collisions EXPECT_FALSE(group->collide()); sphere->setRadius(1.1); // The shapes of the collision geometries have been expanded enough that they // should collide again. EXPECT_TRUE(group->collide()); auto box = std::make_shared<dart::dynamics::BoxShape>( Eigen::Vector3d::Constant(0.5)); sn_2a->setShape(box); // Now a shape has been replaced with a smaller one, so there should no longer // be a collision. EXPECT_FALSE(group->collide()); auto pair_1b = skel1->createJointAndBodyNodePair<dart::dynamics::FreeJoint>(); auto pair_2b = skel2->createJointAndBodyNodePair<dart::dynamics::FreeJoint>(); tf.translation() = 0.5 * Eigen::Vector3d::UnitX(); pair_1b.first->setTransform(tf); pair_1b.first->setName("1b"); pair_1b.second->setName("1b"); tf.translation()[0] = -0.5; pair_2b.first->setTransform(tf); pair_2b.first->setName("2b"); pair_2b.second->setName("2b"); pair_1b.second->createShapeNodeWith<dart::dynamics::CollisionAspect>(sphere); pair_2b.second->createShapeNodeWith<dart::dynamics::CollisionAspect>(sphere); // The collision group should not be tracking the new BodyNodes, so there // should still be no collisions EXPECT_FALSE(group->collide()); // Change the size of the box so that there are overlapping collision // geometries. The collision information should update automatically, and a // collision should be detected. box->setSize(Eigen::Vector3d::Constant(2.0)); EXPECT_TRUE(group->collide()); sn_1a->remove(); // A shape node has been removed, so there should no longer be a collision EXPECT_FALSE(group->collide()); pair_1a.second->createShapeNodeWith<dart::dynamics::CollisionAspect>(sphere); // A new shape node has been added with the same geometry as the one that was // removed, so there should be a collision again EXPECT_TRUE(group->collide()); // Remove one of the BodyNodes so that there should no longer be a collision. group->removeShapeFramesOf(pair_1a.second); EXPECT_FALSE(group->collide()); } INSTANTIATE_TEST_CASE_P( CollisionEngine, CollisionGroupsTest, testing::Values("dart", "fcl", "bullet", "ode"));
37.730627
80
0.714034
alinen
780ff2c79e995e6a678625367d678f9f8de1c611
4,723
cpp
C++
ex_ocare_control/src/diffmodbus.cpp
SiChiTong/ros_ocare_nav
5df256ae9f398cb05f3d0d8c9be124fed5fc2c26
[ "Apache-2.0" ]
null
null
null
ex_ocare_control/src/diffmodbus.cpp
SiChiTong/ros_ocare_nav
5df256ae9f398cb05f3d0d8c9be124fed5fc2c26
[ "Apache-2.0" ]
null
null
null
ex_ocare_control/src/diffmodbus.cpp
SiChiTong/ros_ocare_nav
5df256ae9f398cb05f3d0d8c9be124fed5fc2c26
[ "Apache-2.0" ]
1
2018-08-17T03:31:44.000Z
2018-08-17T03:31:44.000Z
#include "diffmodbus.h" DiffModbus::DiffModbus(char* _name, size_t _length) : HWModule(_name, _length), m_chassis_mode(ChassisModeCMD::MODE_STOP_CMD), m_left_wheel_torque(0), m_right_wheel_torque(0), m_track_torque_mode(TrackingTorqueModeCMD::TORQUE_MED_CMD), m_sensor_bw_mode(SensorBWModeCMD::WHITE_CMD), m_read_chassis_mode(ChassisMode::MODE_STOP), m_read_left_wheel_torque(0), m_read_right_wheel_torque(0), m_read_track_torque_mode(TrackingTorqueMode::TORQUE_MED), m_read_sensor_bw_mode(SensorBWMode::WHITE){ // Initial the Sensor data to read write <at value = 610 m_read_sensor_datas[0] = 610; m_read_sensor_datas[1] = 610; // Set the slave ID m_slave_id = 6; } DiffModbus::~DiffModbus() {} bool DiffModbus::write() { uint16_t reg[REG_CMD_END-REG_CMD_START+1]; /******************* The arduino mapping design * * mb.addHreg(CHASSIS_MODE); **Read Only * mb.addHreg(LEFT_WHEEL_TORQUE); **Read Only * mb.addHreg(RIGHT_WHEEL_TORQUE); **Read Only * mb.addHreg(TRACKLINE_TORQUE_MODE); **Read Only * mb.addHreg(SENSOR_BW_MODE); **Read Only * mb.addHreg(CMD_CHASSIS_MODE); **Write Only * mb.addHreg(CMD_LEFT_WHEEL_TORQUE); **Write Only * mb.addHreg(CMD_RIGHT_WHEEL_TORQUE); **Write Only * mb.addHreg(CMD_TRACKLINE_TORQUE_MODE); **Write Only * mb.addHreg(CMD_SENSOR_BW_MODE); **Write Only * **********************************************/ // Note there is a continue register reg[CMD_CHASSIS_MODE - REG_CMD_START] = static_cast<uint16_t>(m_chassis_mode); reg[CMD_LEFT_WHEEL_TORQUE - REG_CMD_START] = m_left_wheel_torque; reg[CMD_RIGHT_WHEEL_TORQUE - REG_CMD_START] = m_right_wheel_torque; reg[CMD_TRACKLINE_TORQUE_MODE - REG_CMD_START] = static_cast<uint16_t>(m_track_torque_mode); reg[CMD_SENSOR_BW_MODE - REG_CMD_START] = static_cast<uint16_t>(m_sensor_bw_mode); int num = modbus_write_registers( m_ctx, REG_CMD_START, REG_CMD_END-REG_CMD_START+1, reg); if (num != REG_CMD_END-REG_CMD_START+1) {// number of writed registers is not the one expected #ifdef _ROS ROS_ERROR( "Failed to write: %s\n", modbus_strerror(errno)) #else fprintf(stderr, "Failed to write: %s\n", modbus_strerror(errno)); #endif return false; } return true; } bool DiffModbus::read() { uint16_t reg[REG_READ_END-REG_READ_START+1]; uint16_t sensor_reg[SENSOR_REG_COUNT]; int num = modbus_read_registers( m_ctx, REG_READ_START, REG_READ_END-REG_READ_START+1, reg); if (num != REG_READ_END-REG_READ_START+1) {// number of writed registers is not the one expected #ifdef _ROS ROS_ERROR( "Failed to read: %s\n", modbus_strerror(errno)) #else fprintf(stderr, "Failed to read: %s\n", modbus_strerror(errno)); #endif return false; } int sensor_read_num = modbus_read_registers( m_ctx, SENSOR_REG_START, SENSOR_REG_COUNT, sensor_reg); if (sensor_read_num != SENSOR_REG_COUNT) {// number of writed registers is not the one expected #ifdef _ROS ROS_ERROR( "Failed to read: %s\n", modbus_strerror(errno)) #else fprintf(stderr, "Failed to read: %s\n", modbus_strerror(errno)); #endif return false; } /******************* The arduino mapping design * * mb.addHreg(CHASSIS_MODE); **Read Only * mb.addHreg(LEFT_WHEEL_TORQUE); **Read Only * mb.addHreg(RIGHT_WHEEL_TORQUE); **Read Only * mb.addHreg(TRACKLINE_TORQUE_MODE); **Read Only * mb.addHreg(SENSOR_BW_MODE); **Read Only * mb.addHreg(CMD_CHASSIS_MODE); **Write Only * mb.addHreg(CMD_LEFT_WHEEL_TORQUE); **Write Only * mb.addHreg(CMD_RIGHT_WHEEL_TORQUE); **Write Only * mb.addHreg(CMD_TRACKLINE_TORQUE_MODE); **Write Only * mb.addHreg(CMD_SENSOR_BW_MODE); **Write Only * **********************************************/ // Note there is a continue register m_read_chassis_mode = ChassisMode(reg[CHASSIS_MODE - REG_READ_START]); m_read_left_wheel_torque = reg[LEFT_WHEEL_TORQUE - REG_READ_START]; m_read_right_wheel_torque = reg[RIGHT_WHEEL_TORQUE - REG_READ_START]; m_read_track_torque_mode = TrackingTorqueMode(reg[TRACKLINE_TORQUE_MODE - REG_READ_START]); m_read_sensor_bw_mode = SensorBWMode(reg[SENSOR_BW_MODE - REG_READ_START]); for(int i=0;i<SENSOR_REG_COUNT;i++) { m_read_sensor_datas[i] = sensor_reg[i]; } return true; }
37.784
100
0.650646
SiChiTong