hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
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
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
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
d7f93776653b25a3465ac8fefd089c38b6d4401e
382
hpp
C++
examples/12_pubsvc/generated/src/NECommon.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
70
2021-07-20T11:26:16.000Z
2022-03-27T11:17:43.000Z
examples/12_pubsvc/generated/src/NECommon.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
32
2021-07-31T05:20:44.000Z
2022-03-20T10:11:52.000Z
examples/12_pubsvc/generated/src/NECommon.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
40
2021-11-02T09:45:38.000Z
2022-03-27T11:17:46.000Z
#pragma once /************************************************************************ * \file generated/src/NECommon.hpp * \ingroup 12_pubsvc * \brief Namespace contains common constants. ************************************************************************/ namespace NECommon { constexpr char ServiceHelloName[] { "ServiceHello" }; }
29.384615
74
0.387435
Ali-Nasrolahi
d7fb35577f44d1f67139fd49e9a7e9af1d4d0987
3,946
cpp
C++
tmain_form.cpp
stasinek/Koperek
35b241fe37d7e1b3b0215368b0e35c43c3c16660
[ "BSD-2-Clause" ]
null
null
null
tmain_form.cpp
stasinek/Koperek
35b241fe37d7e1b3b0215368b0e35c43c3c16660
[ "BSD-2-Clause" ]
null
null
null
tmain_form.cpp
stasinek/Koperek
35b241fe37d7e1b3b0215368b0e35c43c3c16660
[ "BSD-2-Clause" ]
null
null
null
/*Koperek32(R) Copyright (c) Stanislaw Stasiak, [email protected] <2014> All rights reserved. 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. Permission is granted to anyone use this software for any purpose, including commercial application, and to alter it, and may be redistributed freely, in subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. 2. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. This notice may not be removed or altered from any source distribution. */ #include "tmain_form.h" #include "ui_tmain_form.h" #include "../Kop32/kop32_main.h" TMain_form::TMain_form(QWidget *a_parent) : QDialog(a_parent), ui(new Ui::TMain_form) { ui->setupUi(this); ui->tableWidget->setColumnCount(3); QStringList Header; Header << "Path"; Header << "Name"; Header << "Size"; ui->tableWidget->setHorizontalHeaderLabels(Header); ui->tableWidget->setAlternatingRowColors(true); //ui->Animation_graphicsView->setScene(Application->FileAnimationScene); //ui->Chart_graphicsView->setScene(Application->FileChartScene); ui->Animation_graphicsView->setVisible(0); // QWidget *p = ui->Animation_graphicsView->parentWidget(); // while (p) { // p->adjustSize(); // p = parent->parentWidget(); // } ui->toolButton_F->click(); //ui->verticalLayout_4->setSizeConstraint(QLayout::SetFixedSize); } TMain_form::~TMain_form() { delete ui; } /* bool TMain_form::nativeEvent(const QByteArray& eventType, void* message, long* result) { return QWidget::nativeEvent(eventType,message,result); MSG *msg = reinterpret_cast<MSG*>(message); switch (msg->message) { case WM_NCLBUTTONDOWN: //return false; break; default: break; } *result = 0; return QWidget::nativeEvent(eventType,message,result); } */ void TMain_form::on_toolButton_F_clicked(bool checked) { //ui->verticalLayout_4->setSizeConstraint(QLayout::SetFixedSize); if (checked) ui->widget_5->setVisible(1); else ui->widget_5->setVisible(0); QWidget *p = ui->widget_5->parentWidget(); while (p) { p->adjustSize(); p = p->parentWidget(); } } void TMain_form::on_tableWidget_2_cellChanged(int row, int column) { ui->stackedWidget->setCurrentIndex(row); } void TMain_form::on_progressBar_1_valueChanged(int value) { } void TMain_form::on_progressBar_2_valueChanged(int value) { } void TMain_form::on_toolButton_2_clicked(bool checked) { } void TMain_form::on_toolButton_3_clicked() { Application->Finished = true; reject(); } void TMain_form::on_toolButton_MENU_clicked() { Application->Menu->exec( QWidget::mapToGlobal(ui->toolButton_MENU->pos()+QPoint(ui->toolButton_MENU->width(),0))); } void TMain_form::showEvent(QShowEvent *e) { //static int first = 0; Application->MenuActions_SwitchToMainWindow->setEnabled(0); Application->MenuActions_SwitchToMiniWindow->setEnabled(1); Application->MenuActions_SwitchToConsoleWindow->setEnabled(1); QDialog::showEvent(e); //if (!first); //first = 1; } void TMain_form::hideEvent(QHideEvent *e) { if (Application->Finished) Application->closeAllWindows(); }
34.313043
460
0.714901
stasinek
d7ff5d4fd97327cc62a6fd222e54de480b4a9c0c
290
hpp
C++
TreeWalkInterpreter/includes/Stmt/ExprStmt.hpp
dipeshkaphle/Lox-cpp
9c73987f08aa366234b291df938261f5592a140f
[ "MIT" ]
null
null
null
TreeWalkInterpreter/includes/Stmt/ExprStmt.hpp
dipeshkaphle/Lox-cpp
9c73987f08aa366234b291df938261f5592a140f
[ "MIT" ]
null
null
null
TreeWalkInterpreter/includes/Stmt/ExprStmt.hpp
dipeshkaphle/Lox-cpp
9c73987f08aa366234b291df938261f5592a140f
[ "MIT" ]
null
null
null
#pragma once #include "Stmt.hpp" #include "StmtVisitor.hpp" #include "includes/Expr/Expr.hpp" #include <memory> class expr_stmt : public Stmt { public: std::unique_ptr<Expr> expr; expr_stmt(std::unique_ptr<Expr> expr); std::any accept(stmt_visitor<std::any> &visitor) override; };
19.333333
60
0.724138
dipeshkaphle
cc047f3556dcd9d4e2ebccffebff5f9c42567681
2,921
cpp
C++
paint/solutions/modified2-ryno-full.cpp
acio-olympiad/ACIO2022Contest2
53c7ced66ae916b118cfab8c72e4531dd08defd2
[ "MIT" ]
null
null
null
paint/solutions/modified2-ryno-full.cpp
acio-olympiad/ACIO2022Contest2
53c7ced66ae916b118cfab8c72e4531dd08defd2
[ "MIT" ]
null
null
null
paint/solutions/modified2-ryno-full.cpp
acio-olympiad/ACIO2022Contest2
53c7ced66ae916b118cfab8c72e4531dd08defd2
[ "MIT" ]
null
null
null
/* N <= 2e3, K <= 2e3 fracturing search O(NK log NK) */ #include <algorithm> #include <iostream> #include <queue> #include <vector> #include <assert.h> using namespace std; typedef long long ll; ll N, K, D; vector<ll> costs[2005]; vector<ll> prevUsed[2005]; struct State { // used is represented by prevUsed[i] ll i; // modify day `d`, if d == -1 dont modify ll d = -1; // what to increment it to. if itemI == costs[d].size(), then remove this day ll itemI = -1; // updated stats ll numItems, cost = 0; ll hasChoice; // day is discarded when used[d] = cost[d].size() bool operator<(State o) const { if (numItems == o.numItems) return cost > o.cost; return numItems < o.numItems; } vector<ll> applyUpdate() { vector<ll> used = prevUsed[i]; if (d != -1) used[d] = itemI; return used; } }; priority_queue<State> pq; State initState() { State output; prevUsed[0].resize(D + 1); output.i = 0; output.numItems = D; for (ll d = 0; d < D; ++d) output.cost += costs[d][0]; output.hasChoice = 0; return output; } void fracturingSearch() { pq.push(initState()); for (ll i = 0; i < K - 1; ++i) { State curr = pq.top(); pq.pop(); // apply update, store in prevUsed[i] prevUsed[i] = curr.applyUpdate(); // find children for (ll d = curr.hasChoice; d < D; ++d) { // option 1: increment the cost for (ll itemI = prevUsed[i][d] + 1; itemI < (ll)costs[d].size(); ++itemI) { State neighbour; neighbour.i = i; neighbour.d = d; neighbour.itemI = itemI; neighbour.cost = curr.cost + costs[d][itemI] - costs[d][prevUsed[i][d]]; neighbour.numItems = curr.numItems; neighbour.hasChoice = d + 1; pq.push(neighbour); } // option 2: remove this day if (prevUsed[i][d] != (ll)costs[d].size()) { State neighbour; neighbour.i = i; neighbour.d = d; neighbour.itemI = costs[d].size(); neighbour.cost = curr.cost - costs[d][prevUsed[i][d]]; neighbour.numItems = curr.numItems - 1; neighbour.hasChoice = d + 1; pq.push(neighbour); } } } cout << pq.top().numItems << " " << pq.top().cost << "\n"; } int main() { cin.tie(0); ios::sync_with_stdio(0); cin >> N >> K >> D; for (ll d, w, i = 0; i < N; ++i) { cin >> d >> w; --d; costs[d].push_back(w); } for (ll d = 0; d < D; ++d) sort(costs[d].begin(), costs[d].end()); fracturingSearch(); }
26.080357
89
0.480315
acio-olympiad
cc07184363eb3095efc9e4fd5dad22f7bd4ef33c
1,783
cpp
C++
android-31/android/view/ActionProvider.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/view/ActionProvider.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/view/ActionProvider.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../content/Context.hpp" #include "./View.hpp" #include "./ActionProvider.hpp" namespace android::view { // Fields // QJniObject forward ActionProvider::ActionProvider(QJniObject obj) : JObject(obj) {} // Constructors ActionProvider::ActionProvider(android::content::Context arg0) : JObject( "android.view.ActionProvider", "(Landroid/content/Context;)V", arg0.object() ) {} // Methods jboolean ActionProvider::hasSubMenu() const { return callMethod<jboolean>( "hasSubMenu", "()Z" ); } jboolean ActionProvider::isVisible() const { return callMethod<jboolean>( "isVisible", "()Z" ); } android::view::View ActionProvider::onCreateActionView() const { return callObjectMethod( "onCreateActionView", "()Landroid/view/View;" ); } android::view::View ActionProvider::onCreateActionView(JObject arg0) const { return callObjectMethod( "onCreateActionView", "(Landroid/view/MenuItem;)Landroid/view/View;", arg0.object() ); } jboolean ActionProvider::onPerformDefaultAction() const { return callMethod<jboolean>( "onPerformDefaultAction", "()Z" ); } void ActionProvider::onPrepareSubMenu(JObject arg0) const { callMethod<void>( "onPrepareSubMenu", "(Landroid/view/SubMenu;)V", arg0.object() ); } jboolean ActionProvider::overridesItemVisibility() const { return callMethod<jboolean>( "overridesItemVisibility", "()Z" ); } void ActionProvider::refreshVisibility() const { callMethod<void>( "refreshVisibility", "()V" ); } void ActionProvider::setVisibilityListener(JObject arg0) const { callMethod<void>( "setVisibilityListener", "(Landroid/view/ActionProvider$VisibilityListener;)V", arg0.object() ); } } // namespace android::view
20.033708
75
0.691531
YJBeetle
cc0a20905abad9eac184c28663875b7fe134c9d3
14,635
hpp
C++
third_party/jsonxx.v0.9.2/include/jsonxx/json_unicode.hpp
vectordb-io/vectordb
3175b0d7f795d4f5daa22eb58ff86a01cf66780d
[ "Apache-2.0" ]
9
2021-06-16T08:02:19.000Z
2021-11-04T11:49:27.000Z
third_party/jsonxx.v0.9.2/include/jsonxx/json_unicode.hpp
vectordb-io/vectordb
3175b0d7f795d4f5daa22eb58ff86a01cf66780d
[ "Apache-2.0" ]
null
null
null
third_party/jsonxx.v0.9.2/include/jsonxx/json_unicode.hpp
vectordb-io/vectordb
3175b0d7f795d4f5daa22eb58ff86a01cf66780d
[ "Apache-2.0" ]
2
2021-06-17T14:21:03.000Z
2021-08-13T16:37:35.000Z
// Copyright (c) 2018-2020 jsonxx - Nomango // // 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 "json_exception.hpp" #include <array> // std::array #include <cstdint> // uint32_t #include <string> // std::string, std::wstring, std::u16string, std::u32string #include <type_traits> // std::char_traits, std::true_type, std::false_type #include <vector> // std::vector // unicode constants #define JSONXX_UNICODE_SUR_BASE 0x10000 #define JSONXX_UNICODE_SUR_LEAD_BEGIN 0xD800 #define JSONXX_UNICODE_SUR_LEAD_END 0xDBFF #define JSONXX_UNICODE_SUR_TRAIL_BEGIN 0xDC00 #define JSONXX_UNICODE_SUR_TRAIL_END 0xDFFF #define JSONXX_UNICODE_SUR_BITS 10 #define JSONXX_UNICODE_SUR_MAX 0x3FF namespace jsonxx { namespace detail { inline uint32_t merge_surrogates(uint32_t lead_surrogate, uint32_t trail_surrogate) { uint32_t code = ((lead_surrogate - JSONXX_UNICODE_SUR_LEAD_BEGIN) << JSONXX_UNICODE_SUR_BITS); code += (trail_surrogate - JSONXX_UNICODE_SUR_TRAIL_BEGIN); code += JSONXX_UNICODE_SUR_BASE; return code; } // // unicode_reader // template <typename _StrTy> struct unicode_reader; template <> struct unicode_reader<std::string> { using string_type = std::string; const string_type& val; const bool escape_unicode; uint8_t state = 0; unicode_reader(const string_type& val, const bool escape_unicode) : val(val) , escape_unicode(escape_unicode) { } inline uint8_t get_byte(size_t i) const { return static_cast<uint8_t>(val.at(i)); } bool get_code(size_t& i, uint32_t& code_output) { // Unicode UTF-8 // U+0000...U+007F 0xxxxxxx // U+0080...U+07FF 110xxxxx 10xxxxxx // U+0800...U+FFFF 1110xxxx 10xxxxxx 10xxxxxx // U+10000...U+10FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx static const std::array<std::uint8_t, 256> utf8_extra_bytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, }; static const std::array<std::uint32_t, 6> utf8_offsets = { 0x00000000, 0x00003080, 0x000E2080, 0x03C82080, 0xFA082080, 0x82082080, }; if (i >= val.size()) { return false; } if (!escape_unicode) { // code point will not be escaped const auto byte = get_byte(i); code_output = static_cast<uint32_t>(byte); i++; return true; } const auto first_byte = get_byte(i); const auto extra_bytes_to_read = utf8_extra_bytes[first_byte]; if ((i + static_cast<size_t>(extra_bytes_to_read)) >= val.size()) { throw json_serialize_error("string was incomplete"); } // read bytes uint32_t code = 0; switch (extra_bytes_to_read) { case 5: code += static_cast<uint32_t>(get_byte(i)); i++; code <<= 6; case 4: code += static_cast<uint32_t>(get_byte(i)); i++; code <<= 6; case 3: code += static_cast<uint32_t>(get_byte(i)); i++; code <<= 6; case 2: code += static_cast<uint32_t>(get_byte(i)); i++; code <<= 6; case 1: code += static_cast<uint32_t>(get_byte(i)); i++; code <<= 6; case 0: code += static_cast<uint32_t>(get_byte(i)); i++; } code -= utf8_offsets[extra_bytes_to_read]; code_output = code; return true; } }; template <> struct unicode_reader<std::wstring> { using string_type = std::wstring; using char_type = typename string_type::value_type; const string_type& val; const bool escape_unicode; unicode_reader(const string_type& val, const bool escape_unicode) : val(val) , escape_unicode(escape_unicode) { } bool get_code(size_t& i, uint32_t& code) { return get_code(i, code, std::integral_constant<bool, sizeof(char_type) == 4>()); } bool get_code(size_t& i, uint32_t& code, std::true_type /* sizeof(wchar_t) == 4 */) { if (i >= val.size()) { return false; } code = static_cast<uint32_t>(val.at(i)); i++; return true; } bool get_code(size_t& i, uint32_t& code, std::false_type /* sizeof(wchar_t) == 2 */) { if (i >= val.size()) { return false; } code = static_cast<uint32_t>(static_cast<uint16_t>(val.at(i))); i++; if (!escape_unicode) { // code point will not be escaped return true; } if (JSONXX_UNICODE_SUR_LEAD_BEGIN <= code && code <= JSONXX_UNICODE_SUR_LEAD_END) { if (i >= val.size()) { throw json_serialize_error("string was incomplete"); } uint32_t lead_surrogate = code; uint32_t trail_surrogate = static_cast<uint32_t>(static_cast<uint16_t>(val.at(i))); code = merge_surrogates(lead_surrogate, trail_surrogate); i++; } return true; } }; template <> struct unicode_reader<std::u32string> { using string_type = std::u32string; using char_type = typename string_type::value_type; const string_type& val; const bool escape_unicode; unicode_reader(const string_type& val, const bool escape_unicode) : val(val) , escape_unicode(escape_unicode) { } bool get_code(size_t& i, uint32_t& code) { if (i >= val.size()) { return false; } code = static_cast<uint32_t>(val.at(i)); i++; return true; } }; template <> struct unicode_reader<std::u16string> { using string_type = std::u16string; using char_type = typename string_type::value_type; const string_type& val; const bool escape_unicode; unicode_reader(const string_type& val, const bool escape_unicode) : val(val) , escape_unicode(escape_unicode) { } bool get_code(size_t& i, uint32_t& code) { if (i >= val.size()) { return false; } code = static_cast<uint32_t>(static_cast<uint16_t>(val.at(i))); i++; if (!escape_unicode) { // code point will not be escaped return true; } if (JSONXX_UNICODE_SUR_LEAD_BEGIN <= code && code <= JSONXX_UNICODE_SUR_LEAD_END) { if (i >= val.size()) { throw json_serialize_error("string was incomplete"); } uint32_t lead_surrogate = code; uint32_t trail_surrogate = static_cast<uint32_t>(static_cast<uint16_t>(val.at(i))); code = merge_surrogates(lead_surrogate, trail_surrogate); i++; } return true; } }; // // unicode_writer // template <typename _StrTy> struct unicode_writer; template <> struct unicode_writer<std::string> { using string_type = std::string; using char_type = typename string_type::value_type; using char_traits = std::char_traits<char_type>; using char_int_type = typename char_traits::int_type; string_type& buffer; unicode_writer(string_type& buffer) : buffer(buffer){}; inline void add_char(const char_int_type ch) { buffer.push_back(char_traits::to_char_type(ch)); } inline void add_code(uint32_t code) { if (!(0x00 <= code && code <= 0x10FFFF)) { // invalid unicode return; } // Unicode UTF-8 // U+0000...U+007F 0xxxxxxx // U+0080...U+07FF 110xxxxx 10xxxxxx // U+0800...U+FFFF 1110xxxx 10xxxxxx 10xxxxxx // U+10000...U+10FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if (code < 0x80) { // 0xxxxxxx add_char(static_cast<char_int_type>(code)); } else if (code <= 0x7FF) { // 110xxxxx 10xxxxxx add_char(static_cast<char_int_type>(0xC0 | (code >> 6))); add_char(static_cast<char_int_type>(0x80 | (code & 0x3F))); } else if (code <= 0xFFFF) { // 1110xxxx 10xxxxxx 10xxxxxx add_char(static_cast<char_int_type>(0xE0 | (code >> 12))); add_char(static_cast<char_int_type>(0x80 | ((code >> 6) & 0x3F))); add_char(static_cast<char_int_type>(0x80 | (code & 0x3F))); } else { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx add_char(static_cast<char_int_type>(0xF0 | (code >> 18))); add_char(static_cast<char_int_type>(0x80 | ((code >> 12) & 0x3F))); add_char(static_cast<char_int_type>(0x80 | ((code >> 6) & 0x3F))); add_char(static_cast<char_int_type>(0x80 | (code & 0x3F))); } } inline void add_surrogates(uint32_t lead_surrogate, uint32_t trail_surrogate) { add_code(merge_surrogates(lead_surrogate, trail_surrogate)); } }; template <> struct unicode_writer<std::wstring> { using string_type = std::wstring; using char_type = typename string_type::value_type; using char_traits = std::char_traits<char_type>; using char_int_type = typename char_traits::int_type; string_type& buffer; unicode_writer(string_type& buffer) : buffer(buffer){}; inline void add_char(const char_int_type ch) { buffer.push_back(char_traits::to_char_type(ch)); } inline void add_code(uint32_t code) { add_code(code, std::integral_constant<bool, sizeof(char_type) == 4>()); } inline void add_code(uint32_t code, std::true_type /* sizeof(wchar_t) == 4 */) { add_char(static_cast<char_int_type>(code)); } inline void add_code(uint32_t code, std::false_type /* sizeof(wchar_t) == 2 */) { if (code < 0xFFFF) { add_char(static_cast<char_int_type>(code)); } else { throw json_parse_error("invalid 16-bits unicode character"); } } inline void add_surrogates(uint32_t lead_surrogate, uint32_t trail_surrogate) { add_surrogates(lead_surrogate, trail_surrogate, std::integral_constant<bool, sizeof(char_type) == 4>()); } inline void add_surrogates(uint32_t lead_surrogate, uint32_t trail_surrogate, std::true_type /* sizeof(wchar_t) == 4 */) { add_code(merge_surrogates(lead_surrogate, trail_surrogate)); } inline void add_surrogates(uint32_t lead_surrogate, uint32_t trail_surrogate, std::false_type /* sizeof(wchar_t) == 2 */) { add_code(lead_surrogate); add_code(trail_surrogate); } }; template <> struct unicode_writer<std::u16string> { using string_type = std::u16string; using char_type = typename string_type::value_type; using char_traits = std::char_traits<char_type>; using char_int_type = typename char_traits::int_type; string_type& buffer; unicode_writer(string_type& buffer) : buffer(buffer){}; inline void add_char(const char_int_type ch) { buffer.push_back(char_traits::to_char_type(ch)); } inline void add_code(uint32_t code) { if (code < 0xFFFF) { add_char(static_cast<char_int_type>(code)); } else { throw json_parse_error("invalid 16-bits unicode character"); } } inline void add_surrogates(uint32_t lead_surrogate, uint32_t trail_surrogate) { add_code(lead_surrogate); add_code(trail_surrogate); } }; template <> struct unicode_writer<std::u32string> { using string_type = std::u32string; using char_type = typename string_type::value_type; using char_traits = std::char_traits<char_type>; using char_int_type = typename char_traits::int_type; string_type& buffer; unicode_writer(string_type& buffer) : buffer(buffer){}; inline void add_char(const char_int_type ch) { buffer.push_back(char_traits::to_char_type(ch)); } inline void add_code(uint32_t code) { add_char(static_cast<char_int_type>(code)); } inline void add_surrogates(uint32_t lead_surrogate, uint32_t trail_surrogate) { add_code(merge_surrogates(lead_surrogate, trail_surrogate)); } }; } // namespace detail } // namespace jsonxx
29.685598
112
0.586334
vectordb-io
cc0d28d510e6dbac65cfd501c410ebe8d8cdccc9
14,246
hpp
C++
src/smilesection.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
27
2016-11-19T16:51:21.000Z
2021-09-08T16:44:15.000Z
src/smilesection.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
1
2016-12-28T16:38:38.000Z
2017-02-17T05:32:13.000Z
src/smilesection.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
10
2016-12-28T02:31:38.000Z
2021-06-15T09:02:07.000Z
/* Copyright (C) 2016 -2017 Jerry Jin */ #ifndef smilesection_h #define smilesection_h #include <nan.h> #include <string> #include <queue> #include <utility> #include "../quantlibnode.hpp" #include <oh/objecthandler.hpp> using namespace node; using namespace v8; using namespace std; class FlatSmileSectionWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mOptionDate; double mVolatility; string mDayCounter; ObjectHandler::property_t mRefDate; double mAtmValue; string mVolatilityType; double mDisplacement; string mReturnValue; string mError; FlatSmileSectionWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t OptionDate ,double Volatility ,string DayCounter ,ObjectHandler::property_t RefDate ,double AtmValue ,string VolatilityType ,double Displacement ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mOptionDate(OptionDate) ,mVolatility(Volatility) ,mDayCounter(DayCounter) ,mRefDate(RefDate) ,mAtmValue(AtmValue) ,mVolatilityType(VolatilityType) ,mDisplacement(Displacement) { }; //~FlatSmileSectionWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrInterpolatedSmileSectionWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mOptionDate; double mForwardRate; std::vector<double> mStrike; bool mFloatingStrike; double mAtmVolatility; std::vector<double> mVolatilitySpreads; double mAlpha; double mBeta; double mNu; double mRho; bool mAlphaIsFixed; bool mBetaIsFixed; bool mNuIsFixed; bool mRhoIsFixed; bool mVegaWeighted; string mEndCriteria; string mMethod; string mDayCounter; string mReturnValue; string mError; SabrInterpolatedSmileSectionWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t OptionDate ,double ForwardRate ,std::vector<double> Strike ,bool FloatingStrike ,double AtmVolatility ,std::vector<double> VolatilitySpreads ,double Alpha ,double Beta ,double Nu ,double Rho ,bool AlphaIsFixed ,bool BetaIsFixed ,bool NuIsFixed ,bool RhoIsFixed ,bool VegaWeighted ,string EndCriteria ,string Method ,string DayCounter ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mOptionDate(OptionDate) ,mForwardRate(ForwardRate) ,mStrike(Strike) ,mFloatingStrike(FloatingStrike) ,mAtmVolatility(AtmVolatility) ,mVolatilitySpreads(VolatilitySpreads) ,mAlpha(Alpha) ,mBeta(Beta) ,mNu(Nu) ,mRho(Rho) ,mAlphaIsFixed(AlphaIsFixed) ,mBetaIsFixed(BetaIsFixed) ,mNuIsFixed(NuIsFixed) ,mRhoIsFixed(RhoIsFixed) ,mVegaWeighted(VegaWeighted) ,mEndCriteria(EndCriteria) ,mMethod(Method) ,mDayCounter(DayCounter) { }; //~SabrInterpolatedSmileSectionWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrInterpolatedSmileSection1Worker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mOptionDate; ObjectHandler::property_t mForwardRate; std::vector<double> mStrike; bool mFloatingStrike; ObjectHandler::property_t mAtmVolatility; std::vector<ObjectHandler::property_t> mVolatilitySpreads; double mAlpha; double mBeta; double mNu; double mRho; bool mAlphaIsFixed; bool mBetaIsFixed; bool mNuIsFixed; bool mRhoIsFixed; bool mVegaWeighted; string mEndCriteria; string mMethod; string mDayCounter; string mReturnValue; string mError; SabrInterpolatedSmileSection1Worker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t OptionDate ,ObjectHandler::property_t ForwardRate ,std::vector<double> Strike ,bool FloatingStrike ,ObjectHandler::property_t AtmVolatility ,std::vector<ObjectHandler::property_t> VolatilitySpreads ,double Alpha ,double Beta ,double Nu ,double Rho ,bool AlphaIsFixed ,bool BetaIsFixed ,bool NuIsFixed ,bool RhoIsFixed ,bool VegaWeighted ,string EndCriteria ,string Method ,string DayCounter ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mOptionDate(OptionDate) ,mForwardRate(ForwardRate) ,mStrike(Strike) ,mFloatingStrike(FloatingStrike) ,mAtmVolatility(AtmVolatility) ,mVolatilitySpreads(VolatilitySpreads) ,mAlpha(Alpha) ,mBeta(Beta) ,mNu(Nu) ,mRho(Rho) ,mAlphaIsFixed(AlphaIsFixed) ,mBetaIsFixed(BetaIsFixed) ,mNuIsFixed(NuIsFixed) ,mRhoIsFixed(RhoIsFixed) ,mVegaWeighted(VegaWeighted) ,mEndCriteria(EndCriteria) ,mMethod(Method) ,mDayCounter(DayCounter) { }; //~SabrInterpolatedSmileSection1Worker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrSmileSectionWorker : public Nan::AsyncWorker { public: string mObjectID; double mOptionTime; std::vector<double> mStrikes; std::vector<ObjectHandler::property_t> mStdDevs; ObjectHandler::property_t mForward; double mAlpha; double mBeta; double mNu; double mRho; bool mAlphaIsFixed; bool mBetaIsFixed; bool mNuIsFixed; bool mRhoIsFixed; bool mVegaWeighted; string mEndCriteria; string mMethod; string mReturnValue; string mError; SabrSmileSectionWorker( Nan::Callback *callback ,string ObjectID ,double OptionTime ,std::vector<double> Strikes ,std::vector<ObjectHandler::property_t> StdDevs ,ObjectHandler::property_t Forward ,double Alpha ,double Beta ,double Nu ,double Rho ,bool AlphaIsFixed ,bool BetaIsFixed ,bool NuIsFixed ,bool RhoIsFixed ,bool VegaWeighted ,string EndCriteria ,string Method ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mOptionTime(OptionTime) ,mStrikes(Strikes) ,mStdDevs(StdDevs) ,mForward(Forward) ,mAlpha(Alpha) ,mBeta(Beta) ,mNu(Nu) ,mRho(Rho) ,mAlphaIsFixed(AlphaIsFixed) ,mBetaIsFixed(BetaIsFixed) ,mNuIsFixed(NuIsFixed) ,mRhoIsFixed(RhoIsFixed) ,mVegaWeighted(VegaWeighted) ,mEndCriteria(EndCriteria) ,mMethod(Method) { }; //~SabrSmileSectionWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class InterpolatedSmileSectionWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mOptionDate; std::vector<double> mStrikes; std::vector<ObjectHandler::property_t> mStdDevs; ObjectHandler::property_t mAtmLevel; string mDayCounter; string mVolatilityType; double mDisplacement; string mReturnValue; string mError; InterpolatedSmileSectionWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t OptionDate ,std::vector<double> Strikes ,std::vector<ObjectHandler::property_t> StdDevs ,ObjectHandler::property_t AtmLevel ,string DayCounter ,string VolatilityType ,double Displacement ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mOptionDate(OptionDate) ,mStrikes(Strikes) ,mStdDevs(StdDevs) ,mAtmLevel(AtmLevel) ,mDayCounter(DayCounter) ,mVolatilityType(VolatilityType) ,mDisplacement(Displacement) { }; //~InterpolatedSmileSectionWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SmileSectionFromSabrVolSurfaceWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mSabrVolSurface; double mOptionTime; string mReturnValue; string mError; SmileSectionFromSabrVolSurfaceWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t SabrVolSurface ,double OptionTime ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mSabrVolSurface(SabrVolSurface) ,mOptionTime(OptionTime) { }; //~SmileSectionFromSabrVolSurfaceWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SmileSectionVolatilityWorker : public Nan::AsyncWorker { public: string mObjectID; double mStrike; double mReturnValue; string mError; SmileSectionVolatilityWorker( Nan::Callback *callback ,string ObjectID ,double Strike ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mStrike(Strike) { }; //~SmileSectionVolatilityWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SmileSectionVarianceWorker : public Nan::AsyncWorker { public: string mObjectID; double mStrike; double mReturnValue; string mError; SmileSectionVarianceWorker( Nan::Callback *callback ,string ObjectID ,double Strike ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mStrike(Strike) { }; //~SmileSectionVarianceWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SmileSectionAtmLevelWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; SmileSectionAtmLevelWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SmileSectionAtmLevelWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SmileSectionExerciseDateWorker : public Nan::AsyncWorker { public: string mObjectID; long mReturnValue; string mError; SmileSectionExerciseDateWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SmileSectionExerciseDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SmileSectionDayCounterWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; SmileSectionDayCounterWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SmileSectionDayCounterWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrInterpolatedSmileSectionAlphaWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; SabrInterpolatedSmileSectionAlphaWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SabrInterpolatedSmileSectionAlphaWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrInterpolatedSmileSectionBetaWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; SabrInterpolatedSmileSectionBetaWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SabrInterpolatedSmileSectionBetaWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrInterpolatedSmileSectionNuWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; SabrInterpolatedSmileSectionNuWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SabrInterpolatedSmileSectionNuWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrInterpolatedSmileSectionRhoWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; SabrInterpolatedSmileSectionRhoWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SabrInterpolatedSmileSectionRhoWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrInterpolatedSmileSectionErrorWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; SabrInterpolatedSmileSectionErrorWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SabrInterpolatedSmileSectionErrorWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrInterpolatedSmileSectionMaxErrorWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; SabrInterpolatedSmileSectionMaxErrorWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SabrInterpolatedSmileSectionMaxErrorWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SabrInterpolatedSmileSectionEndCriteriaWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; SabrInterpolatedSmileSectionEndCriteriaWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SabrInterpolatedSmileSectionEndCriteriaWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; #endif
19.435198
79
0.659273
quantlibnode
cc0ee718e93af0c434dd888f299c64c242d010ad
2,013
cc
C++
libs/xmi/operation.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
libs/xmi/operation.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
libs/xmi/operation.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
//========================================================================== // ObTools::XMI: operation.cc // // UML::Operation functionality // // Copyright (c) 2003 Paul Clark. All rights reserved // This code comes with NO WARRANTY and is subject to licence agreement //========================================================================== #include "ot-uml.h" using namespace ObTools::UML; //-------------------------------------------------------------------------- // Constructor Operation::Operation(XMI::Reader& rdr, XML::Element& xe) :BehaviouralFeature(rdr, xe) { // Read parameter sub-elements from XML source read_subelements("UML:Parameter", create_element<Parameter>); // Get basic properties is_abstract = get_bool_property("isAbstract", "UML:Operation.isAbstract"); is_root = get_bool_property("isRoot", "UML:Operation.isRoot"); is_leaf = get_bool_property("isLeaf", "UML:Operation.isLeaf"); string cck = get_property("concurrency", "UML:Operation.concurrency"); if (cck=="sequential") concurrency=CONCURRENCY_SEQUENTIAL; else if (cck=="guarded") concurrency=CONCURRENCY_GUARDED; else if (cck.empty() || cck=="concurrent") concurrency=CONCURRENCY_CONCURRENT; else { reader.warning("Unknown operation concurrency: ", cck); concurrency=CONCURRENCY_SEQUENTIAL; // Safest } } //-------------------------------------------------------------------------- // Printer void Operation::print_header(ostream& sout) { BehaviouralFeature::print_header(sout); if (is_abstract) sout << " (abstract)"; if (is_root) sout << " (root)"; if (is_leaf) sout << " (leaf)"; switch (concurrency) { case CONCURRENCY_SEQUENTIAL: sout << " (sequential)"; break; case CONCURRENCY_GUARDED: sout << " (guarded)"; break; case CONCURRENCY_CONCURRENT: // Default - don't clutter break; } }
27.575342
76
0.545951
sandtreader
cc0ee9a73145bbbca35e45e7a96a494223a2dc46
1,117
cpp
C++
BAC/exercises/ch9/UVa103.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC/exercises/ch9/UVa103.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC/exercises/ch9/UVa103.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa103 Stacking Boxes // Rujia Liu // 题意:输入k个n维盒子(k<=30, n<=10),找一个最长嵌套序列。 // 算法:DAG上的最长路。首先把盒子的各个维排序,这样判断起来比较简单 #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxk = 30 + 5; const int maxn = 10 + 5; int n, k, box[maxk][maxn], d[maxk], next[maxk]; int dp(int i) { int& ans = d[i]; if(ans > 0) return ans; ans = 1; next[i] = -1; for(int j = 0; j < k; j++) { bool bigger = true; for(int dim = 0; dim < n; dim++) if(box[j][dim] <= box[i][dim]) { bigger = false; break; } if(bigger && dp(j) + 1 > ans) { ans = dp(j) + 1; next[i] = j; } } return ans; } int main() { while(scanf("%d%d", &k, &n) == 2) { for(int i = 0; i < k; i++) { for(int j = 0; j < n; j++) scanf("%d", &box[i][j]); sort(box[i], box[i]+n); } memset(d, 0, sizeof(d)); int ans = 0, first = -1; for(int i = 0; i < k; i++) if(dp(i) > ans) { ans = dp(i); first = i; } printf("%d\n%d", ans, first+1); for(int idx = next[first]; idx >= 0; idx = next[idx]) printf(" %d", idx+1); printf("\n"); } return 0; }
22.795918
63
0.498657
Anyrainel
cc1733618c8c9d3d16f8ff8bce6fba2e120a08b7
1,507
cpp
C++
VPKReader/VPKReader.cpp
hufuman/VPKReader
d17af846a8212caa1e739852e266fe8ee6a5c1ea
[ "MIT" ]
14
2015-05-07T15:05:38.000Z
2020-12-04T07:00:45.000Z
VPKReader/VPKReader.cpp
hufuman/VPKReader
d17af846a8212caa1e739852e266fe8ee6a5c1ea
[ "MIT" ]
null
null
null
VPKReader/VPKReader.cpp
hufuman/VPKReader
d17af846a8212caa1e739852e266fe8ee6a5c1ea
[ "MIT" ]
6
2015-05-21T16:03:03.000Z
2021-05-17T17:17:52.000Z
// VPKReader.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "VPKReader.h" #include "VPKReaderDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CVPKReaderApp BEGIN_MESSAGE_MAP(CVPKReaderApp, CWinApp) END_MESSAGE_MAP() // CVPKReaderApp construction CVPKReaderApp::CVPKReaderApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CVPKReaderApp object CVPKReaderApp theApp; // CVPKReaderApp initialization BOOL CVPKReaderApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); CVPKReaderDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
22.161765
71
0.746516
hufuman
cc182522136bfe6534e23bb5db502489f80c5c6f
1,296
cpp
C++
code/RegulaFalsi.cpp
Shiv-sharma-111/Numerical-Methods
3a85a1b643f3b4c00fb1b6d3c13af124e9d084e9
[ "MIT" ]
null
null
null
code/RegulaFalsi.cpp
Shiv-sharma-111/Numerical-Methods
3a85a1b643f3b4c00fb1b6d3c13af124e9d084e9
[ "MIT" ]
null
null
null
code/RegulaFalsi.cpp
Shiv-sharma-111/Numerical-Methods
3a85a1b643f3b4c00fb1b6d3c13af124e9d084e9
[ "MIT" ]
null
null
null
// Program for implementation of Bisection Method for #include<bits/stdc++.h> using namespace std; #define MAX_ITER 1000000 //Define the maximium iteration according to your questio // An example function whose solution is determined using // Bisection Method. The function is x^3 - x^2 + 2 double func(double x) { return x*x*x - x*x + 2; } // Prints root of func(x) in interval [a, b] void regulaFalsi(double a, double b) { if (func(a) * func(b) >= 0) { cout << "You have not assumed right a and b"<<endl; return; } double c = a; // Initialize result for (int i=0; i < MAX_ITER; i++) { // Find the point that touches x axis c = (a*func(b) - b*func(a))/ (func(b) - func(a)); // Check if the above found point is root if (func(c)==0) break; // Decide the side to repeat the steps else if (func(c)*func(a) < 0) b = c; else a = c; } cout << "The value of root is : " << c; } // main function int main() { // Plz enter the initial values of A & B; cout<<"Plz Enter the value A and B"; double a,b; cin>>a>>b; //double a =-200, b = 300; regulaFalsi(a, b); return 0; }
24
60
0.53858
Shiv-sharma-111
cc216d860d51144982fd80709e6f1d1178ebfd37
270
hpp
C++
src/pulse/extensions/Vector.hpp
Rypac/pulse
c3d6ae0cab947aa6d380a0e225913b62b8883d8b
[ "Apache-2.0" ]
2
2016-10-12T01:31:55.000Z
2017-01-06T21:07:25.000Z
src/pulse/extensions/Vector.hpp
Rypac/pulse
c3d6ae0cab947aa6d380a0e225913b62b8883d8b
[ "Apache-2.0" ]
1
2016-10-28T22:36:04.000Z
2016-11-18T07:59:50.000Z
src/pulse/extensions/Vector.hpp
Rypac/pulse
c3d6ae0cab947aa6d380a0e225913b62b8883d8b
[ "Apache-2.0" ]
null
null
null
#pragma once #include "cocos2d.h" namespace pulse { template <typename T> inline cocos2d::Vector<T> toVector(const std::vector<T>& vec) { cocos2d::Vector<T> out; for (auto&& element : vec) { out.pushBack(element); } return out; } } // pulse
15.882353
63
0.622222
Rypac
cc22eb5c2ee4b4475fb0962b2590c0cd830c552d
47,400
cpp
C++
drishti/networkobject.cpp
stranddw/drishti
63973422fd0272e55f755aa51378ee1da0f4ef8a
[ "MIT" ]
118
2016-11-01T06:01:44.000Z
2022-03-30T05:20:19.000Z
drishti/networkobject.cpp
stranddw/drishti
63973422fd0272e55f755aa51378ee1da0f4ef8a
[ "MIT" ]
56
2016-09-30T09:29:36.000Z
2022-03-31T17:15:32.000Z
drishti/networkobject.cpp
stranddw/drishti
63973422fd0272e55f755aa51378ee1da0f4ef8a
[ "MIT" ]
28
2016-07-31T23:48:51.000Z
2021-05-25T05:32:47.000Z
#include "global.h" #include "staticfunctions.h" #include "networkobject.h" #include "matrix.h" #if defined(Q_OS_WIN32) #include <netcdfcpp.h> #endif void NetworkObject::setScale(float s) { m_scaleV = m_scaleE = s; } float NetworkObject::scaleV() { return m_scaleV; } void NetworkObject::setScaleV(float s) { m_scaleV = s; } float NetworkObject::scaleE() { return m_scaleE; } void NetworkObject::setScaleE(float s) { m_scaleE = s; } void NetworkObject::gridSize(int &nx, int &ny, int &nz) { nx = m_nX; ny = m_nY; nz = m_nZ; } void NetworkObject::setVstops(QGradientStops stops) { m_Vstops = stops; m_resampledVstops = StaticFunctions::resampleGradientStops(stops); } void NetworkObject::setEstops(QGradientStops stops) { m_Estops = stops; m_resampledEstops = StaticFunctions::resampleGradientStops(stops); } QString NetworkObject::vertexAttributeString(int va) { if (va < m_vertexAttribute.count()) return m_vertexAttribute[va].first; return QString(); } QString NetworkObject::edgeAttributeString(int ea) { if (ea < m_edgeAttribute.count()) return m_edgeAttribute[ea].first; return QString(); } bool NetworkObject::vMinmax(int va, float& vmin, float& vmax) { if (va < m_vertexAttribute.count()) { vmin = m_Vminmax[va].first; vmax = m_Vminmax[va].second; return true; } return false; } bool NetworkObject::userVminmax(int va, float& vmin, float& vmax) { if (va < m_vertexAttribute.count()) { vmin = m_userVminmax[va].first; vmax = m_userVminmax[va].second; return true; } return false; } void NetworkObject::setVminmax(int va, float vmin, float vmax) { if (va < m_vertexAttribute.count()) m_Vminmax[va] = qMakePair(vmin, vmax); } void NetworkObject::setUserVminmax(int va, float vmin, float vmax) { if (va < m_vertexAttribute.count()) m_userVminmax[va] = qMakePair(vmin, vmax); } void NetworkObject::setUserVminmax(float vmin, float vmax) { m_userVminmax[m_Vatt] = qMakePair(vmin, vmax); } bool NetworkObject::eMinmax(int ea, float& emin, float& emax) { if (ea < m_edgeAttribute.count()) { emin = m_Eminmax[ea].first; emax = m_Eminmax[ea].second; return true; } return false; } bool NetworkObject::userEminmax(int ea, float& emin, float& emax) { if (ea < m_edgeAttribute.count()) { emin = m_userEminmax[ea].first; emax = m_userEminmax[ea].second; return true; } return false; } void NetworkObject::setEminmax(int ea, float emin, float emax) { if (ea < m_edgeAttribute.count()) m_Eminmax[ea] = qMakePair(emin, emax); } void NetworkObject::setUserEminmax(int ea, float emin, float emax) { if (ea < m_edgeAttribute.count()) m_userEminmax[ea] = qMakePair(emin, emax); } void NetworkObject::setUserEminmax(float emin, float emax) { m_userEminmax[m_Eatt] = qMakePair(emin, emax); } NetworkObject::NetworkObject() { clear(); } NetworkObject::~NetworkObject() { clear(); } void NetworkObject::enclosingBox(Vec &boxMin, Vec &boxMax) { boxMin = m_enclosingBox[0]; boxMax = m_enclosingBox[6]; } void NetworkObject::clear() { m_show = true; m_fileName.clear(); m_centroid = Vec(0,0,0); m_nX = m_nY = m_nZ = 0; m_Vopacity = 1.0; m_Eopacity = 1.0; m_Vstops << QGradientStop(0.0, QColor(250,230,200,255)) << QGradientStop(1.0, QColor(200,100,50,255)); m_resampledVstops = StaticFunctions::resampleGradientStops(m_Vstops); m_Estops << QGradientStop(0.0, QColor(200,230,250,255)) << QGradientStop(1.0, QColor(50,100,200,255)); m_resampledEstops = StaticFunctions::resampleGradientStops(m_Estops); m_Vatt = 0; m_Eatt = 0; m_Vminmax.clear(); m_Eminmax.clear(); m_userVminmax.clear(); m_userEminmax.clear(); m_Vvertices.clear(); m_Vovertices.clear(); m_Vocolor.clear(); m_VtexValues.clear(); m_Evertices.clear(); m_Eovertices.clear(); m_EtexValues.clear(); m_scaleV = 1; m_scaleE = 1; m_vertexRadiusAttribute = -1; m_edgeRadiusAttribute = -1; m_vertexAttribute.clear(); m_edgeAttribute.clear(); m_vertexCenters.clear(); m_edgeNeighbours.clear(); } bool NetworkObject::load(QString flnm) { if (StaticFunctions::checkExtension(flnm, "network")) return loadTextNetwork(flnm); else if (StaticFunctions::checkExtension(flnm, "graphml")) return loadGraphML(flnm); else return loadNetCDF(flnm); return false; } bool NetworkObject::loadTextNetwork(QString flnm) { m_fileName = flnm; m_nodeAtt.clear(); m_edgeAtt.clear(); QFile fl(m_fileName); if (!fl.open(QIODevice::ReadOnly | QIODevice::Text)) return false; QTextStream in(&fl); QString line; QStringList words; int nvert = 0; int nedge = 0; int nva = 0; int nea = 0; line = in.readLine(); words = line.split(" ", QString::SkipEmptyParts); nvert = words[0].toInt(); if (words.count() > 1) nva = words[1].toInt(); line = in.readLine(); words = line.split(" ", QString::SkipEmptyParts); nedge = words[0].toInt(); if (words.count() > 1) nea = words[1].toInt(); for(int i=0; i<nva; i++) { line = in.readLine(); words = line.split("#", QString::SkipEmptyParts); m_nodeAtt << words[0]; } for(int i=0; i<nea; i++) { line = in.readLine(); words = line.split("#", QString::SkipEmptyParts); m_edgeAtt << words[0]; } m_vertexRadiusAttribute = -1; m_edgeRadiusAttribute = -1; for(int i=0; i<m_nodeAtt.count(); i++) { if (m_nodeAtt[i].contains("radius", Qt::CaseInsensitive) || m_nodeAtt[i].contains("diameter", Qt::CaseInsensitive)) { m_vertexRadiusAttribute = i; break; } } for(int i=0; i<m_edgeAtt.count(); i++) { if (m_edgeAtt[i].contains("radius", Qt::CaseInsensitive) || m_edgeAtt[i].contains("diameter", Qt::CaseInsensitive)) { m_edgeRadiusAttribute = i; break; } } //------------------------------------ // read node information { m_vertexAttribute.clear(); m_vertexCenters.clear(); QVector<float> *vat; // not expecting more than 20 attributes int nvat = m_nodeAtt.count(); vat = new QVector<float> [nvat]; for(int i=0; i<nvert; i++) { line = in.readLine(); line = line.simplified(); words = line.split(" ", QString::SkipEmptyParts); float x, y, z; x = words[0].toFloat(); y = words[1].toFloat(); z = words[2].toFloat(); m_vertexCenters << Vec(x,y,z); for (int j=0; j<qMin((int)(words.count()-3),nvat); j++) vat[j] << words[3+j].toFloat(); } int nv = m_vertexCenters.count(); for(int c=0; c<m_nodeAtt.count(); c++) { if (vat[c].count() < nv) vat[c] << 0.0; } for(int vi=0; vi<m_nodeAtt.count(); vi++) m_vertexAttribute << qMakePair(m_nodeAtt[vi], vat[vi]); if (m_vertexRadiusAttribute == -1) { m_vertexRadiusAttribute = m_nodeAtt.count(); QVector<float> rad; rad.resize(m_vertexCenters.count()); rad.fill(2); m_nodeAtt << "vertex_radius"; m_vertexAttribute << qMakePair(QString("vertex_radius"), rad); } for(int i=0; i<nvat; i++) vat[i].clear(); delete [] vat; } //------------------------------------ //------------------------------------ // read edge information { m_edgeAttribute.clear(); m_edgeNeighbours.clear(); QVector<float> *vat; // not expecting more than 20 attributes int nvat = m_edgeAtt.count(); vat = new QVector<float> [nvat]; for(int i=0; i<nedge; i++) { line = in.readLine(); line = line.simplified(); words = line.split(" ", QString::SkipEmptyParts); int a, b; a = words[0].toInt(); b = words[1].toInt(); m_edgeNeighbours << qMakePair(a,b); for (int j=0; j<qMin((int)(words.count()-2),nvat); j++) vat[j] << words[2+j].toFloat(); } int nv = m_edgeNeighbours.count(); for(int c=0; c<m_edgeAtt.count(); c++) { if (vat[c].count() < nv) vat[c] << 0.0; } for(int e=0; e<m_edgeAtt.count(); e++) { if (m_edgeAtt[e].contains("diameter", Qt::CaseInsensitive)) { for(int vi=0; vi<vat[e].count(); vi++) vat[e][vi] /= 2; } } for(int vi=0; vi<m_edgeAtt.count(); vi++) m_edgeAttribute << qMakePair(m_edgeAtt[vi], vat[vi]); if (m_edgeRadiusAttribute == -1) { m_edgeRadiusAttribute = m_edgeAtt.count(); QVector<float> rad; rad.resize(m_edgeNeighbours.count()); rad.fill(2); m_edgeAtt << "edge_radius"; m_edgeAttribute << qMakePair(QString("edge_radius"), rad); } for(int i=0; i<nvat; i++) vat[i].clear(); delete [] vat; } //------------------------------------ //--------------------- Vec bmin = m_vertexCenters[0]; Vec bmax = m_vertexCenters[0]; for(int i=0; i<m_vertexCenters.count(); i++) { bmin = StaticFunctions::minVec(bmin, m_vertexCenters[i]); bmax = StaticFunctions::maxVec(bmax, m_vertexCenters[i]); } m_centroid = (bmin + bmax)/2; m_enclosingBox[0] = Vec(bmin.x, bmin.y, bmin.z); m_enclosingBox[1] = Vec(bmax.x, bmin.y, bmin.z); m_enclosingBox[2] = Vec(bmax.x, bmax.y, bmin.z); m_enclosingBox[3] = Vec(bmin.x, bmax.y, bmin.z); m_enclosingBox[4] = Vec(bmin.x, bmin.y, bmax.z); m_enclosingBox[5] = Vec(bmax.x, bmin.y, bmax.z); m_enclosingBox[6] = Vec(bmax.x, bmax.y, bmax.z); m_enclosingBox[7] = Vec(bmin.x, bmax.y, bmax.z); // m_nZ = (bmax.x - bmin.x) + 1; // m_nY = (bmax.y - bmin.y) + 1; // m_nX = (bmax.z - bmin.z) + 1; m_nZ = bmax.x; m_nY = bmax.y; m_nX = bmax.z; if (!Global::batchMode()) { QString str; str = QString("Grid Size : %1 %2 %3\n").arg(m_nX).arg(m_nY).arg(m_nZ); str += QString("Vertices : %1\n").arg(m_vertexCenters.count()); str += QString("Edges : %1\n").arg(m_edgeNeighbours.count()); str += QString("\n"); str += QString("Vertex Attributes : %1\n").arg(m_vertexAttribute.count()); for(int i=0; i<m_vertexAttribute.count(); i++) str += QString(" %1\n").arg(m_vertexAttribute[i].first); str += QString("\n"); str += QString("Edge Attributes : %1\n").arg(m_edgeAttribute.count()); for(int i=0; i<m_edgeAttribute.count(); i++) str += QString(" %1\n").arg(m_edgeAttribute[i].first); QMessageBox::information(0, "Network loaded", str); } m_Vatt = 0; m_Eatt = 0; m_Vminmax.clear(); m_Eminmax.clear(); m_userVminmax.clear(); m_userEminmax.clear(); for(int i=0; i<m_vertexAttribute.count(); i++) { float vmin = m_vertexAttribute[i].second[0]; float vmax = m_vertexAttribute[i].second[0]; for(int j=1; j<m_vertexAttribute[i].second.count(); j++) { vmin = qMin((float)m_vertexAttribute[i].second[j], vmin); vmax = qMax((float)m_vertexAttribute[i].second[j], vmax); } m_Vminmax.append(qMakePair(vmin, vmax)); m_userVminmax.append(qMakePair((vmin+vmax)/2, vmax)); } for(int i=0; i<m_edgeAttribute.count(); i++) { float emin = m_edgeAttribute[i].second[0]; float emax = m_edgeAttribute[i].second[0]; for(int j=1; j<m_edgeAttribute[i].second.count(); j++) { emin = qMin((float)m_edgeAttribute[i].second[j], emin); emax = qMax((float)m_edgeAttribute[i].second[j], emax); } m_Eminmax.append(qMakePair(emin, emax)); m_userEminmax.append(qMakePair((emin+emax)/2, emax)); } return true; } bool NetworkObject::loadNetCDF(QString flnm) { #if defined(Q_OS_WIN32) m_fileName = flnm; NcError err(NcError::verbose_nonfatal); NcFile ncfFile(flnm.toLatin1().data(), NcFile::ReadOnly); NcAtt *att; NcVar *var; // ---- get gridsize ----- att = ncfFile.get_att("gridsize"); m_nX = att->as_int(0); m_nY = att->as_int(1); m_nZ = att->as_int(2); //------------------------ // ---- get vertex centers ----- var = ncfFile.get_var("vertex_centers"); if (!var) var = ncfFile.get_var("vertex_center"); if (!var) var = ncfFile.get_var("vertex_centres"); if (!var) var = ncfFile.get_var("vertex_centre"); int nv = var->get_dim(0)->size(); float *vc = new float [3*nv]; var->get(vc, nv, 3); m_vertexCenters.resize(nv); for(int i=0; i<nv; i++) m_vertexCenters[i] = Vec(vc[3*i+0], vc[3*i+1], vc[3*i+2]); delete [] vc; //------------------------ // ---- get edges ----- var = ncfFile.get_var("edge_neighbours"); int ne = var->get_dim(0)->size(); int *ed = new int [2*ne]; var->get(ed, ne, 2); m_edgeNeighbours.resize(ne); for(int i=0; i<ne; i++) m_edgeNeighbours[i] = qMakePair(ed[2*i], ed[2*i+1]); delete [] ed; //------------------------ Vec bmin = m_vertexCenters[0]; Vec bmax = m_vertexCenters[0]; for(int i=0; i<m_vertexCenters.count(); i++) { bmin = StaticFunctions::minVec(bmin, m_vertexCenters[i]); bmax = StaticFunctions::maxVec(bmax, m_vertexCenters[i]); } m_centroid = (bmin + bmax)/2; m_enclosingBox[0] = Vec(bmin.x, bmin.y, bmin.z); m_enclosingBox[1] = Vec(bmax.x, bmin.y, bmin.z); m_enclosingBox[2] = Vec(bmax.x, bmax.y, bmin.z); m_enclosingBox[3] = Vec(bmin.x, bmax.y, bmin.z); m_enclosingBox[4] = Vec(bmin.x, bmin.y, bmax.z); m_enclosingBox[5] = Vec(bmax.x, bmin.y, bmax.z); m_enclosingBox[6] = Vec(bmax.x, bmax.y, bmax.z); m_enclosingBox[7] = Vec(bmin.x, bmax.y, bmax.z); // QStringList vatt, eatt; int nvars = ncfFile.num_vars(); // for (int i=0; i < nvars; i++) // { // var = ncfFile.get_var(i); // QString attname = var->name(); // attname.toLower(); // if (attname.contains("vertex_") && // ( attname != "vertex_centers" || // attname != "vertex_centres")) // vatt.append(attname); // else if (attname.contains("edge_") && // attname != "edge_neighbours") // eatt.append(attname); // } m_vertexAttribute.clear(); m_edgeAttribute.clear(); m_vertexRadiusAttribute = -1; m_edgeRadiusAttribute = -1; int vri = 0; int eri = 0; for (int i=0; i < nvars; i++) { var = ncfFile.get_var(i); QString attname = var->name(); attname.toLower(); if (attname.contains("vertex_") && attname != "vertex_center" && attname != "vertex_centre" && attname != "vertex_centers" && attname != "vertex_centres") { if (attname == "vertex_radius") m_vertexRadiusAttribute = vri; vri++; QVector<float> val; val.clear(); if (var->type() == ncByte || var->type() == ncChar) { uchar *v = new uchar[nv]; var->get((ncbyte *)v, nv); for(int j=0; j<nv; j++) val.append(v[j]); delete [] v; } else if (var->type() == ncShort) { short *v = new short[nv]; var->get((short *)v, nv); for(int j=0; j<nv; j++) val.append(v[j]); delete [] v; } else if (var->type() == ncInt) { int *v = new int[nv]; var->get((int *)v, nv); for(int j=0; j<nv; j++) val.append(v[j]); delete [] v; } else if (var->type() == ncFloat) { float *v = new float[nv]; var->get((float *)v, nv); for(int j=0; j<nv; j++) val.append(v[j]); delete [] v; } if (val.count() > 0) m_vertexAttribute.append(qMakePair(attname, val)); } else if (attname.contains("edge_") && attname != "edge_neighbours") { if (attname == "edge_radius") m_edgeRadiusAttribute = eri; eri++; QVector<float> val; val.clear(); if (var->type() == ncByte || var->type() == ncChar) { uchar *v = new uchar[ne]; var->get((ncbyte *)v, ne); for(int j=0; j<ne; j++) val.append(v[j]); delete [] v; } else if (var->type() == ncShort) { short *v = new short[ne]; var->get((short *)v, ne); for(int j=0; j<ne; j++) val.append(v[j]); delete [] v; } else if (var->type() == ncInt) { int *v = new int[ne]; var->get((int *)v, ne); for(int j=0; j<ne; j++) val.append(v[j]); delete [] v; } else if (var->type() == ncFloat) { float *v = new float[ne]; var->get((float *)v, ne); for(int j=0; j<ne; j++) val.append(v[j]); delete [] v; } if (val.count() > 0) m_edgeAttribute.append(qMakePair(attname, val)); } } ncfFile.close(); if (!Global::batchMode()) { QString str; str = QString("Grid Size : %1 %2 %3\n").arg(m_nX).arg(m_nY).arg(m_nZ); str += QString("Vertices : %1\n").arg(m_vertexCenters.count()); str += QString("Edges : %1\n").arg(m_edgeNeighbours.count()); str += QString("\n"); str += QString("Vertex Attributes : %1\n").arg(m_vertexAttribute.count()); for(int i=0; i<m_vertexAttribute.count(); i++) str += QString(" %1\n").arg(m_vertexAttribute[i].first); str += QString("\n"); str += QString("Edge Attributes : %1\n").arg(m_edgeAttribute.count()); for(int i=0; i<m_edgeAttribute.count(); i++) str += QString(" %1\n").arg(m_edgeAttribute[i].first); QMessageBox::information(0, "Network loaded", str); } m_Vatt = 0; m_Eatt = 0; m_Vminmax.clear(); m_Eminmax.clear(); m_userVminmax.clear(); m_userEminmax.clear(); for(int i=0; i<m_vertexAttribute.count(); i++) { float vmin = m_vertexAttribute[i].second[0]; float vmax = m_vertexAttribute[i].second[0]; for(int j=1; j<m_vertexAttribute[i].second.count(); j++) { vmin = qMin((float)m_vertexAttribute[i].second[j], vmin); vmax = qMax((float)m_vertexAttribute[i].second[j], vmax); } m_Vminmax.append(qMakePair(vmin, vmax)); m_userVminmax.append(qMakePair((vmin+vmax)/2, vmax)); } for(int i=0; i<m_edgeAttribute.count(); i++) { float emin = m_edgeAttribute[i].second[0]; float emax = m_edgeAttribute[i].second[0]; for(int j=1; j<m_edgeAttribute[i].second.count(); j++) { emin = qMin((float)m_edgeAttribute[i].second[j], emin); emax = qMax((float)m_edgeAttribute[i].second[j], emax); } m_Eminmax.append(qMakePair(emin, emax)); m_userEminmax.append(qMakePair((emin+emax)/2, emax)); } #endif return true; } bool NetworkObject::save(QString flnm) { return true; } void NetworkObject::postdraw(QGLViewer *viewer, int x, int y, bool active, int idx) { if (!m_show || !active) return; viewer->startScreenCoordinatesSystem(); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // blend on top QString str = QString("network %1").arg(idx); QFont font = QFont(); QFontMetrics metric(font); int ht = metric.height(); int wd = metric.width(str); //x -= wd/2; x += 10; StaticFunctions::renderText(x+2, y, str, font, Qt::black, Qt::white); viewer->stopScreenCoordinatesSystem(); } void NetworkObject::draw(QGLViewer *viewer, bool active, float pnear, float pfar, bool backToFront) { if (!m_show) return; if (active) { Vec lineColor = Vec(0.7f, 0.3f, 0.0f); StaticFunctions::drawEnclosingCube(m_tenclosingBox, lineColor); } if (m_Vopacity < 0.05 && m_Eopacity < 0.05) return; glShadeModel(GL_SMOOTH); // emissive when active if (active) { float emiss[] = { 0.5f, 0, 0, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emiss); } else { float emiss[] = { 0, 0, 0, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emiss); } drawNetwork(pnear, pfar, backToFront); { // reset emissivity float emiss[] = { 0, 0, 0, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emiss); } } void NetworkObject::predraw(QGLViewer *viewer, double *Xform, Vec pn, QList<Vec> clipPos, QList<Vec> clipNormal, QList<CropObject> crops, Vec lightVector) { if (!m_show) return; generateSphereSpriteTexture(lightVector); generateCylinderSpriteTexture(lightVector); predrawVertices(viewer, Xform, pn, clipPos, clipNormal, crops); predrawEdges(viewer, Xform, pn, clipPos, clipNormal, crops); // m_tcentroid = Matrix::xformVec(Xform, m_centroid); // // for(int i=0; i<8; i++) // m_tenclosingBox[i] = Matrix::xformVec(Xform, m_enclosingBox[i]); Vec bmin, bmax; Global::bounds(bmin, bmax); Vec vmin = m_enclosingBox[0]; Vec vmax = m_enclosingBox[6]; vmin.x = qMax(vmin.x, bmin.x); vmin.y = qMax(vmin.y, bmin.y); vmin.z = qMax(vmin.z, bmin.z); vmax.x = qMin(vmax.x, bmax.x); vmax.y = qMin(vmax.y, bmax.y); vmax.z = qMin(vmax.z, bmax.z); Vec centroid = (vmin + vmax)/2; m_tcentroid = Matrix::xformVec(Xform, centroid); Vec box[8]; box[0] = Vec(vmin.x, vmin.y, vmin.z); box[1] = Vec(vmax.x, vmin.y, vmin.z); box[2] = Vec(vmax.x, vmax.y, vmin.z); box[3] = Vec(vmin.x, vmax.y, vmin.z); box[4] = Vec(vmin.x, vmin.y, vmax.z); box[5] = Vec(vmax.x, vmin.y, vmax.z); box[6] = Vec(vmax.x, vmax.y, vmax.z); box[7] = Vec(vmin.x, vmax.y, vmax.z); for(int i=0; i<8; i++) m_tenclosingBox[i] = Matrix::xformVec(Xform, box[i]); } void NetworkObject::generateSphereSpriteTexture(Vec lightVector) { int texsize = 64; int t2 = texsize/2; int fx, fy; fx = t2 - (t2-1)*lightVector.x; fy = t2 + (t2-1)*lightVector.y; QRadialGradient rg(t2, t2, t2-1, fx, fy); rg.setColorAt(0.0, Qt::white); rg.setColorAt(1.0, Qt::black); QImage texImage(texsize, texsize, QImage::Format_ARGB32); texImage.fill(0); QPainter p(&texImage); p.setBrush(QBrush(rg)); p.setPen(Qt::transparent); p.drawEllipse(0, 0, texsize, texsize); uchar *thetexture = new uchar[2*texsize*texsize]; const uchar *bits = texImage.bits(); for(int i=0; i<texsize*texsize; i++) { uchar lum = 255; float a = (float)bits[4*i+2]/255.0f; a = 1-a; if (a < 0.5) { if (lightVector.z >= 0.0) a = qMax(a/0.5f, 0.5f); else { a = 0.7f; lum = 50; } } else if (a >= 1) { a = 0; lum = 0; } else { if (lightVector.z >= 0.0) { a = 1-(a-0.5f)/0.5f; lum *= a; a = 0.9f; } else { lum *= 1-fabs(a-0.75f)/0.25f; a = 0.9f; } } a *= 255; thetexture[2*i] = lum; thetexture[2*i+1] = a; } glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, Global::sphereTexture()); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, texsize, texsize, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, thetexture); delete [] thetexture; } void NetworkObject::generateCylinderSpriteTexture(Vec lightVector) { int texsize = 64; float fp = 0.5f+0.5f*lightVector.y; QLinearGradient lg(0, 0, texsize, 0); lg.setColorAt(0.0, Qt::black); lg.setColorAt(1.0, Qt::black); lg.setColorAt(fp, Qt::white); QImage texImage(texsize, texsize, QImage::Format_ARGB32); texImage.fill(0); QPainter p(&texImage); p.setBrush(QBrush(lg)); p.setPen(Qt::transparent); //p.drawEllipse(0, 0, texsize, texsize); p.drawRect(0, 0, texsize, texsize); uchar *thetexture = new uchar[2*texsize*texsize]; const uchar *bits = texImage.bits(); for(int i=0; i<texsize*texsize; i++) { uchar lum = 255; float a = (float)bits[4*i+2]/255.0f; a = 1-a; if (a < 0.5) { if (lightVector.z >= 0.0) a = qMax(a/0.5f, 0.5f); else { a = 0.7f; lum = 50; } } else if (a >= 1) { a = 0; lum = 0; } else { if (lightVector.z >= 0.0f) { a = 1-(a-0.5f)/0.5f; lum *= a; a = 0.9f; } else { lum *= 1-fabs(a-0.75f)/0.25f; a = 0.9f; } } a *= 255; thetexture[2*i] = lum; thetexture[2*i+1] = a; } glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, Global::cylinderTexture()); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, texsize, texsize, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, thetexture); delete [] thetexture; } void NetworkObject::predrawVertices(QGLViewer *viewer, double *Xform, Vec pn, QList<Vec> clipPos, QList<Vec> clipNormal, QList<CropObject> crops) { Vec bmin, bmax; Global::bounds(bmin, bmax); // QMessageBox::information(0, "", QString("%1 %2 %3\n%4 %5 %6").\ // arg(bmin.x).arg(bmin.y).arg(bmin.z).\ // arg(bmax.x).arg(bmax.y).arg(bmax.z)); m_Vovertices.resize(m_vertexCenters.count()); m_Vocolor.resize(m_vertexCenters.count()); QVector<float> rad; rad.resize(m_vertexCenters.count()); int stopsCount = m_resampledVstops.count()-1; float aint = (m_userVminmax[m_Vatt].second-m_userVminmax[m_Vatt].first); if (aint <= 0.0001) aint = 1; QString txt; int nv=0; for(int i=0; i<m_vertexCenters.count(); i++) { bool ok = true; if (m_vertexAttribute[m_Vatt].second[i] < m_userVminmax[m_Vatt].first || m_vertexAttribute[m_Vatt].second[i] > m_userVminmax[m_Vatt].second) ok = false; if (ok) { for(int c=0; c<clipPos.count(); c++) { if ((m_vertexCenters[i]-clipPos[c])*clipNormal[c] > 0) { ok = false; break; } } if (ok) { for(int ci=0; ci<crops.count(); ci++) { ok &= crops[ci].checkCropped(m_vertexCenters[i]); if (!ok) break; } } if (ok) { if (m_vertexCenters[i].x >= bmin.x && m_vertexCenters[i].y >= bmin.y && m_vertexCenters[i].z >= bmin.z && m_vertexCenters[i].x <= bmax.x && m_vertexCenters[i].y <= bmax.y && m_vertexCenters[i].z <= bmax.z) { m_Vovertices[nv] = Matrix::xformVec(Xform, m_vertexCenters[i]); //rad[nv] = 1.5*m_vertexAttribute[m_vertexRadiusAttribute].second[i]; rad[nv] = m_scaleV * m_vertexAttribute[m_vertexRadiusAttribute].second[i]; float stp = (m_vertexAttribute[m_Vatt].second[i] - m_userVminmax[m_Vatt].first) / aint; QColor col = m_resampledVstops[stp*stopsCount].second; float r = col.red()/255.0; float g = col.green()/255.0; float b = col.blue()/255.0; m_Vocolor[nv] = Vec(r,g,b); nv++; } } } } m_Vovertices.resize(nv+1); m_VtexValues.resize(m_Vovertices.count()); for(int i=0; i<m_Vovertices.count(); i++) m_VtexValues[i] = pn*m_Vovertices[i]; Vec p = pn^viewer->camera()->upVector(); Vec q = pn^p; p.normalize(); q.normalize(); m_Vvertices.resize(4*m_Vovertices.count()); for(int i=0; i<m_Vovertices.count(); i++) { m_Vvertices[4*i+0] = m_Vovertices[i]-rad[i]*p-rad[i]*q; m_Vvertices[4*i+1] = m_Vovertices[i]-rad[i]*p+rad[i]*q; m_Vvertices[4*i+2] = m_Vovertices[i]+rad[i]*p+rad[i]*q; m_Vvertices[4*i+3] = m_Vovertices[i]+rad[i]*p-rad[i]*q; } } void NetworkObject::predrawEdges(QGLViewer *viewer, double *Xform, Vec pn, QList<Vec> clipPos, QList<Vec> clipNormal, QList<CropObject> crops) { Vec bmin, bmax; Global::bounds(bmin, bmax); m_Eovertices.resize(2*m_edgeNeighbours.count()); m_Eocolor.resize(m_edgeNeighbours.count()); QVector<float> rad; rad.resize(m_edgeNeighbours.count()); int stopsCount = m_resampledEstops.count()-1; float aint = (m_userEminmax[m_Eatt].second-m_userEminmax[m_Eatt].first); if (aint <= 0.0001) aint = 1; int nv = 0; for(int i=0; i<m_edgeNeighbours.count(); i++) { bool ok = true; if (m_edgeAttribute[m_Eatt].second[i] < m_userEminmax[m_Eatt].first || m_edgeAttribute[m_Eatt].second[i] > m_userEminmax[m_Eatt].second) ok = false; if (ok) { int a = m_edgeNeighbours[i].first; int b = m_edgeNeighbours[i].second; Vec pa = m_vertexCenters[a]; Vec pb = m_vertexCenters[b]; for(int c=0; c<clipPos.count(); c++) { if ((pa-clipPos[c])*clipNormal[c] > 0 || (pb-clipPos[c])*clipNormal[c] > 0) { ok = false; break; } } if (ok) { for(int ci=0; ci<crops.count(); ci++) { ok &= crops[ci].checkCropped(pa); if (!ok) break; ok &= crops[ci].checkCropped(pb); if (!ok) break; } } if (ok) { pa = Matrix::xformVec(Xform, pa); pb = Matrix::xformVec(Xform, pb); if (m_vertexCenters[a].x >= bmin.x && m_vertexCenters[a].y >= bmin.y && m_vertexCenters[a].z >= bmin.z && m_vertexCenters[a].x <= bmax.x && m_vertexCenters[a].y <= bmax.y && m_vertexCenters[a].z <= bmax.z && m_vertexCenters[b].x >= bmin.x && m_vertexCenters[b].y >= bmin.y && m_vertexCenters[b].z >= bmin.z && m_vertexCenters[b].x <= bmax.x && m_vertexCenters[b].y <= bmax.y && m_vertexCenters[b].z <= bmax.z) { if (m_Vopacity > 0.5) { Vec p = pb-pa; p.normalize(); pa = pa + p*m_vertexAttribute[m_vertexRadiusAttribute].second[a]; pb = pb - p*m_vertexAttribute[m_vertexRadiusAttribute].second[b]; } m_Eovertices[2*nv] = pa; m_Eovertices[2*nv+1] = pb; //rad[nv] = m_edgeAttribute[m_edgeRadiusAttribute].second[i]; rad[nv] = m_scaleE * m_edgeAttribute[m_edgeRadiusAttribute].second[i]; float stp = (m_edgeAttribute[m_Eatt].second[i] - m_userEminmax[m_Eatt].first) / aint; QColor col = m_resampledEstops[stp*stopsCount].second; float r = col.red()/255.0; float g = col.green()/255.0; float b = col.blue()/255.0; m_Eocolor[nv] = Vec(r,g,b); nv ++; } } } } m_Eovertices.resize(2*(nv+1)); m_EtexValues.resize(m_Eovertices.count()); for(int i=0; i<m_Eovertices.count(); i++) m_EtexValues[i] = pn*m_Eovertices[i]; Vec p = pn^viewer->camera()->upVector(); Vec q = pn^p; p.normalize(); q.normalize(); m_Evertices.resize(2*m_Eovertices.count()); for(int i=0; i<m_Eovertices.count()/2; i++) { Vec pa = m_Eovertices[2*i]; Vec pb = m_Eovertices[2*i+1]; Vec p = pn^(pa-pb); p.normalize(); p *= rad[i]; m_Evertices[4*i+0] = pa-p; m_Evertices[4*i+1] = pb-p; m_Evertices[4*i+2] = pb+p; m_Evertices[4*i+3] = pa+p; } } void NetworkObject::drawNetwork(float pnear, float pfar, bool backToFront) { if (backToFront) { if (m_Eopacity > 0.01) drawEdges(pnear, pfar); if (m_Vopacity > 0.01) drawVertices(pnear, pfar); } else { if (m_Vopacity > 0.01) drawVertices(pnear, pfar); if (m_Eopacity > 0.01) drawEdges(pnear, pfar); } } void NetworkObject::drawEdges(float pnear, float pfar) { // glColor4f(m_Ecolor.x*m_Eopacity, // m_Ecolor.y*m_Eopacity, // m_Ecolor.z*m_Eopacity, // m_Eopacity); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, Global::cylinderTexture()); glBegin(GL_QUADS); for(int i=0; i<m_Eovertices.count()/2; i++) { if ( ! (m_EtexValues[2*i] < pnear && m_EtexValues[2*i+1] < pnear) || (m_EtexValues[2*i] > pfar && m_EtexValues[2*i+1] > pfar) ) { glColor4f(m_Eocolor[i].x*m_Eopacity, m_Eocolor[i].y*m_Eopacity, m_Eocolor[i].z*m_Eopacity, m_Eopacity); glTexCoord2f(0, 0); glVertex3fv(m_Evertices[4*i+0]); glTexCoord2f(0, 1); glVertex3fv(m_Evertices[4*i+1]); glTexCoord2f(1, 1); glVertex3fv(m_Evertices[4*i+2]); glTexCoord2f(1, 0); glVertex3fv(m_Evertices[4*i+3]); } } glEnd(); glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_2D); } void NetworkObject::drawVertices(float pnear, float pfar) { glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, Global::sphereTexture()); glBegin(GL_QUADS); for(int i=0; i<m_Vovertices.count(); i++) { if ( m_VtexValues[i] >= pnear && m_VtexValues[i] <= pfar ) { glColor4f(m_Vocolor[i].x*m_Vopacity, m_Vocolor[i].y*m_Vopacity, m_Vocolor[i].z*m_Vopacity, m_Vopacity); glTexCoord2f(0, 0); glVertex3fv(m_Vvertices[4*i+0]); glTexCoord2f(0, 1); glVertex3fv(m_Vvertices[4*i+1]); glTexCoord2f(1, 1); glVertex3fv(m_Vvertices[4*i+2]); glTexCoord2f(1, 0); glVertex3fv(m_Vvertices[4*i+3]); } } glEnd(); glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_2D); } QDomElement NetworkObject::domElement(QDomDocument &doc) { QDomElement de = doc.createElement("network"); { QDomElement de0 = doc.createElement("name"); QDomText tn0 = doc.createTextNode(m_fileName); de0.appendChild(tn0); de.appendChild(de0); } { QDomElement de0 = doc.createElement("vopacity"); QDomText tn0 = doc.createTextNode(QString("%1").arg(m_Vopacity)); de0.appendChild(tn0); de.appendChild(de0); } { QDomElement de0 = doc.createElement("vstops"); QString str; for(int s=0; s<m_Vstops.count(); s++) { float pos = m_Vstops[s].first; QColor col = m_Vstops[s].second; int r = col.red(); int g = col.green(); int b = col.blue(); int a = col.alpha(); str += QString("%1 %2 %3 %4 %5 ").\ arg(pos).arg(r).arg(g).arg(b).arg(a); } QDomText tn0 = doc.createTextNode(str); de0.appendChild(tn0); de.appendChild(de0); } { QDomElement de0 = doc.createElement("eopacity"); QDomText tn0 = doc.createTextNode(QString("%1").arg(m_Eopacity)); de0.appendChild(tn0); de.appendChild(de0); } { QDomElement de0 = doc.createElement("estops"); QString str; for(int s=0; s<m_Estops.count(); s++) { float pos = m_Estops[s].first; QColor col = m_Estops[s].second; int r = col.red(); int g = col.green(); int b = col.blue(); int a = col.alpha(); str += QString("%1 %2 %3 %4 %5 ").\ arg(pos).arg(r).arg(g).arg(b).arg(a); } QDomText tn0 = doc.createTextNode(str); de0.appendChild(tn0); de.appendChild(de0); } return de; } bool NetworkObject::fromDomElement(QDomElement de) { clear(); bool ok = false; QString name; QDomNodeList dlist = de.childNodes(); for(int i=0; i<dlist.count(); i++) { QDomElement dnode = dlist.at(i).toElement(); QString str = dnode.toElement().text(); if (dnode.tagName() == "name") ok = load(str); else if (dnode.tagName() == "vopacity") m_Vopacity = str.toFloat(); else if (dnode.tagName() == "vstops") { QStringList xyz = str.split(" "); for(int s=0; s<xyz.count()/5; s++) { float pos; int r,g,b,a; pos = xyz[5*s+0].toFloat(); r = xyz[5*s+1].toInt(); g = xyz[5*s+2].toInt(); b = xyz[5*s+3].toInt(); a = xyz[5*s+4].toInt(); m_Vstops << QGradientStop(pos, QColor(r,g,b,a)); } } else if (dnode.tagName() == "eopacity") m_Eopacity = str.toFloat(); else if (dnode.tagName() == "estops") { QStringList xyz = str.split(" "); for(int s=0; s<xyz.count()/5; s++) { float pos; int r,g,b,a; pos = xyz[5*s+0].toFloat(); r = xyz[5*s+1].toInt(); g = xyz[5*s+2].toInt(); b = xyz[5*s+3].toInt(); a = xyz[5*s+4].toInt(); m_Vstops << QGradientStop(pos, QColor(r,g,b,a)); } } } return ok; } NetworkInformation NetworkObject::get() { NetworkInformation ti; ti.filename = m_fileName; ti.Vopacity = m_Vopacity; ti.Eopacity = m_Eopacity; ti.Vatt = m_Vatt; ti.Eatt = m_Eatt; ti.userVmin = m_userVminmax[m_Vatt].first; ti.userVmax = m_userVminmax[m_Vatt].second; ti.userEmin = m_userEminmax[m_Eatt].first; ti.userEmax = m_userEminmax[m_Eatt].second; ti.Vstops = m_Vstops; ti.Estops = m_Estops; ti.scalee = m_scaleE; ti.scalev = m_scaleV; return ti; } bool NetworkObject::set(NetworkInformation ti) { bool ok = false; if (m_fileName != ti.filename) ok = load(ti.filename); else ok = true; m_Vopacity = ti.Vopacity; m_Eopacity = ti.Eopacity; m_Vatt = ti.Vatt; m_Eatt = ti.Eatt; m_userVminmax[m_Vatt] = qMakePair(ti.userVmin, ti.userVmax); m_userEminmax[m_Eatt] = qMakePair(ti.userEmin, ti.userEmax); m_Vstops = ti.Vstops; m_resampledVstops = StaticFunctions::resampleGradientStops(m_Vstops); m_Estops = ti.Estops; m_resampledEstops = StaticFunctions::resampleGradientStops(m_Estops); m_scaleE = ti.scalee; m_scaleV = ti.scalev; return ok; } void NetworkObject::getKey(QDomElement main) { m_nodeAtt.clear(); m_edgeAtt.clear(); m_nodeAttName.clear(); m_edgeAttName.clear(); m_nodePosAttr.clear(); m_nodePosAttr << "x"; m_nodePosAttr << "y"; m_nodePosAttr << "z"; QDomNodeList dlist = main.childNodes(); for(int i=0; i<dlist.count(); i++) { if (dlist.at(i).isElement()) { QDomElement ele = dlist.at(i).toElement(); QString str = ele.nodeName(); if (str == "key") { QDomNamedNodeMap attr = ele.attributes(); int nattr = attr.count(); bool isnode = false; bool isedge = false; for(int na=0; na<nattr; na++) { QDomNode node = attr.item(na); QString name = node.nodeName(); QString val = node.nodeValue(); if (name == "for" && val == "node") { isnode = true; break; } if (name == "for" && val == "edge") { isedge = true; break; } } if (isedge) { bool notstr = true; for(int na=0; na<nattr; na++) { QDomNode node = attr.item(na); QString name = node.nodeName(); QString val = node.nodeValue(); if (name == "attr.type" && val == "string") { notstr = false; break; } } if (notstr) { for(int na=0; na<nattr; na++) { QDomNode node = attr.item(na); QString name = node.nodeName(); QString val = node.nodeValue(); if (name == "id") m_edgeAtt << val; if (name == "attr.name") m_edgeAttName << val; } } } if (isnode) { bool posatt = false; for(int na=0; na<nattr; na++) { QDomNode node = attr.item(na); QString name = node.nodeName(); QString val = node.nodeValue(); if (name == "attr.name" && (val == "Position X" || val == "Position Y" || val == "Position Z")) { posatt = true; for(int a=0; a<nattr; a++) { QDomNode nde = attr.item(a); QString nme = nde.nodeName(); QString vle = nde.nodeValue(); if (nme == "id") { int pa = 0; if (val == "Position X") pa = 0; if (val == "Position Y") pa = 1; if (val == "Position Z") pa = 2; m_nodePosAttr[pa] = vle; } } break; } } if (!posatt) // not position attribute { for(int na=0; na<nattr; na++) { QDomNode node = attr.item(na); QString name = node.nodeName(); QString val = node.nodeValue(); //if (val == "attr.name") if (name == "id") m_nodeAtt << val; if (name == "attr.name") m_nodeAttName << val; } } } } } } m_vertexRadiusAttribute = -1; m_edgeRadiusAttribute = -1; for(int i=0; i<m_nodeAtt.count(); i++) { if (m_nodeAtt[i].contains("radius", Qt::CaseInsensitive) || m_nodeAtt[i].contains("diameter", Qt::CaseInsensitive)) { m_vertexRadiusAttribute = i; break; } } for(int i=0; i<m_edgeAtt.count(); i++) { if (m_edgeAtt[i].contains("radius", Qt::CaseInsensitive) || m_edgeAtt[i].contains("diameter", Qt::CaseInsensitive)) { m_edgeRadiusAttribute = i; break; } } } void NetworkObject::loadNodeInfo(QDomNodeList nnodes) { m_vertexAttribute.clear(); m_vertexCenters.clear(); m_nodeId.clear(); QVector<float> *vat; // not expecting more than 20 attributes int nvat = m_nodeAtt.count(); vat = new QVector<float> [nvat]; int nn = nnodes.count(); for(int n=0; n<nn; n++) { QDomElement ele = nnodes.item(n).toElement(); QString id = ele.attributeNode("id").value(); m_nodeId << id; Vec pos; QDomNodeList nlist = nnodes.item(n).childNodes(); int nc = nlist.count(); for(int c=0; c<nc; c++) { QDomNode node = nlist.item(c); QDomElement ele = node.toElement(); QString et = ele.text(); QDomNamedNodeMap attr = ele.attributes(); QString name = attr.item(0).nodeName(); QString val = attr.item(0).nodeValue(); if (val == m_nodePosAttr[0]) pos.x = et.toFloat(); else if (val == m_nodePosAttr[1]) pos.y = et.toFloat(); else if (val == m_nodePosAttr[2]) pos.z = et.toFloat(); else { int vi = m_nodeAtt.indexOf(val); if (vi >= 0) vat[vi] << et.toFloat(); } } m_vertexCenters << pos; int nv = m_vertexCenters.count(); for(int c=0; c<m_nodeAtt.count(); c++) { if (vat[c].count() < nv) vat[c] << 0.0; } } for(int e=0; e<m_nodeAtt.count(); e++) { if (m_nodeAtt[e].contains("diameter", Qt::CaseInsensitive)) { for(int vi=0; vi<vat[e].count(); vi++) vat[e][vi] /= 2; } } for(int vi=0; vi<m_nodeAtt.count(); vi++) m_vertexAttribute << qMakePair(m_nodeAttName[vi], vat[vi]); if (m_vertexRadiusAttribute == -1) { m_vertexRadiusAttribute = m_nodeAtt.count(); QVector<float> rad; rad.resize(m_vertexCenters.count()); rad.fill(2); m_nodeAtt << "vertex_radius"; m_vertexAttribute << qMakePair(QString("vertex_radius"), rad); } for(int i=0; i<nvat; i++) vat[i].clear(); delete [] vat; } void NetworkObject::loadEdgeInfo(QDomNodeList nnodes) { m_edgeAttribute.clear(); m_edgeNeighbours.clear(); QVector<float> *vat; // not expecting more than 20 attributes int nvat = m_edgeAtt.count(); vat = new QVector<float> [nvat]; int nn = nnodes.count(); for(int n=0; n<nn; n++) { QDomElement ele = nnodes.item(n).toElement(); QString id = ele.attributeNode("id").value(); QString src = ele.attributeNode("source").value(); QString tar = ele.attributeNode("target").value(); int a,b; a = m_nodeId.indexOf(src); b = m_nodeId.indexOf(tar); if (a >= 0 && b >= 0) m_edgeNeighbours << qMakePair(a,b); QDomNodeList nlist = nnodes.item(n).childNodes(); int nc = nlist.count(); for(int c=0; c<nc; c++) { QDomNode node = nlist.item(c); QDomElement ele = node.toElement(); QString et = ele.text(); QDomNamedNodeMap attr = ele.attributes(); QString name = attr.item(0).nodeName(); QString val = attr.item(0).nodeValue(); int vi = m_edgeAtt.indexOf(val); if (vi >= 0) vat[vi] << et.toFloat(); } int nv = m_edgeNeighbours.count(); for(int c=0; c<m_edgeAtt.count(); c++) { if (vat[c].count() < nv) vat[c] << 0.0; } } for(int e=0; e<m_edgeAtt.count(); e++) { if (m_edgeAtt[e].contains("diameter", Qt::CaseInsensitive)) { for(int vi=0; vi<vat[e].count(); vi++) vat[e][vi] /= 2; } } for(int vi=0; vi<m_edgeAtt.count(); vi++) m_edgeAttribute << qMakePair(m_edgeAttName[vi], vat[vi]); if (m_edgeRadiusAttribute == -1) { m_edgeRadiusAttribute = m_edgeAtt.count(); QVector<float> rad; rad.resize(m_edgeNeighbours.count()); rad.fill(2); m_edgeAtt << "edge_radius"; m_edgeAttribute << qMakePair(QString("edge_radius"), rad); } for(int i=0; i<nvat; i++) vat[i].clear(); delete [] vat; } bool NetworkObject::loadGraphML(QString flnm) { m_fileName = flnm; QDomDocument doc; QFile f(flnm.toLatin1().data()); if (f.open(QIODevice::ReadOnly)) { doc.setContent(&f); f.close(); } QDomElement main = doc.documentElement(); getKey(main); // m_log->insertPlainText("Node Attributes \n"); // for(int i=0; i<m_nodeAtt.count(); i++) // m_log->insertPlainText(" "+m_nodeAtt[i]+"\n"); // m_log->insertPlainText("\n"); // m_log->insertPlainText("Edge Attributes \n"); // for(int i=0; i<m_edgeAtt.count(); i++) // m_log->insertPlainText(" "+m_edgeAtt[i]+"\n"); // m_log->insertPlainText("\n"); QDomNodeList dlist = main.childNodes(); for(int i=0; i<dlist.count(); i++) { if (dlist.at(i).isElement()) { QDomElement ele = dlist.at(i).toElement(); QString str = ele.nodeName(); if (str == "graph") { QDomNodeList nnodes = ele.elementsByTagName("node"); loadNodeInfo(nnodes); QDomNodeList nedges = ele.elementsByTagName("edge"); loadEdgeInfo(nedges); } } } //--------------------- Vec bmin = m_vertexCenters[0]; Vec bmax = m_vertexCenters[0]; for(int i=0; i<m_vertexCenters.count(); i++) { bmin = StaticFunctions::minVec(bmin, m_vertexCenters[i]); bmax = StaticFunctions::maxVec(bmax, m_vertexCenters[i]); } m_centroid = (bmin + bmax)/2; m_enclosingBox[0] = Vec(bmin.x, bmin.y, bmin.z); m_enclosingBox[1] = Vec(bmax.x, bmin.y, bmin.z); m_enclosingBox[2] = Vec(bmax.x, bmax.y, bmin.z); m_enclosingBox[3] = Vec(bmin.x, bmax.y, bmin.z); m_enclosingBox[4] = Vec(bmin.x, bmin.y, bmax.z); m_enclosingBox[5] = Vec(bmax.x, bmin.y, bmax.z); m_enclosingBox[6] = Vec(bmax.x, bmax.y, bmax.z); m_enclosingBox[7] = Vec(bmin.x, bmax.y, bmax.z); // m_nX = (bmax.x - bmin.x) + 1; // m_nY = (bmax.y - bmin.y) + 1; // m_nZ = (bmax.z - bmin.z) + 1; m_nX = bmax.x; m_nY = bmax.y; m_nZ = bmax.z; if (!Global::batchMode()) { QString str; str = QString("Grid Size : %1 %2 %3\n").arg(m_nX).arg(m_nY).arg(m_nZ); str += QString("Vertices : %1\n").arg(m_vertexCenters.count()); str += QString("Edges : %1\n").arg(m_edgeNeighbours.count()); str += QString("\n"); str += QString("Vertex Attributes : %1\n").arg(m_vertexAttribute.count()); for(int i=0; i<m_vertexAttribute.count(); i++) str += QString(" %1\n").arg(m_vertexAttribute[i].first); str += QString("\n"); str += QString("Edge Attributes : %1\n").arg(m_edgeAttribute.count()); for(int i=0; i<m_edgeAttribute.count(); i++) str += QString(" %1\n").arg(m_edgeAttribute[i].first); QMessageBox::information(0, "Network loaded", str); } m_Vatt = 0; m_Eatt = 0; m_Vminmax.clear(); m_Eminmax.clear(); m_userVminmax.clear(); m_userEminmax.clear(); for(int i=0; i<m_vertexAttribute.count(); i++) { float vmin = m_vertexAttribute[i].second[0]; float vmax = m_vertexAttribute[i].second[0]; for(int j=1; j<m_vertexAttribute[i].second.count(); j++) { vmin = qMin((float)m_vertexAttribute[i].second[j], vmin); vmax = qMax((float)m_vertexAttribute[i].second[j], vmax); } m_Vminmax.append(qMakePair(vmin, vmax)); m_userVminmax.append(qMakePair((vmin+vmax)/2, vmax)); } for(int i=0; i<m_edgeAttribute.count(); i++) { float emin = m_edgeAttribute[i].second[0]; float emax = m_edgeAttribute[i].second[0]; for(int j=1; j<m_edgeAttribute[i].second.count(); j++) { emin = qMin((float)m_edgeAttribute[i].second[j], emin); emax = qMax((float)m_edgeAttribute[i].second[j], emax); } m_Eminmax.append(qMakePair(emin, emax)); m_userEminmax.append(qMakePair((emin+emax)/2, emax)); } // QString str; // str += "Vertex\n"; // for(int i=0; i<m_vertexAttribute.count(); i++) // { // str += m_vertexAttribute[i].first + QString(" %1 %2\n").\ // arg(m_Vminmax[i].first). // arg(m_Vminmax[i].second); // } // str += "\n\nEdges\n"; // for(int i=0; i<m_edgeAttribute.count(); i++) // { // str += m_edgeAttribute[i].first + QString(" %1 %2\n").\ // arg(m_Eminmax[i].first). // arg(m_Eminmax[i].second); // } // QMessageBox::information(0, "", str); return true; }
24.295233
80
0.593397
stranddw
cc23a8ba22778c5cf90dd9e8b25bcd5e96664c77
1,295
cpp
C++
cutrod.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
cutrod.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
cutrod.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
1
2019-01-19T01:05:07.000Z
2019-01-19T01:05:07.000Z
#include <iostream> #include <cstdlib> #include <cmath> #include <algorithm> #include <string> #include <cstring> #include <iomanip> using std::cerr; using std::cin; using std::cout; using std::endl; using std::string; int n, k; int ropes[10010] = {0}; bool check(int len) { int tot = 0; for (int i = 1; i <= n; i++) { tot += (ropes[i] / len); } return (tot >= k); } int find(int l, int r, int n) { //nothing to do } int main() { cin >> n >> k; for (int i = 1; i <= n; i++) { double tmp; cin >> tmp; //cout << tmp; ropes[i] = (tmp * 100); } // for (int i = 0; i < n; i++) // { // cout << ropes[i + 1]; // } int l = 0; int r = 1e8 + 10; int res = 0; while (l <= r) { int mid = (l + r) >> 1; if (mid == 0) break; //Very Important!!!!!!!!!!! // if (check(mid)) // r = mid - 1; // else // { // l = mid + 1; // res = mid; // } if (!check(mid)) r = mid - 1; else { l = mid + 1; res = mid; } } double ans = (res * 1.0) / 100.0; cout << std::fixed << std::setprecision(2) << ans << endl; return 0; }
17.986111
62
0.403861
W-YXN
cc280a5d7476322d006fa06d8955609bb5b6a495
3,794
hpp
C++
hpx/plugins/parcel/message_buffer.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/plugins/parcel/message_buffer.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/plugins/parcel/message_buffer.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2013 Hartmut Kaiser // // 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) #if !defined(HPX_RUNTIME_PARCELSET_POLICIES_COALESCING_MESSAGE_BUFFER_MAR_07_2013_1250PM) #define HPX_RUNTIME_PARCELSET_POLICIES_COALESCING_MESSAGE_BUFFER_MAR_07_2013_1250PM #include <hpx/hpx_fwd.hpp> #include <hpx/runtime/parcelset/parcelport.hpp> #include <hpx/util/move.hpp> #include <vector> #include <boost/noncopyable.hpp> namespace hpx { namespace plugins { namespace parcel { namespace detail { class message_buffer { BOOST_COPYABLE_AND_MOVABLE(message_buffer); public: enum message_buffer_append_state { normal = 0, first_message = 1, buffer_now_full = 2, singleton_buffer = 3 }; message_buffer() : max_messages_(0) {} message_buffer(std::size_t max_messages) : max_messages_(max_messages) {} message_buffer(message_buffer const& rhs) : messages_(rhs.messages_), handlers_(rhs.handlers_), max_messages_(rhs.max_messages_) {} message_buffer(BOOST_RV_REF(message_buffer) rhs) : messages_(boost::move(rhs.messages_)), handlers_(boost::move(rhs.handlers_)), max_messages_(rhs.max_messages_) {} message_buffer& operator=(BOOST_COPY_ASSIGN_REF(message_buffer) rhs) { if (&rhs != this) { max_messages_ = rhs.max_messages_; messages_ = rhs.messages_; handlers_ = rhs.handlers_; } return *this; } message_buffer& operator=(BOOST_RV_REF(message_buffer) rhs) { if (&rhs != this) { max_messages_ = rhs.max_messages_; messages_ = boost::move(rhs.messages_); handlers_ = boost::move(rhs.handlers_); } return *this; } void operator()(parcelset::parcelport* set) { if (!messages_.empty()) set->put_parcels(messages_, handlers_); } message_buffer_append_state append(parcelset::parcel& p, parcelset::parcelport::write_handler_type const& f) { BOOST_ASSERT(messages_.size() == handlers_.size()); int result = normal; if (messages_.empty()) result = first_message; messages_.push_back(p); handlers_.push_back(f); if (messages_.size() >= max_messages_) result = buffer_now_full; return message_buffer_append_state(result); } bool empty() const { BOOST_ASSERT(messages_.size() == handlers_.size()); return messages_.empty(); } void clear() { messages_.clear(); handlers_.clear(); } std::size_t size() const { BOOST_ASSERT(messages_.size() == handlers_.size()); return messages_.size(); } double fill_ratio() const { return double(messages_.size()) / double(max_messages_); } void swap(message_buffer& o) { std::swap(max_messages_, o.max_messages_); std::swap(messages_, o.messages_); std::swap(handlers_, o.handlers_); } std::size_t capacity() const { return max_messages_; } private: std::vector<parcelset::parcel> messages_; std::vector<parcelset::parcelport::write_handler_type> handlers_; std::size_t max_messages_; }; }}}} #endif
27.897059
89
0.576173
andreasbuhr
cc33a61e7eb6b7d24d5b18d88053f1ecc17ee91d
7,772
cpp
C++
Tree/binaryTree.cpp
harshallgarg/Diversified-Programming
7e6fb135c4639dbaa0651b85f98397f994a5b11d
[ "MIT" ]
2
2020-08-09T02:09:50.000Z
2020-08-09T07:07:47.000Z
Tree/binaryTree.cpp
harshallgarg/Diversified-Programming
7e6fb135c4639dbaa0651b85f98397f994a5b11d
[ "MIT" ]
null
null
null
Tree/binaryTree.cpp
harshallgarg/Diversified-Programming
7e6fb135c4639dbaa0651b85f98397f994a5b11d
[ "MIT" ]
5
2020-09-21T12:49:07.000Z
2020-09-29T16:13:09.000Z
// // binaryTree.cpp // AnishC++ // // Created by Anish Mookherjee on 01/11/19. // Copyright © 2019 Anish Mookherjee. All rights reserved. // #include <iostream> using namespace std; struct node { int data; struct node *left; struct node *right; }*tree; void createTree(struct node* tree) { tree=NULL; } struct node* searchElement(struct node *tree,int val) { if(tree->data==val||tree==NULL) return tree; else if(val<tree->data) return searchElement(tree->left, val); else return searchElement(tree->right, val); } struct node *insertElement(struct node *tree, int val) { struct node *ptr, *nodeptr, *parentptr; ptr=(struct node*)malloc(sizeof(struct node)); ptr->data = val; ptr->left = NULL; ptr->right = NULL; if(tree==NULL) { tree=ptr; tree->left=NULL; tree->right=NULL; } else { parentptr=NULL; nodeptr=tree; while(nodeptr!=NULL) { parentptr=nodeptr; if(val<nodeptr->data) nodeptr=nodeptr->left; else nodeptr = nodeptr->right; } if(val<parentptr->data) parentptr->left = ptr; else parentptr->right = ptr; } return tree; } void preorder(struct node* tree) { if(tree!=NULL) { cout<<tree->data<<" "; preorder(tree->left); preorder(tree->right); } } void inorder(struct node* tree) { if(tree!=NULL) { inorder(tree->left); cout<<tree->data<<" "; inorder(tree->right); } } void postorder(struct node* tree) { if(tree!=NULL) { postorder(tree->left); postorder(tree->right); cout<<tree->data<<" "; } } struct node* largest(struct node* tree) { if(tree==NULL||tree->right==NULL) return tree; else return largest(tree->right); } struct node* smallest(struct node* tree) { if(tree==NULL||tree->left==NULL) return tree; else return smallest(tree->left); } struct node *deleteElement(struct node *tree, int val) { struct node *cur, *parent, *suc, *psuc, *ptr; if(tree->left==NULL) { printf("\nThe tree is empty "); return(tree); } parent = tree; cur = tree->left; while(cur!=NULL && val!= cur->data) { parent = cur; cur = (val<cur->data)? cur->left:cur->right; } if(cur == NULL) { printf("\nThe value to be deleted is not present in the tree"); return(tree); } if(cur->left == NULL) ptr = cur->right; else if(cur->right == NULL) ptr = cur->left; else { // Find the in–order successor and its parent psuc = cur; cur = cur->left; while(suc->left!=NULL) { psuc = suc; suc = suc->left; } if(cur==psuc) { // Situation 1 suc->left = cur->right; } else { // Situation 2 suc->left = cur->left; psuc->left = suc->right; suc->right = cur->right; } ptr = suc; } // Attach ptr to the parent node if(parent->left == cur) parent->left=ptr; else parent->right=ptr; free(cur); return tree; } int height(struct node* tree) { int lh,rh; if(tree==NULL) { return 0; } else { lh=height(tree->left); rh=height(tree->right); if(lh>rh) return lh+1; else return rh+1; } } int totalNodes(struct node* tree) { if(tree==NULL) return 0; else return totalNodes(tree->left)+totalNodes(tree->right)+1; } int internalNodes(struct node* tree) { if(tree==NULL) return 0; else if(tree->left==NULL&&tree->right==NULL) return 0; else return internalNodes(tree->left)+internalNodes(tree->right)+1; } int externalNodes(struct node* tree) { if(tree==NULL) return 0; else if(tree->left==NULL&&tree->right==NULL) return 1; else return externalNodes(tree->left)+externalNodes(tree->right); } void deleteTree(struct node* tree) { if(tree!=NULL) { deleteTree(tree->left); deleteTree(tree->right); free(tree); } } int main() { int option,val; struct node* ptr; ptr=(struct node*)malloc(sizeof(struct node)); createTree(tree); do { cout<<"1.INSERT ELEMENT"<<endl; cout<<"2.SEARCH ELEMENT"<<endl; cout<<"3.SMALLEST ELEMENT"<<endl; cout<<"4.LARGEST ELEMENT"<<endl; cout<<"5.DELETE ELEMENT"<<endl; cout<<"6.HEIGHT"<<endl; cout<<"7.TOTAL NODES"<<endl; cout<<"8.TOTAL INTERNAL NODES"<<endl; cout<<"9.TOTAL EXTERNAL NODES"<<endl; cout<<"10.DELETE TREE"<<endl; cout<<"11.PRE-ORDER TRAVERSAL"<<endl; cout<<"12.IN-ORDER TRAVERSAL"<<endl; cout<<"13.POST-ORDER TRAVERSAL"<<endl; cout<<"14.EXIT"<<endl; cin>>option; switch(option) { case 1: cout<<"Insert the element you want to enter:"<<endl; cin>>val; tree=insertElement(tree, val); break; case 2: cout<<"Enter element you want to search:"<<endl; cin>>val; if(searchElement(tree, val)==NULL) cout<<"Element not found"<<endl; else cout<<"Element found"<<endl; break; case 3: ptr=smallest(tree); cout<<"The smallest element is: "<<ptr->data<<endl; break; case 4: ptr=largest(tree); cout<<"The largest element is: "<<ptr->data<<endl; break; case 5: cout<<"Enter the element to be deleted"<<endl; cin>>val; tree=deleteElement(tree, val); if(tree==NULL) cout<<"Element not found"<<endl; else cout<<"Element deleted"<<endl; break; case 6: cout<<"Height of the tree is: "<<height(tree)<<endl; break; case 7: cout<<"Total no. of nodes present are: "<<totalNodes(tree)<<endl; break; case 8: cout<<"Total no. of internal nodes are: "<<internalNodes(tree)<<endl; break; case 9: cout<<"Total no. of external nodes are: "<<externalNodes(tree)<<endl; break; case 10: cout<<"Deleting the entire tree."<<endl; deleteTree(tree); break; case 11: cout<<"Pre-order traversal:"<<endl; preorder(tree); cout<<endl; break; case 12: cout<<"In-order traversal:"<<endl; inorder(tree); cout<<endl; break; case 13: cout<<"Post-order traversal:"<<endl; postorder(tree); cout<<endl; break; case 14: cout<<"EXIT"<<endl; break; default: cout<<"Wrong choice, enter again."<<endl; } }while(option!=14); return 0; }
25.233766
85
0.476969
harshallgarg
cc34aa7ac8c65869c77ecb684d326d21e6cca705
4,204
cpp
C++
demos/glut/multibody/src/scenes/setup_domino_spiral.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
null
null
null
demos/glut/multibody/src/scenes/setup_domino_spiral.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
null
null
null
demos/glut/multibody/src/scenes/setup_domino_spiral.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
null
null
null
// // OpenTissue Template Library Demo // - A specific demonstration of the flexibility of OTTL. // Copyright (C) 2008 Department of Computer Science, University of Copenhagen. // // OTTL and OTTL Demos are licensed under zlib. // #include "setup_domino_spiral.h" #include <OpenTissue/core/geometry/geometry_compute_box_mass_properties.h> #include <OpenTissue/core/geometry/geometry_compute_sphere_mass_properties.h> #include <OpenTissue/core/math/math_random.h> void setup_domino_spiral(Data & data) { real_type const friction = .25; real_type const restitution = .4; real_type density = 10,mass; vector3_type r,diag_inertia; matrix3x3_type R,I; R = OpenTissue::math::diag(value_traits::one()); quaternion_type Q; data.m_configuration.clear(); data.m_library.clear(); data.m_simulator.clear(); data.m_bodies.resize(502); data.m_box.set(vector3_type(value_traits::zero(),value_traits::zero(),value_traits::zero()),R,vector3_type(700,700,.5)); data.m_bodies[0].set_fixed(true); data.m_bodies[0].set_geometry(&data.m_box); data.m_configuration.add(&data.m_bodies[0]); int i = 1; real_type W = .8; real_type H = .2; real_type D = value_traits::two(); real_type W2 = .4; real_type H2 = .1; real_type D2 = value_traits::one(); size_type N = 500; real_type radius = 3*W; assert(radius>=W); real_type theta = 0; data.m_sphere[0].radius(.25); OpenTissue::geometry::compute_sphere_mass_properties(data.m_sphere[0].radius(),density,mass,diag_inertia); I= OpenTissue::math::diag(diag_inertia(0),diag_inertia(1),diag_inertia(2)); real_type x = radius*cos(theta-0.05); real_type y = radius*sin(theta-0.05); real_type z = 3.0*D; Q.Rz(theta); data.m_bodies[i].set_position(vector3_type(x,y,z)); data.m_bodies[i].set_orientation(Q); data.m_bodies[i].attach(&data.m_gravity); data.m_bodies[i].set_geometry(&data.m_sphere[0]); data.m_bodies[i].set_mass(mass); data.m_bodies[i].set_inertia_bf(I); data.m_configuration.add(&data.m_bodies[i]); ++i; data.m_small_box.set(vector3_type(value_traits::zero(),value_traits::zero(),value_traits::zero()),R,vector3_type(W2,H2,D2)); OpenTissue::geometry::compute_box_mass_properties(data.m_small_box.ext(),density,mass,diag_inertia); I= OpenTissue::math::diag(diag_inertia(0),diag_inertia(1),diag_inertia(2)); for(size_type n=0;n<N;++n) { x = radius*cos(theta); y = radius*sin(theta); z = D2 + .5; Q.Rz(theta); data.m_bodies[i].set_position(vector3_type(x,y,z)); data.m_bodies[i].set_orientation(Q); data.m_bodies[i].attach(&data.m_gravity); data.m_bodies[i].set_geometry(&data.m_small_box); data.m_bodies[i].set_mass(mass); data.m_bodies[i].set_inertia_bf(I); data.m_configuration.add(&data.m_bodies[i]); real_type delta_theta = 0; real_type D4 = D*.25; if ((D4 +H)<=(value_traits::two()*radius)) delta_theta = value_traits::two()* asin((D4+H)/(value_traits::two()*radius)); else delta_theta = value_traits::two()*asin(H/radius); theta += delta_theta; radius = theta + 3*W; ++i; } //data.m_sphere[1].radius(.75); //compute_sphere_mass_properties(data.m_sphere[1].radius(),density,mass,diag_inertia); //I= OpenTissue::math::diag(diag_inertia(0),diag_inertia(1),diag_inertia(2)); //x = 600; //y = 0; //z = data.m_sphere[1].radius() + .5; //Q.identity(); //data.m_bodies[i].set_position(vector3_type(x,y,z)); //data.m_bodies[i].set_velocity(vector3_type(-20,0,0)); //data.m_bodies[i].set_orientation(Q); //data.m_bodies[i].attach(&data.m_gravity); //data.m_bodies[i].set_geometry(&data.m_sphere[1]); //data.m_bodies[i].set_mass(mass); //data.m_bodies[i].set_inertia_bf(I); //data.m_configuration.add(&data.m_bodies[i]); //++i; data.m_gravity.set_acceleration(vector3_type(0,0,-9.81)); data.m_simulator.init(data.m_configuration); material_type * default_material = data.m_library.default_material(); default_material->set_friction_coefficient(friction); default_material->normal_restitution() = (restitution); data.m_configuration.set_material_library(data.m_library); data.m_simulator.get_stepper()->get_solver()->set_max_iterations(10); }
33.903226
126
0.709087
ricortiz
cc3615ff211ed0a434cab0856157758739c55d1d
19,385
cpp
C++
src/Mobs.cpp
Cavantar/RoqueLike
c2466c5950730f51a9d582d3757548299b226327
[ "WTFPL" ]
null
null
null
src/Mobs.cpp
Cavantar/RoqueLike
c2466c5950730f51a9d582d3757548299b226327
[ "WTFPL" ]
null
null
null
src/Mobs.cpp
Cavantar/RoqueLike
c2466c5950730f51a9d582d3757548299b226327
[ "WTFPL" ]
null
null
null
#include "Mobs.h" #include <sstream> #include <iomanip> #include <iostream> Mob::Mob(const EntityPosition& position, int mobLevel, int health) : mobLevel(mobLevel), health(health) { this->position = position; renderData.type = ER_MOB; } void Mob::addHealth(float amount) { if(amount < 0) { amount += getShieldValue(); if(amount > 0) amount = 0; } health += amount; if(health > maxHealth) health = maxHealth; else if(health < 0) die(); OverlayTextData overlayTextData = {"", 2.0f, Vec3f(), 1.1f}; std::stringstream tempText; tempText << std::fixed << std::setw(11) << std::setprecision(2); if(amount != 0) tempText << amount << " Health"; if(amount > 0) { overlayTextData.color = Vec3f(0, 200.0f, 0); } else if(amount < 0) { overlayTextData.color = Vec3f(200.0f, 0, 0); } else { tempText << "Blocked"; overlayTextData.color = Vec3f(0, 0, 250); } overlayTextData.text = tempText.str(); Entity* overlayText = new OverlayText(position, overlayTextData); level->addOverlayEntity(EntityPtr(overlayText)); } void Mob::spawnXp(int xpToSpawn) const { assert(!(xpToSpawn%10)); //xpToSpawn *= 20; while(xpToSpawn) { float value = -1; // Getting Randomly valued experience orb (in range) // I assume that the xp is divisible by 10 value = (((rand() % (xpToSpawn/10)) + 1) * 10) % (xpToSpawn + 10); if(value > 50) value = 50; Entity* entity = new XpOrb(getCollisionCenter(), Vec2f::directionVector() * (1.0f + 0.25f * ((rand()%12) + 1)), value); level->addEntity(EntityPtr(entity)); //std::cout << "Spawning: " << value << " xp \n"; xpToSpawn -= value; } } void Mob::performDeathAction() { int xpToSpawn = mobLevel * 20; spawnXp(xpToSpawn); } const EntityRenderData* Mob::getRenderData() { renderData.life = health / maxHealth; return &renderData; } MobSpawner::MobSpawner(const EntityPosition& position, int level, MOB_TYPE mobType) : Mob(position, level), mobType(mobType) { dimensions = Vec2f(1.0f, 1.0f); renderData.spriteName = "cannonBase"; std::stringstream caption; caption << "MobSpawner"; switch(mobType) { case MT_RAT: caption << "(Rat)"; break; case MT_SNAKE: caption << "(Snake)"; break; case MT_FOLLOWER: caption << "(Follower)"; break; case MT_VARIOUS: caption << "(Various)"; break; } caption << " lvl: " << level; renderData.caption = caption.str(); maxHealth = 20 + (level - 1) * 10; health = maxHealth; damageValue = (level + 1.0f) / 5.0f; localTime = (rand()%100000) / 100.0f; renderData.spriteColor = Vec3f(138, 7, 7); } void MobSpawner::update(const float lastDelta) { float spawnPeriod = 10.0f - (mobLevel * 0.5f); renderData.spriteColorAlpha = 0.2f + (localTime / spawnPeriod) * 0.8f; Player* player = level->getPlayer(); if(localTime < 0) localTime = 0; if(player) { EntityPosition playerPosition = player->getCollisionCenter(); Vec2f distanceVec = EntityPosition::calculateDistanceInTiles(position, playerPosition, level->getTileMap()->getTileChunkSize()); // If There's Player in Radius of given length if(distanceVec.getLength() < 15.0f) { localTime += lastDelta; if(localTime >= spawnPeriod) { localTime = fmodf(localTime, spawnPeriod); distanceVec.normalize(); Entity* entity; do { Vec2f directionVec = Vec2f::directionVector(); switch(mobType) { case MT_RAT: entity = new Rat(position + directionVec * 2.0f, mobLevel); break; case MT_SNAKE: entity = new Snake(position + directionVec * 2.0f, mobLevel); break; case MT_FOLLOWER: entity = new Follower(position + directionVec * 2.0f, mobLevel); break; case MT_VARIOUS: if(rand()%3 == 0) entity = new Rat(position + directionVec * 2.0f, mobLevel); else if(rand()%3 == 1) entity = new Snake(position + directionVec * 2.0f, mobLevel); else entity = new Follower(position + directionVec * 2.0f, mobLevel); break; } } while(!level->addEntity(EntityPtr(entity))); } } else localTime -= lastDelta; } else localTime -= lastDelta; } void MobSpawner::performDeathAction() { int xpToSpawn = mobLevel * 50; spawnXp(xpToSpawn); } Cannon::Cannon(const EntityPosition& position, int level) : Mob(position, level) { dimensions = Vec2f(1.0f, 1.0f); renderData.spriteName = "cannonBase"; std::stringstream caption; caption << "Cannon lvl: " << level; renderData.caption = caption.str(); maxHealth = 10 + (level - 1) * 5; health = maxHealth; damageValue = (level + 1.0f) / 5.0f; } void Cannon::update(const float lastDelta) { float shootPeriod = 5.0f / mobLevel; localTime += lastDelta; if(localTime >= shootPeriod) { localTime = fmodf(localTime, shootPeriod); Player* player = level->getPlayer(); if(player && level->canSeeEachOther(this, player, 15.0f)) { EntityPosition playerPosition = player->getCollisionCenter(); Vec2f distanceVec = EntityPosition::calculateDistanceInTiles(position, playerPosition, level->getTileMap()->getTileChunkSize()); // If There's Player in Radius of given length if(distanceVec.getLength() < 15.0f) { distanceVec.normalize(); Vec2f directionVec = distanceVec; float bulletRadius = 0.7f + mobLevel / 10; float bulletSpeedModifier = (mobLevel / 10.0f) + 1.0f; Entity* bullet; bullet = new Bullet(position + directionVec * 2.0f, directionVec * 10.0f * bulletSpeedModifier, Vec2f(bulletRadius, bulletRadius), damageValue); level->addEntity(EntityPtr(bullet)); } } } } Follower::Follower(const EntityPosition& position, int level) : Mob(position, level) { dimensions = Vec2f(1.0f, 2.0f); renderData.spriteName = "followerBase"; std::stringstream caption; caption << "Follower lvl: " << level; renderData.caption = caption.str(); maxHealth = 5 + (level - 1) * 5; health = maxHealth; damageValue = (level + 1.0f) / 5.0f; } void Follower::update(const float lastDelta) { Player* player = level->getPlayer(); if(player && level->canSeeEachOther(this, player, 15.0f)) { EntityPosition playerPosition = player->getCollisionCenter(); EntityPosition followerPosition = getCollisionCenter(); Vec2f distanceVec = EntityPosition::calculateDistanceInTiles(followerPosition, playerPosition, level->getTileMap()->getTileChunkSize()); // If There's Player in Radius of given length if(distanceVec.getLength() < 15.0f) { distanceVec.normalize(); Vec2f directionVec = distanceVec; acceleration = directionVec; } } EntityPosition collisionCenter = getCollisionCenter(); float friction = level->getFrictionValueAtPosition(collisionCenter); float accelerationModifier = level->getAccelerationModifierAtPosition(collisionCenter); Vec2f positionDeltaVec = getPositionDeltaVec(lastDelta, friction, accelerationModifier); EntityCollisionResult collisionResult = level->checkCollisions(this, positionDeltaVec); handleCollisionResult(collisionResult, positionDeltaVec); } FloatRect Follower::getCollisionRect() const { const float width = 0.6f; const float height = 0.3f; return FloatRect(0.5f - (width / 2.0f), 2.0f - height, width, height); } void Follower::onWorldCollision(COLLISION_PLANE collisionPlane) { velocity = getReflectedVelocity(collisionPlane, 0.5f); } void Follower::onEntityCollision(COLLISION_PLANE collisionPlane, Entity* entity) { if(entity->isPlayer()) { entity->addHealth(-damageValue); entity->addVelocity(velocity * 2.5f); } else entity->addVelocity(velocity * 0.5f); velocity = getReflectedVelocity(collisionPlane, 0.5f); } Snake::Snake(const EntityPosition& position, int level) : Mob(position, level) { dimensions = Vec2f(1.0f, 1.0f); renderData.spriteName = "snakeBase"; std::stringstream caption; caption << "Snake lvl: " << level; renderData.caption = caption.str(); maxHealth = 5 + (level - 1) * 5; health = maxHealth; damageValue = (level + 1.0f) / 5.0f; currentDirection = Vec2f::cardinalDirection((CARDINAL_DIRECTION)(rand()%4)); metersPerSecondSquared = idleSpeedValue; localAttackingTime = 0; } void Snake::update(const float lastDelta) { Player* player = level->getPlayer(); if(player && metersPerSecondSquared != attackSpeedValue) { Vec2f checkResult = level->canSeeEachOtherCardinal(this, player, 15.0f); if(checkResult != Vec2f()) { velocity = 0; currentDirection = checkResult; metersPerSecondSquared = attackSpeedValue; } } if(metersPerSecondSquared == attackSpeedValue) { localAttackingTime += lastDelta; } static const float maxAttackingTime = 2.0f; if(localAttackingTime > maxAttackingTime) { localAttackingTime = 0; metersPerSecondSquared = idleSpeedValue; } acceleration = currentDirection; EntityPosition collisionCenter = getCollisionCenter(); float friction = level->getFrictionValueAtPosition(collisionCenter); float accelerationModifier = level->getAccelerationModifierAtPosition(collisionCenter); Vec2f positionDeltaVec = getPositionDeltaVec(lastDelta, friction, accelerationModifier); EntityCollisionResult collisionResult = level->checkCollisions(this, positionDeltaVec); handleCollisionResult(collisionResult, positionDeltaVec); } FloatRect Snake::getCollisionRect() const { const float width = 0.8f; const float height = 0.3f; return FloatRect(0.5f - (width / 2.0f), 1.0f - height, width, height); } void Snake::onWorldCollision(COLLISION_PLANE collisionPlane) { velocity = 0; if(currentDirection.x != 0) currentDirection = Vec2f::cardinalDirection(rand()%2 ? CD_UP : CD_DOWN); else currentDirection = Vec2f::cardinalDirection(rand()%2 ? CD_LEFT : CD_RIGHT); metersPerSecondSquared = idleSpeedValue; } void Snake::onEntityCollision(COLLISION_PLANE collisionPlane, Entity* entity) { if(entity->isPlayer()) entity->addHealth(-damageValue); entity->addVelocity(velocity * 2.5f); //velocity = getReflectedVelocity(collisionPlane, 0.5f); velocity = 0; if(currentDirection.x != 0) currentDirection = Vec2f::cardinalDirection(rand()%2 ? CD_UP : CD_DOWN); else currentDirection = Vec2f::cardinalDirection(rand()%2 ? CD_LEFT : CD_RIGHT); metersPerSecondSquared = idleSpeedValue; } Rat::Rat(const EntityPosition& position, int level) : Mob(position, level) { dimensions = Vec2f(1.0f, 1.0f); renderData.spriteName = "ratBase"; std::stringstream caption; caption << "Rat lvl: " << level; renderData.caption = caption.str(); maxHealth = 5 + (mobLevel - 1) * 5; health = maxHealth; damageValue = 1.0f + ((mobLevel - 1.0f) * 2.0f); currentDirection = Vec2f::directionVector(); metersPerSecondSquared = 10.0f; ratState = RS_SNIFFING; localStateTime = 2.0f + (rand()%5) * 0.5f; } void Rat::update(const float lastDelta) { bool dying = (health / maxHealth) < 0.2f; bool shouldUpdateState = true; Player* player = level->getPlayer(); // If There's player in close Proximity if(player && level->canSeeEachOther(this, player, 15.0f)) { EntityPosition playerPosition = player->getCollisionCenter(); EntityPosition followerPosition = getCollisionCenter(); Vec2f distanceVec = EntityPosition::calculateDistanceInTiles(followerPosition, playerPosition, level->getTileMap()->getTileChunkSize()); // I either move towards him if(distanceVec.getLength() < 4.0f + (mobLevel * 0.5f) && !dying) { distanceVec.normalize(); currentDirection = distanceVec; shouldUpdateState = false; } // Or go Away from him if I'm dying else if(dying) { distanceVec.normalize(); currentDirection = distanceVec * -1.0f; shouldUpdateState = false; } } if(shouldUpdateState) { localStateTime -= lastDelta; if(localStateTime < 0) { switch(ratState) { case RS_SNIFFING: { // Going into thinking state if(rand()%3 == 0) { localStateTime = 0.5f + (rand()%5) * 0.2f; ratState = RS_THINKING; currentDirection = Vec2f(); } // Still Sniffing else { localStateTime = 2.0f + (rand()%5) * 0.5f; currentDirection = Vec2f::directionVector(); } } break; case RS_THINKING: { localStateTime = 2.0f + (rand()%5) * 0.5f; ratState = RS_SNIFFING; } break; } } } acceleration = currentDirection; EntityPosition collisionCenter = getCollisionCenter(); float friction = level->getFrictionValueAtPosition(collisionCenter); float accelerationModifier = level->getAccelerationModifierAtPosition(collisionCenter); Vec2f positionDeltaVec = getPositionDeltaVec(lastDelta, friction, accelerationModifier); EntityCollisionResult collisionResult = level->checkCollisions(this, positionDeltaVec); handleCollisionResult(collisionResult, positionDeltaVec); } FloatRect Rat::getCollisionRect() const { const float width = 0.8f; const float height = 0.3f; return FloatRect(0.5f - (width / 2.0f), 1.0f - height, width, height); } void Rat::onWorldCollision(COLLISION_PLANE collisionPlane) { velocity = getReflectedVelocity(collisionPlane, 1.0f); if(collisionPlane == COLLISION_PLANE_VERTICAL) { currentDirection.x *= -1.0f; } else currentDirection.y *= -1.0f; } void Rat::onEntityCollision(COLLISION_PLANE collisionPlane, Entity* entity) { if(entity->isPlayer()) { entity->addHealth(-damageValue); entity->addVelocity(velocity * 2.5f); } else { entity->addVelocity(velocity * 1.5f); } //velocity = getReflectedVelocity(collisionPlane, 0.5f); velocity = 0; } Player::Player(const EntityPosition& position) : Mob(position, 1, 1.0f) { dimensions = Vec2f(1.0f, 2.0f); renderData.spriteName = "playerBase"; renderData.caption = "Player"; damageValue = 1.0f; } void Player::update(const float lastDelta) { EntityPosition collisionCenter = getCollisionCenter(); float friction = level->getFrictionValueAtPosition(collisionCenter); float accelerationModifier = level->getAccelerationModifierAtPosition(collisionCenter); Vec2f positionDeltaVec = getPositionDeltaVec(lastDelta, friction, accelerationModifier); EntityCollisionResult collisionResult = level->checkCollisions(this, positionDeltaVec); handleCollisionResult(collisionResult, positionDeltaVec); if(xpAmount >= getNextLevelXp()) levelUp(); stamina += (lastDelta / 5.0f) * maxStamina; if(stamina >= maxStamina) stamina = maxStamina; } void Player::onWorldCollision(COLLISION_PLANE collisionPlane) { const float bounceFactor = 0.5f; velocity = getReflectedVelocity(collisionPlane, bounceFactor); spawnDustParticles(getCollisionCenter(), 10, 2); } void Player::onEntityCollision(COLLISION_PLANE collisionPlane, Entity* entity) { static const float speedIncrease = 1.05f; entity->addVelocity(velocity * 0.01f); velocity = getReflectedVelocity(collisionPlane, speedIncrease); } FloatRect Player::getCollisionRect() const { const float width = 0.5f; const float height = 0.3f; return FloatRect(width / 2.0f, 2.0f - height, width, height); } void Player::addXp(const float amount) { xpAmount += amount; OverlayTextData overlayTextData = {"", 2.0f, Vec3f(), 1.1f}; std::stringstream tempText; tempText << std::fixed << std::setw(11) << std::setprecision(2); tempText << amount << " Xp"; overlayTextData.color = Vec3f(0, 200.0f, 0); overlayTextData.text = tempText.str(); Entity* overlayText = new OverlayText(position, overlayTextData); level->addOverlayEntity(EntityPtr(overlayText)); } void Player::levelUp() { mobLevel++; skillPointCount++; maxHealth += 5.0f; health = maxHealth; maxStamina += 20.0f; OverlayTextData overlayTextData = {"", 4.0f, Vec3f(), 1.5f}; overlayTextData.color = Vec3f(0, 200.0f, 0); overlayTextData.text = "Leveled Up !"; Entity* overlayText = new OverlayText(position, overlayTextData); level->addOverlayEntity(EntityPtr(overlayText)); } EventNameList Player::getEntityEvents() { EventNameList eventNameList; eventNameList.push_back("HelloThere"); eventNameList.push_back("Player"); return eventNameList; } void Player::handlePlayerInput(const PlayerInput& playerInput) { if(playerInput.up) { direction = MOB_FACING_UP; acceleration += Vec2f(0, -1.0f); } if(playerInput.right) { direction = MOB_FACING_RIGHT; acceleration += Vec2f(1.0f, 0); } if(playerInput.down) { direction = MOB_FACING_DOWN; acceleration += Vec2f(0, 1.0f); } if(playerInput.left) { direction = MOB_FACING_LEFT; acceleration += Vec2f(-1.0f, 0); } if(playerInput.actionUp || playerInput.actionRight || playerInput.actionDown || playerInput.actionLeft) { float bulletRadius = 0.5f; static const float bulletDistance = 1.5f; Vec2f tempDirectionVec; if(playerInput.actionUp) tempDirectionVec = Vec2f(0, -1.0f); if(playerInput.actionRight) tempDirectionVec = Vec2f(1.0f, 0); if(playerInput.actionDown) tempDirectionVec = Vec2f(0, 1.0f); if(playerInput.actionLeft) tempDirectionVec = Vec2f(-1.0f, 0); EntityPosition bulletPosition = position + getLocalCollisionCenter() + tempDirectionVec * bulletDistance; bulletPosition -=Vec2f(0, bulletRadius); if(playerInput.actionRight || playerInput.actionLeft) bulletPosition -= Vec2f(0, 1.0f); Entity* bullet = new Bullet(bulletPosition, velocity + tempDirectionVec * bulletVelocity, Vec2f(bulletRadius, bulletRadius), damageValue); if(stamina > 20 && level->addEntity(EntityPtr(bullet))) stamina -= 20; //spawnDustParticles(getCollisionCenter(), 10, 10); } if(skillPointCount > 0) { if(playerInput.playerKey1) upgradeAbility(PU_SHIELD); if(playerInput.playerKey2) upgradeAbility(PU_DAMAGE); if(playerInput.playerKey3) upgradeAbility(PU_MOVESPEED); if(playerInput.playerKey4) upgradeAbility(PU_BULLETSPEED); if(playerInput.playerKey5) upgradeAbility(PU_HEALTH); if(playerInput.playerKey6) upgradeAbility(PU_STAMINA); } } void Player::onEvent(const std::string& eventName, EventArgumentDataMap eventDataMap) { if(eventName == "HelloThere") { std::cout << eventName << ": " << eventDataMap["text"].asString() << " "; std::cout << eventDataMap["number"].asFloat() << std::endl; WorldPosition worldPos = eventDataMap["position"].asWorldPosition(); std::cout << worldPos.tilePosition.x << std::endl; } } void Player::performDeathAction() { int xpToSpawn = mobLevel * 100 + xpAmount; spawnXp(xpToSpawn); } void Player::upgradeAbility(PLAYER_UPGRADE upgrade) { switch(upgrade) { case PU_SHIELD: shieldValue *= 1.5f; break; case PU_DAMAGE: damageValue *= 1.5f; break; case PU_MOVESPEED: metersPerSecondSquared += 5.0f; break; case PU_BULLETSPEED: bulletVelocity *= 1.2f; break; case PU_HEALTH: maxHealth *= 1.5f; break; case PU_STAMINA: maxStamina *= 1.5f; break; } --skillPointCount; }
25.373037
124
0.682177
Cavantar
cc365f8b2bffd09ab59c4e654f53bcb02cc8951b
442
cpp
C++
solved/0-b/ant-on-a-chessboard/uva/gen.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/0-b/ant-on-a-chessboard/uva/gen.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/0-b/ant-on-a-chessboard/uva/gen.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cstdio> #include <cstdlib> #include <ctime> #define MAXT 100 #define MAXN 2000000000 int T; void gen() { int n = rand() % MAXN + 1; int r = rand() % 10; if (n >= 100 && r < 1) n = rand() % 100 + 1; if (n >= 10000 && r < 3) n = rand() % 10000 + 1; if (n >= 1000000 && r < 5) n = rand() % 1000000 + 1; printf("%d\n", n); --T; } int main() { srand(time(NULL)); T = MAXT; while (T) gen(); puts("0"); return 0; }
11.945946
53
0.50905
abuasifkhan
cc38878a5553da50f5beb70eae85b22c6c2fc7d6
245
cpp
C++
src/common/Spinlock.cpp
cas1k/rewind-viewer
6307158c6b99dd2da0be23f1816e3418eea5771f
[ "MIT" ]
71
2017-10-28T14:34:34.000Z
2020-12-30T06:55:55.000Z
src/common/Spinlock.cpp
cas1k/rewind-viewer
6307158c6b99dd2da0be23f1816e3418eea5771f
[ "MIT" ]
42
2017-11-02T12:12:25.000Z
2020-12-10T09:53:31.000Z
src/common/Spinlock.cpp
cas1k/rewind-viewer
6307158c6b99dd2da0be23f1816e3418eea5771f
[ "MIT" ]
30
2017-11-05T18:09:48.000Z
2020-12-06T20:03:46.000Z
// // Created by Vladimir A. Kiselev on 08.11.2020. // #include "Spinlock.h" void Spinlock::lock() { while (lock_.test_and_set(std::memory_order_acquire)) ; } void Spinlock::unlock() { lock_.clear(std::memory_order_release); }
17.5
57
0.665306
cas1k
cc395d389d520027d5325d925f9085f1ead925e4
285
cpp
C++
ExpressionEvaluation/parse/mock/compiler_for_parser_mock/compiler_for_parser_mock.cpp
suiyili/Algorithms
d6ddc8262c5d681ecc78938b6140510793a29d91
[ "MIT" ]
null
null
null
ExpressionEvaluation/parse/mock/compiler_for_parser_mock/compiler_for_parser_mock.cpp
suiyili/Algorithms
d6ddc8262c5d681ecc78938b6140510793a29d91
[ "MIT" ]
null
null
null
ExpressionEvaluation/parse/mock/compiler_for_parser_mock/compiler_for_parser_mock.cpp
suiyili/Algorithms
d6ddc8262c5d681ecc78938b6140510793a29d91
[ "MIT" ]
null
null
null
#ifdef TEST #include "compiler_for_parser_mock.hpp" compiler_for_parser_mock::compiler_for_parser_mock(size_t &merge_called) : merge_called_(merge_called) {} void compiler_for_parser_mock::merge(std::unique_ptr<compiler_i> other) { merge_called_++; return; } #endif // TEST
21.923077
73
0.782456
suiyili
cc39868dc2e2a56022643ac78bd67bf109a533c4
547
cpp
C++
engine/calculators/source/MagicalAttackSpeedCalculator.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/calculators/source/MagicalAttackSpeedCalculator.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/calculators/source/MagicalAttackSpeedCalculator.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "Game.hpp" #include "MagicalAttackSpeedCalculator.hpp" using namespace std; ActionCostValue MagicalAttackSpeedCalculator::calculate(CreaturePtr creature) { ActionCostValue action_cost_value = ActionCostConstants::DEFAULT; if (creature) { string spell_id = creature->get_spell_knowledge_ref().get_most_recently_cast_spell_id(); if (!spell_id.empty()) { Spell spell = Game::instance().get_spells_ref().find(spell_id)->second; action_cost_value = spell.get_speed(); } } return action_cost_value; }
23.782609
92
0.744059
sidav
cc3c467c959a7d153ef63099a9c5e0aa100c596a
8,920
cpp
C++
Source/SystemQOR/MSWindows/WinQL/System/Devices/Interfaces/WinQLDeviceInterfaceClassCollection.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/MSWindows/WinQL/System/Devices/Interfaces/WinQLDeviceInterfaceClassCollection.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/MSWindows/WinQL/System/Devices/Interfaces/WinQLDeviceInterfaceClassCollection.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//WinQLDeviceInterfaceClassCollection.cpp // Copyright Querysoft Limited 2013, 2017 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "WinQL/CodeServices/WinQLPolicy.h" #include "WinQL/Application/Threading/WinQLCriticalSection.h" #include "WinQL/Application/ErrorSystem/WinQLError.h" #include "WinQL/CodeServices/Text/WinString.h" #include "WinQL/System/Devices/Interfaces/WinQLDeviceInterfaceClassCollection.h" #include "WinQL/System/Devices/Interfaces/WinQLDeviceInterfaceClass.h" #include "WinQL/Definitions/Constants.h" #include "WinQL/GUI/Window.h" #include "WinQL/System/WinQLSystem.h" #include "WinQAPI/Kernel32.h" #include "WinQAPI/SetupAPI.h" //-------------------------------------------------------------------------------- namespace nsWin32 { using namespace nsWinQAPI; //-------------------------------------------------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( CDeviceInterfaceClassCollection ); nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::BUS1394_CLASS_GUID = { 0x6BDD1FC1, 0x810F, 0x11d0, { 0xBE, 0xC7, 0x08, 0x00, 0x2B, 0xE2, 0x09, 0x2F } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_61883_CLASS = { 0x7EBEFBC0, 0x3200, 0x11d2, { 0xB4, 0xC2, 0x00, 0xA0, 0xC9, 0x69, 0x7D, 0x07 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVICE_APPLICATIONLAUNCH_BUTTON = { 0x629758EE, 0x986E, 0x4D9E, { 0x8E, 0x47, 0xDE, 0x27, 0xF8, 0xAB, 0x05, 0x4D } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVICE_BATTERY = { 0x72631E54, 0x78A4, 0x11D0, { 0xBC, 0xF7, 0x00, 0xAA, 0x00, 0xB7, 0xB3, 0x2A } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVICE_LID = { 0x4AFA3D52, 0x74A7, 0x11d0, { 0xbe, 0x5e, 0x00, 0xA0, 0xC9, 0x06, 0x28, 0x57 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVICE_MEMORY = { 0x3FD0F03D, 0x92E0, 0x45FB, { 0xB7, 0x5C, 0x5E, 0xD8, 0xFF, 0xB0, 0x10, 0x21 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVICE_MESSAGE_INDICATOR = { 0xCD48A365, 0xFA94, 0x4CE2, { 0xA2, 0x32, 0xA1, 0xB7, 0x64, 0xE5, 0xD8, 0xB4 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVICE_PROCESSOR = { 0x97FADB10, 0x4E33, 0x40AE, { 0x35, 0x9C, 0x8B, 0xEF, 0x02, 0x9D, 0xBD, 0xD0 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVICE_SYS_BUTTON = { 0x4AFA3D53, 0x74A7, 0x11d0, { 0xbe, 0x5e, 0x00, 0xA0, 0xC9, 0x06, 0x28, 0x57 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVICE_THERMAL_ZONE = { 0x4AFA3D51, 0x74A7, 0x11d0, { 0xbe, 0x5e, 0x00, 0xA0, 0xC9, 0x06, 0x28, 0x57 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_BTHPORT_DEVICE_INTERFACE = { 0x0850302A, 0xB344, 0x4fda, { 0x9B, 0xE9, 0x90, 0x57, 0x6B, 0x8D, 0x46, 0xF0 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVINTERFACE_BRIGHTNESS = { 0xFDE5BBA4, 0xB3F9, 0x46FB, { 0xBD, 0xAA, 0x07, 0x28, 0xCE, 0x31, 0x00, 0xB4 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVINTERFACE_DISPLAY_ADAPTER = { 0x5B45201D, 0xF2F2, 0x4F3B, { 0x85, 0xBB, 0x30, 0xFF, 0x1F, 0x95, 0x35, 0x99 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVINTERFACE_I2C = { 0x2564AA4F, 0xDDDB, 0x4495, { 0xB4, 0x97, 0x6A, 0xD4, 0xA8, 0x41, 0x63, 0xD7 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVINTERFACE_IMAGE = { 0x6BDD1FC6, 0x810F, 0x11D0, { 0xBE, 0xC7, 0x08, 0x00, 0x2B, 0xE2, 0x09, 0x2F } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVINTERFACE_MONITOR = { 0xE6F07B5F, 0xEE97, 0x4a90, { 0xB0, 0x76, 0x33, 0xF5, 0x7B, 0xF4, 0xEA, 0xA7 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVINTERFACE_OPM = { 0xBF4672DE, 0x6B4E, 0x4BE4, { 0xA3, 0x25, 0x68, 0xA9, 0x1E, 0xA4, 0x9C, 0x09 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVINTERFACE_VIDEO_OUTPUT_ARRIVAL = { 0x1AD9E4F0, 0xF88D, 0x4360, { 0xBA, 0xB9, 0x4C, 0x2D, 0x55, 0xE5, 0x64, 0xCD } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DISPLAY_DEVICE_ARRIVAL = { 0x1CA05180, 0xA699, 0x450A, { 0x9A, 0x0C, 0xDE, 0x4F, 0xBE, 0x3D, 0xDD, 0x89 } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVINTERFACE_KEYBOARD = { 0x884b96c3, 0x56ef, 0x11d1, { 0xbc, 0x8c, 0x00, 0xa0, 0xc9, 0x14, 0x05, 0xdd } }; nsCodeQOR::__mxGUID CDeviceInterfaceClassCollection::GUID_DEVINTERFACE_MOUSE = { 0x378de44c, 0x56ef, 0x11d1, { 0xbc, 0x8c, 0x00, 0xa0, 0xc9, 0x14, 0x05, 0xdd } }; //-------------------------------------------------------------------------------- CDeviceInterfaceClassCollection::CDeviceInterfaceClassCollection( const mxTCHAR* szMachine ) : std::map< nsCodeQOR::__mxGUID*, CDeviceInterfaceClass* >(), m_Library( CSetupAPI::Instance() ) , m_szMachine( szMachine ) { _WINQ_FCONTEXT( "CDeviceInterfaceClassCollection::CDeviceInterfaceClassCollection" ); RegisterInterfaceClass( &BUS1394_CLASS_GUID ); RegisterInterfaceClass( &GUID_61883_CLASS ); RegisterInterfaceClass( &GUID_DEVICE_APPLICATIONLAUNCH_BUTTON ); RegisterInterfaceClass( &GUID_DEVICE_BATTERY ); RegisterInterfaceClass( &GUID_DEVICE_LID ); RegisterInterfaceClass( &GUID_DEVICE_MEMORY ); RegisterInterfaceClass( &GUID_DEVICE_MESSAGE_INDICATOR ); RegisterInterfaceClass( &GUID_DEVICE_PROCESSOR ); RegisterInterfaceClass( &GUID_DEVICE_SYS_BUTTON ); RegisterInterfaceClass( &GUID_DEVICE_THERMAL_ZONE ); RegisterInterfaceClass( &GUID_BTHPORT_DEVICE_INTERFACE ); RegisterInterfaceClass( &GUID_DEVINTERFACE_KEYBOARD ); RegisterInterfaceClass( &GUID_DEVINTERFACE_MOUSE ); RegisterInterfaceClass( &GUID_DEVINTERFACE_BRIGHTNESS ); RegisterInterfaceClass( &GUID_DEVINTERFACE_DISPLAY_ADAPTER ); RegisterInterfaceClass( &GUID_DEVINTERFACE_I2C ); RegisterInterfaceClass( &GUID_DEVINTERFACE_IMAGE ); RegisterInterfaceClass( &GUID_DEVINTERFACE_MONITOR ); RegisterInterfaceClass( &GUID_DEVINTERFACE_OPM ); RegisterInterfaceClass( &GUID_DEVINTERFACE_VIDEO_OUTPUT_ARRIVAL ); RegisterInterfaceClass( &GUID_DISPLAY_DEVICE_ARRIVAL ); } //-------------------------------------------------------------------------------- CDeviceInterfaceClassCollection::CDeviceInterfaceClassCollection( const CDeviceInterfaceClassCollection& src ) : m_Library( CSetupAPI::Instance() ) { _WINQ_FCONTEXT( "CDeviceInterfaceClassCollection::CDeviceInterfaceClassCollection" ); *this = src; } //-------------------------------------------------------------------------------- CDeviceInterfaceClassCollection& CDeviceInterfaceClassCollection::operator = ( const CDeviceInterfaceClassCollection& src ) { _WINQ_FCONTEXT( "CDeviceInterfaceClassCollection::operator =" ); if( &src != this ) { m_szMachine = src.m_szMachine; BaseType::operator=(src); } return *this; } //-------------------------------------------------------------------------------- CDeviceInterfaceClassCollection::~CDeviceInterfaceClassCollection() { _WINQ_FCONTEXT( "CDeviceInterfaceClassCollection::~CDeviceInterfaceClassCollection" ); } //-------------------------------------------------------------------------------- nsCodeQOR::CTLRef< CDeviceInterfaceClass > CDeviceInterfaceClassCollection::RegisterInterfaceClass( nsCodeQOR::__mxGUID* pGUID ) { _WINQ_FCONTEXT( "CDeviceInterfaceClassCollection::RegisterInterfaceClass" ); CDeviceInterfaceClass* pDeviceInterfaceClass = new CDeviceInterfaceClass( *pGUID, m_szMachine ); insert( std::make_pair( pGUID, pDeviceInterfaceClass ) ); nsCodeQOR::CTLRef< CDeviceInterfaceClass > Result( pDeviceInterfaceClass, false ); return Result; } }//nsWin32
63.262411
190
0.726682
mfaithfull
cc3ec7713db5e387daeb5c2614a49d6be4c640a5
2,514
cpp
C++
RemoteMessage/Message.cpp
deping/RemoteMessage
cb6782814a51904ca45cb3c00fefc48594d40789
[ "MIT" ]
null
null
null
RemoteMessage/Message.cpp
deping/RemoteMessage
cb6782814a51904ca45cb3c00fefc48594d40789
[ "MIT" ]
null
null
null
RemoteMessage/Message.cpp
deping/RemoteMessage
cb6782814a51904ca45cb3c00fefc48594d40789
[ "MIT" ]
null
null
null
/*************************************************************************** * Copyright (C) 2017, Deping Chen, [email protected] * * All rights reserved. * For permission requests, write to the publisher. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. ***************************************************************************/ #include "Message.h" #include "utility.h" namespace RMsg { Message::Message() : m_SessionId(0) , m_MsgIdEx(KEEP_ALIVE_MSG) , m_MsgCat(0) , m_MsgCls(0) , m_MsgRst(0) , m_pNext(nullptr) { } Message::~Message() { } void Message::CopyHeader(const Message & src) { m_MsgIdEx = src.m_MsgIdEx; m_MsgCat = src.m_MsgCat; m_MsgCls = src.m_MsgCls; m_MsgRst = src.m_MsgRst; } void Message::SerializeToVector(std::vector<char>& header) { ASSERT_DEBUG_INFO(header.size() == s_SizeOfHeader); char* buffer = header.data(); memcpy(buffer, &m_MsgIdEx, sizeof(m_MsgIdEx)); buffer += sizeof(m_MsgIdEx); memcpy(buffer, &m_MsgCat, sizeof(m_MsgCat)); buffer += sizeof(m_MsgCat); memcpy(buffer, &m_MsgCls, sizeof(m_MsgCls)); buffer += sizeof(m_MsgCls); memcpy(buffer, &m_MsgRst, sizeof(m_MsgRst)); buffer += sizeof(m_MsgRst); // Assume payload size is less than 4G. uint32_t payloadSize = uint32_t(m_Payload.size()); memcpy(buffer, &payloadSize, sizeof(payloadSize)); buffer += sizeof(payloadSize); } uint32_t Message::ParseFromVector(const std::vector<char>& header) { ASSERT_DEBUG_INFO(header.size() == s_SizeOfHeader); const char* buffer = header.data(); memcpy(&m_MsgIdEx, buffer, sizeof(m_MsgIdEx)); buffer += sizeof(m_MsgIdEx); memcpy(&m_MsgCat, buffer, sizeof(m_MsgCat)); buffer += sizeof(m_MsgCat); memcpy(&m_MsgCls, buffer, sizeof(m_MsgCls)); buffer += sizeof(m_MsgCls); memcpy(&m_MsgRst, buffer, sizeof(m_MsgRst)); buffer += sizeof(m_MsgRst); uint32_t payloadSize; memcpy(&payloadSize, buffer, sizeof(payloadSize)); buffer += sizeof(payloadSize); return payloadSize; } void AppendList(Message*& pList1, Message* pList2) { if (!pList1) { pList1 = pList2; return; } if (!pList2) { return; } Message* curr = pList1; while (curr->m_pNext) { curr = curr->m_pNext; } curr->m_pNext = pList2; } Message* ReverseList(Message* pMsg) { Message* prev = nullptr; Message* curr = pMsg; while (curr) { // keep next Message* next = curr->m_pNext; // revert curr->m_pNext = prev; // advance prev = curr; curr = next; } // here, curr is nullptr return prev; } }
22.247788
76
0.658313
deping
cc40b34a90096d376091f0eb6ff64a32fd9f48dd
15,609
hh
C++
dune/gdt/operators/darcy.hh
tobiasleibner/dune-gdt
5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b
[ "BSD-2-Clause" ]
null
null
null
dune/gdt/operators/darcy.hh
tobiasleibner/dune-gdt
5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b
[ "BSD-2-Clause" ]
null
null
null
dune/gdt/operators/darcy.hh
tobiasleibner/dune-gdt
5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b
[ "BSD-2-Clause" ]
null
null
null
// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2014 - 2017) // Rene Milk (2016 - 2017) // Tobias Leibner (2014) #ifndef DUNE_GDT_OPERATORS_DARCY_HH #define DUNE_GDT_OPERATORS_DARCY_HH #include <limits> #include <boost/numeric/conversion/cast.hpp> #include <dune/geometry/quadraturerules.hh> #include <dune/xt/common/exceptions.hh> #include <dune/xt/common/fvector.hh> #include <dune/xt/common/fmatrix.hh> #include <dune/xt/common/type_traits.hh> #include <dune/xt/grid/type_traits.hh> #include <dune/xt/functions/interfaces.hh> #include <dune/xt/la/container.hh> #include <dune/xt/la/solver.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/exceptions.hh> #include <dune/gdt/spaces/cg/interface.hh> #include <dune/gdt/spaces/rt/interface.hh> #include "interfaces.hh" namespace Dune { namespace GDT { // forward, to be used in the traits template <class GridLayerImp, class FunctionImp> class DarcyOperator; namespace internal { template <class GridLayerImp, class FunctionImp> class DarcyOperatorTraits { static_assert(XT::Functions::is_localizable_function<FunctionImp>::value, "FunctionImp has to be derived from XT::Functions::is_localizable_function!"); static_assert(std::is_same<typename GridLayerImp::ctype, typename FunctionImp::DomainFieldType>::value, "Types do not match!"); static_assert(GridLayerImp::dimension == FunctionImp::dimDomain, "Dimensions do not match!"); static_assert(FunctionImp::dimRange == FunctionImp::dimRangeCols, "Dimensions do not match!"); public: typedef DarcyOperator<GridLayerImp, FunctionImp> derived_type; typedef GridLayerImp GridLayerType; typedef typename FunctionImp::RangeFieldType FieldType; typedef NoJacobian JacobianType; }; // class DarcyOperatorTraits } // namespace internal /** * \note Only works for scalar valued function atm. * \todo add make_darcy_operator **/ template <class GridLayerImp, class FunctionImp> class DarcyOperator : public OperatorInterface<internal::DarcyOperatorTraits<GridLayerImp, FunctionImp>> { typedef OperatorInterface<internal::DarcyOperatorTraits<GridLayerImp, FunctionImp>> BaseType; public: typedef internal::DarcyOperatorTraits<GridLayerImp, FunctionImp> Traits; typedef typename Traits::GridLayerType GridLayerType; typedef typename Traits::FieldType FieldType; typedef typename Traits::JacobianType JacobianType; using EntityType = XT::Grid::extract_entity_t<GridLayerType>; typedef typename GridLayerType::ctype DomainFieldType; static const size_t dimDomain = GridLayerType::dimension; DarcyOperator(const GridLayerType& grd_vw, const FunctionImp& function) : grid_layer_(grd_vw) , function_(function) { } /** * \brief Applies the operator. * \note See redirect_apply for the implementation (depending on the type of the range space). * \sa redirect_apply */ template <class S, class V, size_t r, size_t rC> void apply(const XT::Functions::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, r, rC>& source, DiscreteFunction<S, V>& range, const Dune::XT::Common::Parameter& param = {}) const { redirect_apply(range.space(), source, range, param); } template <class SourceType> JacobianType jacobian(const SourceType& /*source*/, const Dune::XT::Common::Parameter& /*param*/ = {}) const { DUNE_THROW(NotImplemented, "This operator does not provide a jacobian (yet)!"); return JacobianType(); } template <class SourceType> void jacobian(const SourceType& /*source*/, JacobianType& /*jac*/, const Dune::XT::Common::Parameter& /*param*/ = {}) const { DUNE_THROW(NotImplemented, "This operator does not provide a jacobian (yet)!"); } private: template <class R, size_t r, size_t rC> struct Helper { static_assert(AlwaysFalse<R>::value, "This should not happen (see check in Traits)!"); }; template <class R, size_t r> struct Helper<R, r, r> { typedef XT::Common::FieldMatrix<R, r, r> type; }; template <class R> struct Helper<R, 1, 1> { typedef XT::Common::FieldVector<R, 1> type; }; typedef typename Helper<typename FunctionImp::RangeFieldType, FunctionImp::dimRange, FunctionImp::dimRangeCols>::type ValueType; /** * \brief Does an L2 projection of '- function * \gradient source' onto range. */ template <class T, class S, class V> void redirect_apply( const CgSpaceInterface<T, dimDomain, dimDomain, 1>& /*space*/, const XT::Functions::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, 1, 1>& source, DiscreteFunction<S, V>& range, const XT::Common::Parameter param) const { typedef typename XT::LA::Container<FieldType, V::sparse_matrix_type>::MatrixType MatrixType; MatrixType lhs( range.space().mapper().size(), range.space().mapper().size(), range.space().compute_volume_pattern()); V rhs(range.space().mapper().size()); // walk the grid const auto entity_it_end = grid_layer_.template end<0>(); for (auto entity_it = grid_layer_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; const auto local_function = function_.local_function(entity); const auto local_source = source.local_function(entity); const auto basis = range.space().base_function_set(entity); // do a volume quadrature const size_t integrand_order = std::max(local_function->order() + ssize_t(local_source->order()) - 1, basis.order()) + basis.order(); const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain>::rule(entity.type(), boost::numeric_cast<int>(integrand_order)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto xx = quadrature_it->position(); const auto quadrature_weight = quadrature_it->weight(); const auto integration_element = entity.geometry().integrationElement(xx); const ValueType function_value = local_function->evaluate(xx, param); const auto source_gradient = local_source->jacobian(xx, param); const auto basis_value = basis.evaluate(xx, param); for (size_t ii = 0; ii < basis.size(); ++ii) { const size_t global_ii = range.space().mapper().mapToGlobal(entity, ii); rhs.add_to_entry(global_ii, integration_element * quadrature_weight * -1.0 * ((function_value * source_gradient[0]) * basis_value[ii])); for (size_t jj = 0; jj < basis.size(); ++jj) { const size_t global_jj = range.space().mapper().mapToGlobal(entity, jj); lhs.add_to_entry( global_ii, global_jj, integration_element * quadrature_weight * (basis_value[ii] * basis_value[jj])); } } } // do a volume quadrature } // walk the grid // solve try { XT::LA::Solver<MatrixType>(lhs).apply(rhs, range.vector()); } catch (XT::LA::Exceptions::linear_solver_failed& ee) { DUNE_THROW(operator_error, "Application of the Darcy operator failed because a matrix could not be inverted!\n\n" << "This was the original error: " << ee.what()); } } // ... redirect_apply(...) template <class T, class S, class V> void redirect_apply( const RtSpaceInterface<T, dimDomain, dimDomain, 1>& /*space*/, const XT::Functions::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, 1>& source, DiscreteFunction<S, V>& range, const XT::Common::Parameter param) const { static_assert(RtSpaceInterface<T, dimDomain, 1>::polOrder == 0, "Untested!"); const auto& rtn0_space = range.space(); auto& range_vector = range.vector(); const auto infinity = std::numeric_limits<FieldType>::infinity(); for (size_t ii = 0; ii < range_vector.size(); ++ii) range_vector[ii] = infinity; // walk the grid const auto entity_it_end = grid_layer_.template end<0>(); for (auto entity_it = grid_layer_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity); const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity); assert(global_DoF_indices.size() == local_DoF_indices.size()); const auto local_function = function_.local_function(entity); const auto local_source = source.local_function(entity); const auto local_basis = rtn0_space.base_function_set(entity); // walk the intersections const auto intersection_it_end = grid_layer_.iend(entity); for (auto intersection_it = grid_layer_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; if (intersection.neighbor() && !intersection.boundary()) { const auto neighbor = intersection.outside(); if (grid_layer_.indexSet().index(entity) < grid_layer_.indexSet().index(neighbor)) { const auto local_function_neighbor = function_.local_function(neighbor); const auto local_source_neighbor = source.local_function(neighbor); const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = local_function->order(); const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain - 1>::rule( intersection.type(), boost::numeric_cast<int>(integrand_order)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto xx_intersection = quadrature_it->position(); const auto normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weight = quadrature_it->weight(); const auto xx_entity = intersection.geometryInInside().global(xx_intersection); const auto xx_neighbor = intersection.geometryInOutside().global(xx_intersection); // evaluate ValueType function_value = local_function->evaluate(xx_entity, param); function_value *= 0.5; ValueType function_value_neighbor = local_function_neighbor->evaluate(xx_neighbor, param); function_value_neighbor *= 0.5; function_value += function_value_neighbor; auto source_gradient = local_source->jacobian(xx_entity, param)[0]; source_gradient *= 0.5; auto source_gradient_neighbor = local_source_neighbor->jacobian(xx_neighbor, param)[0]; source_gradient_neighbor *= 0.5; source_gradient += source_gradient_neighbor; const auto basis_values = local_basis.evaluate(xx_entity, param); const auto basis_value = basis_values[local_DoF_index]; // compute integrals lhs += integration_factor * weight * (basis_value * normal); rhs += integration_factor * weight * -1.0 * compute_value(function_value, source_gradient, normal); } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; assert(!(range_vector[global_DoF_index] < infinity)); range_vector[global_DoF_index] = rhs / lhs; } } else if (intersection.boundary() && !intersection.neighbor()) { const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = local_function->order(); const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain - 1>::rule( intersection.type(), boost::numeric_cast<int>(integrand_order)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto xx_intersection = quadrature_it->position(); const auto normal = intersection.unitOuterNormal(xx_intersection); const auto integration_factor = intersection.geometry().integrationElement(xx_intersection); const auto weight = quadrature_it->weight(); const auto xx_entity = intersection.geometryInInside().global(xx_intersection); // evalaute const ValueType function_value = local_function->evaluate(xx_entity, param); const auto source_gradient = local_source->jacobian(xx_entity, param)[0]; const auto basis_values = local_basis.evaluate(xx_entity, param); const auto basis_value = basis_values[local_DoF_index]; // compute integrals lhs += integration_factor * weight * (basis_value * normal); rhs += integration_factor * weight * -1.0 * compute_value(function_value, source_gradient, normal); } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; assert(!(range_vector[global_DoF_index] < infinity)); range_vector[global_DoF_index] = rhs / lhs; } else DUNE_THROW(XT::Common::Exceptions::internal_error, "Unknown intersection type!"); } // walk the intersections } // walk the grid } // ... redirect_apply(...) template <class R, int d> R compute_value(const FieldVector<R, 1>& function_value, const FieldVector<R, d>& source_gradient, const FieldVector<R, d>& normal) const { return function_value * (source_gradient * normal); } template <class R, int d> typename std::enable_if<(d > 1), R>::type compute_value(const XT::Common::FieldMatrix<R, d, d>& function_value, const FieldVector<R, d>& source_gradient, const FieldVector<R, d>& normal) const { return (function_value * source_gradient) * normal; } const GridLayerType& grid_layer_; const FunctionImp& function_; }; // class DarcyOperator template <class G, class F> std::unique_ptr<DarcyOperator<G, F>> make_darcy(const G& grid_layer, const F& function) { return std::unique_ptr<DarcyOperator<G, F>>(new DarcyOperator<G, F>(grid_layer, function)); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_DARCY_HH
45.375
120
0.677622
tobiasleibner
cc4a9577fb50e1a12d7044ea8c8f5779059d7f55
1,620
cpp
C++
app_modules/01_keyboard_module/src/application.cpp
LucaRitz/learn_with_tello
f7fc45e7a9e9a2903638ec8367c9b355a4f1afc9
[ "Apache-2.0" ]
null
null
null
app_modules/01_keyboard_module/src/application.cpp
LucaRitz/learn_with_tello
f7fc45e7a9e9a2903638ec8367c9b355a4f1afc9
[ "Apache-2.0" ]
null
null
null
app_modules/01_keyboard_module/src/application.cpp
LucaRitz/learn_with_tello
f7fc45e7a9e9a2903638ec8367c9b355a4f1afc9
[ "Apache-2.0" ]
null
null
null
#include "application.hpp" #include <tello/tello.hpp> #include "keyboard_view.hpp" #include "keyboard_controller.hpp" using tello::Tello; using tello::Response; Application::Application() : _baseSettings(nullptr), _keyboardView(std::make_unique<KeyboardView>()), _keyboardController(std::make_unique<KeyboardController>(_keyboardView.get(), this)){ } ModuleId Application::id() const { return ModuleId::KEYBOARD_MODULE; } string* Application::name() const { return new string {"Keyboard"}; } vector<ModuleId> Application::dependsOn() const { return vector<ModuleId>{ModuleId::BASE}; } uint8_t Application::init() { return 0; } void Application::tearDown() { } #include <iostream> void Application::update(ModuleId moduleId, const ISettings* settings) { switch (moduleId) { case ModuleId::BASE: { _baseSettings = dynamic_cast<const BaseSettings*>(settings); std::cout << "Update settings in module 1: " << _baseSettings->tellos().at(0)->ip() << std::endl; /* auto& tello = _baseSettings->tellos().at(0); future<Response> command_future = tello->command(); command_future.wait(); future<Response> takeoff_future = tello->takeoff(); takeoff_future.wait(); future<Response> land_future = tello->land(); land_future.wait();*/ break; } default: break; } } BaseController* Application::controller() { return _keyboardController.get(); } ISettingsController* Application::settingsController() { return nullptr; }
24.179104
109
0.652469
LucaRitz
cc4d488f19a45a637ad4a82810a5eb173f26c8e0
16,538
cc
C++
util/unittest/iostream.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
util/unittest/iostream.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
10
2022-02-27T18:52:11.000Z
2022-03-21T14:11:35.000Z
util/unittest/iostream.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2022, Stable Cloud Computing, Inc. 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. */ #include <util/iostream.h> #include <util/rwloopbuf.h> #include <util/rwcounter.h> #include <gtest/gtest.h> #include <iostream> #include <string> #include <vector> #include <sstream> /** \addtogroup util_iostream @{ */ /** Tests for \ref util_iostream \file */ /** \example util/unittest/iostream.cc */ /** @} */ using std::cout; using std::endl; using std::string; using std::stringstream; using std::ios; using scc::util::RwLoopBuffer; using scc::util::InStream; using scc::util::OutStream; using scc::util::IoStream; using scc::util::RwCounter; using scc::util::Reader; using scc::util::Writer; //! [I/O stream decorator stack] static string test_word = "QuotesFromOscarWilde"; static string test_line = "It is always a silly thing to give advice, but to give good advice is fatal."; static string test_long = "One can survive everything, nowadays, except death, and live down everything except a good reputation.\n" "One should always play fairly when one has the winning cards.\n" "Patriotism is the virtue of the vicious.\n" "Selfishness is not living as one wishes to live, it is asking others to live as one wishes to live."; TEST(iostream_test, example_decorator_stack) { RwLoopBuffer rwbuf; // loopback stream buffer RwCounter rwcount(rwbuf, rwbuf); // decorator provides read() and write() for the stream buffer IoStream rws(rwcount, rwcount); // provides std::iostream std::stringstream sstr; // std::stringstream is a std::iostream // verify stream write behavior rws << test_line << endl; // std::endl writes a newline char and flushes the stream rws << test_long << endl; sstr << test_line << endl; sstr << test_long << endl; ASSERT_EQ(rwbuf.str(), sstr.str()); ASSERT_EQ(rwcount.write_count(), sstr.str().size()); ASSERT_EQ(rwcount.read_count(), 0); // verify stream read behavior string reads, tests; while (sstr >> reads) { ASSERT_TRUE(rws >> tests); ASSERT_EQ(reads, tests); } ASSERT_FALSE(rws >> tests); // verify the RwLoopBuffer stream is done as well ASSERT_EQ(rwcount.read_count(), sstr.str().size()); ASSERT_EQ(rwbuf.str().size(), 0); // the loopback buffer is now empty } struct iostreamTest : public testing::Test { std::vector<string> all; iostreamTest() { all.push_back(test_word); all.push_back(test_line); all.push_back(test_long); } virtual ~iostreamTest() {} void readwords_test(const string s, int recvbuf_size=10) { stringstream sstr(s); RwLoopBuffer rw(s); InStream ins(rw); ins.recvbuf_size(recvbuf_size); ASSERT_EQ(ins.recvbuf_size(), recvbuf_size); cout << "readwords_test: " << s.substr(0,10) << "... size=" << s.size() << " recvbuf_size= " << ins.recvbuf_size() << endl; string reads, tests; while (sstr >> reads) { ASSERT_TRUE(ins >> tests); ASSERT_EQ(reads, tests); } } void readlines_test(const string s, int recvbuf_size=10) { stringstream sstr(s); RwLoopBuffer rw(s); InStream ins(rw); ins.recvbuf_size(recvbuf_size); ASSERT_EQ(ins.recvbuf_size(), recvbuf_size); cout << "readlines_test: " << s.substr(0,10) << "... size=" << s.size() << " recvbuf_size= " << ins.recvbuf_size() << endl; string reads, tests; while (std::getline(sstr, reads)) { ASSERT_TRUE(std::getline(ins, tests)); ASSERT_EQ(reads, tests); } } void writewords_test(const string s, int sendbuf_size=10) { stringstream sstr(s); RwLoopBuffer rw; OutStream ous(rw); ous.sendbuf_size(sendbuf_size); ASSERT_EQ(ous.sendbuf_size(), sendbuf_size); cout << "writewords_test: " << s.substr(0,10) << "... size=" << s.size() << " sendbuf_size= " << ous.sendbuf_size() << endl; string reads; stringstream writess; while (sstr >> reads) { writess << reads; ASSERT_TRUE(ous << reads); } writess.flush(); ous.flush(); ASSERT_EQ(writess.str(), rw.str()); } void writelines_test(const string s, int sendbuf_size=10) { stringstream sstr(s); RwLoopBuffer rw; OutStream ous(rw); ous.sendbuf_size(sendbuf_size); ASSERT_EQ(ous.sendbuf_size(), sendbuf_size); cout << "writelines_test: " << s.substr(0,10) << "... size=" << s.size() << " sendbuf_size= " << ous.sendbuf_size() << endl; string reads; stringstream writess; while (std::getline(sstr, reads)) { writess << reads << endl; ASSERT_TRUE(ous << reads << endl); } writess.flush(); ous.flush(); ASSERT_EQ(writess.str(), rw.str()); } void readchunks_test(const string s, int rbuf1=10, int rsz1=1024, int rbuf2=10) { RwLoopBuffer rw(s); InStream ins(rw); ins.recvbuf_size(rbuf1); ASSERT_EQ(ins.recvbuf_size(), rbuf1); int toread = s.size(); cout << "readchunks_test1: " << s.substr(0,10) << "... read=" << rsz1 << " toread=" << toread << " recvbuf_size= " << ins.recvbuf_size() << endl; char bin1[rsz1]; ins.read(bin1, rsz1); auto lastread = ins.gcount(); ASSERT_EQ(lastread, std::min(rsz1, toread)); ASSERT_EQ(memcmp(s.data(), bin1, lastread), 0); toread -= lastread; if (lastread < rsz1) { ASSERT_EQ((ins.rdstate()&std::ios_base::eofbit), std::ios_base::eofbit); } if (toread) { ins.recvbuf_size(rbuf2); ASSERT_EQ(ins.recvbuf_size(), rbuf2); cout << "readchunks_test2: " << s.substr(0,10) << "... read=" << toread << " toread=" << toread << " recvbuf_size= " << ins.recvbuf_size() << endl; char bin2[toread]; ins.read(bin2, toread); auto lastread2 = ins.gcount(); ASSERT_EQ(lastread2, toread); ASSERT_EQ(memcmp(s.data()+lastread, bin2, lastread2), 0); ASSERT_NE((ins.rdstate()&std::ios_base::eofbit), std::ios_base::eofbit); } } void writechunks_test(const string s, int wbuf1=10, int wsz1=1024, int wbuf2=10) { RwLoopBuffer rw; OutStream ous(rw); ous.sendbuf_size(wbuf1); ASSERT_EQ(ous.sendbuf_size(), wbuf1); int towrite = s.size(); wsz1 = std::min(wsz1, towrite); cout << "writechunks_test1: " << s.substr(0,10) << "... write=" << wsz1 << " towrite=" << towrite << " sendbuf_size= " << ous.sendbuf_size() << endl; ASSERT_TRUE(ous.write(s.data(), wsz1)); towrite -= wsz1; if (towrite) { ous.sendbuf_size(wbuf2); ASSERT_EQ(ous.sendbuf_size(), wbuf2); cout << "writechunks_test2: " << s.substr(0,10) << "... write=" << towrite << " towrite=" << towrite << " sendbuf_size= " << ous.sendbuf_size() << endl; ASSERT_TRUE(ous.write(s.data()+wsz1, towrite)); } ous.flush(); ASSERT_EQ(s, rw.str()); } }; TEST_F(iostreamTest, read) { for (auto& s : all) { readwords_test(s); } for (auto& s : all) { readlines_test(s); } } TEST_F(iostreamTest, write) { for (auto& s : all) { writewords_test(s); } for (auto& s : all) { writelines_test(s); } } TEST_F(iostreamTest, readchunks) { for (auto& s : all) { readchunks_test(s); // buf 10, read all readchunks_test(s, 10, 5, 20); // buf 10, read 5, buf 20, read all readchunks_test(s, 10, 8, 5); // buf 10, read 8, buf 5, read all } } TEST_F(iostreamTest, writechunks) { for (auto& s : all) { writechunks_test(s); // buf 10, write all writechunks_test(s, 10, 5, 20); // buf 10, write 5, buf 20, write all writechunks_test(s, 10, 8, 5); // buf 10, write 8, buf 5, write all } } TEST(iostream_test, write_read) { string val("this\nis\na\ntest\n"); RwLoopBuffer rw; IoStream ios(rw, rw); ASSERT_TRUE(ios.write(val.data(), val.size())); ios.flush(); char buf[sizeof(val)]; ASSERT_TRUE(ios.read(buf, val.size())); ASSERT_EQ(ios.gcount(), val.size()); ASSERT_EQ(memcmp(buf, val.data(), val.size()), 0); ASSERT_FALSE(ios.read(buf, val.size())); } TEST(iostream_test, stream_write_read) { string val("this\nis\na\ntest\n"); RwLoopBuffer rw; IoStream ios(rw, rw); ASSERT_TRUE(ios << val); ios.flush(); string s; ASSERT_TRUE(ios >> s); ASSERT_EQ(s, "this"); ASSERT_TRUE(ios >> s); ASSERT_EQ(s, "is"); ASSERT_TRUE(ios >> s); ASSERT_EQ(s, "a"); ASSERT_TRUE(ios >> s); ASSERT_EQ(s, "test"); } string printstate(int state) { stringstream st; st << "state: "; if (state == 0) st << "good "; if ((state&std::ios_base::badbit)==std::ios_base::badbit) st << "bad "; if ((state&std::ios_base::failbit)==std::ios_base::failbit) st << "fail "; if ((state&std::ios_base::eofbit)==std::ios_base::eofbit) st << "eof "; return st.str(); } TEST(iostream_test, write_buffer_states_test) { RwLoopBuffer rw; OutStream st(rw, 10); string s1 = "This is a test", s2 = " of the stream bit stuff."; cout << "***OutStream test" << endl; cout << "Before " << printstate(st.rdstate()) << endl; ASSERT_EQ(st.rdstate(), 0); st << s1; cout << "write '"<<s1<<"' string: '" << rw.str() << "' " << printstate(st.rdstate()) << endl; ASSERT_EQ(st.rdstate(), 0); ASSERT_EQ(rw.str(), s1.substr(0, 10)); st.setstate(std::ios_base::eofbit); cout << "seteof string: '" << rw.str() << "' " << printstate(st.rdstate()) << endl; ASSERT_EQ(st.rdstate(), std::ios_base::eofbit); st << s2; cout << "write '"<<s2<<"' string: '" << rw.str() << "' " << printstate(st.rdstate()) << endl; ASSERT_EQ(st.rdstate(), std::ios_base::eofbit|std::ios_base::failbit); ASSERT_EQ(rw.str(), s1.substr(0, 10)); st.clear(); cout << "clear string: '" << rw.str() << "' " << printstate(st.rdstate()) << endl; st << s2; cout << "write '"<<s2<<"' string: '" << rw.str() << "' " << printstate(st.rdstate()) << endl; st.flush(); cout << "flush string: '" << rw.str() << "' " << printstate(st.rdstate()) << endl; ASSERT_EQ(st.rdstate(), 0); ASSERT_EQ(rw.str(), s1+s2); } TEST(iostream_test, move_assign) { RwLoopBuffer rw; IoStream io1(rw, rw); io1 << "test"; io1.flush(); IoStream io2 = std::move(io1); string s; io2 >> s; cout << "got: " << s << endl; ASSERT_EQ(s, "test"); } TEST(iostream_test, move_moveconstruct) { RwLoopBuffer rw; IoStream io1(rw, rw); io1 << "test"; io1.flush(); IoStream io2(std::move(io1)); string s; io2 >> s; cout << "got: " << s << endl; ASSERT_EQ(s, "test"); } TEST(instream_test, move_assign) { RwLoopBuffer rw("test"); InStream in1(rw); InStream in2 = std::move(in1); string s; in2 >> s; cout << "got: " << s << endl; ASSERT_EQ(s, "test"); } TEST(instream_test, move_construct) { RwLoopBuffer rw("test"); InStream in1(rw); InStream in2(std::move(in1)); string s; in2 >> s; cout << "got: " << s << endl; ASSERT_EQ(s, "test"); } TEST(outstream_test, move_assign) { RwLoopBuffer rw; OutStream ou1(rw); OutStream ou2 = std::move(ou1); ou2 << "test"; ou2.flush(); cout << "got: " << rw.str() << endl; ASSERT_EQ(rw.str(), "test"); } TEST(outstream_test, move_construct) { RwLoopBuffer rw; OutStream ou1(rw); OutStream ou2(std::move(ou1)); ou2 << "test"; ou2.flush(); cout << "got: " << rw.str() << endl; ASSERT_EQ(rw.str(), "test"); } TEST(fail_test, outstream_except) { string line("test"); struct ExReader : public Reader { bool fail; ExReader() : fail(true) {} size_t read(void* loc, size_t len) { if (fail) throw std::runtime_error("test"); return len; } }; struct ExWriter : public Writer { bool fail; ExWriter() : fail(true) {} size_t write(const void*, size_t len) { if (fail) throw std::runtime_error("test"); return len; } }; ExReader rd; ExWriter wr; InStream is(rd); OutStream os(wr); IoStream io(rd, wr); is.read((char*)line.data(), 4); ASSERT_TRUE(is.fail()); ASSERT_EQ(is.rdstate() & ios::badbit, ios::badbit); ASSERT_EQ(is.recv_fail(), "test"); is.clear(); ASSERT_EQ(is.recv_fail(), ""); rd.fail = false; is.read((char*)line.data(), 4); ASSERT_FALSE(is.fail()); ASSERT_EQ(is.recv_fail(), ""); os << "test"; os.flush(); ASSERT_TRUE(os.fail()); ASSERT_EQ(os.rdstate() & ios::badbit, ios::badbit); ASSERT_EQ(os.send_fail(), "test"); os.clear(); ASSERT_EQ(os.send_fail(), ""); wr.fail = false; os << "test"; os.flush(); ASSERT_FALSE(os.fail()); ASSERT_EQ(os.send_fail(), ""); io.clear(); rd.fail = true; wr.fail = true; io.read((char*)line.data(), 4); io << "test"; io.flush(); ASSERT_TRUE(io.fail()); ASSERT_EQ(io.rdstate() & ios::badbit, ios::badbit); ASSERT_EQ(io.send_fail(), ""); ASSERT_EQ(io.recv_fail(), "test"); io.clear(); io << "test"; io.flush(); io.read((char*)line.data(), 4); ASSERT_TRUE(io.fail()); ASSERT_EQ(io.send_fail(), "test"); ASSERT_EQ(io.recv_fail(), ""); io.clear(); rd.fail = false; wr.fail = false; io << "test"; io.flush(); io.read((char*)line.data(), 4); ASSERT_FALSE(io.fail()); ASSERT_EQ(io.send_fail(), ""); ASSERT_EQ(io.recv_fail(), ""); } TEST(shared_ptr_test, shared_io) { std::shared_ptr<RwLoopBuffer> buf(new RwLoopBuffer); IoStream io(buf, buf); for (char ch : test_long) io.put(ch); io.flush(); ASSERT_EQ(test_long, buf->str()); string got; for (char ch; io.get(ch);) got.push_back(ch); ASSERT_EQ(test_long, got); cout << "io buf references: " << buf.use_count() << endl; ASSERT_EQ(buf.use_count(), 3); } TEST(shared_ptr_test, shared_in) { std::shared_ptr<RwLoopBuffer> buf(new RwLoopBuffer); InStream io(buf); buf->set(test_long.data(), test_long.size()); string got; for (char ch; io.get(ch);) got.push_back(ch); ASSERT_EQ(test_long, got); cout << "in buf references: " << buf.use_count() << endl; ASSERT_EQ(buf.use_count(), 2); } TEST(shared_ptr_test, shared_out) { std::shared_ptr<RwLoopBuffer> buf(new RwLoopBuffer); OutStream io(buf); for (char ch : test_long) io.put(ch); io.flush(); ASSERT_EQ(test_long, buf->str()); cout << "out buf references: " << buf.use_count() << endl; ASSERT_EQ(buf.use_count(), 2); } TEST(basic_stream_test, sync_n_flush) { RwLoopBuffer buf; RwCounter count(buf, buf); IoStream io(count, count, 10, 10); for (unsigned i = 0; i < 7; i++) io.put(test_long[i]); cout << "partial put buf size: " << buf.size() << endl; cout << "partial put idx: " << buf.idx() << endl; // ASSERT_TRUE(buf.empty()); // ASSERT_EQ(buf.idx(), 0); io.flush(); // flush the write buffer cout << "partial write buf size: " << buf.size() << endl; cout << "partial write idx: " << buf.idx() << endl; // ASSERT_EQ(buf.str(), test_long.substr(0, 7)); // ASSERT_EQ(buf.idx(), 0); for (unsigned i = 7; i < test_long.size(); i++) io.put(test_long[i]); io.flush(); cout << "full write buf size: " << buf.size() << endl; cout << "full write idx: " << buf.idx() << endl; // ASSERT_EQ(buf.str(), test_long); // ASSERT_EQ(buf.idx(), 0); string got; char ch; for (unsigned i = 0; i < 7 && io.get(ch); i++) got.push_back(ch); cout << "partial read got: " << got << endl; cout << "partial read buf size: " << buf.size() << endl; cout << "partial read idx: " << buf.idx() << endl; io.sync(); // sync the read buffer for (unsigned i = 0; i < 2 && io.get(ch); i++) got.push_back(ch); cout << "sync & read 2 more got: " << got << endl; cout << "sync & read 2 more buf size: " << buf.size() << endl; cout << "sync & read 2 more idx: " << buf.idx() << endl; while (io.get(ch)) got.push_back(ch); cout << "full read got: " << got << endl; cout << "full read buf size: " << buf.size() << endl; cout << "full read idx: " << buf.idx() << endl; }
25.365031
126
0.649837
stablecc
cc5684e092292d8ad5f042a20f9f0c835fd1938b
863
cpp
C++
Baekjoon/2098.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/2098.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/2098.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> using namespace std; const int INF = 1e9; int N; vector<vector<int> > W; vector<vector<int> > dp; int TSP(int cur, int visited) { int ret = dp[cur][visited]; if (ret != 0) return ret; if (visited == (1 << N) - 1) { if (W[cur][0] != 0) return W[cur][0]; return INF; } ret = INF; for (int i = 0; i < N; i++) { if (visited & (1 << i) || W[cur][i] == 0) continue; int sub = TSP(i, visited | (1 << i)) + W[cur][i]; ret = ret < sub ? ret : sub; } dp[cur][visited] = ret; return ret; } int main(void) { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(false); cin >> N; W = vector<vector<int> >(N, vector<int>(N)); dp = vector<vector<int> >(N, vector<int>(1 << N, 0)); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) cin >> W[i][j]; cout << TSP(0, 1); }
17.612245
54
0.537659
Twinparadox
7fde3da7497c8b023c3281fcd01f899d9fdfd495
323
hpp
C++
library/ATF/CPageSetupDialog.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/CPageSetupDialog.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/CPageSetupDialog.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CCommonDialog.hpp> #include <tagPSDA.hpp> START_ATF_NAMESPACE struct CPageSetupDialog : CCommonDialog { tagPSDA m_psd; }; END_ATF_NAMESPACE
21.533333
108
0.736842
lemkova
7fe573db8c51212b03c5026a081fb67862125d1a
4,701
cpp
C++
examples/triangleTesselation.cpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
1
2016-11-15T09:04:12.000Z
2016-11-15T09:04:12.000Z
examples/triangleTesselation.cpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
null
null
null
examples/triangleTesselation.cpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 maldicion069 * * Authors: Cristian Rodríguez Bernal <[email protected]> * * This file is part of MonkeyBrushPlusPlus * <https://github.com/maldicion069/monkeybrushplusplus> * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3.0 as published * by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <iostream> #include <mb/mb.h> mb::ScenePtr scene; void renderFunc( float dt ); class ChangeTessLevelComponent : public mb::Component { public: ChangeTessLevelComponent( const float& tessLevel ) : mb::Component( ) , _tessLevel( tessLevel ) { } virtual void fixedUpdate( const float& ) override { if ( mb::Input::isKeyPressed( mb::Keyboard::Key::Plus ) ) { _tessLevel += 0.1f; getNode( )->getMesh( )->getMaterial( )->uniform( "tess_level" )->value( _tessLevel ); } else if ( mb::Input::isKeyPressed( mb::Keyboard::Key::Minus ) ) { _tessLevel -= 0.1f; getNode( )->getMesh( )->getMaterial( )->uniform( "tess_level" )->value( _tessLevel ); } } protected: float _tessLevel; }; int main(void) { mb::GLContext context( 4, 4, 1024, 768, "Triangle tesselation" ); auto engine = std::make_shared<mb::Engine>( &context, false ); scene = std::make_shared<mb::Scene>( engine, new mb::SimpleCamera( mb::Vect3( 0.2f, 0.18f, 8.44f ) ) ); mb::DrawablePtr model = std::make_shared<mb::Tetrahedron>( 1.0f ); std::vector<std::pair<mb::ShaderType, const char*> > shaders = { { mb::VertexShader, R"( #version 440 layout(location = 0) in vec3 position; uniform mat4 projection; uniform mat4 view; uniform mat4 model; void main( void ) { gl_Position = projection * view * model * vec4(position, 1.0f); } )" }, { mb::TesselationControlShader, R"( #version 440 layout (vertices = 3) out; uniform float tess_level; #define ID gl_InvocationID void main(void) { if (ID == 0) { gl_TessLevelInner[0] = tess_level; gl_TessLevelOuter[0] = tess_level; gl_TessLevelOuter[1] = tess_level; gl_TessLevelOuter[2] = tess_level; } gl_out[ID].gl_Position = gl_in[ID].gl_Position; } )" }, { mb::TesselationEvaluationShader, R"( #version 440 layout (triangles) in; void main(void) { gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position) + (gl_TessCoord.y * gl_in[1].gl_Position) + (gl_TessCoord.z * gl_in[2].gl_Position); } )" }, { mb::FragmentShader, R"( #version 440 out vec4 fragColor; uniform vec3 color; void main( void ) { fragColor = vec4(color, 1.0); } )" } }; float tess_level = 2.0f; std::vector<std::pair<const char*, mb::Uniform*> > uniforms = { std::make_pair( "projection", new mb::Uniform( mb::Matrix4 ) ), std::make_pair( "view", new mb::Uniform( mb::Matrix4 ) ), std::make_pair( "model", new mb::Uniform( mb::Matrix4 ) ), std::make_pair( "color", new mb::Uniform( mb::Vector3, mb::Vect3( mb::Color3::Pink ) ) ), std::make_pair( "tess_level", new mb::Uniform( mb::Float, tess_level ) ) }; mb::ShaderMaterialPtr material = std::make_shared<mb::ShaderMaterial>( "triangleTesselation", shaders, uniforms ); material->Cull = false; material->PolygonMode = GL_LINE; mb::NodePtr mbNode = std::make_shared<mb::Node>( std::string( "model" ) ); // Same as MeshRenderer(model, &material, GL_PATCHES) mbNode->addComponent( std::make_shared<mb::MeshRendererTesselation>( model, material ) ); mbNode->addComponent( std::make_shared<mb::ChangeTransformationComponent>( ) ); mbNode->addComponent( std::make_shared<mb::MoveComponent>( ) ); mbNode->addComponent( std::make_shared<ChangeTessLevelComponent>( tess_level ) ); scene->root( )->addChild( mbNode ); engine->run( renderFunc ); return 0; } void renderFunc( float dt ) { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); scene->render( dt ); }
29.753165
91
0.633057
maldicion069
7fe64908148936a470b6d209a967c22820589f1d
295
cpp
C++
Week 1 May 1st to May 7th/numberComplement.cpp
huynhtruc0309/May-LeetCoding-Challenge
958de292527ff15502af495c695d17f10eedd697
[ "MIT" ]
16
2020-05-06T14:56:33.000Z
2020-05-10T17:32:16.000Z
Week 1 May 1st to May 7th/numberComplement.cpp
huynhtruc0309/May-LeetCoding-Challenge
958de292527ff15502af495c695d17f10eedd697
[ "MIT" ]
null
null
null
Week 1 May 1st to May 7th/numberComplement.cpp
huynhtruc0309/May-LeetCoding-Challenge
958de292527ff15502af495c695d17f10eedd697
[ "MIT" ]
1
2020-05-17T09:31:30.000Z
2020-05-17T09:31:30.000Z
class Solution { public: int findComplement(int num) { int result = 0; int i = 0; while(num) { if ((num & 1) == 0) result += 1 << i; i += 1; num >>= 1; } return result; } };
18.4375
33
0.332203
huynhtruc0309
7fea0a7772e523c1b08eb7d4330533cfc1d042f6
3,563
cpp
C++
PJDL/SimpleToken.cpp
szopeno/skeleton-parser-civetweb
440d684675e4446d8e4fea5e333452b36f33614c
[ "MIT" ]
null
null
null
PJDL/SimpleToken.cpp
szopeno/skeleton-parser-civetweb
440d684675e4446d8e4fea5e333452b36f33614c
[ "MIT" ]
null
null
null
PJDL/SimpleToken.cpp
szopeno/skeleton-parser-civetweb
440d684675e4446d8e4fea5e333452b36f33614c
[ "MIT" ]
null
null
null
#include "SimpleToken.h" #include <stdlib.h> #include <stdio.h> #include <string.h> SimpleToken::SimpleToken() : indent(-1), _level(0), isInt(false) { value[0] = 0; numValue = 0; } //const char *const str ? SimpleToken::SimpleToken(const char str[]) { int i; //long *dst = (long *)value,*src = (long *) str; for (i=0;str[i];i++) value[i]=str[i]; value[i]=0; /* for (i=0;i<(MAX_LITERAL_SIZE/(sizeof(long)));i++) { dst[i]=src[i]; } dst[i]=0; */ numValue = 0; } SimpleToken *SimpleToken::createKey(char const val[]) { SimpleToken *t = new SimpleToken(val); t->basicTokenType = T_KEY; return t; } SimpleToken *SimpleToken::createString(char const val[]) { SimpleToken *t = new SimpleToken(val); t->basicTokenType = T_STRING; return t; } SimpleToken *SimpleToken::createAttrib(char const val[]) { SimpleToken *t = new SimpleToken(val); t->basicTokenType = T_ATTRIB; return t; } SimpleToken *SimpleToken::createVar(char const val[]) { SimpleToken *t = new SimpleToken(val); t->basicTokenType = T_VAR; return t; } SimpleToken *SimpleToken::createNumber(char const val[], bool isInt) { SimpleToken *t = new SimpleToken(); t->basicTokenType = T_NUMBER; t->numValue = strtold(val,0); t->isInt = isInt; snprintf(t->value, MAX_LITERAL_SIZE-1, "%.8lf", t->numValue); return t; } SimpleToken *SimpleToken::createOper(const char val) { SimpleToken *t = new SimpleToken(); t->value[0] = val; t->value[1] = 0; t->basicTokenType = T_OPER; return t; } SimpleToken *SimpleToken::createEOF() { SimpleToken *t = new SimpleToken(); t->value[0] = 4; t->value[1] = 0; t->basicTokenType = T_EOF; return t; } std::string SimpleToken::toString() const { switch ( basicTokenType ) { case T_OPER: return std::string("operator<")+std::string(value)+std::string(">"); case T_KEY: return std::string("keyword<")+std::string(value)+std::string(">"); case T_STRING: return std::string("string<")+std::string(value)+std::string(">"); case T_NUMBER: return std::string("number<")+std::string(value)+std::string(">"); case T_ATTRIB: return std::string("attrib<")+std::string(value)+std::string(">"); case T_VAR: return std::string("var<")+std::string(value)+std::string(">"); case T_EOF: return std::string("eof<")+std::string(value)+std::string(">"); } return std::string("unknown<")+std::string(value)+std::string(">"); } std::string SimpleToken::stringValue() const { return std::string(value); } void SimpleToken::setString( std::string val) { strncpy( value, val.c_str(), MAX_LITERAL_SIZE); } void SimpleToken::setNumber(double n) { numValue = n; snprintf(value, MAX_LITERAL_SIZE-1, "%.8lf", numValue); } std::string SimpleToken::fieldsStr() const { char tmpi[32], tmpl[32], tmpf[32],tmpp[32]; snprintf(tmpi,32,"%d", indent); snprintf(tmpl,32,"%d", _level); snprintf(tmpf,32,"%d", fileLine); snprintf(tmpp,32,"%d", filePos); return std::string("[ ") + std::string(source) + std::string(" ") + \ std::string( tmpf) + std::string( ":" ) + std::string( tmpi ) + \ std::string( " (") + std::string( tmpp ) + std::string(") ") + \ std::string( "" ) + std::string( first?"true ":"false ") + \ std::string( "L: ") + std::string( tmpl ) + std::string(" ]"); }
25.633094
80
0.588549
szopeno
7ff3641a9471cf5c90711469cde3e63d53daed85
11,978
hpp
C++
src/protocol.hpp
Fingercomp/oc-vremote
db93fd9c246e52b9a7fbcac41ef703135f3d4b10
[ "Apache-2.0" ]
null
null
null
src/protocol.hpp
Fingercomp/oc-vremote
db93fd9c246e52b9a7fbcac41ef703135f3d4b10
[ "Apache-2.0" ]
null
null
null
src/protocol.hpp
Fingercomp/oc-vremote
db93fd9c246e52b9a7fbcac41ef703135f3d4b10
[ "Apache-2.0" ]
null
null
null
#pragma once #include <sstream> #include <string> #include <vector> #include "util.hpp" // We're using uint32_t as uint24_t: // 32-bit integers has the long type using uint24_t = uint32_t; enum NetMessageCode { MSG_ERROR, // = 0 MSG_AUTH_CLIENT, // = 1 MSG_AUTH_SERVER, // = 2 MSG_INITIAL_DATA, // = 3 MSG_SET_BG, // = 4 MSG_SET_FG, // = 5 MSG_SET_PALETTE, // = 6 MSG_SET_RESOLUTION, // = 7 MSG_SET_CHARS, // = 8 MSG_COPY, // = 9 MSG_FILL, // = 10 MSG_TURN_ON_OFF, // = 11 MSG_SET_PRECISE, // = 12 MSG_FETCH, // = 13 MSG_EVENT_TOUCH, // = 14 MSG_EVENT_DRAG, // = 15 MSG_EVENT_DROP, // = 16 MSG_EVENT_SCROLL, // = 17 MSG_EVENT_KEY_DOWN, // = 18 MSG_EVENT_KEY_UP, // = 19 MSG_EVENT_CLIPBOARD, // = 20 MSG_PING, // = 21 MSG_PONG // = 22 }; enum class ConnectionMode { GpuKbd, // = 0 Gpu, // = 1 Kbd, // = 2 Custom // = 3 }; enum class AuthResult { Authenticated, // = 0 WrongCredentials, // = 1 UnsupportedMode // = 2 }; struct Resolution { uint8_t w; uint8_t h; }; struct Char { long c; uint8_t fg; uint8_t bg; }; struct NetMessage { virtual NetMessageCode code() const = 0; }; namespace nmsg { struct NetMessageError: public NetMessage { virtual NetMessageCode code() const { return MSG_ERROR; } std::string description; }; struct NetMessageAuthClient: public NetMessage { virtual NetMessageCode code() const { return MSG_AUTH_CLIENT; } std::string user; std::string password; ConnectionMode connectionMode; uint16_t pingInterval; }; struct NetMessageAuthServer: public NetMessage { virtual NetMessageCode code() const { return MSG_AUTH_SERVER; } AuthResult result; std::string displayString; }; struct NetMessageInitialData: public NetMessage { virtual NetMessageCode code() const { return MSG_INITIAL_DATA; } Palette palette; uint8_t fg; uint8_t bg; Resolution resolution; bool screenState; bool preciseMode; std::vector<Char> chars; }; struct NetMessageSetBG: public NetMessage { virtual NetMessageCode code() const { return MSG_SET_BG; } uint8_t index; }; struct NetMessageSetFG: public NetMessage { virtual NetMessageCode code() const { return MSG_SET_FG; } uint8_t index; }; struct NetMessageSetPalette: public NetMessage { virtual NetMessageCode code() const { return MSG_SET_PALETTE; } Color color; uint8_t index; }; struct NetMessageSetResolution: public NetMessage { virtual NetMessageCode code() const { return MSG_SET_RESOLUTION; } uint8_t w; uint8_t h; }; struct NetMessageSetChars: public NetMessage { virtual NetMessageCode code() const { return MSG_SET_CHARS; } uint8_t x; uint8_t y; std::string chars; bool vertical; }; struct NetMessageCopy: public NetMessage { virtual NetMessageCode code() const { return MSG_COPY; } uint8_t x; uint8_t y; uint8_t w; uint8_t h; uint8_t tx; uint8_t ty; }; struct NetMessageFill: public NetMessage { virtual NetMessageCode code() const { return MSG_FILL; } uint8_t x; uint8_t y; uint8_t w; uint8_t h; long c; }; struct NetMessageTurnOnOff: public NetMessage { virtual NetMessageCode code() const { return MSG_TURN_ON_OFF; } bool on; }; struct NetMessageSetPrecise: public NetMessage { virtual NetMessageCode code() const { return MSG_SET_PRECISE; } bool precise; }; struct NetMessageFetch: public NetMessage { virtual NetMessageCode code() const { return MSG_FETCH; } }; struct NetMessageEventTouch: public NetMessage { virtual NetMessageCode code() const { return MSG_EVENT_TOUCH; } uint8_t x; uint8_t y; uint8_t button; }; struct NetMessageEventDrag: public NetMessage { virtual NetMessageCode code() const { return MSG_EVENT_DRAG; } uint8_t x; uint8_t y; uint8_t button; }; struct NetMessageEventDrop: public NetMessage { virtual NetMessageCode code() const { return MSG_EVENT_DROP; } uint8_t x; uint8_t y; uint8_t button; }; struct NetMessageEventScroll: public NetMessage { virtual NetMessageCode code() const { return MSG_EVENT_SCROLL; } uint8_t x; uint8_t y; bool direction; uint8_t delta; }; struct NetMessageEventKeyDown: public NetMessage { virtual NetMessageCode code() const { return MSG_EVENT_KEY_DOWN; } long chr; long cod; }; struct NetMessageEventKeyUp: public NetMessage { virtual NetMessageCode code() const { return MSG_EVENT_KEY_UP; } long chr; long cod; }; struct NetMessageEventClipboard: public NetMessage { virtual NetMessageCode code() const { return MSG_EVENT_CLIPBOARD; } std::string data; }; struct NetMessagePing: public NetMessage { virtual NetMessageCode code() const { return MSG_PING; } uint64_t ping; }; struct NetMessagePong: public NetMessage { virtual NetMessageCode code() const { return MSG_PONG; } uint64_t pong; }; } std::stringstream& pack(std::stringstream &result, const long data); std::stringstream& pack(std::stringstream &result, const uint24_t data); std::stringstream& pack(std::stringstream &result, const uint16_t data); std::stringstream& pack(std::stringstream &result, const uint8_t data); std::stringstream& pack(std::stringstream &result, const std::string &data); std::stringstream& pack(std::stringstream &result, const NetMessageCode data); std::stringstream& pack(std::stringstream &result, const ConnectionMode data); std::stringstream& pack(std::stringstream &result, const AuthResult data); std::stringstream& pack(std::stringstream &result, const Resolution &data); std::stringstream& pack(std::stringstream &result, const bool data); std::stringstream& pack(std::stringstream &result, const Char &data); std::stringstream& pack(std::stringstream &result, const Color &color); template <typename T> std::stringstream& pack(std::stringstream &result, const std::vector<T> &data) { pack(result, static_cast<uint24_t>(data.size())); for (auto i: data) { pack(result, i); } return result; } std::stringstream& pack(std::stringstream &result, const Palette &data); std::stringstream& pack(std::stringstream &result, const uint64_t data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageError &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageAuthClient &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageAuthServer &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageInitialData &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetBG &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetFG &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetPalette &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetResolution &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetChars &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageCopy &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageFill &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageTurnOnOff &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetPrecise &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageFetch &); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventTouch &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventDrag &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventDrop &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventScroll &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventKeyDown &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventKeyUp &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventClipboard &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessagePing &data); std::stringstream& pack(std::stringstream &result, const nmsg::NetMessagePong &data); void unpack(std::stringstream &str, long &result); void unpack(std::stringstream &str, uint24_t &result); void unpack(std::stringstream &str, uint16_t &result); void unpack(std::stringstream &str, uint8_t &result); void unpack(std::stringstream &str, std::string &result); void unpack(std::stringstream &str, NetMessageCode &result); void unpack(std::stringstream &str, ConnectionMode &result); void unpack(std::stringstream &str, AuthResult &result); void unpack(std::stringstream &str, Resolution &result); void unpack(std::stringstream &str, bool &result); void unpack(std::stringstream &str, Char &result); void unpack(std::stringstream &str, Color &result); void unpack(std::stringstream &str, Palette &result); void unpack(std::stringstream &str, uint64_t &result); template <typename T> void unpack(std::stringstream &str, std::vector<T> &result) { uint24_t len; unpack(str, len); for (uint24_t i = 0; i < len; ++i) { T element; unpack(str, element); result.push_back(element); } } void unpack(std::stringstream &str, nmsg::NetMessageError &result); void unpack(std::stringstream &str, nmsg::NetMessageAuthClient &result); void unpack(std::stringstream &str, nmsg::NetMessageAuthServer &result); void unpack(std::stringstream &str, nmsg::NetMessageInitialData &result); void unpack(std::stringstream &str, nmsg::NetMessageSetBG &result); void unpack(std::stringstream &str, nmsg::NetMessageSetFG &result); void unpack(std::stringstream &str, nmsg::NetMessageSetPalette &result); void unpack(std::stringstream &str, nmsg::NetMessageSetResolution &result); void unpack(std::stringstream &str, nmsg::NetMessageSetChars &result); void unpack(std::stringstream &str, nmsg::NetMessageCopy &result); void unpack(std::stringstream &str, nmsg::NetMessageFill &result); void unpack(std::stringstream &str, nmsg::NetMessageTurnOnOff &result); void unpack(std::stringstream &str, nmsg::NetMessageSetPrecise &result); void unpack(std::stringstream &, nmsg::NetMessageFetch &); void unpack(std::stringstream &str, nmsg::NetMessageEventTouch &result); void unpack(std::stringstream &str, nmsg::NetMessageEventDrag &result); void unpack(std::stringstream &str, nmsg::NetMessageEventDrop &result); void unpack(std::stringstream &str, nmsg::NetMessageEventScroll &result); void unpack(std::stringstream &str, nmsg::NetMessageEventKeyDown &result); void unpack(std::stringstream &str, nmsg::NetMessageEventKeyUp &result); void unpack(std::stringstream &str, nmsg::NetMessageEventClipboard &result); void unpack(std::stringstream &str, nmsg::NetMessagePing &result); void unpack(std::stringstream &str, nmsg::NetMessagePong &result);
32.726776
95
0.67098
Fingercomp
7ff9bb86d836248aba8bbdfc0129cbcba4e251a2
518
hpp
C++
protean/detail/sequence.hpp
proteanic/protean
dcbb0d0d2da708dd7f524124e64a8085ccb8b9e5
[ "BSL-1.0" ]
2
2017-11-08T19:40:50.000Z
2017-11-24T18:43:09.000Z
protean/detail/sequence.hpp
roederja/protean
502cccd10b5721bd74385959362890ec6b5e5d29
[ "BSL-1.0" ]
3
2017-12-20T13:37:00.000Z
2018-12-04T11:31:14.000Z
protean/detail/sequence.hpp
roederja/protean
502cccd10b5721bd74385959362890ec6b5e5d29
[ "BSL-1.0" ]
7
2015-02-11T14:43:16.000Z
2020-06-20T21:06:38.000Z
#ifndef PROTEAN_DETAIL_SEQUENCE_HPP #define PROTEAN_DETAIL_SEQUENCE_HPP #include <protean/config.hpp> #include <protean/detail/collection.hpp> namespace protean { class variant; namespace detail { class PROTEAN_DECL sequence : public collection { public: virtual const variant& at(size_t index) const = 0; virtual variant& at(size_t index) = 0; }; } // namespace protean::detail } // namespace protean #endif // PROTEAN_DETAIL_SEQUENCE_HPP
19.185185
62
0.671815
proteanic
7ffc2ff07c26e8a54e280caa0d73deff81c874f7
804
cpp
C++
src/1000/1012.cpp14.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
8
2018-04-12T15:54:09.000Z
2020-06-05T07:41:15.000Z
src/1000/1012.cpp14.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
src/1000/1012.cpp14.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
#include <cstdio> using namespace std; const int move_x[4]={1, -1, 0, 0}; const int move_y[4]={ 0, 0, 1, -1}; bool map[51][52]={}, visit[52][52]={}; int count; int dfs(int x, int y) { for(int i=0; i<4; i++) { int nx=x+move_x[i], ny=y+move_y[i]; if(map[nx][ny] && !visit[nx][ny]) visit[nx][ny]=true, dfs(nx, ny); } } int main() { int t, row, col, n; scanf("%d", &t); while(t--) { scanf("%d %d %d", &row, &col, &n); for(int i=1; i<=row; i++) for(int j=1; j<=col; j++) map[i][j]=visit[i][j]=false; while(n--) { int x, y; scanf("%d %d", &x, &y); map[x+1][y+1]=true; } for(int i=1; i<=row; i++) for(int j=1; j<=col; j++) { if(map[i][j] && !visit[i][j]) visit[i][j]=true, count++, dfs(i, j); } printf("%d\n", count); count=0; } return 0; }
17.106383
42
0.483831
upple
7fff156a502f4205f09f91f15687ebf7d3debff8
7,055
cpp
C++
calculation/BigInt/SignedBigInt.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
calculation/BigInt/SignedBigInt.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
calculation/BigInt/SignedBigInt.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
struct SignedBigInt { bool is_minus; UnsignedBigInt absVal; SignedBigInt() : is_minus(false) {} explicit SignedBigInt(int num) : absVal(std::abs(num)), is_minus(num < 0) {} explicit SignedBigInt(LL num) : absVal(std::abs(num)), is_minus(num < 0) {} explicit SignedBigInt(const string& num) { if(!isdigit(num[0])) { is_minus = (num[0] == '-'); absVal = num.c_str() + 1; } else { is_minus = false; absVal = num; } } explicit SignedBigInt(const UnsignedBigInt& val) : absVal(val), is_minus(false) {} explicit operator int() { return is_minus ? -(int)absVal : (int)absVal; } explicit operator double() const { return is_minus ? -(double)absVal : (double)absVal; } explicit operator string() const { string ans; if (absVal.s.empty()) { ans = '0'; } else { if (is_minus) ans += '-'; ans += (string)absVal; } return ans; } explicit operator bool() const { return !absVal.s.empty(); } explicit operator int() const { return absVal.s.empty() ? 0 : (is_minus ? -absVal.s[0] : absVal.s[0]); } SignedBigInt& operator = (const int num) { return (*this = SignedBigInt(num)); } SignedBigInt& operator = (const string& num) { return (*this = SignedBigInt(num)); } bool operator == (const SignedBigInt& b) const { return absVal.s.empty() && b.absVal.s.empty() ? 1 : (is_minus != b.is_minus ? 0 : absVal == b.absVal); } bool operator < (const SignedBigInt& b) const { return absVal.s.empty() && b.absVal.s.empty() ? 0 : (is_minus != b.is_minus ? is_minus : (is_minus ? b.absVal < absVal : absVal < b.absVal)); } bool operator <= (const SignedBigInt& b) const { return *this < b || *this == b; } bool operator > (const SignedBigInt& b) const { return b < *this; } bool operator >= (const SignedBigInt& b) const { return b <= *this; } bool operator != (const SignedBigInt& b) const { return !(*this == b); } bool operator == (int b) const { return (b < 0) ^ is_minus ? (absVal.s.empty() && b == 0) : absVal == UnsignedBigInt(std::abs(b)); } bool operator < (int b) const { return absVal.s.empty() ? b > 0 : ((b < 0) ^ is_minus ? is_minus : (is_minus ? -b < absVal : absVal < b)); } bool operator <= (int rhs) const { return *this < rhs || *this == rhs; } bool operator > (int rhs) const { return !(*this <= rhs); } bool operator >= (int rhs) const { return !(*this < rhs); } bool operator != (int rhs) const { return !(*this == rhs); } SignedBigInt& AddEq(bool b_is_minus, const UnsignedBigInt& b_absVal) { if(is_minus ^ b_is_minus)//different sign { if(absVal < b_absVal) { absVal = b_absVal - absVal; is_minus = b_is_minus; } else absVal -= b_absVal; } else absVal += b_absVal; return *this; } SignedBigInt& operator += (const SignedBigInt& b) { return AddEq(b.is_minus, b.absVal); } SignedBigInt operator + (const SignedBigInt& b) const { SignedBigInt ans = *this; return ans += b; } //SignedBigInt& AddEq(bool b_is_minus, const UnsignedBigInt& b_absVal) SignedBigInt& operator -= (const SignedBigInt& b) { return AddEq(!b.is_minus, b.absVal); } SignedBigInt operator - (const SignedBigInt& b) const { return SignedBigInt(*this) -= b; } SignedBigInt operator - () const { SignedBigInt ans; ans.is_minus = !is_minus; ans.absVal = absVal; return ans; } SignedBigInt operator * (const SignedBigInt& b) const { SignedBigInt ans; ans.is_minus = is_minus ^ b.is_minus; ans.absVal = absVal * b.absVal; return ans; } SignedBigInt& operator *= (const SignedBigInt& b) { return *this = *this * b; } SignedBigInt operator / (const SignedBigInt& b) const { SignedBigInt ans; ans.is_minus = is_minus ^ b.is_minus; ans.absVal = absVal / b.absVal; return ans; } SignedBigInt& operator /= (const SignedBigInt& b) { return *this = *this / b; } SignedBigInt operator % (const SignedBigInt& b) const { SignedBigInt ans; ans.is_minus = is_minus; ans.absVal = absVal % b.absVal; return ans; } SignedBigInt& operator %= (const SignedBigInt& b) { return *this = *this % b; } SignedBigInt abs() const { return SignedBigInt(absVal); } SignedBigInt& operator += (int rhs) { if (is_minus ^ (rhs<0)) { if (absVal >= rhs) { absVal -= rhs; } else { absVal = UnsignedBigInt(rhs - absVal); is_minus = !is_minus; } } else { absVal += rhs; } return *this; } SignedBigInt& operator ++ () { return *this += 1; } SignedBigInt operator + (int rhs) { SignedBigInt ans = *this; return ans += rhs; } SignedBigInt& operator -= (int rhs) { if (rhs >= 0) { if (is_minus) { absVal += rhs; } else { absVal -= rhs; } } else { absVal += -rhs; } return *this; } SignedBigInt& operator -- () { return *this -= 1; } SignedBigInt operator - (int rhs) { SignedBigInt ans = *this; return ans -= rhs; } SignedBigInt& operator *= (int rhs) { if (rhs < 0) { is_minus = !is_minus; rhs = -rhs; } absVal *= rhs; return *this; } SignedBigInt operator * (int rhs) { SignedBigInt ans = *this; return ans *= rhs; } SignedBigInt& operator /= (int rhs) { assert(rhs); if (rhs < 0) { is_minus = !is_minus; rhs = -rhs; } absVal /= rhs; return *this; } SignedBigInt operator / (int rhs) { SignedBigInt ans = *this; return ans /= rhs; } int operator % (int rhs) { int ans = absVal % std::abs(rhs); return is_minus ? -ans : ans; } SignedBigInt& operator %= (int rhs) { absVal %= std::abs(rhs); return *this; } }; ostream& operator << (ostream& out, const SignedBigInt& a) { return out << string(a); } istream& operator >> (istream& in, SignedBigInt& a) { string str; if (in >> str) a = str; return in; } SignedBigInt sqrt(const SignedBigInt& x, int m) { assert(!x.is_minus); return SignedBigInt(sqrt(x.absVal, m)); }
26.03321
149
0.514245
searchstar2017
3d013b42ee6c78efc856be9afffc62665f89f08d
15,394
cpp
C++
src/Core/DS_Config.cpp
WinT-3794/libDS
87ae5b3018e968bfb932d6cb8929e9ffefb273ab
[ "MIT" ]
12
2015-09-21T03:05:57.000Z
2016-04-27T17:46:41.000Z
src/Core/DS_Config.cpp
WinT-3794/LibDS
87ae5b3018e968bfb932d6cb8929e9ffefb273ab
[ "MIT" ]
null
null
null
src/Core/DS_Config.cpp
WinT-3794/LibDS
87ae5b3018e968bfb932d6cb8929e9ffefb273ab
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 Alex Spataru <[email protected]> * * This file is part of the LibDS, which is released under the MIT license. * For more information, please read the LICENSE file in the root directory * of this project. */ #include "DS_Config.h" #include "DriverStation.h" #include <QThread> #include <QElapsedTimer> #include <Core/Logger.h> DS_Config::DS_Config() { m_timer = new QElapsedTimer; m_logger = new Logger; m_team = 0; m_voltage = 0; m_cpuUsage = 0; m_ramUsage = 0; m_diskUsage = 0; m_libVersion = ""; m_pcmVersion = ""; m_pdpVersion = ""; m_simulated = false; m_timerEnabled = false; m_position = kPosition1; m_alliance = kAllianceRed; m_codeStatus = kCodeFailing; m_operationStatus = kNormal; m_fmsCommStatus = kCommsFailing; m_enableStatus = kDisabled; m_voltageStatus = kVoltageNormal; m_radioCommStatus = kCommsFailing; m_robotCommStatus = kCommsFailing; m_controlMode = kControlTeleoperated; /* Move the robot logger to another thread */ QThread* thread = new QThread (this); m_logger->moveToThread (thread); thread->start (QThread::NormalPriority); /* Begin elapsed time loop */ updateElapsedTime(); } /** * Returns the instance of the robot logger object */ Logger* DS_Config::logger() { return m_logger; } /** * Returns the one and only instance of */ DS_Config* DS_Config::getInstance() { static DS_Config instance; return &instance; } /** * Returns the current team number */ int DS_Config::team() const { return m_team; } /** * Returns the current CPU usage of the robot (0 - 100) */ int DS_Config::cpuUsage() const { return m_cpuUsage; } /** * Returns the current RAM usage of the robot */ int DS_Config::ramUsage() const { return m_ramUsage; } /** * Returns the current disk usage of the robot */ int DS_Config::diskUsage() const { return m_diskUsage; } /** * Returns the current voltage of the robot */ qreal DS_Config::voltage() const { if (isConnectedToRobot()) return m_voltage; return 0; } /** * Returns \c true if the robot is enabled. Otherwise, it returns \c false */ bool DS_Config::isEnabled() const { return enableStatus() == DS::kEnabled; } /** * Returns \c true if the robot is simulated. Otherwise, it returns \c false */ bool DS_Config::isSimulated() const { return m_simulated; } /** * Returns the current alliance of the robot (be it user-set or FMS-set) */ DS::Alliance DS_Config::alliance() const { return m_alliance; } /** * Returns the current position of the robot (be it user-set or FMS-set) */ DS::Position DS_Config::position() const { return m_position; } /** * Returns \c true if the Driver Station is connected to the Field Management * System (FMS). */ bool DS_Config::isFMSAttached() const { return fmsCommStatus() == DS::kCommsWorking; } /** * Returns the library version of the robot */ QString DS_Config::libVersion() const { return m_libVersion; } /** * Returns the PCM version of the robot */ QString DS_Config::pcmVersion() const { return m_pcmVersion; } /** * Returns the PDP version of the robot */ QString DS_Config::pdpVersion() const { return m_pdpVersion; } /** * Returns \c true if the robot is emergency stopped. Otherwise, it returns * \c false. */ bool DS_Config::isEmergencyStopped() const { return operationStatus() == DS::kEmergencyStop; } /** * Returns \c true if the robot code is running. Otherwise, it returns \c false */ bool DS_Config::isRobotCodeRunning() const { return robotCodeStatus() == DS::kCodeRunning; } /** * Returns \c true if the Driver Station is connected to the radio. Otherwise, * it returns \c false */ bool DS_Config::isConnectedToRadio() const { return radioCommStatus() == DS::kCommsWorking; } /** * Returns \c true if the Driver Station is connected to the robot. Otherwise, * it returns \c false */ bool DS_Config::isConnectedToRobot() const { return robotCommStatus() == DS::kCommsWorking; } /** * Returns the current control mode of the robot */ DS::ControlMode DS_Config::controlMode() const { return m_controlMode; } /** * Returns the current status of the FMS communications. * \note You can also use the \c isConnectedToFMS() function */ DS::CommStatus DS_Config::fmsCommStatus() const { return m_fmsCommStatus; } /** * Returns the current enabled status of the robot * \note You can also use the \c isEnabled() function */ DS::EnableStatus DS_Config::enableStatus() const { return m_enableStatus; } /** * Returns the current status of the radio communications * \note You can also use the \c isConnectedToRadio() function */ DS::CommStatus DS_Config::radioCommStatus() const { return m_radioCommStatus; } /** * Returns the current status of the robot communications * \note You can also use the \c isConnectedToRobot() function */ DS::CommStatus DS_Config::robotCommStatus() const { return m_robotCommStatus; } /** * Returns the current status of the robot code * \note You can also use the \c isRobotCodeRunning() function */ DS::CodeStatus DS_Config::robotCodeStatus() const { return m_codeStatus; } /** * Returns the current voltage brownout status of the robot. */ DS::VoltageStatus DS_Config::voltageStatus() const { return m_voltageStatus; } /** * Returns the current operation status of the robot. * \note You can also use the \c isEmergencyStopped() function */ DS::OperationStatus DS_Config::operationStatus() const { return m_operationStatus; } /** * Changes the \a team number and fires the appropriate signals if required */ void DS_Config::updateTeam (int team) { if (m_team != team) { m_team = team; emit teamChanged (m_team); qDebug() << "Team number set to" << team; } } /** * Changes the robot \a code status and fires the appropriate signals if * required */ void DS_Config::setRobotCode (bool code) { DS::CodeStatus status = DS::kCodeFailing; if (code) status = DS::kCodeRunning; updateRobotCodeStatus (status); } /** * Changes the \a enabled status and fires the appropriate signals if required */ void DS_Config::setEnabled (bool enabled) { DS::EnableStatus status = DS::kDisabled; if (enabled) status = DS::kEnabled; updateEnabled (status); } /** * Changes the CPU \a usage and fires the appropriate signals if required */ void DS_Config::updateCpuUsage (int usage) { m_cpuUsage = 0; emit cpuUsageChanged (usage); } /** * Changes the RAM \a usage and fires the appropriate signals if required */ void DS_Config::updateRamUsage (int usage) { m_ramUsage = 0; emit ramUsageChanged (usage); } /** * Changes the disk \a usage and fires the appropriate signals if required */ void DS_Config::updateDiskUsage (int usage) { m_diskUsage = 0; emit diskUsageChanged (usage); } /** * Changes the voltage \a brownout status and fires the appropriate signals * if required. */ void DS_Config::setBrownout (bool brownout) { DS::VoltageStatus status = DS::kVoltageNormal; if (brownout) status = DS::kVoltageBrownout; updateVoltageStatus (status); } /** * Changes the \a estop status and fires the appropriate signals if required */ void DS_Config::setEmergencyStop (bool estop) { DS::OperationStatus status = DS::kNormal; if (estop) status = DS::kEmergencyStop; updateOperationStatus (status); } /** * Changes the robot \a voltage and fires the appropriate signals if required */ void DS_Config::updateVoltage (qreal voltage) { /* Round voltage to two decimal places */ m_voltage = roundf (voltage * 100) / 100; /* Avoid this: http://i.imgur.com/iAAi1bX.png */ if (m_voltage > DriverStation::getInstance()->maxBatteryVoltage()) m_voltage = DriverStation::getInstance()->maxBatteryVoltage(); /* Separate voltage into natural and decimal numbers */ int integer = static_cast<int> (m_voltage); int decimal = static_cast<qreal> (m_voltage - integer) * 100; /* Convert the obtained numbers into strings */ QString integer_str = QString::number (integer); QString decimal_str = QString::number (decimal); /* Prepend a 0 to the decimal numbers if required */ if (decimal < 10) decimal_str.prepend ("0"); /* Emit signals */ emit voltageChanged (m_voltage); emit voltageChanged (integer_str + "." + decimal_str + " V"); /* Log robot voltage */ m_logger->registerVoltage (m_voltage); } /** * Changes the \a simulated status and fires the appropriate signals if * required */ void DS_Config::updateSimulated (bool simulated) { m_simulated = simulated; emit simulatedChanged (simulated); } /** * Changes the \a alliance and fires the appropriate signals if required */ void DS_Config::updateAlliance (Alliance alliance) { if (m_alliance != alliance) { m_alliance = alliance; m_logger->registerAlliance (alliance); } emit allianceChanged (m_alliance); } /** * Changes the \a position and fires the appropriate signals if required */ void DS_Config::updatePosition (Position position) { if (m_position != position) { m_position = position; m_logger->registerPosition (position); } emit positionChanged (m_position); } /** * Changes the robot code \a status and fires the appropriate signals if * required */ void DS_Config::updateRobotCodeStatus (CodeStatus status) { if (m_codeStatus != status) { m_codeStatus = status; m_logger->registerCodeStatus (status); } emit codeStatusChanged (m_codeStatus); emit statusChanged (DriverStation::getInstance()->generalStatus()); } /** * Changes the robot control \a mode and fires the appropriate signals if * required */ void DS_Config::updateControlMode (ControlMode mode) { if (m_controlMode != mode) { m_controlMode = mode; m_logger->registerControlMode (mode); } emit controlModeChanged (m_controlMode); emit statusChanged (DriverStation::getInstance()->generalStatus()); } /** * Changes the robot library \a version and fires the appropriate signals if * required */ void DS_Config::updateLibVersion (const QString& version) { if (m_libVersion != version) { m_libVersion = version; qDebug() << "LIB version set to" << version; } emit libVersionChanged (m_libVersion); } /** * Changes the PCM \a version and fires the appropriate signals if required */ void DS_Config::updatePcmVersion (const QString& version) { if (m_pcmVersion != version) { m_pcmVersion = version; qDebug() << "PCM version set to" << version; } emit pcmVersionChanged (m_pcmVersion); } /** * Changes the PDP/PDB \a version and fires the appropriate signals if required */ void DS_Config::updatePdpVersion (const QString& version) { if (m_pdpVersion != version) { m_pdpVersion = version; qDebug() << "PDP version set to" << version; } emit pdpVersionChanged (m_pdpVersion); } /** * Changes the enabled \a status and fires the appropriate signals if required */ void DS_Config::updateEnabled (EnableStatus status) { if (m_enableStatus != status) { m_enableStatus = status; if (status == DS::kEnabled) { m_timer->restart(); m_timerEnabled = true; } else m_timerEnabled = false; m_logger->registerEnableStatus (status); } emit enabledChanged (m_enableStatus); emit statusChanged (DriverStation::getInstance()->generalStatus()); } /** * Changes the FMS communication \a status and fires the appropriate signals * if required */ void DS_Config::updateFMSCommStatus (CommStatus status) { if (m_fmsCommStatus != status) { m_fmsCommStatus = status; qDebug() << "FMS comm. status set to" << status; } emit fmsCommStatusChanged (m_fmsCommStatus); emit statusChanged (DriverStation::getInstance()->generalStatus()); } /** * Changes the radio communication \a status and fires the appropriate signals * if required */ void DS_Config::updateRadioCommStatus (CommStatus status) { if (m_radioCommStatus != status) { m_radioCommStatus = status; m_logger->registerRadioCommStatus (status); } emit radioCommStatusChanged (m_radioCommStatus); } /** * Changes the robot communication \a status and fires the appropriate signals * if required */ void DS_Config::updateRobotCommStatus (CommStatus status) { if (m_robotCommStatus != status) { m_robotCommStatus = status; m_logger->registerRobotCommStatus (status); } emit robotCommStatusChanged (m_robotCommStatus); emit statusChanged (DriverStation::getInstance()->generalStatus()); } /** * Changes the voltage brownout \a status and fires the appropriate signals * if required */ void DS_Config::updateVoltageStatus (VoltageStatus status) { if (m_voltageStatus != status) { m_voltageStatus = status; m_logger->registerVoltageStatus (status); } emit voltageStatusChanged (m_voltageStatus); emit statusChanged (DriverStation::getInstance()->generalStatus()); } /** * Changes the robot operation \a status and fires the appropriate signals * if required */ void DS_Config::updateOperationStatus (OperationStatus status) { if (m_operationStatus != status) { m_operationStatus = status; updateEnabled (DS::kDisabled); m_logger->registerOperationStatus (status); } emit operationStatusChanged (m_operationStatus); emit statusChanged (DriverStation::getInstance()->generalStatus()); } /** * Calculates the elapsed time since the robot has been enabled (regardless of * the operation mode). * * This function is called every 100 milliseconds. * * \note This function will not run if there is no communication status with * the robot or if the robot is emergency stopped * \note The elapsed time will be resetted when the user changes the control * mode of the robot */ void DS_Config::updateElapsedTime() { if (m_timerEnabled && isConnectedToRobot() && !isEmergencyStopped()) { quint32 msec = m_timer->elapsed(); quint32 secs = (msec / 1000); quint32 mins = (secs / 60) % 60; secs = secs % 60; msec = msec % 1000; emit elapsedTimeChanged (msec); emit elapsedTimeChanged (QString ("%1:%2.%3") .arg (mins, 2, 10, QLatin1Char ('0')) .arg (secs, 2, 10, QLatin1Char ('0')) .arg (QString::number (msec).at (0))); } DS_Schedule (100, this, SLOT (updateElapsedTime())); }
26.450172
80
0.654476
WinT-3794
3d03852efc50f17976123526503114185e2edf71
19,901
cpp
C++
scanmatcher/src/image_projection.cpp
rsasaki0109/li_slam_ros2
09e8cd3df514c10cbc1058896828dd1eb8e900be
[ "BSD-2-Clause" ]
113
2020-07-09T01:08:53.000Z
2022-03-25T07:52:05.000Z
scanmatcher/src/image_projection.cpp
rsasaki0109/li_slam_ros2
09e8cd3df514c10cbc1058896828dd1eb8e900be
[ "BSD-2-Clause" ]
5
2020-10-07T14:31:34.000Z
2021-08-01T13:01:03.000Z
scanmatcher/src/image_projection.cpp
rsasaki0109/li_slam_ros2
09e8cd3df514c10cbc1058896828dd1eb8e900be
[ "BSD-2-Clause" ]
15
2020-07-11T13:50:01.000Z
2022-03-17T03:11:36.000Z
// BSD 3-Clause License // // Copyright (c) 2020, Tixiao Shan // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "scanmatcher/utility.h" #include <pcl/console/print.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/conversions.h> #include <pcl/impl/pcl_base.hpp> typedef pcl::PointXYZI PointType; struct PointXYZIRT { PCL_ADD_POINT4D PCL_ADD_INTENSITY uint16_t ring; float time; EIGEN_MAKE_ALIGNED_OPERATOR_NEW } EIGEN_ALIGN16; POINT_CLOUD_REGISTER_POINT_STRUCT( PointXYZIRT, (float, x, x)(float, y, y)(float, z, z) (float, intensity, intensity)( uint16_t, ring, ring) (float, time, time) ) const int queueLength = 500; class ImageProjection : public ParamServer { private: std::mutex imuLock; std::mutex odoLock; rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr subLaserCloud; rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr pubLaserCloud; rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr pubExtractedCloud; rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr subImu; std::deque<sensor_msgs::msg::Imu> imuQueue; rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr subOdom; std::deque<nav_msgs::msg::Odometry> odomQueue; std::deque<sensor_msgs::msg::PointCloud2> cloudQueue; sensor_msgs::msg::PointCloud2 currentCloudMsg; double * imuTime = new double[queueLength]; double * imuRotX = new double[queueLength]; double * imuRotY = new double[queueLength]; double * imuRotZ = new double[queueLength]; int imuPointerCur; bool firstPointFlag; Eigen::Affine3f transStartInverse; pcl::PointCloud<PointXYZIRT>::Ptr laserCloudIn; pcl::PointCloud<PointType>::Ptr fullCloud; pcl::PointCloud<PointType>::Ptr extractedCloud; int deskewFlag; cv::Mat rangeMat; bool odomDeskewFlag; float odomIncreX; float odomIncreY; float odomIncreZ; double timeScanCur; double timeScanNext; std_msgs::msg::Header cloudHeader; public: ImageProjection(const rclcpp::NodeOptions & options) : ParamServer("image_projection", options), deskewFlag(0) { auto imu_callback = [this](const sensor_msgs::msg::Imu::ConstPtr msg) -> void { imuHandler(msg); }; subImu = create_subscription<sensor_msgs::msg::Imu>( imuTopic, rclcpp::SensorDataQoS(), imu_callback); auto odom_callback = [this](const nav_msgs::msg::Odometry::ConstPtr msg) -> void { odometryHandler(msg); }; subOdom = create_subscription<nav_msgs::msg::Odometry>( odomTopic, rclcpp::SensorDataQoS(), odom_callback); auto lc_callback = [this](const sensor_msgs::msg::PointCloud2::ConstPtr msg) -> void { cloudHandler(msg); }; subLaserCloud = create_subscription<sensor_msgs::msg::PointCloud2>( pointCloudTopic, 5, lc_callback); pubExtractedCloud = create_publisher<sensor_msgs::msg::PointCloud2>("cloud_deskewed", 2000); allocateMemory(); resetParameters(); } void allocateMemory() { laserCloudIn.reset(new pcl::PointCloud<PointXYZIRT>()); fullCloud.reset(new pcl::PointCloud<PointType>()); extractedCloud.reset(new pcl::PointCloud<PointType>()); fullCloud->points.resize(N_SCAN * Horizon_SCAN); resetParameters(); } void resetParameters() { laserCloudIn->clear(); extractedCloud->clear(); // reset range matrix for range image projection rangeMat = cv::Mat(N_SCAN, Horizon_SCAN, CV_32F, cv::Scalar::all(FLT_MAX)); imuPointerCur = 0; firstPointFlag = true; odomDeskewFlag = false; for (int i = 0; i < queueLength; ++i) { imuTime[i] = 0; imuRotX[i] = 0; imuRotY[i] = 0; imuRotZ[i] = 0; } } ~ImageProjection() {} void imuHandler(const sensor_msgs::msg::Imu::ConstPtr & imuMsg) { sensor_msgs::msg::Imu thisImu = imuConverter(*imuMsg); std::lock_guard<std::mutex> lock1(imuLock); imuQueue.push_back(thisImu); // debug IMU data // cout << std::setprecision(6); // cout << "IMU acc: " << endl; // cout << "x: " << thisImu.linear_acceleration.x << // ", y: " << thisImu.linear_acceleration.y << // ", z: " << thisImu.linear_acceleration.z << endl; // cout << "IMU gyro: " << endl; // cout << "x: " << thisImu.angular_velocity.x << // ", y: " << thisImu.angular_velocity.y << // ", z: " << thisImu.angular_velocity.z << endl; // double imuRoll, imuPitch, imuYaw; // tf::Quaternion orientation; // tf::quaternionMsgToTF(thisImu.orientation, orientation); // tf::Matrix3x3(orientation).getRPY(imuRoll, imuPitch, imuYaw); // cout << "IMU roll pitch yaw: " << endl; // cout << "roll: " << imuRoll << ", pitch: " << imuPitch << ", yaw: " << imuYaw << endl << endl; } void odometryHandler(const nav_msgs::msg::Odometry::ConstPtr & odometryMsg) { std::lock_guard<std::mutex> lock2(odoLock); odomQueue.push_back(*odometryMsg); } void cloudHandler(const sensor_msgs::msg::PointCloud2::ConstPtr & laserCloudMsg) { if (!cachePointCloud(laserCloudMsg)) { return; } if (!deskewInfo()) { return; } projectPointCloud(); cloudExtraction(); publishCloud(); resetParameters(); } bool cachePointCloud(const sensor_msgs::msg::PointCloud2::ConstPtr & laserCloudMsg) { // cache point cloud cloudQueue.push_back(*laserCloudMsg); if (cloudQueue.size() <= 2) { return false; } else { currentCloudMsg = cloudQueue.front(); cloudQueue.pop_front(); cloudHeader = currentCloudMsg.header; // timeScanCur = cloudHeader.stamp.toSec(); timeScanCur = cloudHeader.stamp.sec + cloudHeader.stamp.nanosec * 1e-9; // timeScanNext = cloudQueue.front().header.stamp.toSec(); timeScanNext = cloudQueue.front().header.stamp.sec + cloudQueue.front().header.stamp.nanosec * 1e-9; } // convert cloud pcl::fromROSMsg(currentCloudMsg, *laserCloudIn); // check dense flag if (laserCloudIn->is_dense == false) { RCLCPP_ERROR( get_logger(), "Point cloud is not in dense format, please remove NaN points first!"); rclcpp::shutdown(); } // check ring channel static int ringFlag = 0; if (ringFlag == 0) { ringFlag = -1; for (int i = 0; i < currentCloudMsg.fields.size(); ++i) { if (currentCloudMsg.fields[i].name == "ring") { ringFlag = 1; break; } } if (ringFlag == -1) { RCLCPP_ERROR( get_logger(), "Point cloud ring channel not available, please configure your point cloud data!"); rclcpp::shutdown(); } } // check point time if (deskewFlag == 0) { deskewFlag = -1; for (int i = 0; i < currentCloudMsg.fields.size(); ++i) { if (currentCloudMsg.fields[i].name == "time") { deskewFlag = 1; break; } } if (deskewFlag == -1) { RCLCPP_WARN( get_logger(), "Point cloud timestamp not available, deskew function disabled, system will drift significantly!"); } } return true; } bool deskewInfo() { std::lock_guard<std::mutex> lock1(imuLock); std::lock_guard<std::mutex> lock2(odoLock); // make sure IMU data available for the scan auto t_f = imuQueue.front().header.stamp.sec + imuQueue.front().header.stamp.nanosec * 1e-9; auto t_b = imuQueue.back().header.stamp.sec + imuQueue.back().header.stamp.nanosec * 1e-9; // if (imuQueue.empty() || imuQueue.front().header.stamp.toSec() > timeScanCur || imuQueue.back().header.stamp.toSec() < timeScanNext) if (imuQueue.empty() || t_f > timeScanCur || t_b < timeScanNext) { RCLCPP_DEBUG(get_logger(), "Waiting for IMU data ..."); return false; } imuDeskewInfo(); odomDeskewInfo(); return true; } void imuDeskewInfo() { while (!imuQueue.empty()) { auto t_f = imuQueue.front().header.stamp.sec + imuQueue.front().header.stamp.nanosec * 1e-9; if (t_f < timeScanCur - 0.01) { imuQueue.pop_front(); } else { break; } } if (imuQueue.empty()) { return; } imuPointerCur = 0; for (int i = 0; i < imuQueue.size(); ++i) { sensor_msgs::msg::Imu thisImuMsg = imuQueue[i]; //double currentImuTime = thisImuMsg.header.stamp.toSec(); double currentImuTime = thisImuMsg.header.stamp.sec + thisImuMsg.header.stamp.nanosec * 1e-9; if (currentImuTime > timeScanNext + 0.01) { break; } if (imuPointerCur == 0) { imuRotX[0] = 0; imuRotY[0] = 0; imuRotZ[0] = 0; imuTime[0] = currentImuTime; ++imuPointerCur; continue; } // get angular velocity double angular_x, angular_y, angular_z; imuAngular2rosAngular(&thisImuMsg, &angular_x, &angular_y, &angular_z); // integrate rotation double timeDiff = currentImuTime - imuTime[imuPointerCur - 1]; imuRotX[imuPointerCur] = imuRotX[imuPointerCur - 1] + angular_x * timeDiff; imuRotY[imuPointerCur] = imuRotY[imuPointerCur - 1] + angular_y * timeDiff; imuRotZ[imuPointerCur] = imuRotZ[imuPointerCur - 1] + angular_z * timeDiff; imuTime[imuPointerCur] = currentImuTime; ++imuPointerCur; } --imuPointerCur; if (imuPointerCur <= 0) { return; } } void odomDeskewInfo() { while (!odomQueue.empty()) { auto time = odomQueue.front().header.stamp.sec + odomQueue.front().header.stamp.nanosec * 1e-9; //if (odomQueue.front().header.stamp.toSec() < timeScanCur - 0.01) if (time < timeScanCur - 0.01) { odomQueue.pop_front(); } else { break; } } if (odomQueue.empty()) { return; } auto t_f = odomQueue.front().header.stamp.sec + odomQueue.front().header.stamp.nanosec * 1e-9; // if (odomQueue.front().header.stamp.toSec() > timeScanCur) if (t_f > timeScanCur) { return; } // get start odometry at the beinning of the scan nav_msgs::msg::Odometry startOdomMsg; for (int i = 0; i < odomQueue.size(); ++i) { startOdomMsg = odomQueue[i]; if (ROS_TIME(&startOdomMsg) < timeScanCur) { continue; } else { break; } } tf2::Quaternion orientation; // tf2::quaternionMsgToTF(startOdomMsg.pose.pose.orientation, orientation); tf2::fromMsg(startOdomMsg.pose.pose.orientation, orientation); double roll, pitch, yaw; tf2::Matrix3x3(orientation).getRPY(roll, pitch, yaw); // get end odometry at the end of the scan odomDeskewFlag = false; auto t_b = odomQueue.back().header.stamp.sec + odomQueue.back().header.stamp.nanosec * 1e-9; if (t_b < timeScanNext) { return; } nav_msgs::msg::Odometry endOdomMsg; for (int i = 0; i < odomQueue.size(); ++i) { endOdomMsg = odomQueue[i]; if (ROS_TIME(&endOdomMsg) < timeScanNext) { continue; } else { break; } } if (int(round(startOdomMsg.pose.covariance[0])) != int(round(endOdomMsg.pose.covariance[0]))) { return; } Eigen::Affine3f transBegin = pcl::getTransformation( startOdomMsg.pose.pose.position.x, startOdomMsg.pose.pose.position.y, startOdomMsg.pose.pose.position.z, roll, pitch, yaw); tf2::fromMsg(endOdomMsg.pose.pose.orientation, orientation); tf2::Matrix3x3(orientation).getRPY(roll, pitch, yaw); Eigen::Affine3f transEnd = pcl::getTransformation( endOdomMsg.pose.pose.position.x, endOdomMsg.pose.pose.position.y, endOdomMsg.pose.pose.position.z, roll, pitch, yaw); Eigen::Affine3f transBt = transBegin.inverse() * transEnd; float rollIncre, pitchIncre, yawIncre; pcl::getTranslationAndEulerAngles( transBt, odomIncreX, odomIncreY, odomIncreZ, rollIncre, pitchIncre, yawIncre); odomDeskewFlag = true; } void findRotation(double pointTime, float * rotXCur, float * rotYCur, float * rotZCur) { *rotXCur = 0; *rotYCur = 0; *rotZCur = 0; int imuPointerFront = 0; while (imuPointerFront < imuPointerCur) { if (pointTime < imuTime[imuPointerFront]) { break; } ++imuPointerFront; } if (pointTime > imuTime[imuPointerFront] || imuPointerFront == 0) { *rotXCur = imuRotX[imuPointerFront]; *rotYCur = imuRotY[imuPointerFront]; *rotZCur = imuRotZ[imuPointerFront]; } else { int imuPointerBack = imuPointerFront - 1; double ratioFront = (pointTime - imuTime[imuPointerBack]) / (imuTime[imuPointerFront] - imuTime[imuPointerBack]); double ratioBack = (imuTime[imuPointerFront] - pointTime) / (imuTime[imuPointerFront] - imuTime[imuPointerBack]); *rotXCur = imuRotX[imuPointerFront] * ratioFront + imuRotX[imuPointerBack] * ratioBack; *rotYCur = imuRotY[imuPointerFront] * ratioFront + imuRotY[imuPointerBack] * ratioBack; *rotZCur = imuRotZ[imuPointerFront] * ratioFront + imuRotZ[imuPointerBack] * ratioBack; } } void findPosition(double relTime, float * posXCur, float * posYCur, float * posZCur) { *posXCur = 0; *posYCur = 0; *posZCur = 0; // If the sensor moves relatively slow, like walking speed, positional deskew seems to have little benefits. Thus code below is commented. // if (odomDeskewFlag == false) // return; // float ratio = relTime / (timeScanNext - timeScanCur); // *posXCur = ratio * odomIncreX; // *posYCur = ratio * odomIncreY; // *posZCur = ratio * odomIncreZ; } PointType deskewPoint(PointType * point, double relTime) { if (deskewFlag == -1) { return *point; } double pointTime = timeScanCur + relTime; float rotXCur, rotYCur, rotZCur; findRotation(pointTime, &rotXCur, &rotYCur, &rotZCur); float posXCur, posYCur, posZCur; findPosition(relTime, &posXCur, &posYCur, &posZCur); if (firstPointFlag == true) { transStartInverse = (pcl::getTransformation(posXCur, posYCur, posZCur, rotXCur, rotYCur, rotZCur)).inverse(); firstPointFlag = false; } // transform points to start Eigen::Affine3f transFinal = pcl::getTransformation( posXCur, posYCur, posZCur, rotXCur, rotYCur, rotZCur); Eigen::Affine3f transBt = transStartInverse * transFinal; PointType newPoint; newPoint.x = transBt( 0, 0) * point->x + transBt(0, 1) * point->y + transBt(0, 2) * point->z + transBt(0, 3); newPoint.y = transBt( 1, 0) * point->x + transBt(1, 1) * point->y + transBt(1, 2) * point->z + transBt(1, 3); newPoint.z = transBt( 2, 0) * point->x + transBt(2, 1) * point->y + transBt(2, 2) * point->z + transBt(2, 3); newPoint.intensity = point->intensity; return newPoint; } void projectPointCloud() { int cloudSize = laserCloudIn->points.size(); // range image projection for (int i = 0; i < cloudSize; ++i) { PointType thisPoint; thisPoint.x = laserCloudIn->points[i].x; thisPoint.y = laserCloudIn->points[i].y; thisPoint.z = laserCloudIn->points[i].z; thisPoint.intensity = laserCloudIn->points[i].intensity; int rowIdn = laserCloudIn->points[i].ring; if (rowIdn < 0 || rowIdn >= N_SCAN) { continue; } float horizonAngle = atan2(thisPoint.x, thisPoint.y) * 180 / M_PI; float ang_res_x = 360.0 / float(Horizon_SCAN); int columnIdn = -round((horizonAngle - 90.0) / ang_res_x) + Horizon_SCAN / 2; if (columnIdn >= Horizon_SCAN) { columnIdn -= Horizon_SCAN; } if (columnIdn < 0 || columnIdn >= Horizon_SCAN) { continue; } float range = pointDistance(thisPoint); if (range < 1.0) { continue; } if (rangeMat.at<float>(rowIdn, columnIdn) != FLT_MAX) {continue;} // for the amsterdam dataset // if (range < 6.0 && rowIdn <= 7 && (columnIdn >= 1600 || columnIdn <= 200)) // continue; // if (thisPoint.z < -2.0) // continue; rangeMat.at<float>(rowIdn, columnIdn) = range; thisPoint = deskewPoint(&thisPoint, laserCloudIn->points[i].time); int index = columnIdn + rowIdn * Horizon_SCAN; fullCloud->points[index] = thisPoint; } } void cloudExtraction() { int count = 0; // extract segmented cloud for lidar odometry for (int i = 0; i < N_SCAN; ++i) { for (int j = 0; j < Horizon_SCAN; ++j) { if (rangeMat.at<float>(i, j) != FLT_MAX) { // save extracted cloud extractedCloud->push_back(fullCloud->points[j + i * Horizon_SCAN]); // size of extracted cloud ++count; } } } } void publishCloud() { sensor_msgs::msg::PointCloud2 tempCloud; pcl::toROSMsg(*extractedCloud, tempCloud); tempCloud.header.stamp = cloudHeader.stamp; tempCloud.header.frame_id = "base_link"; pubExtractedCloud->publish(tempCloud); } template<typename T> void imuAngular2rosAngular( sensor_msgs::msg::Imu * thisImuMsg, T * angular_x, T * angular_y, T * angular_z) { *angular_x = thisImuMsg->angular_velocity.x; *angular_y = thisImuMsg->angular_velocity.y; *angular_z = thisImuMsg->angular_velocity.z; } template<typename T> void imuAccel2rosAccel(sensor_msgs::msg::Imu * thisImuMsg, T * acc_x, T * acc_y, T * acc_z) { *acc_x = thisImuMsg->linear_acceleration.x; *acc_y = thisImuMsg->linear_acceleration.y; *acc_z = thisImuMsg->linear_acceleration.z; } float pointDistance(PointType p) { return sqrt(p.x * p.x + p.y * p.y + p.z * p.z); } float pointDistance(PointType p1, PointType p2) { return sqrt( (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) + (p1.z - p2.z) * (p1.z - p2.z)); } }; int main(int argc, char ** argv) { rclcpp::init(argc, argv); rclcpp::NodeOptions options; options.use_intra_process_comms(true); rclcpp::executors::SingleThreadedExecutor exec; auto ip = std::make_shared<ImageProjection>(options); exec.add_node(ip); std::cout << "\033[1;32m----> ImageProjection Started.\033[0m" << std::endl; exec.spin(); rclcpp::shutdown(); return 0; return 0; }
29.309278
142
0.64042
rsasaki0109
3d1351b6ef7af2fd5e3f7c34d1e7488e77921c28
1,536
cpp
C++
c++/solution2055.cpp
imafish/leetcodetests
abee2c2d6c0b25a21ef4294bceb7e069b6547b85
[ "MIT" ]
null
null
null
c++/solution2055.cpp
imafish/leetcodetests
abee2c2d6c0b25a21ef4294bceb7e069b6547b85
[ "MIT" ]
null
null
null
c++/solution2055.cpp
imafish/leetcodetests
abee2c2d6c0b25a21ef4294bceb7e069b6547b85
[ "MIT" ]
null
null
null
#include "afx.h" using namespace std; class Solution { public: vector<int> platesBetweenCandles(string s, vector<vector<int>> &queries) { std::vector<int> result(queries.size()); prepare(s); for (int i = 0; i < queries.size(); i++) { result[i] = findOne(queries[i]); } return result; } private: int findOne(vector<int> &query) { int left = _data[query[0]][2]; int right = _data[query[1]][1]; if (left == -1 || right == -1 || left >= right) { return 0; } int total = _data[right][0] - _data[left][0]; return total; } void prepare(const string &s) { _data.resize(s.length()); int lastCandle = -1; int plateIndex = 0; int i = 0; for (; i < s.length(); i++) { if (s[i] == '|') { lastCandle = i; _data[i][0] = plateIndex; _data[i][1] = i; } else { _data[i][0] = plateIndex++; _data[i][1] = lastCandle; } } lastCandle = -1; for (i = s.length() - 1; i >= 0; i--) { if (s[i] == '|') { lastCandle = i; _data[i][2] = i; } else { _data[i][2] = lastCandle; } } } private: std::vector<std::array<int, 3>> _data; };
21.633803
76
0.392578
imafish
3d1664daf4eea73225e3392fbd51715403cca37d
85
hpp
C++
shared/logging.hpp
cvrebeatsaber/QuestQualifications
4be76c3e8da9ead1727e2320fd12c083aabdacad
[ "MIT" ]
1
2020-10-07T06:39:16.000Z
2020-10-07T06:39:16.000Z
shared/logging.hpp
cvrebeatsaber/QuestQualifications
4be76c3e8da9ead1727e2320fd12c083aabdacad
[ "MIT" ]
null
null
null
shared/logging.hpp
cvrebeatsaber/QuestQualifications
4be76c3e8da9ead1727e2320fd12c083aabdacad
[ "MIT" ]
1
2021-06-02T23:13:46.000Z
2021-06-02T23:13:46.000Z
#pragma once #include "beatsaber-hook/shared/utils/logging.hpp" Logger& getLogger();
21.25
50
0.776471
cvrebeatsaber
3d168d4f61ba906957acecbee97cc126344c1c1e
936
cpp
C++
1000/90/1091b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
1000/90/1091b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
1000/90/1091b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> #include <vector> using distance_t = std::pair<int, int>; template <typename T, typename U> std::istream& operator >>(std::istream& input, std::pair<T, U>& v) { return input >> v.first >> v.second; } template <typename T> std::istream& operator >>(std::istream& input, std::vector<T>& v) { for (T& a : v) input >> a; return input; } void answer(int x, int y) { std::cout << x << ' ' << y << '\n'; } void solve(const std::vector<distance_t>& p, const std::vector<distance_t>& d) { const size_t n = p.size(); long long sx = 0, sy = 0; for (size_t i = 0; i < n; ++i) { sx+= p[i].first + d[i].first; sy += p[i].second + d[i].second; } answer(sx / n, sy / n); } int main() { size_t n; std::cin >> n; std::vector<distance_t> p(n); std::cin >> p; std::vector<distance_t> d(n); std::cin >> d; solve(p, d); return 0; }
17.018182
78
0.536325
actium
3d1917251618d0eaf76c8f81b742f05eeb14d345
1,502
hpp
C++
src/storage/tree/Units.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/storage/tree/Units.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/storage/tree/Units.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
// Copyright (c) 2018 The Open-Transactions developers // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once #include "Internal.hpp" #include "opentxs/api/storage/Storage.hpp" #include "opentxs/api/Editor.hpp" #include "Node.hpp" namespace opentxs { namespace storage { class Tree; class Units : public Node { private: friend class Tree; void init(const std::string& hash) override; bool save(const std::unique_lock<std::mutex>& lock) const override; proto::StorageUnits serialize() const; Units(const opentxs::api::storage::Driver& storage, const std::string& key); Units() = delete; Units(const Units&) = delete; Units(Units&&) = delete; Units operator=(const Units&) = delete; Units operator=(Units&&) = delete; public: std::string Alias(const std::string& id) const; bool Load( const std::string& id, std::shared_ptr<proto::UnitDefinition>& output, std::string& alias, const bool checking) const; void Map(UnitLambda lambda) const; bool Delete(const std::string& id); bool SetAlias(const std::string& id, const std::string& alias); bool Store( const proto::UnitDefinition& data, const std::string& alias, std::string& plaintext); ~Units() = default; }; } // namespace storage } // namespace opentxs
25.896552
80
0.669774
nopdotcom
3d1ab9f4ddd01a8fbb879a714ab87f1c44a5daaa
37,750
cpp
C++
Fuji/Source/MFString.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
35
2015-01-19T22:07:48.000Z
2022-02-21T22:17:53.000Z
Fuji/Source/MFString.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
1
2022-02-23T09:34:15.000Z
2022-02-23T09:34:15.000Z
Fuji/Source/MFString.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
4
2015-05-11T03:31:35.000Z
2018-09-27T04:55:57.000Z
#include "Fuji_Internal.h" #include "MFString.h" #include "MFHeap_Internal.h" #include "MFObjectPool.h" #include <stdio.h> #include <stdarg.h> #define stricmp strcasecmp #include <string.h> MFObjectPool stringPool; MFObjectPoolGroup stringHeap; int gModuleInitCount = 0; // this is okay as global; it can be shared or duplicated freely MFALIGN_BEGIN(16) static char gStringBuffer[1024*128] MFALIGN_END(16); static size_t gStringOffset = 0; static const MFObjectPoolGroupConfig gStringGroups[] = { { 5, 256, 128 }, { 16, 512, 128 }, { 128, 32, 16 }, { 1024, 4, 4 } }; MFInitStatus MFString_InitModule(int moduleId, bool bPerformInitialisation) { if(!bPerformInitialisation) return MFIS_Succeeded; if(gModuleInitCount == 0) { ++gModuleInitCount; stringHeap.Init(gStringGroups, sizeof(gStringGroups) / sizeof(gStringGroups[0])); stringPool.Init(sizeof(MFStringData), 128, 128); } return MFIS_Succeeded; } void MFString_DeinitModule() { if(--gModuleInitCount == 0) { stringPool.Deinit(); stringHeap.Deinit(); } } MF_API MFString MFString_GetStats() { size_t overhead = stringPool.GetTotalMemory() + stringPool.GetOverheadMemory() + stringHeap.GetOverheadMemory(); size_t waste = 0, averageSize = 0; // calculate waste int numStrings = stringPool.GetNumAllocated(); for(int a=0; a<numStrings; ++a) { MFStringData *pString = (MFStringData*)stringPool.GetItem(a); size_t allocated = pString->allocated; if(allocated) { size_t bytes = pString->bytes+1; averageSize += bytes; waste += allocated - bytes; } } if(numStrings) averageSize /= numStrings; MFString desc; desc.Reserve(1024); desc = MFStr("String heap memory: " MFFMT_SIZE_T " allocated/" MFFMT_SIZE_T " reserved + " MFFMT_SIZE_T " overhead Waste: " MFFMT_SIZE_T " Average length: " MFFMT_SIZE_T "\n\tPool: %d/%d", stringHeap.GetAllocatedMemory(), stringHeap.GetTotalMemory(), overhead, waste, averageSize, stringPool.GetNumAllocated(), stringPool.GetNumReserved()); int numGroups = stringHeap.GetNumPools(); for(int a=0; a<numGroups; ++a) { MFObjectPool *pPool = stringHeap.GetPool(a); desc += MFStr("\n\t\t" MFFMT_SIZE_T " byte: %d/%d", pPool->GetObjectSize(), pPool->GetNumAllocated(), pPool->GetNumReserved()); } return desc; } MF_API void MFString_Dump() { MFString temp = MFString_GetStats(); MFDebug_Log(1, "\n-------------------------------------------------------------------------------------------------------"); MFDebug_Log(1, temp.CStr()); // dump all strings... MFDebug_Log(1, ""); int numStrings = stringPool.GetNumAllocated(); for(int a=0; a<numStrings; ++a) { MFStringData *pString = (MFStringData*)stringPool.GetItem(a); MFDebug_Log(1, MFStr("%d refs, " MFFMT_SIZE_T "b: \"%s\"", pString->refCount, pString->allocated, pString->pMemory)); } } MF_API void *MFCopyMemory(void *pDest, const void *pSrc, size_t size) { return memcpy(pDest, pSrc, size); } MF_API void *MFMemSet(void *pDest, int value, size_t size) { return memset(pDest, value, size); } MF_API void *MFZeroMemory(void *pDest, size_t size) { return memset(pDest, 0, size); } MF_API int MFMemCompare(const void *pBuf1, const void *pBuf2, size_t size) { return memcmp(pBuf1, pBuf2, size); } MF_API char* MFString_Dup(const char *pString) { size_t len = MFString_Length(pString); char *pNew = (char*)MFHeap_Alloc(len + 1); MFString_Copy(pNew, pString); return pNew; } MF_API const char * MFString_ToLower(const char *pString) { char *pBuffer = &gStringBuffer[gStringOffset]; size_t len = MFString_Length(pString); gStringOffset += len+1; char *pT = pBuffer; while(*pString) { *pT = (char)MFToLower(*pString); ++pT; ++pString; } if(gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0; return pBuffer; } MF_API const char * MFString_ToUpper(const char *pString) { char *pBuffer = &gStringBuffer[gStringOffset]; size_t len = MFString_Length(pString); gStringOffset += len+1; char *pT = pBuffer; while(*pString) { *pT = (char)MFToUpper(*pString); ++pT; ++pString; } if(gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0; return pBuffer; } MF_API const char * MFStr(const char *format, ...) { va_list arglist; char *pBuffer = &gStringBuffer[gStringOffset]; int nRes = 0; va_start(arglist, format); nRes = vsprintf(pBuffer, format, arglist); gStringOffset += nRes+1; if(gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0; va_end(arglist); return pBuffer; } MF_API const char * MFStrN(const char *pSource, size_t n) { char *pBuffer = &gStringBuffer[gStringOffset]; MFString_CopyN(pBuffer, pSource, (int)n); pBuffer[n] = 0; gStringOffset += (uint32)n+1; if(gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0; return pBuffer; } MF_API int MFString_Compare(const char *pString1, const char *pString2) { while(*pString1 == *pString2++) { if(*pString1++ == 0) return 0; } return (*(const unsigned char *)pString1 - *(const unsigned char *)(pString2 - 1)); } MF_API int MFString_CompareN(const char *pString1, const char *pString2, size_t n) { if(n == 0) return 0; do { if(*pString1 != *pString2++) return (*(const unsigned char *)pString1 - *(const unsigned char *)(pString2 - 1)); if(*pString1++ == 0) break; } while(--n != 0); return 0; } MF_API int MFString_CaseCmp(const char *pSource1, const char *pSource2) { register unsigned int c1, c2; do { c1 = MFToUpper(*pSource1++); c2 = MFToUpper(*pSource2++); } while(c1 && (c1 == c2)); return c1 - c2; } MF_API int MFString_CaseCmpN(const char *pSource1, const char *pSource2, size_t n) { register int c = 0; while(n) { if((c = MFToUpper(*pSource1) - MFToUpper(*pSource2++) ) != 0 || !*pSource1++) break; n--; } return c; } MF_API bool MFString_PatternMatch(const char *pPattern, const char *pFilename, const char **ppMatchDirectory, bool bCaseSensitive) { if(!pPattern || !pFilename) return false; while(*pPattern && *pFilename) { if(*pPattern == '?') { if(*pFilename == '/' || *pFilename == '\\') break; } else if(*pPattern == '*') { ++pPattern; // if an asterisk is the last character in the pattern, it's a match! if(*pPattern == 0) return true; bool match = false; while(*pFilename) { match = MFString_PatternMatch(pPattern, pFilename, ppMatchDirectory); if(match) break; if(*pFilename == '/' || *pFilename == '\\') break; ++pFilename; } return match; } else if((bCaseSensitive && *pPattern != *pFilename) || (!bCaseSensitive && MFToLower(*pPattern) != MFToLower(*pFilename))) break; ++pPattern; ++pFilename; } if(*pPattern == 0) { if((*pFilename == '/' || *pFilename == '\\') && ppMatchDirectory) *ppMatchDirectory = pFilename + 1; if((ppMatchDirectory && *ppMatchDirectory) || *pFilename == 0) return true; } return false; } MF_API const char* MFStr_URLEncodeString(const char *pString, const char *pExcludeChars) { char *pBuffer = &gStringBuffer[gStringOffset]; size_t sourceLen = MFString_Length(pString); size_t destLen = 0; for(size_t a=0; a<sourceLen; ++a) { int c = (uint8)pString[a]; if(MFIsAlphaNumeric(c) || MFString_Chr("-_.!~*'()", c) || (pExcludeChars && MFString_Chr(pExcludeChars, c))) pBuffer[destLen++] = (char)c; else if(c == ' ') pBuffer[destLen++] = '+'; else destLen += sprintf(pBuffer + destLen, "%%%02X", c); } pBuffer[destLen] = 0; gStringOffset += destLen+1; if(gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0; return pBuffer; } MF_API size_t MFString_URLEncode(char *pDest, const char *pString, const char *pExcludeChars) { size_t sourceLen = MFString_Length(pString); size_t destLen = 0; for(size_t a=0; a<sourceLen; ++a) { int c = (uint8)pString[a]; if(MFIsAlphaNumeric(c) || MFString_Chr("-_.!~*'()", c) || (pExcludeChars && MFString_Chr(pExcludeChars, c))) { if(pDest) pDest[destLen] = (char)c; destLen++; } else if(c == ' ') { if(pDest) pDest[destLen] = '+'; destLen++; } else { if(pDest) destLen += sprintf(pDest + destLen, "%%%02X", c); else destLen += 3; // *** surely this can't write more than 3 chars? '%xx' } } if(pDest) pDest[destLen] = 0; return destLen; } MF_API bool MFString_IsNumber(const char *pString, bool bAllowHex) { pString = MFSkipWhite(pString); int numDigits = 0; if(bAllowHex && pString[0] == '0' && pString[1] == 'x') { // hex number pString += 2; while(*pString) { if(!MFIsHex(*pString++)) return false; ++numDigits; } } else { // decimal number if(*pString == '-' || *pString == '+') ++pString; bool bHasDot = false; while(*pString) { if(!MFIsNumeric(*pString) && (bHasDot || *pString != '.')) return false; if(*pString++ == '.') { bHasDot = true; numDigits = 0; } else ++numDigits; } } return numDigits > 0 ? true : false; } MF_API int MFString_AsciiToInteger(const char *pString, bool bDetectBase, int base, const char **ppNextChar) { pString = MFSkipWhite(pString); int number = 0; if(base == 16 || (bDetectBase && ((pString[0] == '0' && pString[1] == 'x') || pString[0] == '$'))) { // hex number if(pString[0] == '0' && pString[1] == 'x') pString += 2; else if(pString[0] == '$') pString += 1; while(*pString) { int digit = *pString++; if(!MFIsHex(digit)) return number; number <<= 4; number += MFIsNumeric(digit) ? digit - '0' : MFToLower(digit) - 'a' + 10; } } else if(base == 2 || (bDetectBase && pString[0] == 'b')) { if(pString[0] == 'b') ++pString; while(*pString == '0' || *pString == '1') { number <<= 1; number |= *pString - '0'; } } else if(base == 10) { // decimal number bool neg = false; if(*pString == '-' || *pString == '+') { neg = *pString == '-'; ++pString; } while(*pString) { if(!MFIsNumeric(*pString)) return neg ? -number : number; number = number*10 + (*pString++) - '0'; } if(neg) number = -number; } if(ppNextChar) *ppNextChar = pString; return number; } MF_API float MFString_AsciiToFloat(const char *pString, const char **ppNextChar) { pString = MFSkipWhite(pString); int64 number = 0; float frac = 1; // floating poiont number bool neg = false; if(*pString == '-' || *pString == '+') { neg = *pString == '-'; ++pString; } bool bHasDot = false; while(*pString) { int digit = *pString++; if(!MFIsNumeric(digit) && (bHasDot || digit != '.')) return (float)(neg ? -number : number) * frac; if(digit == '.') bHasDot = true; else { number = number*10 + digit - '0'; if(bHasDot) frac *= 0.1f; } } if(neg) number = -number; if(ppNextChar) *ppNextChar = pString; return (float)number * frac; } MF_API int MFString_Enumerate(const char *pString, const char **ppKeys, size_t numKeys, bool bCaseSensitive) { for(size_t i=0; i<numKeys && ppKeys[i]; ++i) { if(bCaseSensitive ? !MFString_Compare(pString, ppKeys[i]) : !MFString_CaseCmp(pString, ppKeys[i])) return (int)i; } return -1; } #if 0 char* MFString_Copy(char *pDest, const char *pSrc) { #if !defined(PREFER_SPEED_OVER_SIZE) char *s = pDest; while(*pDest++ = *pSrc++) { } return s; #else char *dst = dst0; _CONST char *src = src0; long *aligned_dst; _CONST long *aligned_src; /* If SRC or DEST is unaligned, then copy bytes. */ if (!UNALIGNED (src, dst)) { aligned_dst = (long*)dst; aligned_src = (long*)src; /* SRC and DEST are both "long int" aligned, try to do "long int" sized copies. */ while (!DETECTNULL(*aligned_src)) { *aligned_dst++ = *aligned_src++; } dst = (char*)aligned_dst; src = (char*)aligned_src; } while (*dst++ = *src++) ; return dst0; #endif } char* MFString_CopyN(char *pDest, const char *pSrc, int n) { #if !defined(PREFER_SPEED_OVER_SIZE) char *dscan; const char *sscan; dscan = pDest; sscan = pSrc; while(n > 0) { --n; if((*dscan++ = *sscan++) == '\0') break; } while(n-- > 0) *dscan++ = '\0'; return pDest; #else char *dst = dst0; _CONST char *src = src0; long *aligned_dst; _CONST long *aligned_src; /* If SRC and DEST is aligned and count large enough, then copy words. */ if(!UNALIGNED (src, dst) && !TOO_SMALL (count)) { aligned_dst = (long*)dst; aligned_src = (long*)src; /* SRC and DEST are both "long int" aligned, try to do "long int" sized copies. */ while(count >= sizeof (long int) && !DETECTNULL(*aligned_src)) { count -= sizeof (long int); *aligned_dst++ = *aligned_src++; } dst = (char*)aligned_dst; src = (char*)aligned_src; } while(count > 0) { --count; if((*dst++ = *src++) == '\0') break; } while(count-- > 0) *dst++ = '\0'; return dst0; #endif } char* MFString_Cat(char *pDest, const char *pSrc) { #if !defined(PREFER_SPEED_OVER_SIZE) char *s = pDest; while(*pDest) pDest++; while(*pDest++ = *pSrc++) { } return s; #else char *s = s1; /* Skip over the data in s1 as quickly as possible. */ if (ALIGNED (s1)) { unsigned long *aligned_s1 = (unsigned long *)s1; while (!DETECTNULL (*aligned_s1)) aligned_s1++; s1 = (char *)aligned_s1; } while (*s1) s1++; /* s1 now points to the its trailing null character, we can just use strcpy to do the work for us now. ?!? We might want to just include strcpy here. Also, this will cause many more unaligned string copies because s1 is much less likely to be aligned. I don't know if its worth tweaking strcpy to handle this better. */ MFString_Copy(s1, s2); return s; #endif } char* MFString_CopyCat(char *pDest, const char *pSrc, const char *pSrc2) { #if !defined(PREFER_SPEED_OVER_SIZE) char *s = pDest; while(*pDest = *pSrc++) { ++pDest; } while(*pDest++ = *pSrc2++) { } return s; #else char *dst = dst0; _CONST char *src = src0; long *aligned_dst; _CONST long *aligned_src; /* If SRC or DEST is unaligned, then copy bytes. */ if (!UNALIGNED (src, dst)) { aligned_dst = (long*)dst; aligned_src = (long*)src; /* SRC and DEST are both "long int" aligned, try to do "long int" sized copies. */ while (!DETECTNULL(*aligned_src)) { *aligned_dst++ = *aligned_src++; } dst = (char*)aligned_dst; src = (char*)aligned_src; } while (*dst++ = *src++) ; return dst0; #endif /* not PREFER_SIZE_OVER_SPEED */ } #endif // // UTF8 support // MF_API size_t MFWString_CopyUTF8ToUTF16(wchar_t *pBuffer, const char *pString) { const wchar_t *pStart = pBuffer; while(*pString) { int c; pString += MFString_DecodeUTF8(pString, &c); *pBuffer++ = (wchar_t)c; } *pBuffer = 0; return pBuffer - pStart; } MF_API size_t MFString_CopyUTF16ToUTF8(char *pBuffer, const wchar_t *pString) { const char *pStart = pBuffer; while(*pString) pBuffer += MFString_EncodeUTF8(*pString++, pBuffer); *pBuffer = 0; return pBuffer - pStart; } MF_API wchar_t* MFString_UFT8AsWChar(const char *pUTF8String, size_t *pNumChars) { // count number of actual characters in the string size_t numChars = MFString_GetNumChars(pUTF8String); // get some space in the MFStr buffer if(gStringOffset & 1) ++gStringOffset; wchar_t *pBuffer = (wchar_t*)&gStringBuffer[gStringOffset]; gStringOffset += numChars*2 + 2; // if we wrapped the string buffer if(gStringOffset >= sizeof(gStringBuffer) - 1024) { gStringOffset = numChars*2 + 2; pBuffer = (wchar_t*)gStringBuffer; } // copy the string MFWString_CopyUTF8ToUTF16(pBuffer, pUTF8String); if(pNumChars) *pNumChars = numChars; return pBuffer; } MF_API char* MFString_WCharAsUTF8(const wchar_t *pWString, size_t *pNumBytes) { // count number of actual characters in the string size_t numBytes = 0; const wchar_t *pCount = pWString; while (*pCount) numBytes += MFString_EncodeUTF8(*pCount++, NULL); // get some space in the MFStr buffer char *pBuffer = &gStringBuffer[gStringOffset]; gStringOffset += numBytes + 1; // if we wrapped the string buffer if (gStringOffset >= sizeof(gStringBuffer) - 1024) { gStringOffset = numBytes + 1; pBuffer = gStringBuffer; } // copy the string MFString_CopyUTF16ToUTF8(pBuffer, pWString); if (pNumBytes) *pNumBytes = numBytes; return pBuffer; } // // unicode support // MF_API wchar_t* MFWString_Dup(const wchar_t *pString) { size_t len = MFWString_Length(pString); wchar_t *pNew = (wchar_t*)MFHeap_Alloc((len + 1)*sizeof(wchar_t)); MFWString_Copy(pNew, pString); return pNew; } MF_API const wchar_t * MFWStr(const wchar_t *format, ...) { va_list arglist; gStringOffset += gStringOffset & 1; wchar_t *pBuffer = (wchar_t*)&gStringBuffer[gStringOffset]; int nRes = 0; va_start(arglist, format); nRes = vswprintf(pBuffer, format, arglist); gStringOffset += (nRes + 1)*sizeof(wchar_t); if (gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0; va_end(arglist); return pBuffer; } MF_API const wchar_t * MFWStrN(const wchar_t *pSource, size_t n) { gStringOffset += gStringOffset & 1; wchar_t *pBuffer = (wchar_t*)&gStringBuffer[gStringOffset]; MFWString_CopyN(pBuffer, pSource, n); pBuffer[n] = 0; gStringOffset += (n + 1)*sizeof(wchar_t); if (gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0; return pBuffer; } MF_API int MFWString_Compare(const wchar_t *pString1, const wchar_t *pString2) { while(*pString1 == *pString2++) { if(*pString1++ == 0) return 0; } return (*(const uint16 *)pString1 - *(const uint16 *)(pString2 - 1)); } MF_API int MFWString_CaseCmp(const wchar_t *pSource1, const wchar_t *pSource2) { register unsigned int c1, c2; do { c1 = MFToUpper(*pSource1++); c2 = MFToUpper(*pSource2++); } while(c1 && (c1 == c2)); return c1 - c2; } MF_API int MFWString_CompareUTF8(const wchar_t *pString1, const char *pString2) { int c; int len = MFString_DecodeUTF8(pString2, &c); pString2 += len; while(*pString1 == c) { if(*pString1++ == 0) return 0; len = MFString_DecodeUTF8(pString2, &c); pString2 += len; } return *(const uint16 *)pString1 - c; } /**** MFString Functions ****/ MF_API MFStringData *MFStringData_Alloc() { MFStringData *pData = (MFStringData*)stringPool.Alloc(); pData->refCount = 1; pData->pMemory = NULL; pData->allocated = pData->bytes = 0; return pData; } MF_API void MFStringData_Destroy(MFStringData *pStringData) { if(pStringData->allocated) stringHeap.Free(pStringData->pMemory); stringPool.Free(pStringData); } MF_API char *MFStringHeap_Alloc(size_t bytes, size_t *pAllocated) { return (char*)stringHeap.Alloc(bytes, pAllocated); } MF_API void MFStringHeap_Free(char *pString) { stringHeap.Free(pString); } __forceinline void MFStringData_Release(MFStringData *pStringData) { if(--pStringData->refCount == 0) MFStringData_Destroy(pStringData); } MFString::MFString(const char *pString, bool bHoldStaticPointer) { if(!pString) { pData = NULL; } else { pData = MFStringData_Alloc(); pData->bytes = MFString_Length(pString); if(bHoldStaticPointer) { pData->pMemory = (char*)pString; } else { pData->pMemory = (char*)stringHeap.Alloc(pData->bytes + 1, &pData->allocated); MFString_Copy(pData->pMemory, pString); } } } MFString::MFString(const char *pString, size_t maxChars) { if(!pString) { pData = NULL; } else { pData = MFStringData_Alloc(); pData->bytes = MFString_LengthN(pString, (int)maxChars); pData->pMemory = (char*)stringHeap.Alloc(pData->bytes + 1, &pData->allocated); MFString_CopyN(pData->pMemory, pString, (int)pData->bytes); pData->pMemory[pData->bytes] = 0; } } MFString& MFString::operator=(const char *pString) { if(pString) { size_t bytes = MFString_Length(pString); Reserve(bytes + 1, true); MFString_Copy(pData->pMemory, pString); pData->bytes = bytes; } else if(pData) { MFStringData_Release(pData); pData = NULL; } return *this; } MFString& MFString::operator=(const MFString &string) { if(pData) MFStringData_Release(pData); pData = string.pData; if(pData) ++pData->refCount; return *this; } MFString& MFString::operator+=(char c) { Reserve(NumBytes() + 2); pData->pMemory[pData->bytes++] = c; pData->pMemory[pData->bytes] = 0; return *this; } MFString& MFString::operator+=(const char *pString) { if(!pString || *pString == 0) return *this; if(IsEmpty()) { *this = pString; } else { size_t sumBytes = pData->bytes + MFString_Length(pString); Reserve(sumBytes + 1); MFString_Copy(pData->pMemory + pData->bytes, pString); pData->bytes = sumBytes; } return *this; } MFString& MFString::operator+=(const MFString &string) { if(string.IsEmpty()) return *this; if(IsEmpty()) { *this = string; } else { size_t sumBytes = pData->bytes + string.pData->bytes; Reserve(sumBytes + 1); MFString_Copy(pData->pMemory + pData->bytes, string.pData->pMemory); pData->bytes = sumBytes; } return *this; } MFString MFString::operator+(char c) const { MFString s = *this; s += c; return s; } MFString MFString::operator+(const char *pString) const { if(!pString || *pString == 0) return *this; if(IsEmpty()) return MFString(pString); size_t bytes = pData->bytes + MFString_Length(pString); MFString t; t.Reserve(bytes + 1); MFString_CopyCat(t.pData->pMemory, pData->pMemory, pString); t.pData->bytes = bytes; return t; } MFString MFString::operator+(const MFString &string) const { if(string.IsEmpty()) return *this; if(IsEmpty()) return string; size_t bytes = pData->bytes + string.pData->bytes; MFString t; t.Reserve(bytes + 1); MFString_CopyCat(t.pData->pMemory, pData->pMemory, string.pData->pMemory); t.pData->bytes = bytes; return t; } MFString operator+(const char *pString, const MFString &string) { if(string.IsEmpty()) return MFString(pString); if(!pString || *pString == 0) return string; return MFString::Static(pString) + string; } MFString& MFString::SetStaticString(const char *pStaticString) { if(pData) { MFStringData_Release(pData); pData = NULL; } if(pStaticString) { pData = MFStringData_Alloc(); pData->bytes = MFString_Length(pStaticString); pData->pMemory = (char*)pStaticString; } return *this; } MFString& MFString::FromUTF16(const wchar_t *pString) { if(pData) { MFStringData_Release(pData); pData = NULL; } if(pString) { pData = MFStringData_Alloc(); size_t len = 0; const wchar_t *pS = pString; while(*pS) len += MFString_EncodeUTF8(*pS++, NULL); pData->bytes = len; pData->pMemory = (char*)stringHeap.Alloc(pData->bytes + 1, &pData->allocated); MFString_CopyUTF16ToUTF8(pData->pMemory, (const wchar_t*)pString); } return *this; } MFString& MFString::Detach(size_t reserveBytes) { if(pData && (pData->refCount > 1 || pData->allocated == 0)) { MFStringData *pNew = MFStringData_Alloc(); pNew->bytes = pData->bytes; pNew->pMemory = (char*)stringHeap.Alloc(MFMax(pNew->bytes + 1, reserveBytes), &pNew->allocated); MFString_Copy(pNew->pMemory, pData->pMemory); MFStringData_Release(pData); pData = pNew; } return *this; } MFString& MFString::Reserve(size_t bytes, bool bClearString) { // detach instance Detach(bytes); // allocate memory if(!pData) { pData = MFStringData_Alloc(); pData->pMemory = (char*)stringHeap.Alloc(bytes, &pData->allocated); pData->pMemory[0] = 0; pData->bytes = 0; } else { if(bytes > pData->allocated) { bool bNeedFree = pData->allocated != 0; char *pNew = (char*)stringHeap.Alloc(bytes, &pData->allocated); if(!bClearString) MFString_Copy(pNew, pData->pMemory); if(bNeedFree) stringHeap.Free(pData->pMemory); pData->pMemory = pNew; } if(bClearString) { pData->bytes = 0; pData->pMemory[0] = 0; } } return *this; } MFString& MFString::Sprintf(const char *pFormat, ...) { if(pData) { MFStringData_Release(pData); pData = NULL; } va_list arglist; va_start(arglist, pFormat); int nRes = vsnprintf(NULL, 0, pFormat, arglist); va_start(arglist, pFormat); if(nRes >= 0) { pData = MFStringData_Alloc(); pData->bytes = nRes; pData->pMemory = (char*)stringHeap.Alloc(pData->bytes + 1, &pData->allocated); vsprintf(pData->pMemory, pFormat, arglist); } va_end(arglist); return *this; } MFString MFString::Format(const char *pFormat, ...) { MFString t; va_list arglist; va_start(arglist, pFormat); int nRes = vsnprintf(NULL, 0, pFormat, arglist); va_start(arglist, pFormat); if(nRes >= 0) { t.pData = MFStringData_Alloc(); t.pData->bytes = nRes; t.pData->pMemory = (char*)stringHeap.Alloc(t.pData->bytes + 1, &t.pData->allocated); vsprintf(t.pData->pMemory, pFormat, arglist); } va_end(arglist); return t; } MFString& MFString::FromInt(int number) { Sprintf("%d", number); return *this; } MFString& MFString::FromFloat(float number) { Sprintf("%g", number); return *this; } MFString MFString::Upper() const { if(!pData) return *this; // allocate a new string MFString t; t.Reserve(pData->bytes + 1); t.pData->bytes = pData->bytes; // copy upper case for(size_t a=0; a<pData->bytes + 1; ++a) t.pData->pMemory[a] = (char)MFToUpper(pData->pMemory[a]); return t; } MFString MFString::Lower() const { if(!pData) return *this; // allocate a new string MFString t; t.Reserve(pData->bytes + 1); t.pData->bytes = pData->bytes; // copy lower case string for(size_t a=0; a<pData->bytes + 1; ++a) t.pData->pMemory[a] = (char)MFToLower(pData->pMemory[a]); return t; } MFString& MFString::Trim(bool bFront, bool bEnd, const char *pCharacters) { if(pData) { const char *pSrc = pData->pMemory; size_t offset = 0; // trim start if(bFront) { while(pSrc[offset] && MFString_Chr(pCharacters, pSrc[offset])) ++offset; } size_t count = pData->bytes - offset; // trim end if(bEnd) { const char *pEnd = pSrc + offset + count - 1; while(count && MFString_Chr(pCharacters, *pEnd)) { --count; --pEnd; } } *this = SubStr((int)offset, (int)count); } return *this; } MFString& MFString::PadLeft(int minLength, const char *pPadding) { // check if the string is already long enough int len = NumBytes(); if(len >= minLength) return *this; // reserve enough memory Reserve(minLength + 1); pData->bytes = minLength; // move string size_t preBytes = minLength - len; for(int a=len; a>=0; --a) pData->pMemory[a + preBytes] = pData->pMemory[a]; // pre-pad the string size_t padLen = MFString_Length(pPadding); for(size_t a=0, b=0; a<preBytes; ++a, ++b) { if(b >= padLen) b = 0; pData->pMemory[a] = pPadding[b]; } return *this; } MFString& MFString::PadRight(int minLength, const char *pPadding, bool bAlignPadding) { // check if the string is already long enough int len = NumBytes(); if(len >= minLength) return *this; // reserve enough memory Reserve(minLength + 1); pData->bytes = minLength; pData->pMemory[minLength] = 0; // pad the string size_t padLen = MFString_Length(pPadding); size_t b = bAlignPadding ? len%padLen : 0; for(int a=len; a<minLength; ++a, ++b) { if(b >= padLen) b = 0; pData->pMemory[a] = pPadding[b]; } return *this; } MFString MFString::SubStr(int offset, int count) const { if(!pData) return *this; // limit within the strings range int maxChars = (int)pData->bytes - offset; if(count < 0 || count > maxChars) count = maxChars; // bail if we don't need to do anything if(count == (int)pData->bytes) return *this; // allocate a new string MFString t; t.Reserve(count + 1); t.pData->bytes = count; // copy sub string MFString_CopyN(t.pData->pMemory, pData->pMemory + offset, count); t.pData->pMemory[count] = 0; return t; } MFString& MFString::Truncate(int length) { if(pData && (size_t)length < pData->bytes) { Detach(); pData->bytes = length; pData->pMemory[length] = 0; } return *this; } MFString MFString::GetExtension() const { int dot = FindCharReverse('.'); if(dot > FindCharReverse('/') && dot > FindCharReverse('\\')) return SubStr(dot); return MFString(); } MFString& MFString::TruncateExtension() { int dot = FindCharReverse('.'); if(dot >= 0) { pData->pMemory[dot] = 0; pData->bytes = dot; } return *this; } MFString& MFString::ClearRange(int offset, int length) { if(!pData) return *this; // limit within the strings range int maxChars = (int)pData->bytes - offset; if(length > maxChars) length = maxChars; // bail if we don't need to do anything if(length <= 0) return *this; // clear the range Detach(); int postBytes = (int)pData->bytes - (offset + length); pData->bytes -= length; char *pReplace = pData->pMemory + offset; const char *pTail = pReplace + length; for(int a=0; a <= postBytes; ++a) pReplace[a] = pTail[a]; return *this; } MFString& MFString::Replace(int offset, int range, MFString string) { if(!pData) { pData = string.pData; if(pData) ++pData->refCount; return *this; } // limit within the strings range offset = MFMin(offset, (int)pData->bytes); int maxChars = (int)pData->bytes - offset; if(range > maxChars) range = maxChars; // bail if we don't need to do anything int strLen = string.NumBytes(); if(range == 0 && strLen == 0) return *this; int reposition = strLen - range; int newSize = (int)pData->bytes + reposition; // reserve memory for the new string Reserve(newSize); // move tail into place if(reposition) { int tailOffset = offset + range; char *pSrc = pData->pMemory + tailOffset; char *pDest = pSrc + reposition; if(pDest < pSrc) { while(*pSrc) *pDest++ = *pSrc++; *pDest = 0; } else { int len = (int)pData->bytes - tailOffset; while(len >= 0) { pDest[len] = pSrc[len]; --len; } } } // insert string if(strLen) MFString_CopyN(pData->pMemory + offset, string.pData->pMemory, strLen); pData->bytes = newSize; return *this; } int MFString::FindChar(int c, int startOffset) const { if(pData) { const char *pStart = pData->pMemory + startOffset; const char *pT = pStart; while(*pT) { // decode utf8 int t; int bytes = MFString_DecodeUTF8(pT, &t); // check if the characters match if(t == c) return (int)(pT - pStart); // progress to next char pT += bytes; } } return -1; } int MFString::FindCharReverse(int c) const { if(pData) { const char *pT = pData->pMemory + pData->bytes; while(pT >= pData->pMemory) { // decode utf8 int t; MFString_DecodeUTF8(pT, &t); // check if the characters match if(t == c) return (int)(pT - pData->pMemory); // progress to prev char pT = MFString_PrevChar(pT); } } return -1; } MFString& MFString::Join(const MFArray<MFString> &strings, const char *pSeparator, const char *pTokenPrefix, const char *pTokenSuffix, const char *pBefore, const char *pAfter) { MFString result; size_t numTokens = strings.size(); // TODO: we should resize the string in advance... if(pBefore) result += pBefore; // TODO: alternate loops with different availability of parameters? for(size_t i=0; i<numTokens; ++i) { if(pSeparator && i>0) result += pSeparator; if(pTokenPrefix) result += pTokenPrefix; result += strings[i]; if(pTokenSuffix) result += pTokenSuffix; } if(pAfter) result += pAfter; *this = result; return *this; } MFArray<MFString>& MFString::Split(MFArray<MFString> &output, const char *pDelimiters) { output.clear(); if(!pData) return output; const char *pText = pData->pMemory; while(*pText) { const char *pEnd = MFSeekDelimiter(pText, pDelimiters); output.push(MFString(pText, (size_t)(pEnd - pText))); pText = MFSkipDelimiters(pEnd, pDelimiters); } return output; } int MFString::Enumerate(const MFArray<MFString> keys, bool bCaseSensitive) { if(IsEmpty()) return -1; for(size_t i=0; i<keys.size(); ++i) { if(bCaseSensitive ? Equals(keys[i]) : EqualsInsensitive(keys[i])) return (int)i; } return -1; } MFString MFString::StripToken(const char *pDelimiters) { if(!pData) return NULL; // find token const char *pText = CStr(); const char *pToken = MFSkipDelimiters(pText, pDelimiters); const char *pEnd = MFSeekDelimiter(pToken, pDelimiters); const char *pTrim = MFSkipDelimiters(pEnd, pDelimiters); // capture the token MFString token(pToken, (size_t)(pEnd - pToken)); // strip from source string size_t offset = pTrim - pText; if(offset > 0) { Detach(); for(size_t i = offset; i <= pData->bytes; ++i) pData->pMemory[i - offset] = pData->pMemory[i]; pData->bytes -= offset; } return token; } static MFString GetNextBit(const char *&pFormat) { MFString format; while(*pFormat) { if(*pFormat == '%') { if(pFormat[1] == '%') ++pFormat; else break; } else if(*pFormat == '\\') { if(pFormat[1] == 't') { format += '\t'; pFormat += 2; continue; } else if(pFormat[1] == 'n') { format += '\n'; pFormat += 2; continue; } else if(pFormat[1] == 'r') { format += '\r'; pFormat += 2; continue; } else ++pFormat; } format += *pFormat++; } return format; } static int Match(const char *pString, const char *pFormat) { if(!pFormat) return 0; const char *pStart = pString; while(*pFormat) { if(*pFormat == '?') { if(*pString == 0) return -1; } /* elseif(*pFormat == '*') { pString = MFString_Chr(pString, pFormat[1]); ++pFormat; continue; } */ else if(*pString != *pFormat) return -1; ++pString; ++pFormat; } return (int)(pString - pStart); } int MFString::Parse(const char *pFormat, ...) { if(!pData || !pFormat) return 0; va_list arglist; va_start(arglist, pFormat); const char *pS = pData->pMemory; int numArgs = 0; MFString format = GetNextBit(pFormat); int numChars = Match(pS, format.CStr()); while(*pFormat && numChars >= 0) { pS += numChars; ++pFormat; int length = -1; // gather format options... while(*pFormat) { int c = MFToLower(*pFormat++); if(c == 's') { MFString *pStr = va_arg(arglist, MFString*); ++numArgs; format = GetNextBit(pFormat); if(length >= 0) { MFString s(pS, (size_t)length); *pStr = s; numChars = Match(pS, format.CStr()); } else if(format.NumBytes() == 0) { *pStr = pS; } else { const char *pEnd = pS; while(*pEnd && (numChars = Match(pEnd, format.CStr())) < 0) ++pEnd; MFString s(pS, (size_t)(pEnd - pS)); *pStr = s; } pS += pStr->NumBytes(); break; } else if(c == 'd' || c == 'i') { int *pInt = va_arg(arglist, int*); ++numArgs; bool bNeg = *pS == '-'; if(*pS == '-' || *pS == '+') ++pS; *pInt = 0; while(MFIsNumeric(*pS) && ((uint32&)length)-- > 0) *pInt = *pInt*10 + *pS++ - '0'; if(bNeg) *pInt = -*pInt; format = GetNextBit(pFormat); numChars = Match(pS, format.CStr()); break; } else if(c == 'x') { int *pInt = va_arg(arglist, int*); ++numArgs; *pInt = 0; while(MFIsHex(*pS) && ((uint32&)length)-- > 0) { int digit = *pS++; *pInt = (*pInt << 4) + (MFIsNumeric(digit) ? digit - '0' : MFToLower(digit) - 'a' + 10); } format = GetNextBit(pFormat); numChars = Match(pS, format.CStr()); break; } else if(c == 'f') { float *pFloat = va_arg(arglist, float*); ++numArgs; *pFloat = MFString_AsciiToFloat(pS, &pS); format = GetNextBit(pFormat); numChars = Match(pS, format.CStr()); break; } else if(MFIsNumeric(c)) { // read numeric length length = 0; while(true) { length = length*10 + c - '0'; c = *pFormat; if(!MFIsNumeric(c)) break; ++pFormat; } } else if(c == '*') { // read length from varargs length = va_arg(arglist, int); ++numArgs; } } } va_end(arglist); return numArgs; }
20.372369
344
0.611762
TurkeyMan
3d1e3180cadbf87e7b353f14b832e1d99e1c2308
3,005
cpp
C++
MT Game Engine/Source/Interaction/Input.cpp
MatthewATaylor/MT-Game-Engine
bad800163a2ae5476fbe7d08a8c245e6a563c4fb
[ "MIT" ]
3
2019-10-08T20:58:43.000Z
2020-10-17T15:59:01.000Z
MT Game Engine/Source/Interaction/Input.cpp
MatthewATaylor/MT-Game-Engine
bad800163a2ae5476fbe7d08a8c245e6a563c4fb
[ "MIT" ]
null
null
null
MT Game Engine/Source/Interaction/Input.cpp
MatthewATaylor/MT-Game-Engine
bad800163a2ae5476fbe7d08a8c245e6a563c4fb
[ "MIT" ]
null
null
null
#include "Interaction/Input.h" namespace mtge { const int Input::GLFW_KEY_LIST[Input::NUM_KEYS] = { GLFW_KEY_UNKNOWN, GLFW_KEY_CAPS_LOCK, GLFW_KEY_NUM_LOCK, GLFW_KEY_SCROLL_LOCK, GLFW_KEY_PAGE_UP, GLFW_KEY_PAGE_DOWN, GLFW_KEY_HOME, GLFW_KEY_END, GLFW_KEY_PRINT_SCREEN, GLFW_KEY_PAUSE, GLFW_KEY_LEFT_CONTROL, GLFW_KEY_RIGHT_CONTROL, GLFW_KEY_LEFT_ALT, GLFW_KEY_RIGHT_ALT, GLFW_KEY_SPACE, GLFW_KEY_TAB, GLFW_KEY_ENTER, GLFW_KEY_BACKSPACE, GLFW_KEY_DELETE, GLFW_KEY_INSERT, GLFW_KEY_ESCAPE, GLFW_KEY_UP, GLFW_KEY_DOWN, GLFW_KEY_LEFT, GLFW_KEY_RIGHT, GLFW_KEY_A, GLFW_KEY_B, GLFW_KEY_C, GLFW_KEY_D, GLFW_KEY_E, GLFW_KEY_F, GLFW_KEY_G, GLFW_KEY_H, GLFW_KEY_I, GLFW_KEY_J, GLFW_KEY_K, GLFW_KEY_L, GLFW_KEY_M, GLFW_KEY_N, GLFW_KEY_O, GLFW_KEY_P, GLFW_KEY_Q, GLFW_KEY_R, GLFW_KEY_S, GLFW_KEY_T, GLFW_KEY_U, GLFW_KEY_V, GLFW_KEY_W, GLFW_KEY_X, GLFW_KEY_Y, GLFW_KEY_Z, GLFW_KEY_0, GLFW_KEY_1, GLFW_KEY_2, GLFW_KEY_3, GLFW_KEY_4, GLFW_KEY_5, GLFW_KEY_6, GLFW_KEY_7, GLFW_KEY_8, GLFW_KEY_9, GLFW_KEY_COMMA, GLFW_KEY_PERIOD, GLFW_KEY_SLASH, GLFW_KEY_BACKSLASH, GLFW_KEY_SEMICOLON, GLFW_KEY_APOSTROPHE, GLFW_KEY_LEFT_BRACKET, GLFW_KEY_RIGHT_BRACKET, GLFW_KEY_MINUS, GLFW_KEY_EQUAL, GLFW_KEY_GRAVE_ACCENT, GLFW_KEY_KP_0, GLFW_KEY_KP_1, GLFW_KEY_KP_2, GLFW_KEY_KP_3, GLFW_KEY_KP_4, GLFW_KEY_KP_5, GLFW_KEY_KP_6, GLFW_KEY_KP_7, GLFW_KEY_KP_8, GLFW_KEY_KP_9, GLFW_KEY_KP_ADD, GLFW_KEY_KP_SUBTRACT, GLFW_KEY_KP_MULTIPLY, GLFW_KEY_KP_DIVIDE, GLFW_KEY_KP_DECIMAL, GLFW_KEY_F1, GLFW_KEY_F2, GLFW_KEY_F3, GLFW_KEY_F4, GLFW_KEY_F5, GLFW_KEY_F6, GLFW_KEY_F7, GLFW_KEY_F8, GLFW_KEY_F9, GLFW_KEY_F10, GLFW_KEY_F11, GLFW_KEY_F12, GLFW_KEY_F13, GLFW_KEY_F14, GLFW_KEY_F15, GLFW_KEY_F16, GLFW_KEY_F17, GLFW_KEY_F18, GLFW_KEY_F19, GLFW_KEY_F20, GLFW_KEY_F21, GLFW_KEY_F22, GLFW_KEY_F23, GLFW_KEY_F24, GLFW_KEY_F25 }; CursorType Input::cursorType = CursorType::UNDEFINED; double Input::mouseX = 0.0; double Input::mouseY = 0.0; //Private void Input::mouseCursorCallback(GLFWwindow *window, double xPos, double yPos) { mouseX = xPos; mouseY = yPos; } //Public void Input::initCursorInput(Window *window) { glfwSetCursorPosCallback(window->getPtr_GLFW(), mouseCursorCallback); } bool Input::keyPressed(Window *window, Key key) { return (glfwGetKey(window->getPtr_GLFW(), GLFW_KEY_LIST[(int)key]) == GLFW_PRESS); } void Input::pollInput() { glfwPollEvents(); } void Input::setCursorType(Window *window, CursorType cursorType) { int cursorType_GLFW = 0; switch (cursorType) { case CursorType::NORMAL: cursorType_GLFW = GLFW_CURSOR_NORMAL; break; case CursorType::HIDDEN: cursorType_GLFW = GLFW_CURSOR_HIDDEN; break; case CursorType::DISABLED: cursorType_GLFW = GLFW_CURSOR_DISABLED; } glfwSetInputMode(window->getPtr_GLFW(), GLFW_CURSOR, cursorType_GLFW); Input::cursorType = cursorType; } CursorType Input::getCursorType() { return cursorType; } double Input::getMouseX() { return mouseX; } double Input::getMouseY() { return mouseY; } }
46.230769
213
0.797338
MatthewATaylor
3d1f3dd38753110136a4eb68769d5107bb53d903
8,847
hpp
C++
src/AnimationData.hpp
AnimatedLEDStrip/client-cpp
b16ec6b638659d4af0c31c3767590dcfee0290b4
[ "MIT" ]
null
null
null
src/AnimationData.hpp
AnimatedLEDStrip/client-cpp
b16ec6b638659d4af0c31c3767590dcfee0290b4
[ "MIT" ]
null
null
null
src/AnimationData.hpp
AnimatedLEDStrip/client-cpp
b16ec6b638659d4af0c31c3767590dcfee0290b4
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019-2020 AnimatedLEDStrip * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef ANIMATEDLEDSTRIP_ANIMATIONDATA_HPP #define ANIMATEDLEDSTRIP_ANIMATIONDATA_HPP #include <iostream> #include <string> #include <nlohmann/json.hpp> #include "ColorContainer.hpp" #define MAX_LEN 10000 enum Continuous { CONTINUOUS, NONCONTINUOUS, DEFAULT }; enum Direction { FORWARD, BACKWARD }; class AnimationData { public: std::string animation = "Color"; std::vector<ColorContainer> colors; int center = -1; Continuous continuous = DEFAULT; long delay = -1; double delay_mod = 1.0; Direction direction = FORWARD; int distance = -1; std::string id = ""; std::string section = ""; int spacing = -1; AnimationData & setAnimation(const std::string & a) { animation.assign(a); return *this; } AnimationData & setAnimation(const char * a) { animation.assign(a); return *this; } AnimationData & addColor(ColorContainer & c) { colors.push_back(c); return *this; } AnimationData & setCenter(int c) { center = c; return *this; } AnimationData & setContinuous(enum Continuous c) { continuous = c; return *this; } AnimationData & setDelay(long d) { delay = d; return *this; } AnimationData & setDelayMod(double d) { delay_mod = d; return *this; } AnimationData & setDirection(enum Direction d) { direction = d; return *this; } AnimationData & setDistance(int d) { distance = d; return *this; } AnimationData & setId(const std::string & i) { id.assign(i); return *this; } AnimationData & setId(const char * i) { id.assign(i); return *this; } AnimationData & setSection(const std::string & s) { section.assign(s); return *this; } AnimationData & setSection(const char * s) { section.assign(s); return *this; } AnimationData & setSpacing(int s) { spacing = s; return *this; } static std::string continuousToString(enum Continuous c) { switch (c) { case CONTINUOUS: return "true"; case NONCONTINUOUS: return "false"; case DEFAULT: return "null"; } } static enum Direction directionFromString(const std::string & d) { if (std::strcmp(d.c_str(), "BACKWARD") == 0) return BACKWARD; else if (std::strcmp(d.c_str(), "FORWARD") == 0) return FORWARD; else { std::cerr << "Bad direction string " << d << std::endl; return FORWARD; } } static std::string directionToString(enum Direction d) { switch (d) { case FORWARD: return "FORWARD"; case BACKWARD: return "BACKWARD"; } } AnimationData() = default; explicit AnimationData(nlohmann::json data) { if (data["animation"].is_string()) setAnimation(data["animation"].get<std::string>()); else if (!data["animation"].is_null()) std::cerr << "Bad type for animation" << data["animation"].type_name() << std::endl; if (data["colors"].is_array()) for (auto & c : data["colors"].items()) { if (c.value().is_object()) { ColorContainer cc = ColorContainer(c.value()); addColor(cc); } } else if (!data["colors"].is_null()) std::cerr << "Bad type for colors" << data["colors"].type_name() << std::endl; if (data["center"].is_number_integer()) setCenter(data["center"].get<int>()); else if (!data["center"].is_null()) std::cerr << "Bad type for center" << data["center"].type_name() << std::endl; if (data["continuous"].is_null()) setContinuous(DEFAULT); else if (data["continuous"].is_boolean() && data["continuous"].get<bool>()) setContinuous(CONTINUOUS); else if (data["continuous"].is_boolean() && !data["continuous"].get<bool>()) setContinuous(NONCONTINUOUS); else std::cerr << "Bad type for continuous" << data["continuous"].type_name() << std::endl; if (data["delay"].is_number_integer()) setDelay(data["delay"].get<int>()); else if (!data["delay"].is_null()) std::cerr << "Bad type for delay" << data["delay"].type_name() << std::endl; if (data["delayMod"].is_number_float()) setDelayMod(data["delayMod"].get<double>()); else if (!data["delayMod"].is_null()) std::cerr << "Bad type for delayMod" << data["delayMod"].type_name() << std::endl; if (data["direction"].is_string()) setDirection(directionFromString(data["direction"].get<std::string>())); else if (!data["direction"].is_null()) std::cerr << "Bad type for direction" << data["direction"].type_name() << std::endl; if (data["distance"].is_number_integer()) setDistance(data["distance"].get<int>()); else if (!data["distance"].is_null()) std::cerr << "Bad type for distance" << data["distance"].type_name() << std::endl; if (data["id"].is_string()) setId(data["id"].get<std::string>()); else if (!data["id"].is_null()) std::cerr << "Bad type for id" << data["id"].type_name() << std::endl; if (data["section"].is_string()) setSection(data["section"].get<std::string>()); else if (!data["section"].is_null()) std::cerr << "Bad type for section" << data["section"].type_name() << std::endl; if (data["spacing"].is_number_integer()) setSpacing(data["spacing"].get<int>()); else if (!data["spacing"].is_null()) std::cerr << "Bad type for spacing" << data["spacing"].type_name() << std::endl; } std::string colorsString() { std::string cols = "["; for (auto c : colors) { cols.append(c.colorsString(true)); cols.append(","); } if (!colors.empty()) cols.pop_back(); cols.append("]"); return cols; } int json(char ** buff) const { std::string data = "DATA:{"; data.append(R"("animation":")"); data.append(animation); data.append(R"(","colors":[)"); char * cBuff = new char[MAX_LEN]; for (ColorContainer c : colors) { cBuff[0] = 0; c.json(&cBuff); data.append(cBuff); data.append(","); } if (!colors.empty()) data.pop_back(); data.append(R"(],"center":)"); data.append(std::to_string(center)); data.append(R"(,"continuous":)"); data.append(continuousToString(continuous)); data.append(R"(,"delay":)"); data.append(std::to_string(delay)); data.append(R"(,"delayMod":)"); data.append(std::to_string(delay_mod)); data.append(R"(,"direction":")"); data.append(directionToString(direction)); data.append(R"(","distance":)"); data.append(std::to_string(distance)); data.append(R"(,"id":")"); data.append(id); data.append(R"(","section":")"); data.append(section); data.append(R"(","spacing":)"); data.append(std::to_string(spacing)); data.append("}"); std::strcpy(*buff, data.c_str()); return data.size(); } }; #endif // ANIMATEDLEDSTRIP_ANIMATIONDATA_HPP
30.091837
98
0.565163
AnimatedLEDStrip
3d27dda5a7ee08d9aaaca11d0164c87d9e2c07a7
451
cpp
C++
sdk/poeng/stdafx.cpp
hadrien-psydk/pngoptimizer
d92946e63a57a4562af0feaa9e4cfd8628373777
[ "Zlib" ]
90
2016-08-23T00:13:04.000Z
2022-02-22T09:40:46.000Z
sdk/poeng/stdafx.cpp
hadrien-psydk/pngoptimizer
d92946e63a57a4562af0feaa9e4cfd8628373777
[ "Zlib" ]
25
2016-09-01T07:09:03.000Z
2022-01-31T16:18:57.000Z
sdk/poeng/stdafx.cpp
hadrien-psydk/pngoptimizer
d92946e63a57a4562af0feaa9e4cfd8628373777
[ "Zlib" ]
17
2017-05-03T17:49:25.000Z
2021-12-28T06:47:56.000Z
///////////////////////////////////////////////////////////////////////////////////// // This file is part of the POEngine library, part of the PngOptimizer application // Copyright (C) Hadrien Nilsson - psydk.org // This library is distributed under the terms of the GNU LESSER GENERAL PUBLIC LICENSE // See License.txt for the full license. ///////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h"
45.1
87
0.472284
hadrien-psydk
3d2cdd91f776ec8572b6092cb48e06b0890bf686
23
cpp
C++
src/Core_ally.cpp
Riateche/ridual
d91ca5326438e15fccd38a4e4263aeb291d64539
[ "MIT" ]
3
2015-07-08T07:41:36.000Z
2017-11-08T15:01:26.000Z
src/Core_ally.cpp
Riateche/ridual
d91ca5326438e15fccd38a4e4263aeb291d64539
[ "MIT" ]
null
null
null
src/Core_ally.cpp
Riateche/ridual
d91ca5326438e15fccd38a4e4263aeb291d64539
[ "MIT" ]
null
null
null
#include "Core_ally.h"
11.5
22
0.73913
Riateche
3d2de11dd2467a80e4300f297a62b03f5d8620cb
49
hpp
C++
addons/main/script_version.hpp
YonVclaw/6sfdgdemo
f09b4ed8569cd0fcbca4c634aa79289f1ca84014
[ "MIT" ]
null
null
null
addons/main/script_version.hpp
YonVclaw/6sfdgdemo
f09b4ed8569cd0fcbca4c634aa79289f1ca84014
[ "MIT" ]
null
null
null
addons/main/script_version.hpp
YonVclaw/6sfdgdemo
f09b4ed8569cd0fcbca4c634aa79289f1ca84014
[ "MIT" ]
null
null
null
#define MAJOR 1 #define MINOR 14 #define PATCH 2
12.25
16
0.755102
YonVclaw
3d35c3c9a7b42ea5e888bed29e718ccd70f36423
7,306
hpp
C++
include/argot/prov/switch_/detail/generate_switch_provision.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
49
2018-05-09T23:17:45.000Z
2021-07-21T10:05:19.000Z
include/argot/prov/switch_/detail/generate_switch_provision.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
null
null
null
include/argot/prov/switch_/detail/generate_switch_provision.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
2
2019-08-04T03:51:36.000Z
2020-12-28T06:53:29.000Z
/*============================================================================== Copyright (c) 2017, 2018 Matt Calabrese 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 ARGOT_PROV_SWITCH_DETAIL_GENERATE_SWITCH_PROVISION_HPP_ #define ARGOT_PROV_SWITCH_DETAIL_GENERATE_SWITCH_PROVISION_HPP_ #ifndef ARGOT_PREPROCESSING_MODE #include <argot/concepts/switch_body_default.hpp> #include <argot/detail/unreachable.hpp> #include <argot/detail/forward.hpp> #include <argot/gen/is_modeled.hpp> #include <argot/prov/switch_/detail/config.hpp> #include <argot/prov/switch_/detail/switch_impl_fwd.hpp> #include <argot/prov/switch_/detail/switch_provision_base.hpp> #include <argot/prov/switch_/detail/switch_provision_fwd.hpp> #include <argot/switch_traits/argument_list_kinds_of_body_destructive.hpp> #include <argot/switch_traits/argument_list_kinds_of_body_persistent.hpp> #include <argot/switch_traits/case_value_for_type_at.hpp> #include <argot/switch_traits/destructive_provide_case.hpp> #include <argot/switch_traits/destructive_provide_default.hpp> #include <argot/switch_traits/num_cases.hpp> #include <argot/switch_traits/persistent_provide_case.hpp> #include <argot/switch_traits/persistent_provide_default.hpp> #include <argot/unreachable_function.hpp> #include <boost/preprocessor/arithmetic/dec.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <cstddef> namespace argot::prov::switch_detail { #if ARGOT_MAX_PREPROCESSED_SWITCH_CASES_IS_VALID //////////////////////////////////////////////////////////////////////////////// // Begin generation of switch_provision specializations... // //////////////////////////////////////////////////////////////////////////////// #define BOOST_PP_ITERATION_PARAMS_1 \ ( 3, ( 1, ARGOT_MAX_PREPROCESSED_SWITCH_CASES \ , <argot/prov/switch_/detail/generation/switch_generation.hpp> \ ) \ ) #include BOOST_PP_ITERATE() //////////////////////////////////////////////////////////////////////////////// // End generation of switch_provision specializations. // //////////////////////////////////////////////////////////////////////////////// // This default definition handles situations where there are more cases than // can fit in a single, preprocessed switch-statement. An instantation // represents either the first or an intermediate link in a chain of // switch-statements whose maximum number of cases is // ARGOT_MAX_PREPROCESSED_SWITCH_CASES. template< std::size_t NumRemainingCases, provision_kind Kind > struct switch_provision : switch_provision_base< Kind > { using base_t = switch_provision_base< Kind >; template< class T > using with_qualifiers_t = typename base_t::template with_qualifiers_t< T >; template< auto V > using provide_case_t = typename base_t::template provide_case_t< V >; using provide_default_t = typename base_t::provide_default_t; template< class Body, class ValueType > using argument_list_kinds_of_body_t = typename base_t ::template argument_list_kinds_of_body_t< Body, ValueType >; /* TODO(mattcalabrese) Constrain*/ template< class ValueType, class... Bodies, class Receiver > static constexpr decltype( auto ) run ( with_qualifiers_t < prov::switch_detail::switch_impl< ValueType, Bodies... > > self , Receiver&& receiver ) { using body_t = typename prov::switch_detail::switch_impl< ValueType, Bodies... > ::body_t; using qualified_body_t = with_qualifiers_t< body_t >; std::size_t constexpr index_offset = switch_traits::num_cases_v< body_t > - NumRemainingCases; switch( self.value ) { //////////////////////////////////////////////////////////////////////////////// // Begin generation of cases... // //////////////////////////////////////////////////////////////////////////////// #define BOOST_PP_ITERATION_PARAMS_1 \ ( 3, ( 0, ARGOT_MAX_PREPROCESSED_SWITCH_CASES - 1 \ , <argot/prov/switch_/detail/generation/case_generation.hpp> \ ) \ ) #include BOOST_PP_ITERATE() //////////////////////////////////////////////////////////////////////////////// // End generation of cases. // //////////////////////////////////////////////////////////////////////////////// default: return switch_provision < NumRemainingCases - ARGOT_MAX_PREPROCESSED_SWITCH_CASES, Kind >::run ( static_cast < with_qualifiers_t < prov::switch_detail::switch_impl< ValueType, Bodies... > > >( self ) , static_cast< Receiver&& >( receiver ) ); } } }; #endif // ARGOT_MAX_PREPROCESSED_SWITCH_CASES_IS_VALID } // namespace (argot::prov::switch_detail) #else // Otherwise, we are generating the preprocessed forms as files... #define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 1, 2 ) #include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp> #include <argot/prov/switch_/detail/generate_switch_provision_range.hpp> #if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 3 #define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 3, 4 ) #include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp> #include <argot/prov/switch_/detail/generate_switch_provision_range.hpp> #endif #if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 5 #define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 5, 8 ) #include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp> #include <argot/prov/switch_/detail/generate_switch_provision_range.hpp> #endif #if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 9 #define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 9, 16 ) #include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp> #include <argot/prov/switch_/detail/generate_switch_provision_range.hpp> #endif #if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 17 #define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 17, 32 ) #include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp> #include <argot/prov/switch_/detail/generate_switch_provision_range.hpp> #endif #if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 33 #define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 33, 64 ) #include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp> #include <argot/prov/switch_/detail/generate_switch_provision_range.hpp> #endif #if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 65 #error User requested preprocessing for switches with more than 64 cases. #endif #undef ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE #endif // End of preprocessing mode checks #endif // ARGOT_PROV_SWITCH_DETAIL_GENERATE_SWITCH_PROVISION_HPP_
40.142857
85
0.656584
mattcalabrese
3d3bb9d6ec3066e7ae8aa645808da6c09ff82951
678
cpp
C++
simple_model_loader/src/main.cpp
JacobNeal/gl-projects
4ea40797fde28602b9f787f0ec8005dcd164e054
[ "MIT" ]
null
null
null
simple_model_loader/src/main.cpp
JacobNeal/gl-projects
4ea40797fde28602b9f787f0ec8005dcd164e054
[ "MIT" ]
null
null
null
simple_model_loader/src/main.cpp
JacobNeal/gl-projects
4ea40797fde28602b9f787f0ec8005dcd164e054
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include "ModelLoader.hpp" #include "Model.hpp" #include "Window.hpp" #include "Logger.hpp" LOGGER_DECL int main() { Window window("Simple Model Loader", 800, 640); ModelLoader modelLoader; Model * model = modelLoader.load("cube.MODEL"); while (!window.isDone()) { window.beginDraw(); window.update(); window.draw(model); window.endDraw(); } // Clean up after the ModelLoader delete model; std::cout << LOGGER; std::ofstream logFile("log.txt"); if (logFile.is_open()) { logFile << LOGGER; logFile.close(); } return 0; }
14.73913
51
0.589971
JacobNeal
3d3ee1870119b322c1714c4886457ca06e699be7
1,010
cpp
C++
src/random/NormalDistribution.cpp
cuhkshenzhen/CUHKSZLib
4ad122d7e736cda3e768c8ae8dcad1f9fb195a1f
[ "MIT" ]
null
null
null
src/random/NormalDistribution.cpp
cuhkshenzhen/CUHKSZLib
4ad122d7e736cda3e768c8ae8dcad1f9fb195a1f
[ "MIT" ]
29
2017-04-26T09:15:28.000Z
2017-05-21T15:50:37.000Z
src/random/NormalDistribution.cpp
cuhkshenzhen/CUHKSZLib
4ad122d7e736cda3e768c8ae8dcad1f9fb195a1f
[ "MIT" ]
7
2017-04-26T09:32:39.000Z
2021-11-03T02:00:07.000Z
#include "random/NormalDistribution.h" #include <cmath> #include "utils/error.h" namespace cuhksz { void NormalDistribution::init(double mean, double stddev) { if (stddev <= 0) { error("Invalid parameter `stddev` for NormalDistribution"); } mean_ = mean; stddev_ = stddev; } double NormalDistribution::next() { // Marsaglia polar method // (https://en.wikipedia.org/wiki/Marsaglia_polar_method) if (hasSpare) { hasSpare = false; return spareResult * stddev_ + mean_; } double u; double v; double sum; do { u = randomGenerator->nextDouble(-1, 1); v = randomGenerator->nextDouble(-1, 1); sum = u * u + v * v; // disable gcc's warning for comparing with 0.0 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" } while (sum == 0.0 || sum > 1); #pragma GCC diagnostic pop double result = std::sqrt(-2 * std::log(sum) / sum); spareResult = v * result; hasSpare = true; return u * result * stddev_ + mean_; } } // namespace cuhksz
24.634146
63
0.664356
cuhkshenzhen
3d406ccf27012fa7f5b609ec3291bada72ac6268
140
hpp
C++
template-bot/src/utils.hpp
bmstu-iu8-cpp-sem-1/homework-telegram-bot
138f6611e4ca08b9a5c4dde76c54af1cefe6504c
[ "MIT" ]
2
2021-03-09T08:12:28.000Z
2022-02-21T18:10:36.000Z
template-bot/src/utils.hpp
sjuda/telegram-bot
11f7bb7f24044bdd4e0d30b7a65757e5a4d1be8d
[ "MIT" ]
null
null
null
template-bot/src/utils.hpp
sjuda/telegram-bot
11f7bb7f24044bdd4e0d30b7a65757e5a4d1be8d
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <boost/locale.hpp> namespace Utils { std::string fromLocale(const std::string& localeStr); }
12.727273
57
0.714286
bmstu-iu8-cpp-sem-1
3d420cd5393eba0250fc200d6e0304cc05ed703d
3,343
cpp
C++
Code/System/Resource/ResourceLoader.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
[ "MIT" ]
419
2022-01-27T19:37:43.000Z
2022-03-31T06:14:22.000Z
Code/System/Resource/ResourceLoader.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
2
2022-01-28T20:35:33.000Z
2022-03-13T17:42:52.000Z
Code/System/Resource/ResourceLoader.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
20
2022-01-27T20:41:02.000Z
2022-03-26T16:16:57.000Z
#include "ResourceLoader.h" #include "ResourceHeader.h" #include "System/Core/Serialization/BinaryArchive.h" #include "System/Core/Logging/Log.h" //------------------------------------------------------------------------- namespace KRG::Resource { bool ResourceLoader::Load( ResourceID const& resourceID, TVector<Byte>& rawData, ResourceRecord* pResourceRecord ) const { Serialization::BinaryMemoryArchive archive( Serialization::Mode::Read, rawData ); if ( archive.IsValid() ) { // Read resource header Resource::ResourceHeader header; archive >> header; // Set all install dependencies pResourceRecord->m_installDependencyResourceIDs.reserve( header.m_installDependencies.size() ); for ( auto const& depResourceID : header.m_installDependencies ) { pResourceRecord->m_installDependencyResourceIDs.push_back( depResourceID ); } // Perform resource load if ( !LoadInternal( resourceID, pResourceRecord, archive ) ) { KRG_LOG_ERROR( "Resource", "Resource loader failed to load resource: %s", resourceID.c_str() ); return false; } // Loaders must always set a valid resource data ptr, even if the resource internally is invalid // This is enforced to prevent leaks from occurring when a loader allocates a resource, then tries to // load it unsuccessfully and then forgets to release the allocated data. KRG_ASSERT( pResourceRecord->GetResourceData() != nullptr ); return true; } else { KRG_LOG_ERROR( "Resource", "Failed to read binary resource data (%s)", resourceID.c_str() ); return false; } } InstallResult ResourceLoader::Install( ResourceID const& resourceID, ResourceRecord* pResourceRecord, InstallDependencyList const& installDependencies ) const { KRG_ASSERT( pResourceRecord != nullptr ); pResourceRecord->m_pResource->m_resourceID = resourceID; return InstallResult::Succeeded; } InstallResult ResourceLoader::UpdateInstall( ResourceID const& resourceID, ResourceRecord* pResourceRecord ) const { // This function should never be called directly!! // If your resource requires multi-frame installation, you need to override this function in your loader and return InstallResult::InProgress from the install function! KRG_UNREACHABLE_CODE(); return InstallResult::Succeeded; } void ResourceLoader::Unload( ResourceID const& resourceID, ResourceRecord* pResourceRecord ) const { KRG_ASSERT( pResourceRecord != nullptr ); KRG_ASSERT( pResourceRecord->IsUnloading() || pResourceRecord->HasLoadingFailed() ); UnloadInternal( resourceID, pResourceRecord ); pResourceRecord->m_installDependencyResourceIDs.clear(); } void ResourceLoader::UnloadInternal( ResourceID const& resourceID, ResourceRecord* pResourceRecord ) const { IResource* pData = pResourceRecord->GetResourceData(); KRG::Delete( pData ); pResourceRecord->SetResourceData( nullptr ); } }
44.573333
177
0.638648
JuanluMorales
3d4c6a768bef0b77475e30aa4f9b42aff74bbba1
444
cpp
C++
codeforces/1108B.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
codeforces/1108B.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
codeforces/1108B.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> #define le 130 using namespace std; int n[le]; map<int, int> mp; int main(){ //freopen("input.txt", "r", stdin); int len, mx = -INT_MAX, mx1 = -INT_MAX; scanf("%d", &len); for(int i = 0; i < len; i++){ scanf("%d", &n[i]); mx = max(mx, n[i]); } for(int i = 0; i < len; i++){ mp[n[i]]++; if(mx % n[i] != 0 || mp[n[i]] > 1) mx1 = max(mx1, n[i]); } printf("%d %d\n", mx, mx1); return 0; }
21.142857
60
0.481982
cosmicray001
3d4cbc776bb8b6c4f70872c069f5e89785342846
620
cpp
C++
c++11/understanding-cpp11/chapter7/7-3-13.cpp
cuiwm/choe_lib
6992c7bf551e7d6d633399b21b028e6873d5e6e8
[ "MIT" ]
null
null
null
c++11/understanding-cpp11/chapter7/7-3-13.cpp
cuiwm/choe_lib
6992c7bf551e7d6d633399b21b028e6873d5e6e8
[ "MIT" ]
null
null
null
c++11/understanding-cpp11/chapter7/7-3-13.cpp
cuiwm/choe_lib
6992c7bf551e7d6d633399b21b028e6873d5e6e8
[ "MIT" ]
null
null
null
#include <vector> #include <algorithm> using namespace std; vector<int> nums; vector<int> largeNums; const int ubound = 10; inline void LargeNumsFunc(int i){ if (i > ubound) largeNums.push_back(i); } void Above() { // 传统的for循环 for (auto itr = nums.begin(); itr != nums.end(); ++itr) { if (*itr >= ubound) largeNums.push_back(*itr); } // 使用函数指针 for_each(nums.begin(), nums.end(), LargeNumsFunc); // 使用lambda函数和算法for_each for_each(nums.begin(), nums.end(), [=](int i){ if (i > ubound) largeNums.push_back(i); }); }
19.375
61
0.562903
cuiwm
3d4cc3e641a6d66de21abeea0c2035956e900a7d
5,612
cpp
C++
FBConsole.cpp
StereoRocker/fbconsole
a0ad55525f1c6a0a048147f8d5317a081fe372f0
[ "BSD-3-Clause" ]
null
null
null
FBConsole.cpp
StereoRocker/fbconsole
a0ad55525f1c6a0a048147f8d5317a081fe372f0
[ "BSD-3-Clause" ]
null
null
null
FBConsole.cpp
StereoRocker/fbconsole
a0ad55525f1c6a0a048147f8d5317a081fe372f0
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Dominic Houghton. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Framebuffer console driver, using the I_Framebuffer interface #include "FBConsole.hpp" template <class T> FBConsole<T>::FBConsole(I_Framebuffer<T>* framebuffer, uint8_t* font, uint8_t scale) { // These will hold the display's actual dimensions while initialising uint16_t display_width, display_height; // Set the constants within the class _FRAMEBUFFER = framebuffer; _FONT = font; _SCALE = scale; // Calculate the console width and height, store them within the class _FRAMEBUFFER->get_dimensions(&display_width, &display_height); _WIDTH = display_width / (8 * _SCALE); _HEIGHT = display_height / (8 * _SCALE); /* Create a buffer of pixels, large enough to hold a single character. * The put_char function will use this array, so as to maintain a consistent * memory footprint. * * Scaling the font to be larger will increase the memory footprint * exponentially. */ _CHARBUF = new T[(8 * _SCALE) * (8 * _SCALE)]; // Set sane defaults for the runtime variables console_background = _FRAMEBUFFER->get_color(0x00,0x00,0x00); // Black console_foreground = _FRAMEBUFFER->get_color(0xFF,0xFF,0xFF); // White console_x = 0; console_y = 0; } template <class T> void FBConsole<T>::put_char(char c) { // Determine the character to draw uint16_t charindex = 0; bool drawchar = true; int count; // Handle special-case characters, or calculate the font index switch (c) { case '\n': // Line feed, handled unix-style drawchar = false; console_x = 0; console_y++; break; case '\r': // Carriage return drawchar = false; console_x = 0; break; case '\t': // Tab count = _TABSTOP - ((console_x) % _TABSTOP); for (int i = 0; i < count; i++) put_char(' '); drawchar = false; break; case '\b': // Backspace if (console_x > 0) console_x--; drawchar = false; break; // If character is none of the special cases above default: // Test if the character is mapped in the font if (c >= 0x20 || c <= 0x7E) charindex = (c - 0x20); else charindex = 95; // font[95] contains the "invalid" glyph break; } // Fill the character buffer // Iterate through the character data if (drawchar) { T* color; for (int cy = 0; cy < 8; cy++) { for (int cx = 0; cx < 8; cx++) { // Test the bit if ( ((_FONT[(charindex * 8) + cy] << cx) & 0x80) == 0x80 ) color = &console_foreground; else color = &console_background; // Plot the color in the character buffer for (int by = 0; by < _SCALE; by++) { for (int bx = 0; bx < _SCALE; bx++) { //_CHARBUF[((cy + by) * 8 * _SCALE) + (cx * _SCALE) + bx] = *color; //_CHARBUF[(cy * 8 * _SCALE) + (cx * _SCALE) + bx] = *color; _CHARBUF[ (((cy * _SCALE) + by) * (8 * _SCALE)) + (cx * _SCALE) + bx] = *color; } } } } // Plot the character buffer uint16_t dx, dy; dx = (console_x * 8 * _SCALE); dy = (console_y * 8 * _SCALE); _FRAMEBUFFER->plot_block(dx, dy, dx + (8 * _SCALE) - 1, dy + (8 * _SCALE) - 1, _CHARBUF, (8 * _SCALE) * (8 * _SCALE)); // Increase console_x console_x++; } // Test console_x, increment console_y if necessary if (console_x >= _WIDTH) { console_x = 0; console_y++; } // Test console_y, call scroll_vertical if necessary if (console_y >= _HEIGHT) { _FRAMEBUFFER->scroll_vertical(8 * _SCALE); // If scroll_vertical was called, decrement console_y and clear the row console_y--; // Set character with only background for (int cy = 0; cy < 8; cy++) { for (int cx = 0; cx < 8; cx++) { // Plot the color in the character buffer for (int by = 0; by < _SCALE; by++) { for (int bx = 0; bx < _SCALE; bx++) { _CHARBUF[ (((cy * _SCALE) + by) * (8 * _SCALE)) + (cx * _SCALE) + bx] = console_background; } } } } // Clear the row with the background color int dy = (console_y * 8 * _SCALE); int dx; for (int x = 0; x < _WIDTH; x++) { dx = (x * 8 * _SCALE); _FRAMEBUFFER->plot_block(dx, dy, dx + (8 * _SCALE) - 1, dy + (8 * _SCALE) - 1, _CHARBUF, (8 * _SCALE) * (8 * _SCALE)); } } } template <class T> void FBConsole<T>::put_string(const char* str) { int i = 0; for (i = 0; str[i] != 0; i++) put_char(str[i]); } template class FBConsole<uint8_t>; template class FBConsole<uint16_t>; template class FBConsole<uint32_t>;
30.335135
115
0.50392
StereoRocker
3d4d428b5518f3ebfb7a75e47af0c31a1f7b8b90
271
cpp
C++
tester-webserv/CppTester/src/Utility/close_pipe.cpp
aprilmayjune135/42_web_server
46bc46dd6a0008119842e3848d4fe57fcd84526b
[ "MIT" ]
2
2022-01-04T13:07:46.000Z
2022-01-04T13:08:50.000Z
tester-webserv/CppTester/src/Utility/close_pipe.cpp
aprilmayjune135/web-server
46bc46dd6a0008119842e3848d4fe57fcd84526b
[ "MIT" ]
3
2021-09-27T08:35:34.000Z
2021-11-25T09:49:52.000Z
tester-webserv/CppTester/src/Utility/close_pipe.cpp
aprilmayjune135/web-server
46bc46dd6a0008119842e3848d4fe57fcd84526b
[ "MIT" ]
2
2021-11-17T20:26:55.000Z
2021-12-22T21:54:24.000Z
#include "utility.hpp" #include "macros.hpp" #include <unistd.h> #include <stdio.h> namespace util { void closeFd(int fd) { if (close(fd) == -1) { syscallError(_FUNC_ERR("close")); } } void closePipe(int* fds) { closeFd(fds[0]); closeFd(fds[1]); } }
12.318182
36
0.612546
aprilmayjune135
3d5811c0d2006ec2c33ae0fdf33af47b00862d3d
752
cpp
C++
halfacookie.cpp
nemo201/Kattis
887711eece263965a4529048011847f7a2749fec
[ "MIT" ]
null
null
null
halfacookie.cpp
nemo201/Kattis
887711eece263965a4529048011847f7a2749fec
[ "MIT" ]
null
null
null
halfacookie.cpp
nemo201/Kattis
887711eece263965a4529048011847f7a2749fec
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for(int i = a; i < (b); ++i) #define trav(a, x) for(auto& a : x) #define all(x) x.begin(), x.end() #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; int main() { cout << fixed << setprecision(4); double r, x, y; while(cin >> r >> x >> y){ if(sqrt(x * x + y * y) >= r){ cout << "miss" << endl; } else { double h = r - sqrt(x * x + y * y); double area = r * r * 3.141592653589793238462643383; double seg_area = r * r * acos((r - h) / r) - (r - h) * sqrt((2 * r * h - h * h)); cout << area - seg_area << " " << seg_area << endl; } } }
30.08
94
0.482713
nemo201
3d59a072f742b1c1ae7225767f5ef46ae0edec0c
1,088
cpp
C++
Tree Algorithms/Distance Queries.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T12:30:13.000Z
2022-02-12T13:59:20.000Z
Tree Algorithms/Distance Queries.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T11:09:41.000Z
2022-02-12T11:55:49.000Z
Tree Algorithms/Distance Queries.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<vector<int>> adjList; int up[(int)(2e5+1.5)][20] {}; vector<int>tin,tout,d; int n,q,timer; void dfs(int curr,int pre){ tin[curr]=timer++; up[curr][0]=pre; for (int i=1;i<20;++i){ up[curr][i]=up[up[curr][i-1]][i-1]; } for (int &v:adjList[curr]){ if (v==pre) continue; d[v]=d[curr]+1; dfs(v,curr); } tout[curr]=timer++; } bool is_ancestor(int par,int child){ return tin[par]<=tin[child]&&tout[par]>=tout[child]; } int lca(int n1,int n2){ if (is_ancestor(n1,n2)) return n1; if (is_ancestor(n2,n1)) return n2; for (int i=19;i>=0;--i){ if (!is_ancestor(up[n1][i],n2)) n1=up[n1][i]; } return up[n1][0]; } int main(){ ios::sync_with_stdio(false);cin.tie(NULL); cin>>n>>q; adjList.assign(n,vector<int>()); tin.assign(n,-1); tout.assign(n,-1); d.assign(n,-1); d[0]=0; timer=0; for (int i=1;i<n;++i){ int a,b;cin>>a>>b;--a;--b; adjList[a].push_back(b); adjList[b].push_back(a); } dfs(0,0); for (int i=0;i<q;++i){ int a,b; cin>>a>>b;--a;--b; cout<<d[a]+d[b]-2*d[lca(a,b)]<<'\n'; } return 0; }
19.087719
53
0.579963
DecSP
3d5e27cb374a8905ccf9b4d80607ae7935995314
2,235
cpp
C++
sdlpaint/rcolor.cpp
cbries/utilities
86ce97d2c3e0d13b9beb0fc6ec79d31945c14461
[ "MIT" ]
1
2015-02-22T17:40:23.000Z
2015-02-22T17:40:23.000Z
sdlpaint/rcolor.cpp
cbries/utilities
86ce97d2c3e0d13b9beb0fc6ec79d31945c14461
[ "MIT" ]
null
null
null
sdlpaint/rcolor.cpp
cbries/utilities
86ce97d2c3e0d13b9beb0fc6ec79d31945c14461
[ "MIT" ]
null
null
null
/** * Copyright (C) 2007 Christian B. Ries * License: MIT * Website: https://github.com/cbries/utilities */ #include "rcolor.h" RColor::RColor() { setType( COLOR ); } RColor::RColor( const SDL_Surface * surface, int xpos, int ypos, int width, int height ) : RButton( surface, xpos, ypos, width, height ) { setType( COLOR ); } RColor::~RColor() { } void RColor::draw() { SDL_Rect clip; clip.x = x(); clip.y = y(); clip.w = width(); clip.h = height(); SDL_SetClipRect((SDL_Surface*)surface(), &clip); if( _state == NOTACTIVE ) { boxRGBA( (SDL_Surface*)surface(), x(), y(), x_end()-2, y_end()-2, _r, _g, _b, 255 ); rectangleRGBA( (SDL_Surface*)surface(), x(), y(), x_end()-2, y_end()-2, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x() + 2, y_end() - 2, x_end(), y_end() - 2, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x() + 2, y_end() - 1, x_end(), y_end() - 1, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x() + 2, y_end() - 0, x_end(), y_end() - 0, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x_end() - 2, y() + 2, x_end() - 2, y_end() - 2, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x_end() - 1, y() + 2, x_end() - 1, y_end() - 2, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x_end() - 0, y() + 2, x_end() - 0, y_end() - 2, 0, 0, 0, 255 ); } if( _state == ACTIVE ) { boxRGBA( (SDL_Surface*)surface(), x() + 2, y() + 2, x_end() - 2, y_end() - 2, _r, _g, _b, 255 ); rectangleRGBA( (SDL_Surface*)surface(), x() + 2, y() + 2, x_end() - 2, y_end() - 2, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x(), y() + 0, x_end() - 3, y() + 0, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x(), y() + 1, x_end() - 3, y() + 1, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x(), y() + 2, x_end() - 3, y() + 2, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x() + 0, y(), x() + 0, y_end() - 3, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x() + 1, y(), x() + 1, y_end() - 3, 0, 0, 0, 255 ); aalineRGBA( (SDL_Surface*)surface(), x() + 2, y(), x() + 2, y_end() - 3, 0, 0, 0, 255 ); } SDL_UpdateRect((SDL_Surface*)surface(), x(), y(), width(), height() ); }
33.358209
102
0.536913
cbries
3d5fbc8152f3d044e3385f2629cd0cc7640b2fc8
110
hpp
C++
include/lib_B/lib_B.hpp
dep-heaven/lib_B
c7b119372bfe85b8bff8a6dc42c5955a5e2b03fd
[ "MIT" ]
null
null
null
include/lib_B/lib_B.hpp
dep-heaven/lib_B
c7b119372bfe85b8bff8a6dc42c5955a5e2b03fd
[ "MIT" ]
null
null
null
include/lib_B/lib_B.hpp
dep-heaven/lib_B
c7b119372bfe85b8bff8a6dc42c5955a5e2b03fd
[ "MIT" ]
null
null
null
#ifndef LIB_B_HPP #define LIB_B_HPP namespace lib_B { int fn_b(); } // namespace lib_B #endif // LIB_B_HPP
11
20
0.718182
dep-heaven
87d1f145000427ebc429b437c62dd6992a6a9d1e
2,299
cpp
C++
src/_cxx11/_semaphore.cpp
ombre5733/weos
2c3edef042fa80baa7c8fb968ba3104b7119cf2d
[ "BSD-2-Clause" ]
11
2015-10-06T21:00:30.000Z
2021-07-27T05:54:44.000Z
src/_cxx11/_semaphore.cpp
ombre5733/weos
2c3edef042fa80baa7c8fb968ba3104b7119cf2d
[ "BSD-2-Clause" ]
null
null
null
src/_cxx11/_semaphore.cpp
ombre5733/weos
2c3edef042fa80baa7c8fb968ba3104b7119cf2d
[ "BSD-2-Clause" ]
1
2015-10-03T03:51:28.000Z
2015-10-03T03:51:28.000Z
/******************************************************************************* WEOS - Wrapper for embedded operating systems Copyright (c) 2013-2016, Manuel Freiberger All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include "_semaphore.hpp" WEOS_BEGIN_NAMESPACE semaphore::~semaphore() { } void semaphore::post() { std::lock_guard<std::mutex> lock(m_mutex); m_mutex.lock(); ++m_value; m_mutex.unlock(); m_conditionVariable.notify_one(); } void semaphore::wait() { std::unique_lock<std::mutex> lock(m_mutex); m_conditionVariable.wait(lock, [this] { return m_value != 0; }); --m_value; } bool semaphore::try_wait() { std::unique_lock<std::mutex> lock(m_mutex); if (m_value > 0) { --m_value; return true; } else { return false; } } semaphore::value_type semaphore::value() const { std::lock_guard<std::mutex> lock(m_mutex); return m_value; } WEOS_END_NAMESPACE
30.653333
80
0.680731
ombre5733
87d364317e653c45917da8b33c7adfcf1e21c6ab
10,868
cpp
C++
cobs/construction/compact_index.cpp
karasikov/cobs
63ba36f042c59e14f721018e68e36e20a8bf4936
[ "MIT" ]
null
null
null
cobs/construction/compact_index.cpp
karasikov/cobs
63ba36f042c59e14f721018e68e36e20a8bf4936
[ "MIT" ]
null
null
null
cobs/construction/compact_index.cpp
karasikov/cobs
63ba36f042c59e14f721018e68e36e20a8bf4936
[ "MIT" ]
null
null
null
/******************************************************************************* * cobs/construction/compact_index.cpp * * Copyright (c) 2018 Florian Gauger * * All rights reserved. Published under the MIT License in the LICENSE file. ******************************************************************************/ #include <cobs/construction/classic_index.hpp> #include <cobs/construction/compact_index.hpp> #include <cobs/file/classic_index_header.hpp> #include <cobs/file/compact_index_header.hpp> #include <cobs/file/kmer_buffer_header.hpp> #include <cobs/util/calc_signature_size.hpp> #include <cobs/util/file.hpp> #include <iomanip> #include <tlx/die.hpp> #include <tlx/math/div_ceil.hpp> #include <tlx/math/round_to_power_of_two.hpp> #include <tlx/math/round_up.hpp> #include <tlx/string/format_iec_units.hpp> namespace cobs { bool combine_classic_index(const fs::path& in_dir, const fs::path& out_dir, size_t mem_bytes, size_t num_threads) { bool all_combined = true; fs::path result_file; for (fs::directory_iterator it(in_dir), end; it != end; it++) { if (fs::is_directory(it->path())) { bool this_combined = classic_combine( in_dir / it->path().filename(), out_dir / it->path().filename(), result_file, mem_bytes, num_threads); if (!this_combined) all_combined = false; } } if (!gopt_keep_temporary) { fs::remove(in_dir); } return all_combined; } void compact_combine_into_compact( const fs::path& in_dir, const fs::path& out_file, uint64_t page_size, uint64_t memory) { std::vector<fs::path> paths; fs::recursive_directory_iterator it(in_dir), end; std::copy_if(it, end, std::back_inserter(paths), [](const auto& p) { return file_has_header<ClassicIndexHeader>(p); }); std::sort(paths.begin(), paths.end()); unsigned term_size = 0; uint8_t canonicalize = 0; std::vector<CompactIndexHeader::parameter> parameters; std::vector<std::string> file_names; LOG1 << "Combine Compact Index from " << paths.size() << " Classic Indices"; for (size_t i = 0; i < paths.size(); i++) { auto h = deserialize_header<ClassicIndexHeader>(paths[i]); parameters.push_back({ h.signature_size(), h.num_hashes() }); file_names.insert(file_names.end(), h.file_names().begin(), h.file_names().end()); if (term_size == 0) { term_size = h.term_size(); canonicalize = h.canonicalize(); } die_unequal(term_size, h.term_size()); die_unequal(canonicalize, h.canonicalize()); LOG1 << i << ": " << h.row_bits() << " documents " << tlx::format_iec_units(fs::file_size(paths[i])) << 'B' << " row_size " << h.row_size() << " : " << paths[i].string(); if (i < paths.size() - 1) { die_unless(h.row_size() == page_size); } else { die_unless(h.row_size() <= page_size); } } Timer t; CompactIndexHeader h(term_size, canonicalize, parameters, file_names, page_size); std::ofstream ofs; serialize_header(ofs, out_file, h); for (const auto& p : paths) { std::ifstream ifs; uint64_t row_size = deserialize_header<ClassicIndexHeader>(ifs, p).row_size(); if (row_size == page_size) { // row_size is page_size -> direct copy t.active("copy"); ofs << ifs.rdbuf(); t.stop(); } else { // row_size needs to be padded to page_size size_t batch_size = memory / 2 / page_size; uint64_t data_size = get_stream_size(ifs); batch_size = std::min( batch_size, tlx::div_ceil(data_size, page_size)); sLOG0 << "batch_size" << batch_size; std::vector<char> buffer(batch_size* page_size); die_unless(data_size % row_size == 0); while (data_size > 0) { t.active("read"); size_t this_batch = std::min(batch_size, data_size / row_size); ifs.read(buffer.data(), this_batch * row_size); die_unequal(this_batch * row_size, static_cast<size_t>(ifs.gcount())); data_size -= this_batch * row_size; t.active("expand"); // expand each row_size to page_size, start at the back for (size_t b = this_batch; b != 0; ) { --b; std::copy_backward( buffer.begin() + b * row_size, buffer.begin() + (b + 1) * row_size, buffer.begin() + b * page_size + row_size); std::fill( buffer.begin() + b * page_size + row_size, buffer.begin() + (b + 1) * page_size, 0); } t.active("write"); ofs.write(buffer.data(), this_batch * page_size); t.stop(); } } ifs.close(); if (!gopt_keep_temporary) { fs::remove(p); fs::remove(p.parent_path()); } } if (!gopt_keep_temporary) { fs::remove(in_dir); } t.print("compact_combine_into_compact()"); } void compact_construct(const fs::path& in_dir, const fs::path& index_file, const fs::path& tmp_path, CompactIndexParameters params) { size_t iteration = 1; // read file list, sort by size DocumentList doc_list(in_dir); doc_list.sort_by_size(); if (params.page_size == 0) { params.page_size = tlx::round_up_to_power_of_two( static_cast<size_t>(std::sqrt(doc_list.size() / 8))); params.page_size = std::max<uint64_t>(params.page_size, 8); params.page_size = std::min<uint64_t>(params.page_size, 4096); } size_t num_pages = tlx::div_ceil(doc_list.size(), 8 * params.page_size); size_t num_threads = params.num_threads; if (num_threads > num_pages) { // use div_floor() instead num_threads = doc_list.size() / (8 * params.page_size); } if (num_threads == 0) num_threads = 1; LOG1 << "Compact Index Parameters:\n" << " term_size: " << params.term_size << '\n' << " number of documents: " << doc_list.size() << '\n' << " num_hashes: " << params.num_hashes << '\n' << " false_positive_rate: " << params.false_positive_rate << '\n' << " page_size: " << params.page_size << " bytes" << " = " << params.page_size * 8 << " documents" << '\n' << " num_pages: " << num_pages << '\n' << " mem_bytes: " << params.mem_bytes << " = " << tlx::format_iec_units(params.mem_bytes) << 'B' << '\n' << " num_threads: " << num_threads; size_t total_size = 0; doc_list.process_batches( 8 * params.page_size, [&](size_t /* batch_num */, const std::vector<DocumentEntry>& files, fs::path /* out_file */) { size_t max_doc_size = 0; for (const DocumentEntry& de : files) { max_doc_size = std::max( max_doc_size, de.num_terms(params.term_size)); } size_t signature_size = calc_signature_size( max_doc_size, params.num_hashes, params.false_positive_rate); total_size += params.page_size * signature_size; }); LOG1 << " total_size: " << tlx::format_iec_units(total_size) << 'B'; // process batches and create classic indexes for each batch doc_list.process_batches_parallel( 8 * params.page_size, num_threads, [&](size_t batch_num, const std::vector<DocumentEntry>& files, fs::path /* out_file */) { size_t max_doc_size = 0; for (const DocumentEntry& de : files) { max_doc_size = std::max( max_doc_size, de.num_terms(params.term_size)); } size_t signature_size = calc_signature_size( max_doc_size, params.num_hashes, params.false_positive_rate); size_t docsize_roundup = tlx::round_up(files.size(), 8); if (max_doc_size == 0) return; ClassicIndexParameters classic_params; classic_params.term_size = params.term_size; classic_params.canonicalize = params.canonicalize; classic_params.num_hashes = params.num_hashes; classic_params.false_positive_rate = params.false_positive_rate; classic_params.signature_size = signature_size; classic_params.mem_bytes = params.mem_bytes / num_threads; classic_params.num_threads = tlx::div_ceil(params.num_threads, num_threads); classic_params.log_prefix = "[" + pad_index(batch_num, 2) + "/" + pad_index(num_pages, 2) + "] "; LOG1 << "Classic Sub-Index Parameters: " << classic_params.log_prefix << '\n' << " number of documents: " << files.size() << '\n' << " maximum document size: " << max_doc_size << '\n' << " signature_size: " << signature_size << '\n' << " sub-index size: " << (docsize_roundup / 8 * signature_size) << " = " << tlx::format_iec_units(docsize_roundup / 8 * signature_size) << '\n' << " mem_bytes: " << classic_params.mem_bytes << '\n' << " num_threads: " << classic_params.num_threads; DocumentList batch_list(files); fs::path classic_dir = tmp_path / pad_index(iteration); classic_construct_from_documents( batch_list, classic_dir / pad_index(batch_num), classic_params); }); // combine classic indexes while (!combine_classic_index(tmp_path / pad_index(iteration), tmp_path / pad_index(iteration + 1), params.mem_bytes, params.num_threads)) { iteration++; } // combine classic indexes into one compact index compact_combine_into_compact( tmp_path / pad_index(iteration + 1), index_file, params.page_size, params.mem_bytes); // cleanup: this will fail if not _all_ temporary files are removed if (!gopt_keep_temporary) { fs::remove(tmp_path); } } } // namespace cobs /******************************************************************************/
36.592593
80
0.544442
karasikov
87dd82ed0539a26de1a25c25eeb2fc8dda035205
892
hh
C++
dune/xt/common/python.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
2
2020-02-08T04:08:52.000Z
2020-08-01T18:54:14.000Z
dune/xt/common/python.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
35
2019-08-19T12:06:35.000Z
2020-03-27T08:20:39.000Z
dune/xt/common/python.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
1
2020-02-08T04:09:34.000Z
2020-02-08T04:09:34.000Z
// This file is part of the dune-xt project: // https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt // Copyright 2009-2021 dune-xt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2019) // René Fritze (2018 - 2020) // Tobias Leibner (2020) // // Created by r_milk01 on 4/25/18. #ifndef DUNE_XT_COMMON_PYTHON_HH #define DUNE_XT_COMMON_PYTHON_HH #include <functional> #include <dune/pybindxi/pybind11.h> namespace Dune::XT::Common::bindings { void guarded_bind(const std::function<void()>& registrar); } // namespace Dune::XT::Common::bindings #endif // DUNE_XT_COMMON_PYTHON_HH
29.733333
95
0.719731
dune-community
87dda1ed26f9e38adf47580171f95e67e0d5d7d0
24,417
cpp
C++
src/dialman.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
9
2020-04-01T04:15:22.000Z
2021-09-26T21:03:47.000Z
src/dialman.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
17
2020-04-02T19:38:40.000Z
2020-04-12T05:47:08.000Z
src/dialman.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /* SOURCE CONTROL VERSIONS */ /*---------------------------------------------------------------------------*/ /* */ /* Version Date Time Author / Comment (optional) */ /* */ /* $Log: dialman.cpp,v $ /* Revision 1.1 2010/07/21 17:14:56 richard_wood /* Initial checkin of V3.0.0 source code and other resources. /* Initial code builds V3.0.0 RC1 /* /* Revision 1.2 2009/08/25 20:04:25 richard_wood /* Updates for 2.9.9 /* /* Revision 1.1 2009/06/09 13:21:28 richard_wood /* *** empty log message *** /* /* Revision 1.2 2008/09/19 14:51:21 richard_wood /* Updated for VS 2005 /* /* */ /*****************************************************************************/ /********************************************************************************** Copyright (c) 2003, Albert M. Choy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Microplanet, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************/ // TDialupManager - class for managing a dialup connection for Gravity #include "stdafx.h" #include "mplib.h" #include "globals.h" #include "server.h" #include "dialman.h" #include "critsect.h" #include "fileutil.h" #include "resource.h" #include "genutil.h" // GetOS #include "timemb.h" // TimeMsgBox_MessageBox #include "servcp.h" // TServerCountedPtr #include "raserror.h" // ERROR_NO_CONNECTION #include "rasdlg.h" // TRasDialDlg our timer redial dlg #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif TDialupManager dialMgr; // a global P_RASSTATUSFUNC gpfnStatus = 0; // prototypes; static UINT GetRasConnStateStringID( RASCONNSTATE rasconn ); static HWND hWaitDlg; static HWND ghWndOutput = 0; // set within Connect static UINT gmsgOutput = 0; // set within Connect BOOL postSuccess () { PostMessage (ghWndOutput, gmsgOutput, 0, 0); return TRUE; } BOOL postFailure (DWORD dwError) { // stuff error code into wParam PostMessage (ghWndOutput, gmsgOutput, (WPARAM) dwError, 0); return TRUE; } // prototype void WINAPI ras_process_event (UINT uMsg, RASCONNSTATE rasconnstate, DWORD dwError); ///////////////////////////////////////////////////////////////////////////// // TDialupManager ctor - Construct a dialup manager for Gravity ///////////////////////////////////////////////////////////////////////////// TDialupManager::TDialupManager() { m_fRasInstalled = FALSE; m_hConnection = 0; m_fWeCreated = FALSE; m_fCancelled = FALSE; m_ePseudoState = kNotConnected; m_byRedials = 0; m_hCriticalSection = &m_CriticalSection; m_fAskedQuestionAlready = false; InitializeCriticalSection (m_hCriticalSection); } ///////////////////////////////////////////////////////////////////////////// // loads RAS dll ///////////////////////////////////////////////////////////////////////////// BOOL TDialupManager::Initialize () { m_fRasInstalled = m_rasLib.Initialize (); return m_fRasInstalled; } ///////////////////////////////////////////////////////////////////////////// // TDialupManager dtor ///////////////////////////////////////////////////////////////////////////// TDialupManager::~TDialupManager () { DeleteCriticalSection (m_hCriticalSection); } ///////////////////////////////////////////////////////////////////////////// // ShowRasError - Show a RAS error to the user. ///////////////////////////////////////////////////////////////////////////// void TDialupManager::ShowRasError (bool fDuringInit, DWORD errorNum) { CString strIntro; if (fDuringInit) strIntro.LoadString (IDS_ERR_DIALUP_EST); else strIntro.LoadString (IDS_ERR_DIALUP_TERM); TCHAR errorBuff[512]; CString errorString; if (0 != m_rasLib.RasGetErrorString (errorNum, errorBuff, sizeof (errorBuff))) errorBuff[0] = 0; errorString.Format ("%s - %s.", (LPCTSTR)strIntro, errorBuff); NewsMessageBox (TGlobalDef::kMainWnd, errorString, MB_OK | MB_ICONEXCLAMATION); } ///////////////////////////////////////////////////////////////////////////// // Connect - Take the steps to create a dialup networking connection. // // Notes: 1) If ForceConnect is FALSE, then we just return true, // since we assume that the connection has been established. // 2) If PromptBeforeConnecting is set, we prompt before // attempting to make the dialup connection. // 3) If UseExistingConnection, we check to see if the // DUN connection exists by enumerating over the current // connections, and if found, using it. Otherwise // we proceed to build a connection. ///////////////////////////////////////////////////////////////////////////// BOOL TDialupManager::Connect (P_RASSTATUSFUNC pStatusFunc, HWND hWnd, UINT msg) { ghWndOutput = hWnd; gmsgOutput = msg; m_fAskedQuestionAlready = false; TServerCountedPtr cpNewsServer; // smart pointer // act dumb if (!m_fRasInstalled) { return postSuccess (); } if (!IsActiveServer()) throw(new TException (IDS_ERR_NO_SERVER_SET_UP, kError)); // don't let more than one person Try to connect at once... if (TDialupManager::kConnecting == m_ePseudoState) { //TRACE0("we are connecting already...\n"); return FALSE; } // if we're already connected, just return TRUE const CString & strDialupName = cpNewsServer->GetConnectionName(); HRASCONN hFound = 0; if (FindConnectionByName (kFindOurs, strDialupName, hFound)) { //TRACE0("we are Already connected...\n"); TEnterCSection cs(m_hCriticalSection); m_hConnection = hFound; m_ePseudoState = kConnected; return postSuccess (); } if (!cpNewsServer->GetForceConnection() && !cpNewsServer->GetForceDisconnect ()) { // we're not responsible for any RAS work. or this is a LAN connection return postSuccess (); } BOOL fRet; // if we're not told to force a connection, then we just // tell whoever is calling us the connection has been // established if (!cpNewsServer->GetForceConnection()) { TEnterCSection ds(m_hCriticalSection); FindConnectionByName(kFindAny, "", m_hConnection); return postSuccess (); } if (strDialupName.IsEmpty()) { // "You have not selected a dialup connection to use." NewsMessageBox (TGlobalDef::kMainWnd, IDS_DIALUP_NOCONNECTION, MB_OK | MB_ICONSTOP); return TRUE; } if (cpNewsServer->GetUseExistingConnection()) { // iterate over the existing connections and use // the existing one if one is there... HRASCONN hRasConn; if (FindConnectionByName (kFindOurs, strDialupName, hRasConn)) { //TRACE0("Found an existing connection\n"); // we found the connection that the user specified, so // we set that we connected and return TRUE to the user... { TEnterCSection cs(m_hCriticalSection); m_hConnection = hRasConn; } return postSuccess (); } } LPCTSTR pszConnectionName = strDialupName; if (cpNewsServer->GetPromptBeforeConnecting()) { CString connectionPrompt; AfxFormatString1 (connectionPrompt, IDS_DIALUP_CONNECT1, pszConnectionName); // "Connect to %s now?" if (IDNO == NewsMessageBox(TGlobalDef::kMainWnd, connectionPrompt, MB_YESNO | MB_ICONQUESTION)) { return FALSE; } } // get to the nitty gritty gpfnStatus = pStatusFunc; fRet = MakeConnection (pszConnectionName); return fRet; } ///////////////////////////////////////////////////////////////////////////// // Disconnect - Handle disconnecting from the dialup connection we may // or may not have started. This is controlled by two variables // that can be set in the server - ForceDisconnect and // DisconnectIfWeOpened. The method will also show a prompt // if PromptBeforeDisconnecting is set at the server. // // fAutoDisconnect - indicates that Gravity is disconnecting automatically. // Don't let the MessageBoxes halt the shutdown ///////////////////////////////////////////////////////////////////////////// BOOL TDialupManager::Disconnect(BOOL fAutoDisconnect) { DWORD dwRC; TServerCountedPtr cpNewsServer; // smart pointer //TRACE ("%s : %d, thread ID : %d\n", __FILE__, __LINE__, AfxGetThread ()); if (FALSE == m_fRasInstalled) return TRUE; if (!IsActiveServer ()) throw(new TException (IDS_ERR_NO_SERVER_SET_UP, kError)); if (!cpNewsServer->GetForceDisconnect()) { // reset to clean state set_vars_init (); return TRUE; } // if they only want us to disconnect sessions we created, then return if (cpNewsServer->GetDisconnectIfWeOpened ()) { if (!m_fWeCreated) { // reset to clean state set_vars_init (); return TRUE; } } if (kConnecting == m_ePseudoState) { // amc - it's valid to Try to abort a RAS session that is // connecting. Proceed } else if (0 == m_hConnection) { set_vars_init (); return TRUE; } try { // keep from asking the disconnect Question more than once. // this is weird since you might get asked 3 times: // 1) disconnect // 2) mainfrm OnClose // 3) ExitInstance if (m_fAskedQuestionAlready) { set_vars_init (); return FALSE; } if (cpNewsServer->GetPromptBeforeDisconnecting() && !m_fAskedQuestionAlready) { int nMsgRet; CString promptString; AfxFormatString1(promptString, IDS_DIALUP_ASKDISCONNECT1, cpNewsServer->GetConnectionName ()); UINT uBoxFlags = MB_YESNO | MB_ICONQUESTION; if (fAutoDisconnect) { // Timeout after 60 seconds - return IDTIMEOUT nMsgRet = NewsMessageBoxTimeout (60, NULL, promptString, uBoxFlags); } else nMsgRet = NewsMessageBox(TGlobalDef::kMainWnd, promptString, uBoxFlags); m_fAskedQuestionAlready = true; if (IDNO == nMsgRet) { set_vars_init (); return FALSE; } } } catch(...) { LINE_TRACE(); throw; } // go ahead and close the connection.... try { // 2-26-98. Even if the server has dropped us, // (FindConnectionByName==FALSE) // call ras hangup on the m_hConnection handle. It seems to // help ras come back to a clean initial state. if (kConnecting == m_ePseudoState) m_fCancelled = TRUE; { TEnterCSection cs(m_hCriticalSection); dwRC = 0; ASSERT(m_hConnection); //TRACE0("In Disconnect() - call RasHangUp\n"); if (m_hConnection) { dwRC = m_rasLib.RasHangUp (m_hConnection); } if (0 == dwRC) { // wait for handle to become invalid wait_after_hangup (m_hConnection); // set vars to indicate cancelled set_vars_init (); return TRUE; } } // deal with error set_vars_init (); // it's silly to say "Can't hang up - connection was dropped" if (ERROR_NO_CONNECTION != dwRC) { ShowRasError (false, dwRC); } return FALSE; } catch(...) { LINE_TRACE(); throw; } } // ------------------------------------------------------------------------- // set_vars_init -- reset variables to a clean state void TDialupManager::set_vars_init() { TEnterCSection cs(m_hCriticalSection); m_fWeCreated = FALSE; m_fCancelled = FALSE; m_hConnection = NULL; m_ePseudoState = kNotConnected; } //------------------------------------------------------------------------- // called from the dialog box void WINAPI ras_process_event (UINT uMsg, RASCONNSTATE rasconnstate, DWORD dwError) { // wait for 1 of three cases // dwError is not zero - An Error occurred // RASCS_Connected - // someone called RasHangup if (dwError) { //TRACE("callback - (error) %d, %u\n", (int)rasconnstate, dwError); // clear status line if (gpfnStatus) gpfnStatus ( -1 ); // both cases need to set flags to failure values dialMgr.processEventsResult (false); dialMgr.hangup_nowait (); // special handling for ERROR_LINE_BUSY, pass error up, so upper layer can redial if (ERROR_LINE_BUSY == dwError || ERROR_VOICE_ANSWER == dwError) { postFailure (dwError); return ; } if (ERROR_USER_DISCONNECTION == dwError) { // user interrupted dialing themselves, so they don't need to see the error msg. } else dialMgr.ShowRasError (true, dwError); return; } if (gpfnStatus) gpfnStatus ( GetRasConnStateStringID(rasconnstate) ); if (RASCS_DONE & rasconnstate) { dialMgr.processEventsResult (true); // success postSuccess (); } } ///////////////////////////////////////////////////////////////////////////// // TDialupManager::GetDialupState // // Returns: ECheckConnect[kNotConnected, kConnected, // kConnecting, kNotInstalled] // ///////////////////////////////////////////////////////////////////////////// TDialupManager::ECheckConnect TDialupManager::GetDialupState () { if (FALSE == m_fRasInstalled) return kNotInstalled; // don't use FindConnectionByName, use the pseudo var return m_ePseudoState; } ///////////////////////////////////////////////////////////////////////////// BOOL TDialupManager::MakeConnection (LPCTSTR pConnName) { if (RUNNING_ON_WINNT == GetOS()) { m_ePseudoState = kConnecting; RASDIALDLG DlgInfo; ZeroMemory (&DlgInfo, sizeof(DlgInfo)); DlgInfo.dwSize = sizeof(DlgInfo); DlgInfo.hwndOwner = ghWndOutput; // returns 0 for ERROR or if the user Canceled BOOL fRet = m_rasLib.RasNTDialDlg (NULL, // phonebook pConnName, // phbook entry NULL, // override phone number &DlgInfo); if (fRet) { TEnterCSection cs(m_hCriticalSection); FindConnectionByName (kFindOurs, pConnName, m_hConnection); m_ePseudoState = kConnected; m_fWeCreated = TRUE; return postSuccess (); } else { m_ePseudoState = kNotConnected; if (ERROR_LINE_BUSY == DlgInfo.dwError) postFailure (DlgInfo.dwError); return FALSE; } } RASDIALPARAMS rasParms; DWORD dwRC; m_fCancelled = FALSE; // get the dial parameters from the registry... if (FALSE == get_dial_parms ( pConnName, &rasParms )) return FALSE; HRASCONN hConnection = NULL; m_ePseudoState = kConnecting; m_fWeCreated = TRUE; RASDIALEXTENSIONS extensions; ZeroMemory (&extensions, sizeof (extensions)); extensions.dwSize = sizeof (extensions); extensions.dwfOptions |= RDEOPT_PausedStates; // dialog processes events via ras_process_event (in this module) dwRC = m_rasLib.RasDial ( &extensions, // RASDIALEXTENSIONS - we don't use them NULL, // use the default phonebook &rasParms, // parameters for RAS dialer (DWORD) 0 , // treat next param as type RasDialFunc ras_process_event, // pass in our function ptr &hConnection); if (dwRC) { if (true) { TEnterCSection cs(m_hCriticalSection); hangup_and_wait ( hConnection ); m_hConnection = NULL; } if (m_fCancelled) { m_fCancelled = FALSE; // reset to clean state } else ShowRasError (true, dwRC); m_ePseudoState = kNotConnected; m_fWeCreated = FALSE; return FALSE; } else { TEnterCSection cs(m_hCriticalSection); m_hConnection = hConnection; } return TRUE; } DWORD TDialupManager::RasCreatePhonebookEntry(HWND hwnd, LPTSTR pPhoneBook) { return m_rasLib.RasCreatePhonebookEntry(hwnd, pPhoneBook); } DWORD TDialupManager::RasEditPhonebookEntry(HWND hwnd, LPTSTR pPhoneBook, LPTSTR entry) { return m_rasLib.RasEditPhonebookEntry(hwnd, pPhoneBook, entry); } DWORD TDialupManager::RasEnumEntries(LPTSTR r1, LPTSTR pPhoneBook, LPRASENTRYNAME pEntry, LPDWORD lpcb, LPDWORD lpcEntries) { return m_rasLib.RasEnumEntries(r1, pPhoneBook, pEntry, lpcb, lpcEntries); } DWORD TDialupManager::RasGetEntryDialParams(LPTSTR pPhoneBook, LPRASDIALPARAMS pDialParams, LPBOOL pfPassword) { return m_rasLib.RasGetEntryDialParams(pPhoneBook, pDialParams, pfPassword); } DWORD TDialupManager::RasSetEntryDialParams(LPTSTR pBook, LPRASDIALPARAMS pDP, BOOL fRemovePwd) { return m_rasLib.RasSetEntryDialParams(pBook, pDP, fRemovePwd); } //------------------------------------------------------------------------- void TDialupManager::wait_after_hangup (HRASCONN hConnection) { RASCONNSTATUS rasStatus; DWORD dwRC; CTime start = CTime::GetCurrentTime(); do { ZeroMemory (&rasStatus, sizeof(rasStatus)); rasStatus.dwSize = sizeof(rasStatus); dwRC = m_rasLib.RasGetConnectStatus (hConnection, &rasStatus); if (ERROR_INVALID_HANDLE == dwRC) break; Sleep (0); } while ((CTime::GetCurrentTime() - start).GetSeconds() < 15); } //------------------------------------------------------------------------- BOOL TDialupManager::get_dial_parms (LPCTSTR pConnName, RASDIALPARAMS* prasParms) { BOOL fPassword = FALSE; DWORD dwRC; ZeroMemory (prasParms, sizeof(RASDIALPARAMS)); prasParms->dwSize = sizeof(RASDIALPARAMS); if (sizeof(*prasParms) != sizeof(RASDIALPARAMS)) AfxThrowMemoryException(); _tcscpy(prasParms->szEntryName, pConnName); dwRC = m_rasLib.RasGetEntryDialParams( NULL, // use default phonebook prasParms, // pointer to parameters &fPassword); // was password returned? if (0 != dwRC) { // "Error retrieving dialup networking parameters." NewsMessageBox (TGlobalDef::kMainWnd, IDS_DIALUP_ERRGETDIALPARAMS, MB_OK | MB_ICONSTOP); return FALSE; } return TRUE; } // ------------------------------------------------------------------------ // PURPOSE: get the index to the corresponding string // // PARAMETERS: // rasconn - ras connection state // // RETURNS: // index into stringtable. static UINT GetRasConnStateStringID( RASCONNSTATE rasconn ) { switch( rasconn ) { case RASCS_OpenPort: return IDS_OPENPORT; case RASCS_PortOpened: return IDS_PORTOPENED; case RASCS_ConnectDevice: return IDS_CONNECTDEVICE; case RASCS_DeviceConnected: return IDS_DEVICECONNECTED; case RASCS_AllDevicesConnected: return IDS_ALLDEVICESCONNECTED; case RASCS_Authenticate: return IDS_AUTHENTICATE; case RASCS_AuthNotify: return IDS_AUTHNOTIFY; case RASCS_AuthRetry: return IDS_AUTHRETRY; case RASCS_AuthCallback: return IDS_AUTHCALLBACK; case RASCS_AuthChangePassword: return IDS_AUTHCHANGEPASSWORD; case RASCS_AuthProject: return IDS_AUTHPROJECT; case RASCS_AuthLinkSpeed: return IDS_AUTHLINKSPEED; case RASCS_AuthAck: return IDS_AUTHACK; case RASCS_ReAuthenticate: return IDS_REAUTHENTICATE; case RASCS_Authenticated: return IDS_AUTHENTICATED; case RASCS_PrepareForCallback: return IDS_PREPAREFORCALLBACK; case RASCS_WaitForModemReset: return IDS_WAITFORMODEMRESET; case RASCS_WaitForCallback: return IDS_WAITFORCALLBACK; case RASCS_StartAuthentication: return IDS_STARTAUTH; case RASCS_CallbackComplete: return IDS_CALLBACK_COMPLETE; case RASCS_LogonNetwork: return IDS_LOGON_NETWORK; case RASCS_SubEntryConnected: return IDS_SUBENTRYCONNECTED; case RASCS_Interactive: return IDS_INTERACTIVE; case RASCS_RetryAuthentication: return IDS_RETRYAUTHENTICATION; case RASCS_CallbackSetByCaller: return IDS_CALLBACKSETBYCALLER; case RASCS_PasswordExpired: return IDS_PASSWORDEXPIRED; case RASCS_Connected: return IDS_CONNECTED; case RASCS_Disconnected: return IDS_DISCONNECTED; default: return IDS_RAS_UNDEFINED_ERROR; } } //------------------------------------------------------------------------- void TDialupManager::hangup_and_wait (HRASCONN hConnection) { if (hConnection) { m_rasLib.RasHangUp ( hConnection ); wait_after_hangup ( hConnection ); } } ///////////////////////////////////////////////////////////////////////////// // FindConnectionByName - Locate a connection (in the set of current // connections) by name ///////////////////////////////////////////////////////////////////////////// BOOL TDialupManager::FindConnectionByName( EFindConn eFind, const CString & dialupName, HRASCONN & hConnection) { RASCONN connections[10]; // assume there are not more than 10 ras conns DWORD cbSize; DWORD numConnections; DWORD dwRC; cbSize = sizeof (connections); connections[0].dwSize = sizeof (RASCONN); dwRC = m_rasLib.RasEnumConnections (connections, &cbSize, &numConnections); if (0 == dwRC) { for (int i = 0; i < int(numConnections); i++) { if (eFind == kFindOurs) { if (dialupName.CompareNoCase(connections[i].szEntryName) == 0) { hConnection = connections[i].hrasconn; return TRUE; } } else // kFindAny { hConnection = connections[i].hrasconn; return TRUE; } } } hConnection = NULL; return FALSE; } ///////////////////////////////////////////////////////////////////////////// void TDialupManager::processEventsResult (bool fSuccess) { if (fSuccess) { m_ePseudoState = kConnected ; m_byRedials = 0; } else { m_ePseudoState = kNotConnected; } } ///////////////////////////////////////////////////////////////////////////// void TDialupManager::hangup_nowait () { TEnterCSection cs(m_hCriticalSection); if (m_hConnection) { // we are not hanging up a Valid connection, more like freeing the // memory for this handle // come here if we get a busy signal m_rasLib.RasHangUp (m_hConnection); m_hConnection = 0; } } // returns true to redial bool TDialupManager::incrementRedialCount (bool fResetToZero) { BYTE n = m_byRedials + 1; if (n > 4 || fResetToZero) { // over the limit m_byRedials = 0; return false; } else { m_byRedials = n; return true; } } // ------------------------------------------------------------------------ // Returns true for "ok to redial" bool TDialupManager::ShowRedialDlg (CWnd * pAnchor) { TRasDialDlg sDlg(pAnchor); sDlg.DoModal(); return sDlg.getAnswer(); }
27.009956
91
0.60507
taviso
87ddf5a2e5a3747713708066b0d4f8f8c710746c
3,835
cpp
C++
VGP242/06_HelloTexturing/GameState.cpp
TheJimmyGod/JimmyGod_Engine
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
[ "MIT" ]
null
null
null
VGP242/06_HelloTexturing/GameState.cpp
TheJimmyGod/JimmyGod_Engine
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
[ "MIT" ]
null
null
null
VGP242/06_HelloTexturing/GameState.cpp
TheJimmyGod/JimmyGod_Engine
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
[ "MIT" ]
null
null
null
#include "GameState.h" using namespace JimmyGod::Input; using namespace JimmyGod::Graphics; using namespace JimmyGod::Math; void GameState::Initialize() { GraphicsSystem::Get()->SetClearColor(Colors::Black); mCamera.SetPosition({ 0.0f,0.0f,-5.0f }); mCamera.SetDirection({ 0.0f,0.0f,1.0f }); /* Homework Update helloTexturing to use a MeshPX data to draw a texture mapped cubes You will need to add Sampler and Texture classes provided You will need to use DoTexturing fx shaders Add a new class called Graphics::MeshBuilder with the following functions namespace JimmyGod::Graphics { class MeshBuilder { static MeshPX CreatePlanePX(); static MeshPX CreateCylinderPX(); static MeshPX CreateSpherePX(float radius, int ringhs = 16, int slices = 16); } This will allow you to create a mesh easily by doing: auto mesh = MeshBuilder::CreateSpherePX(...); Add HelloEarth to test a texture mapped sphere using Earth texture a plane: for(int y=0; y< height; ++y) for(int x=0; x<width; ++x) mMesh.push_back({x,y,0.0f}...); a cylinder: for(int y=0; y< height; ++y) for(int theta=0; theta<TwoPi; theta += ...) mMesh.push_back({sin(theta),y,cos(theta)}...); a sphere: for(int phi=0; phi< Pi; phi += ...) for(int theta=0; theta<TwoPi; theta += ...) mMesh.push_back({sin(theta) * r,phi,cos(theta) *r}...); }*/ auto Mesh = MeshBuilder::CreateCubePX(); auto Plane = MeshBuilder::CreatePlanePX(2,2); auto Cylinder = MeshBuilder::CreateCylinderPX(36, 36); auto Sphere = MeshBuilder::CreateSpherePX(10); mMeshBuffer.Initialize(Plane); mConstantBuffer.Initialize(sizeof(Matrix4)); mSampler.Initialize(Sampler::Filter::Point, Sampler::AddressMode::Clamp); mTexture.Initialize("../../Assets/Textures/SimYoung.jpg"); // Compile and create vertex shader mVertexShader.Initialize("../../Assets/Shaders/DoTexturing.fx",VertexPX::Format); // Compile and create pixel shader mPixelShader.Initialize("../../Assets/Shaders/DoTexturing.fx"); } void GameState::Terminate() { mVertexShader.Terminate(); mPixelShader.Terminate(); mMeshBuffer.Terminate(); mConstantBuffer.Terminate(); mTexture.Terminate(); mSampler.Terminate(); } void GameState::Update(float deltaTime) { const float kMoveSpeed = 7.5f; const float kTurnSpeed = 0.5f; auto inputSystem = InputSystem::Get(); if (inputSystem->IsKeyDown(KeyCode::W)) { mCamera.Walk(kMoveSpeed*deltaTime); } if (inputSystem->IsKeyDown(KeyCode::S)) { mCamera.Walk(-kMoveSpeed * deltaTime); } mCamera.Yaw(inputSystem->GetMouseMoveX() * kTurnSpeed * deltaTime); mCamera.Pitch(inputSystem->GetMouseMoveY() * kTurnSpeed * deltaTime); if (inputSystem->IsKeyDown(KeyCode::A)) { mRotation += deltaTime; } if (inputSystem->IsKeyDown(KeyCode::D)) { mRotation -= deltaTime; } } void GameState::Render() { auto matView = mCamera.GetViewMatrix(); auto matProj = mCamera.GetPerspectiveMatrix(); mVertexShader.Bind(); mPixelShader.Bind(); mConstantBuffer.BindVS(0); mSampler.BindPS(); mTexture.BindPS(); for (int i = 0; i < 2; i++) { auto matWorld1 = Matrix4::RotationY(mRotation.y); //auto matWorld2 = Matrix4::RotationX(mRotation.x- static_cast<float>(i)); //auto matWorld3 = Matrix4::RotationZ(mRotation.z+ static_cast<float>(i)); auto matTranslation = Matrix4::Identity;// Matrix4::Translation(Vector3(static_cast<float>(i), static_cast<float>(i), static_cast<float>(0))); auto matScl = Matrix4::Scaling(static_cast<float>(i) * 0.25f); auto matWVP = Transpose(matScl*matTranslation*matWorld1 * matView * matProj); mConstantBuffer.Update(&matWVP); mMeshBuffer.Draw(); } /*context->Draw(mVertices.size(), 0);*/ // This is for when we don't have an index buffer }
30.19685
145
0.690743
TheJimmyGod
87e0ec19e6f60dc42bcc6fa3a417c0796aee134d
1,187
hpp
C++
include/codegen/include/GlobalNamespace/BeatmapEventData.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/BeatmapEventData.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/BeatmapEventData.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: BeatmapEventType #include "GlobalNamespace/BeatmapEventType.hpp" // Completed includes // Type namespace: namespace GlobalNamespace { // Autogenerated type: BeatmapEventData class BeatmapEventData : public ::Il2CppObject { public: // public readonly BeatmapEventType type // Offset: 0x10 GlobalNamespace::BeatmapEventType type; // public readonly System.Single time // Offset: 0x14 float time; // public readonly System.Int32 value // Offset: 0x18 int value; // public System.Void .ctor(System.Single time, BeatmapEventType type, System.Int32 value) // Offset: 0xB8D16C static BeatmapEventData* New_ctor(float time, GlobalNamespace::BeatmapEventType type, int value); }; // BeatmapEventData } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BeatmapEventData*, "", "BeatmapEventData"); #pragma pack(pop)
35.969697
101
0.699242
Futuremappermydud
87e24f9b179db7cf817f62262a028bed3a77134d
3,987
hpp
C++
src/main/cpp/USSL/BasicArithmatic.hpp
Crtl-F5/F5RC-Kernel
145cf9f7a34463226e68112033f56e0d121425e3
[ "MIT" ]
1
2018-08-12T03:50:19.000Z
2018-08-12T03:50:19.000Z
src/main/cpp/USSL/BasicArithmatic.hpp
Crtl-F5/F5RC-Kernel
145cf9f7a34463226e68112033f56e0d121425e3
[ "MIT" ]
null
null
null
src/main/cpp/USSL/BasicArithmatic.hpp
Crtl-F5/F5RC-Kernel
145cf9f7a34463226e68112033f56e0d121425e3
[ "MIT" ]
null
null
null
#pragma once #include <ProgramType.hpp> namespace USSL { inline void ADD(ProgramType* args, unsigned char* programMemory) { switch (args[0].type) { case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b + args[2].data.b; break; case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s + args[2].data.s; break; case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i + args[2].data.i; break; case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l + args[2].data.l; break; case f: *((float*)programMemory + args[0].data.i) = args[1].data.f + args[2].data.f; break; case d: *((double*)programMemory + args[0].data.i) = args[1].data.d + args[2].data.d; break; } } inline void SUB((ProgramType* args, unsigned char* programMemory) { switch (args[0].type) { case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b - args[2].data.b; break; case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s - args[2].data.s; break; case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i - args[2].data.i; break; case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l - args[2].data.l; break; case f: *((float*)programMemory + args[0].data.i) = args[1].data.f - args[2].data.f; break; case d: *((double*)programMemory + args[0].data.i) = args[1].data.d - args[2].data.d; break; } } inline void MUL(ProgramType* args, unsigned char* programMemory) { switch (args[0].type) { case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b * args[2].data.b; break; case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s * args[2].data.s; break; case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i * args[2].data.i; break; case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l * args[2].data.l; break; case f: *((float*)programMemory + args[0].data.i) = args[1].data.f * args[2].data.f; break; case d: *((double*)programMemory + args[0].data.i) = args[1].data.d * args[2].data.d; break; } } inline void DIV(ProgramType* args, unsigned char* programMemory) { switch (args[0].type) { case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b / args[2].data.b; break; case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s / args[2].data.s; break; case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i / args[2].data.i; break; case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l / args[2].data.l; break; case f: *((float*)programMemory + args[0].data.i) = args[1].data.f / args[2].data.f; break; case d: *((double*)programMemory + args[0].data.i) = args[1].data.d / args[2].data.d; break; } } inline void MOD(ProgramType* args, unsigned char* memory) { switch (args[0].type) { case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b % args[2].data.b; break; case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s % args[2].data.s; break; case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i % args[2].data.i; break; case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l % args[2].data.l; break; case f: *((float*)programMemory + args[0].data.i) = args[1].data.f % args[2].data.f; break; case d: *((double*)programMemory + args[0].data.i) = args[1].data.d % args[2].data.d; break; } } }
56.957143
114
0.563582
Crtl-F5
87e9cd99ee6892015e96a6141a5649aad854bde2
1,580
cpp
C++
libnativeipc/src/ConnectionFactory.cpp
stream-labs/twitch-native-ipc
81154497fcf55288c51cb5c93e95014ec4f0644d
[ "MIT" ]
8
2020-10-12T21:44:47.000Z
2021-07-29T16:58:41.000Z
libnativeipc/src/ConnectionFactory.cpp
ConnectionMaster/twitch-native-ipc
81154497fcf55288c51cb5c93e95014ec4f0644d
[ "MIT" ]
1
2021-08-28T03:11:34.000Z
2021-08-28T03:11:34.000Z
libnativeipc/src/ConnectionFactory.cpp
ConnectionMaster/twitch-native-ipc
81154497fcf55288c51cb5c93e95014ec4f0644d
[ "MIT" ]
3
2020-10-02T17:34:57.000Z
2021-08-28T03:11:23.000Z
// Copyright Twitch Interactive, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT #include "ClientConnection.h" #include "ConnectionFactoryPrivate.h" #include "Pipe-ClientTransport.h" #include "Pipe-ServerTransport.h" #include "TCP-ClientTransport.h" #include "TCP-ServerTransport.h" #include "ServerConnection.h" #include "ServerConnectionSingle.h" using namespace Twitch::IPC; namespace { std::string pipeNameForEndpoint(const std::string &endpoint) { #ifdef _WIN32 return R"(\\.\pipe\)" + endpoint; #else return "/tmp/" + endpoint; #endif } } // namespace namespace Twitch::IPC::ConnectionFactory { NATIVEIPC_LIBSPEC std::unique_ptr<IConnection> newServerConnection(const std::string &endpoint, bool allowMultiuserAccess) { return std::unique_ptr<IConnection>(std::make_unique<ServerConnectionSingle>( MakeFactory<Transport::Pipe>(), pipeNameForEndpoint(endpoint), allowMultiuserAccess)); } NATIVEIPC_LIBSPEC std::unique_ptr<IConnection> newClientConnection( const std::string &endpoint) { return std::unique_ptr<IConnection>(std::make_unique<ClientConnection>( MakeFactory<Transport::Pipe>(), pipeNameForEndpoint(endpoint))); } NATIVEIPC_LIBSPEC std::unique_ptr<IServerConnection> newMulticonnectServerConnection(const std::string &endpoint, bool allowMultiuserAccess) { return std::unique_ptr<IServerConnection>(std::make_unique<ServerConnection>( MakeFactory<Transport::Pipe>(), pipeNameForEndpoint(endpoint), false, allowMultiuserAccess)); } } // namespace Twitch::IPC::ConnectionFactory
32.244898
140
0.772152
stream-labs
87efcf503e4fdf4c4251b35612961e906b8b0b90
1,361
cpp
C++
TP/starters 12/maxpoint.cpp
ShyrenMore/DSA_Docs
7d489326799886afd8d5f7ec7f4b88311e86e582
[ "Unlicense" ]
null
null
null
TP/starters 12/maxpoint.cpp
ShyrenMore/DSA_Docs
7d489326799886afd8d5f7ec7f4b88311e86e582
[ "Unlicense" ]
null
null
null
TP/starters 12/maxpoint.cpp
ShyrenMore/DSA_Docs
7d489326799886afd8d5f7ec7f4b88311e86e582
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #define deb(x) cout << #x << ": " << x << endl; #define deb2(x, y) cout << #x << ": " << x << " ~ " << #y << ": " << y << endl; #define in(n, arr) \ for (int i = 0; i < n; i++) \ cin >> arr[i] #define out(n, arr) \ for (int i = 0; i < n; i++) \ cout << arr[i] #define lli long long int #define here cout << "\nHERE\n" #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") using namespace std; int main() { // /* #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif // */ ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int A, B, C, X, Y, Z; cin >> A >> B >> C >> X >> Y >> Z; int ans = 0; for (int take_a = 0; take_a <= 20; take_a++) { for (int take_b = 0; take_b <= 20; take_b++) { for (int take_c = 0; take_c <= 20; take_c++) { int time = take_a * A + take_b * B + take_c * C; if (time <= 240) { ans = max(ans, take_a * X + take_b * Y + take_c * Z); } } } } cout << ans << "\n"; } return 0; }
24.745455
79
0.404849
ShyrenMore
87f3b27586d6ffea1b2d3b216f9bea13a9ef1fad
12,602
cpp
C++
game_server/test/misc_test.cpp
CellWarsOfficial/CellWars
40b1e956c871ee686062eba1251a9f9a43d86c2c
[ "Apache-2.0" ]
5
2017-07-20T10:36:23.000Z
2018-01-30T16:18:31.000Z
game_server/test/misc_test.cpp
CellWarsOfficial/CellWars
40b1e956c871ee686062eba1251a9f9a43d86c2c
[ "Apache-2.0" ]
null
null
null
game_server/test/misc_test.cpp
CellWarsOfficial/CellWars
40b1e956c871ee686062eba1251a9f9a43d86c2c
[ "Apache-2.0" ]
null
null
null
#include "misc_test.hpp" #include <cstring> #include <cstdio> #include <cinttypes> #include <constants.hpp> using namespace std; int fails = 0; int tests = 0; int math_tests() { fails = 0; tests = 0; // TODO tests go here //test binary_to_num string test1 = "1101"; string test2 = "00001101"; string test3 = "11000011010011111"; string test4 = "0000100110011010"; string test5 = "100110011010"; unsigned long test6 = 70; unsigned long test7 = 63; unsigned long test8 = 0; unsigned long test9 = 7; unsigned long test10 = 8; string test11 = "000000111"; string test12 = "000000111111"; string test13 = "0010000"; string test14 = "000100000"; string test15 = "000100001"; string test16 = "Mihai"; string test17 = "journey"; string test18 = "persona"; string test19 = "car"; string test20 = "cat"; string test21 = ""; tests++; if(13 != binary_to_num(test1)){ fprintf(stderr, "TEST FAIL: binary_to_num.\n"); fails++; } tests++; if(13 != binary_to_num(test2)){ fprintf(stderr, "TEST FAIL: binary_to_num.\n"); fails++; } tests++; if(99999 != binary_to_num(test3)){ fprintf(stderr, "TEST FAIL: binary_to_num.\n"); fails++; } tests++; if(2458 != binary_to_num(test4)){ fprintf(stderr, "TEST FAIL: binary_to_num.\n"); fails++; } tests++; if(2458 != binary_to_num(test5)){ fprintf(stderr, "TEST FAIL: binary_to_num.\n"); fails++; } //test num_to_binary tests++; if(!str_eq("01000110", num_to_binary(test6))){ fprintf(stderr, "TEST FAIL: num_to_binary.\n"); string s = num_to_binary(test6); printf("HERE:%s\n", s.c_str()); fails++; } tests++; if(!str_eq("00111111", num_to_binary(test7))){ fprintf(stderr, "TEST FAIL: num_to_binary.\n"); fails++; } tests++; if(!str_eq("00000000", num_to_binary(test8))){ fprintf(stderr, "TEST FAIL: num_to_binary.\n"); fails++; } tests++; if(!str_eq("00000111", num_to_binary(test9))){ fprintf(stderr, "TEST FAIL: num_to_binary.\n"); fails++; } tests++; if(!str_eq("00001000", num_to_binary(test10))){ fprintf(stderr, "TEST FAIL: num_to_binary.\n"); fails++; } //test encode_six_bits tests++; if(7 != encode_six_bits(test11, 3)){ fprintf(stderr, "TEST FAIL: encode_six_bits.\n"); fails++; } tests++; if(7 != encode_six_bits(test12, 3)){ fprintf(stderr, "TEST FAIL: encode_six_bits.\n"); fails++; } tests++; if(16 != encode_six_bits(test13, 1)){ fprintf(stderr, "TEST FAIL: encode_six_bits.\n"); fails++; } tests++; if(32 != encode_six_bits(test14, 3)){ fprintf(stderr, "TEST FAIL: encode_six_bits.\n"); fails++; } tests++; if(33 != encode_six_bits(test15, 3)){ fprintf(stderr, "TEST FAIL: encode_six_bits.\n"); fails++; } tests++; if(!str_eq("TWloYWk=", encode_base64((unsigned char *) test16.c_str(), test16.length()))){ printf("OUT: %s\n", (encode_base64((unsigned char *) test16.c_str(), test16.length()).c_str())); fprintf(stderr, "TEST FAIL: encode_base64.\n"); fails++; } tests++; if(!str_eq("am91cm5leQ==", encode_base64((unsigned char *) test17.c_str(), test17.length()))){ printf("OUT: %s\n", (encode_base64((unsigned char *) test17.c_str(), test17.length()).c_str())); fprintf(stderr, "TEST FAIL: encode_base64.\n"); fails++; } tests++; if(!str_eq("cGVyc29uYQ==", encode_base64((unsigned char *) test18.c_str(), test18.length()))){ printf("OUT: %s\n", (encode_base64((unsigned char *) test18.c_str(), test18.length()).c_str())); fprintf(stderr, "TEST FAIL: encode_base64.\n"); fails++; } tests++; if(!str_eq("Y2Fy", encode_base64((unsigned char *) test19.c_str(), test19.length()))){ printf("OUT: %s\n", (encode_base64((unsigned char *) test19.c_str(), test19.length()).c_str())); fprintf(stderr, "TEST FAIL: encode_base64.\n"); fails++; } tests++; if(!str_eq("Y2F0", encode_base64((unsigned char *) test20.c_str(), test20.length()))){ printf("OUT: %s\n", (encode_base64((unsigned char *) test20.c_str(), test20.length()).c_str())); fprintf(stderr, "TEST FAIL: encode_base64.\n"); fails++; } tests++; if(!str_eq("", encode_base64((unsigned char *) test21.c_str(), test21.length()))){ printf("OUT: %s\n", (encode_base64((unsigned char *) test21.c_str(), test21.length()).c_str())); fprintf(stderr, "TEST FAIL: encode_base64.\n"); fails++; } //test encode_base64. fprintf(stderr, "%d/%d tests passed - math\n", tests - fails, tests); return fails; } int strings_tests() { fails = 0; tests = 0; // in tests tests++; if(!in(' ', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");} tests++; if(!in('\f', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");} tests++; if(!in('\n', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");} tests++; if(!in('\r', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");} tests++; if(!in('\t', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");} tests++; if(!in('\v', STR_WHITE)){fails++; fprintf(stderr, "In failing\n");} tests++; if(in(' ', "")){fails++; fprintf(stderr, "In failing empty\n");} tests++; if(in(' ', "asdefaersdvkdjlvc")){fails++; fprintf(stderr, "In failing not\n");} tests++; if(!in('A', "AAAAAAAAAAAAAAAAAAAAA")){fails++; fprintf(stderr, "In failing many\n");} tests++; if(!in('A', "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWA")){fails++; fprintf(stderr, "In failing long\n");} // skip_ws tests tests++; if(*(skip_ws(" qwe")) != 'q'){fails++; fprintf(stderr, "skipped ws failing\n");} tests++; if(*(skip_ws(" \n\n\n")) != (char)0){fails++; fprintf(stderr, "skipped ws failing around sentinel\n");} tests++; if(*(skip_ws("")) != (char)0){fails++; fprintf(stderr, "skipped ws failing for empty\n");} tests++; if(*(skip_ws("asd")) != 'a'){fails++; fprintf(stderr, "skipped ws when not required\n");} // string_seek tests tests++; if(*(string_seek("asdqwerty", "asd")) != 'q'){fails++; fprintf(stderr, "mismatch at asd\n");} tests++; if(*(string_seek("key: MAGIC_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MAGIC\n");} tests++; if(*(string_seek("kkey: MAGICKA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MAGICKA\n");} tests++; if(*(string_seek("kkkkkkkkkkkkkey: MAGICA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MAGICA\n");} tests++; if(*(string_seek("key: MADOKA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MADOKA\n");} tests++; if(*(string_seek("kkey: MAGIKA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at kkey\n");} tests++; if(*(string_seek("kkkkkkkkkkkkkey: AGICKA_KEY", "key:")) != 'A'){fails++; fprintf(stderr, "mismatch at AGICKA\n");} tests++; if(string_seek("qwertyuiop", "key") != NULL){fails++; fprintf(stderr, "mismatch at never\n");} tests++; if(string_seek("kekeroni macaroni.", "key") != NULL){fails++; fprintf(stderr, "mismatch at kek\n");} tests++; if(*(string_seek(" lorem ipsum", "lorem")) != 'i'){fails++; fprintf(stderr, "mismatch at lorem\n");} tests++; if(*(string_seek(" lorem ipsum", "lore")) != 'm'){fails++; fprintf(stderr, "mismatch at lore\n");} tests++; if(string_seek("", "key") != NULL){fails++; fprintf(stderr, "mismatch at null\n");} // string_get_next_token tests string tok; tests++; if((tok = string_get_next_token("qwert", "ert")).compare("qw")){fails++; fprintf(stderr, "mismatch token qwe1\n got \"%s\" expected qw\n", tok.c_str());} tests++; if((tok = string_get_next_token("qwert", "tr")).compare("qwe")){fails++; fprintf(stderr, "mismatch token qwe2\n got \"%s\" expected qwe\n", tok.c_str());} tests++; if((tok = string_get_next_token(" ", STR_WHITE)).compare("")){fails++; fprintf(stderr, "mismatch token empty ws\n got \"%s\" expected nothing\n", tok.c_str());} tests++; if((tok = string_get_next_token("asdqwe ", STR_WHITE)).compare("asdqwe")){fails++; fprintf(stderr, "mismatch token full ws\n got \"%s\" expected asdqwe\n", tok.c_str());} tests++; if((tok = string_get_next_token("asdqwetyi", STR_WHITE)).compare("asdqwetyi")){fails++; fprintf(stderr, "mismatch token no separator\n got \"%s\" expected asdqwetyi\n", tok.c_str());} tests++; if((tok = string_get_next_token(STR_WHITE, "")).compare(STR_WHITE)){fails++; fprintf(stderr, "mismatch token null separator\n got \"%s\" expected whitespace\n", tok.c_str());} tests++; if((tok = string_get_next_token("", "")).compare("")){fails++; fprintf(stderr, "mismatch token empty insanity\n got \"%s\" expected nothing\n", tok.c_str());} // is_num tests tests++; if(!is_num("0")){fails++; fprintf(stderr, "0 not detected as numeric\n");} tests++; if(!is_num("-0")){fails++; fprintf(stderr, "-0 not detected as numeric\n");} tests++; if(!is_num("-12312312312312321321321321312")){fails++; fprintf(stderr, "-long not detected as numeric\n");} tests++; if(is_num("-----123")){fails++; fprintf(stderr, "multiple negation detected as numeric\n");} tests++; if(is_num(" ")){fails++; fprintf(stderr, "space detected as numeric\n");} tests++; if(is_num("-")){fails++; fprintf(stderr, "Just minus detected as numeric\n");} tests++; if(is_num("-asd123")){fails++; fprintf(stderr, "minus string detected as numeric\n");} tests++; if(is_num("asdqwe")){fails++; fprintf(stderr, "text detected as numeric\n");} tests++; if(!is_num("1asdqwe")){fails++; fprintf(stderr, "number prefix not detected as numeric\n");} tests++; if(!is_num("-4asdqwe")){fails++; fprintf(stderr, "negative number prefix not detected as numeric\n");} // combination tests tests++; if((tok = string_get_next_token(string_seek("HTTP1/1 GET /\nws_key: asdqwemihai", "ws_key:"), STR_WHITE)).compare("asdqwemihai")){fails++; fprintf(stderr, "failed key detection\n");} tests++; if(string_get_next_token (string_seek (string_seek ("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????" , "?") , "x=") , " \n\t\f\r\v&") .compare("1")) {fails++; fprintf(stderr, "failed argument parsing for x(first)\n");} tests++; if(string_get_next_token (string_seek (string_seek ("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????" , "?") , "y=") , " \n\t\f\r\v&") .compare("2")) {fails++; fprintf(stderr, "failed argument parsing for y(second)\n");} tests++; if(string_get_next_token (string_seek (string_seek ("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????" , "?") , "t=") , " \n\t\f\r\v&") .compare("3")) {fails++; fprintf(stderr, "failed argument parsing for t(third)\n");} tests++; if(string_get_next_token (string_seek (string_seek ("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????" , "?") , "k=") , " \n\t\f\r\v&") .compare("")) {fails++; fprintf(stderr, "failed argument parsing for t(third)\n");} // null propagation testing tests++; if(in('U', NULL)){fails++; fprintf(stderr, "Null propagation failing for in\n");} tests++; if(skip_ws(NULL)){fails++; fprintf(stderr, "Null propagation failing for skip_ws\n");} tests++; if(string_seek(NULL, "qwe")){fails++; fprintf(stderr, "Null propagation failing for seek(origin)\n");} tests++; if(string_seek("qwe", NULL)){fails++; fprintf(stderr, "Null propagation failing for seek(target)\n");} tests++; if(string_seek(NULL, NULL)){fails++; fprintf(stderr, "Null propagation failing for seek(both)\n");} tests++; if(string_get_next_token(FIXED_STRING, NULL).compare(FIXED_STRING)){fails++; fprintf(stderr, "Null propagation failing for tokenizer when it should work\n");} tests++; if(string_get_next_token(NULL, FIXED_STRING).compare("")){fails++; fprintf(stderr, "Null propagation failing for tokenizer when it should fail\n");} tests++; if(is_num("")){fails++; fprintf(stderr, "empty detected as numeric\n");} tests++; if(is_num(NULL)){fails++; fprintf(stderr, "null detected as numeric\n");} // results and finish fprintf(stderr, "%d/%d tests passed - strings\n", tests - fails, tests); return fails; } int main() { return math_tests() + strings_tests(); }
38.656442
187
0.610062
CellWarsOfficial
87f60818cf08ceae83d9cce078c75e5de85c125d
33,887
cpp
C++
Blizzlike/ArcEmu/C++/World/ScriptMgr.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/ArcEmu/C++/World/ScriptMgr.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/ArcEmu/C++/World/ScriptMgr.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008-2011 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* English Worldstrings as of 08.16.2009 entry text 1 I would like to browse your goods. 2 I seek 3 mage 4 shaman 5 warrior 6 paladin 7 warlock 8 hunter 9 rogue 10 druid 11 priest 12 training 13 Train me in the ways of the beast. 14 Give me a ride. 15 I would like to make a bid. 16 Make this inn your home. 17 I would like to check my deposit box. 18 Bring me back to life. 19 How do I create a guild/arena team? 20 I want to create a guild crest. 21 I would like to go to the battleground. 22 I would like to reset my talents. 23 I wish to untrain my pet. 24 I understand, continue. 25 Yes, please do. 26 This instance is unavailable. 27 You must have The Burning Crusade Expansion to access this content. 28 Heroic mode unavailable for this instance. 29 You must be in a raid group to pass through here. 30 You do not have the required attunement to pass through here. 31 You must be at least level %u to pass through here. 32 You must be in a party to pass through here. 33 You must be level 70 to enter heroic mode. 34 - 35 You must have the item, `%s` to pass through here. 36 You must have the item, UNKNOWN to pass through here. 37 What can I teach you, $N? 38 Alterac Valley 39 Warsong Gulch 40 Arathi Basin 41 Arena 2v2 42 Arena 3v3 43 Arena 5v5 44 Eye of the Storm 45 Unknown Battleground 46 One minute until the battle for %s begins! 47 Thirty seconds until the battle for %s begins! 48 Fifteen seconds until the battle for %s begins! 49 The battle for %s has begun! 50 Arena 51 You have tried to join an invalid instance id. 52 Your queue on battleground instance id %u is no longer valid. Reason: Instance Deleted. 53 You cannot join this battleground as it has already ended. 54 Your queue on battleground instance %u is no longer valid, the instance no longer exists. 55 Sorry, raid groups joining battlegrounds are currently unsupported. 56 You must be the party leader to add a group to an arena. 57 You must be in a team to join rated arena. 58 You have too many players in your party to join this type of arena. 59 Sorry, some of your party members are not level 70. 60 One or more of your party members are already queued or inside a battleground. 61 One or more of your party members are not members of your team. 62 Welcome to 63 Horde 64 Alliance 65 [ |cff00ccffAttention|r ] Welcome! A new challenger (|cff00ff00{%d}|r - |cffff0000%s|r) has arrived and joined into |cffff0000%s|r,their force has already been increased. 66 This instance is scheduled to reset on 67 Auto loot passing is now %s 68 On 69 Off 70 Hey there, $N. How can I help you? 71 You are already in an arena team. 72 That name is already in use. 73 You already have an arena charter. 74 A guild with that name already exists. 75 You already have a guild charter. 76 Item not found. 77 Target is of the wrong faction. 78 Target player cannot sign your charter for one or more reasons. 79 You have already signed that charter. 80 You don't have the required amount of signatures to turn in this petition. 81 You must have Wrath of the Lich King Expansion to access this content. 82 Deathknight */ #include "StdAfx.h" #include <git_version.h> namespace worldstring { } initialiseSingleton(ScriptMgr); initialiseSingleton(HookInterface); ScriptMgr::ScriptMgr() { } ScriptMgr::~ScriptMgr() { } struct ScriptingEngine_dl { Arcemu::DynLib* dl; exp_script_register InitializeCall; uint32 Type; ScriptingEngine_dl() { dl = NULL; InitializeCall = NULL; Type = 0; } }; void ScriptMgr::LoadScripts() { if(HookInterface::getSingletonPtr() == NULL) new HookInterface; Log.Success("Server", "Loading External Script Libraries..."); std::string Path; std::string FileMask; Path = PREFIX; Path += '/'; #ifdef WIN32 /*Path = Config.MainConfig.GetStringDefault( "Script", "BinaryLocation", "script_bin" ); Path += "\\";*/ FileMask = ".dll"; #else #ifndef __APPLE__ FileMask = ".so"; #else FileMask = ".dylib"; #endif #endif Arcemu::FindFilesResult findres; std::vector< ScriptingEngine_dl > Engines; Arcemu::FindFiles(Path.c_str(), FileMask.c_str(), findres); uint32 count = 0; while(findres.HasNext()) { std::stringstream loadmessage; std::string fname = Path + findres.GetNext(); Arcemu::DynLib* dl = new Arcemu::DynLib(fname.c_str()); loadmessage << " " << dl->GetName() << " : "; if(!dl->Load()) { loadmessage << "ERROR: Cannot open library."; LOG_ERROR(loadmessage.str().c_str()); delete dl; continue; } else { exp_get_version vcall = reinterpret_cast< exp_get_version >(dl->GetAddressForSymbol("_exp_get_version")); exp_script_register rcall = reinterpret_cast< exp_script_register >(dl->GetAddressForSymbol("_exp_script_register")); exp_get_script_type scall = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type")); if((vcall == NULL) || (rcall == NULL) || (scall == NULL)) { loadmessage << "ERROR: Cannot find version functions."; LOG_ERROR(loadmessage.str().c_str()); delete dl; continue; } else { const char *version = vcall(); uint32 stype = scall(); if( strcmp( version, BUILD_HASH_STR ) != 0 ) { loadmessage << "ERROR: Version mismatch."; LOG_ERROR(loadmessage.str().c_str()); delete dl; continue; } else { loadmessage << ' ' << std::string( BUILD_HASH_STR ) << " : "; if((stype & SCRIPT_TYPE_SCRIPT_ENGINE) != 0) { ScriptingEngine_dl se; se.dl = dl; se.InitializeCall = rcall; se.Type = stype; Engines.push_back(se); loadmessage << "delayed load"; } else { rcall(this); dynamiclibs.push_back(dl); loadmessage << "loaded"; } LOG_BASIC(loadmessage.str().c_str()); count++; } } } } if(count == 0) { LOG_ERROR(" No external scripts found! Server will continue to function with limited functionality."); } else { Log.Success("Server", "Loaded %u external libraries.", count); Log.Success("Server", "Loading optional scripting engine(s)..."); for(std::vector< ScriptingEngine_dl >::iterator itr = Engines.begin(); itr != Engines.end(); ++itr) { itr->InitializeCall(this); dynamiclibs.push_back(itr->dl); } Log.Success("Server", "Done loading scripting engine(s)..."); } } void ScriptMgr::UnloadScripts() { if(HookInterface::getSingletonPtr()) delete HookInterface::getSingletonPtr(); for(CustomGossipScripts::iterator itr = _customgossipscripts.begin(); itr != _customgossipscripts.end(); ++itr) (*itr)->Destroy(); _customgossipscripts.clear(); for(QuestScripts::iterator itr = _questscripts.begin(); itr != _questscripts.end(); ++itr) delete *itr; _questscripts.clear(); UnloadScriptEngines(); for(DynamicLibraryMap::iterator itr = dynamiclibs.begin(); itr != dynamiclibs.end(); ++itr) delete *itr; dynamiclibs.clear(); } void ScriptMgr::DumpUnimplementedSpells() { std::ofstream of; LOG_BASIC("Dumping IDs for spells with unimplemented dummy/script effect(s)"); uint32 count = 0; of.open("unimplemented1.txt"); for(DBCStorage< SpellEntry >::iterator itr = dbcSpell.begin(); itr != dbcSpell.end(); ++itr) { SpellEntry* sp = *itr; if(!sp->HasEffect(SPELL_EFFECT_DUMMY) && !sp->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT) && !sp->HasEffect(SPELL_EFFECT_SEND_EVENT)) continue; HandleDummySpellMap::iterator sitr = _spells.find(sp->Id); if(sitr != _spells.end()) continue; HandleScriptEffectMap::iterator seitr = SpellScriptEffects.find(sp->Id); if(seitr != SpellScriptEffects.end()) continue; std::stringstream ss; ss << sp->Id; ss << std::endl; of.write(ss.str().c_str(), ss.str().length()); count++; } of.close(); LOG_BASIC("Dumped %u IDs.", count); LOG_BASIC("Dumping IDs for spells with unimplemented dummy aura effect."); std::ofstream of2; of2.open("unimplemented2.txt"); count = 0; for(DBCStorage< SpellEntry >::iterator itr = dbcSpell.begin(); itr != dbcSpell.end(); ++itr) { SpellEntry* sp = *itr; if(!sp->AppliesAura(SPELL_AURA_DUMMY)) continue; HandleDummyAuraMap::iterator ditr = _auras.find(sp->Id); if(ditr != _auras.end()) continue; std::stringstream ss; ss << sp->Id; ss << std::endl; of2.write(ss.str().c_str(), ss.str().length()); count++; } of2.close(); LOG_BASIC("Dumped %u IDs.", count); } void ScriptMgr::register_creature_script(uint32 entry, exp_create_creature_ai callback) { if(_creatures.find(entry) != _creatures.end()) LOG_ERROR("ScriptMgr is trying to register a script for Creature ID: %u even if there's already one for that Creature. Remove one of those scripts.", entry); _creatures.insert(CreatureCreateMap::value_type(entry, callback)); } void ScriptMgr::register_gameobject_script(uint32 entry, exp_create_gameobject_ai callback) { if(_gameobjects.find(entry) != _gameobjects.end()) LOG_ERROR("ScriptMgr is trying to register a script for GameObject ID: %u even if there's already one for that GameObject. Remove one of those scripts.", entry); _gameobjects.insert(GameObjectCreateMap::value_type(entry, callback)); } void ScriptMgr::register_dummy_aura(uint32 entry, exp_handle_dummy_aura callback) { if(_auras.find(entry) != _auras.end()) { LOG_ERROR("ScriptMgr is trying to register a script for Aura ID: %u even if there's already one for that Aura. Remove one of those scripts.", entry); } SpellEntry* sp = dbcSpell.LookupEntryForced(entry); if(sp == NULL) { LOG_ERROR("ScriptMgr is trying to register a dummy aura handler for Spell ID: %u which is invalid.", entry); return; } if(!sp->AppliesAura(SPELL_AURA_DUMMY) && !sp->AppliesAura(SPELL_AURA_PERIODIC_TRIGGER_DUMMY)) LOG_ERROR("ScriptMgr has registered a dummy aura handler for Spell ID: %u ( %s ), but spell has no dummy aura!", entry, sp->Name); _auras.insert(HandleDummyAuraMap::value_type(entry, callback)); } void ScriptMgr::register_dummy_spell(uint32 entry, exp_handle_dummy_spell callback) { if(_spells.find(entry) != _spells.end()) { LOG_ERROR("ScriptMgr is trying to register a script for Spell ID: %u even if there's already one for that Spell. Remove one of those scripts.", entry); return; } SpellEntry* sp = dbcSpell.LookupEntryForced(entry); if(sp == NULL) { LOG_ERROR("ScriptMgr is trying to register a dummy handler for Spell ID: %u which is invalid.", entry); return; } if(!sp->HasEffect(SPELL_EFFECT_DUMMY) && !sp->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT) && !sp->HasEffect(SPELL_EFFECT_SEND_EVENT)) LOG_ERROR("ScriptMgr has registered a dummy handler for Spell ID: %u ( %s ), but spell has no dummy/script/send event effect!", entry, sp->Name); _spells.insert(HandleDummySpellMap::value_type(entry, callback)); } void ScriptMgr::register_gossip_script(uint32 entry, GossipScript* gs) { register_creature_gossip(entry, gs); } void ScriptMgr::register_go_gossip_script(uint32 entry, GossipScript* gs) { register_go_gossip(entry, gs); } void ScriptMgr::register_quest_script(uint32 entry, QuestScript* qs) { Quest* q = QuestStorage.LookupEntry(entry); if(q != NULL) { if(q->pQuestScript != NULL) LOG_ERROR("ScriptMgr is trying to register a script for Quest ID: %u even if there's already one for that Quest. Remove one of those scripts.", entry); q->pQuestScript = qs; } _questscripts.insert(qs); } void ScriptMgr::register_instance_script(uint32 pMapId, exp_create_instance_ai pCallback) { if(mInstances.find(pMapId) != mInstances.end()) LOG_ERROR("ScriptMgr is trying to register a script for Instance ID: %u even if there's already one for that Instance. Remove one of those scripts.", pMapId); mInstances.insert(InstanceCreateMap::value_type(pMapId, pCallback)); }; void ScriptMgr::register_creature_script(uint32* entries, exp_create_creature_ai callback) { for(uint32 y = 0; entries[y] != 0; y++) { register_creature_script(entries[y], callback); } }; void ScriptMgr::register_gameobject_script(uint32* entries, exp_create_gameobject_ai callback) { for(uint32 y = 0; entries[y] != 0; y++) { register_gameobject_script(entries[y], callback); } }; void ScriptMgr::register_dummy_aura(uint32* entries, exp_handle_dummy_aura callback) { for(uint32 y = 0; entries[y] != 0; y++) { register_dummy_aura(entries[y], callback); } }; void ScriptMgr::register_dummy_spell(uint32* entries, exp_handle_dummy_spell callback) { for(uint32 y = 0; entries[y] != 0; y++) { register_dummy_spell(entries[y], callback); } }; void ScriptMgr::register_script_effect(uint32* entries, exp_handle_script_effect callback) { for(uint32 y = 0; entries[y] != 0; y++) { register_script_effect(entries[y], callback); } }; void ScriptMgr::register_script_effect(uint32 entry, exp_handle_script_effect callback) { HandleScriptEffectMap::iterator itr = SpellScriptEffects.find(entry); if(itr != SpellScriptEffects.end()) { LOG_ERROR("ScriptMgr tried to register more than 1 script effect handlers for Spell %u", entry); return; } SpellEntry* sp = dbcSpell.LookupEntryForced(entry); if(sp == NULL) { LOG_ERROR("ScriptMgr tried to register a script effect handler for Spell %u, which is invalid.", entry); return; } if(!sp->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT) && !sp->HasEffect(SPELL_EFFECT_SEND_EVENT)) LOG_ERROR("ScriptMgr has registered a script effect handler for Spell ID: %u ( %s ), but spell has no scripted effect!", entry, sp->Name); SpellScriptEffects.insert(std::pair< uint32, exp_handle_script_effect >(entry, callback)); } CreatureAIScript* ScriptMgr::CreateAIScriptClassForEntry(Creature* pCreature) { CreatureCreateMap::iterator itr = _creatures.find(pCreature->GetEntry()); if(itr == _creatures.end()) return NULL; exp_create_creature_ai function_ptr = itr->second; return (function_ptr)(pCreature); } GameObjectAIScript* ScriptMgr::CreateAIScriptClassForGameObject(uint32 uEntryId, GameObject* pGameObject) { GameObjectCreateMap::iterator itr = _gameobjects.find(pGameObject->GetEntry()); if(itr == _gameobjects.end()) return NULL; exp_create_gameobject_ai function_ptr = itr->second; return (function_ptr)(pGameObject); } InstanceScript* ScriptMgr::CreateScriptClassForInstance(uint32 pMapId, MapMgr* pMapMgr) { InstanceCreateMap::iterator Iter = mInstances.find(pMapMgr->GetMapId()); if(Iter == mInstances.end()) return NULL; exp_create_instance_ai function_ptr = Iter->second; return (function_ptr)(pMapMgr); }; bool ScriptMgr::CallScriptedDummySpell(uint32 uSpellId, uint32 i, Spell* pSpell) { HandleDummySpellMap::iterator itr = _spells.find(uSpellId); if(itr == _spells.end()) return false; exp_handle_dummy_spell function_ptr = itr->second; return (function_ptr)(i, pSpell); } bool ScriptMgr::HandleScriptedSpellEffect(uint32 SpellId, uint32 i, Spell* s) { HandleScriptEffectMap::iterator itr = SpellScriptEffects.find(SpellId); if(itr == SpellScriptEffects.end()) return false; exp_handle_script_effect ptr = itr->second; return (ptr)(i, s); } bool ScriptMgr::CallScriptedDummyAura(uint32 uSpellId, uint32 i, Aura* pAura, bool apply) { HandleDummyAuraMap::iterator itr = _auras.find(uSpellId); if(itr == _auras.end()) return false; exp_handle_dummy_aura function_ptr = itr->second; return (function_ptr)(i, pAura, apply); } bool ScriptMgr::CallScriptedItem(Item* pItem, Player* pPlayer) { Arcemu::Gossip::Script* script = this->get_item_gossip(pItem->GetEntry()); if(script != NULL) { script->OnHello(pItem, pPlayer); return true; } return false; } void ScriptMgr::register_item_gossip_script(uint32 entry, GossipScript* gs) { register_item_gossip(entry, gs); } /* CreatureAI Stuff */ CreatureAIScript::CreatureAIScript(Creature* creature) : _unit(creature), linkedCreatureAI(NULL) { } CreatureAIScript::~CreatureAIScript() { //notify our linked creature that we are being deleted. if(linkedCreatureAI != NULL) linkedCreatureAI->LinkedCreatureDeleted(); } void CreatureAIScript::RegisterAIUpdateEvent(uint32 frequency) { //sEventMgr.AddEvent(_unit, &Creature::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, frequency, 0,0); sEventMgr.AddEvent(_unit, &Creature::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, frequency, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT); } void CreatureAIScript::ModifyAIUpdateEvent(uint32 newfrequency) { sEventMgr.ModifyEventTimeAndTimeLeft(_unit, EVENT_SCRIPT_UPDATE_EVENT, newfrequency); } void CreatureAIScript::RemoveAIUpdateEvent() { sEventMgr.RemoveEvents(_unit, EVENT_SCRIPT_UPDATE_EVENT); } void CreatureAIScript::LinkedCreatureDeleted() { linkedCreatureAI = NULL; } void CreatureAIScript::SetLinkedCreature(CreatureAIScript* creatureAI) { //notify our linked creature that we are not more linked if(linkedCreatureAI != NULL) linkedCreatureAI->LinkedCreatureDeleted(); //link to the new creature linkedCreatureAI = creatureAI; } bool CreatureAIScript::IsAlive() { return _unit->isAlive(); } /* GameObjectAI Stuff */ GameObjectAIScript::GameObjectAIScript(GameObject* goinstance) : _gameobject(goinstance) { } void GameObjectAIScript::ModifyAIUpdateEvent(uint32 newfrequency) { sEventMgr.ModifyEventTimeAndTimeLeft(_gameobject, EVENT_SCRIPT_UPDATE_EVENT, newfrequency); } void GameObjectAIScript::RemoveAIUpdateEvent() { sEventMgr.RemoveEvents(_gameobject, EVENT_SCRIPT_UPDATE_EVENT); } void GameObjectAIScript::RegisterAIUpdateEvent(uint32 frequency) { sEventMgr.AddEvent(_gameobject, &GameObject::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, frequency, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT); } /* InstanceAI Stuff */ InstanceScript::InstanceScript(MapMgr* pMapMgr) : mInstance(pMapMgr) { }; void InstanceScript::RegisterUpdateEvent(uint32 pFrequency) { sEventMgr.AddEvent(mInstance, &MapMgr::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, pFrequency, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT); }; void InstanceScript::ModifyUpdateEvent(uint32 pNewFrequency) { sEventMgr.ModifyEventTimeAndTimeLeft(mInstance, EVENT_SCRIPT_UPDATE_EVENT, pNewFrequency); }; void InstanceScript::RemoveUpdateEvent() { sEventMgr.RemoveEvents(mInstance, EVENT_SCRIPT_UPDATE_EVENT); }; /* Hook Stuff */ void ScriptMgr::register_hook(ServerHookEvents event, void* function_pointer) { ARCEMU_ASSERT(event < NUM_SERVER_HOOKS); _hooks[event].insert(function_pointer); } bool ScriptMgr::has_creature_script(uint32 entry) const { return (_creatures.find(entry) != _creatures.end()); } bool ScriptMgr::has_gameobject_script(uint32 entry) const { return (_gameobjects.find(entry) != _gameobjects.end()); } bool ScriptMgr::has_dummy_aura_script(uint32 entry) const { return (_auras.find(entry) != _auras.end()); } bool ScriptMgr::has_dummy_spell_script(uint32 entry) const { return (_spells.find(entry) != _spells.end()); } bool ScriptMgr::has_script_effect(uint32 entry) const { return (SpellScriptEffects.find(entry) != SpellScriptEffects.end()); } bool ScriptMgr::has_instance_script(uint32 id) const { return (mInstances.find(id) != mInstances.end()); } bool ScriptMgr::has_hook(ServerHookEvents evt, void* ptr) const { return (_hooks[evt].size() != 0 && _hooks[evt].find(ptr) != _hooks[evt].end()); } bool ScriptMgr::has_quest_script(uint32 entry) const { Quest* q = QuestStorage.LookupEntry(entry); return (q == NULL || q->pQuestScript != NULL); } void ScriptMgr::register_creature_gossip(uint32 entry, Arcemu::Gossip::Script* script) { GossipMap::iterator itr = creaturegossip_.find(entry); if(itr == creaturegossip_.end()) creaturegossip_.insert(make_pair(entry, script)); //keeping track of all created gossips to delete them all on shutdown _customgossipscripts.insert(script); } bool ScriptMgr::has_creature_gossip(uint32 entry) const { return creaturegossip_.find(entry) != creaturegossip_.end(); } Arcemu::Gossip::Script* ScriptMgr::get_creature_gossip(uint32 entry) const { GossipMap::const_iterator itr = creaturegossip_.find(entry); if(itr != creaturegossip_.end()) return itr->second; return NULL; } void ScriptMgr::register_item_gossip(uint32 entry, Arcemu::Gossip::Script* script) { GossipMap::iterator itr = itemgossip_.find(entry); if(itr == itemgossip_.end()) itemgossip_.insert(make_pair(entry, script)); //keeping track of all created gossips to delete them all on shutdown _customgossipscripts.insert(script); } void ScriptMgr::register_go_gossip(uint32 entry, Arcemu::Gossip::Script* script) { GossipMap::iterator itr = gogossip_.find(entry); if(itr == gogossip_.end()) gogossip_.insert(make_pair(entry, script)); //keeping track of all created gossips to delete them all on shutdown _customgossipscripts.insert(script); } bool ScriptMgr::has_item_gossip(uint32 entry) const { return itemgossip_.find(entry) != itemgossip_.end(); } bool ScriptMgr::has_go_gossip(uint32 entry) const { return gogossip_.find(entry) != gogossip_.end(); } Arcemu::Gossip::Script* ScriptMgr::get_go_gossip(uint32 entry) const { GossipMap::const_iterator itr = gogossip_.find(entry); if(itr != gogossip_.end()) return itr->second; return NULL; } Arcemu::Gossip::Script* ScriptMgr::get_item_gossip(uint32 entry) const { GossipMap::const_iterator itr = itemgossip_.find(entry); if(itr != itemgossip_.end()) return itr->second; return NULL; } void ScriptMgr::ReloadScriptEngines() { //for all scripting engines that allow reloading, assuming there will be new scripting engines. exp_get_script_type version_function; exp_engine_reload engine_reloadfunc; for(DynamicLibraryMap::iterator itr = dynamiclibs.begin(); itr != dynamiclibs.end(); ++itr) { Arcemu::DynLib* dl = *itr; version_function = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type")); if(version_function == NULL) continue; if((version_function() & SCRIPT_TYPE_SCRIPT_ENGINE) != 0) { engine_reloadfunc = reinterpret_cast< exp_engine_reload >(dl->GetAddressForSymbol("_export_engine_reload")); if(engine_reloadfunc != NULL) engine_reloadfunc(); } } } void ScriptMgr::UnloadScriptEngines() { //for all scripting engines that allow unloading, assuming there will be new scripting engines. exp_get_script_type version_function; exp_engine_unload engine_unloadfunc; for(DynamicLibraryMap::iterator itr = dynamiclibs.begin(); itr != dynamiclibs.end(); ++itr) { Arcemu::DynLib* dl = *itr; version_function = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type")); if(version_function == NULL) continue; if((version_function() & SCRIPT_TYPE_SCRIPT_ENGINE) != 0) { engine_unloadfunc = reinterpret_cast< exp_engine_unload >(dl->GetAddressForSymbol("_exp_engine_unload")); if(engine_unloadfunc != NULL) engine_unloadfunc(); } } } //support for Gossip scripts added before r4106 changes void GossipScript::OnHello(Object* pObject, Player* Plr) { GossipHello(pObject, Plr); } void GossipScript::OnSelectOption(Object* pObject, Player* Plr, uint32 Id, const char* EnteredCode) { uint32 IntId = Id; if(Plr->CurrentGossipMenu != NULL) { GossipMenuItem item = Plr->CurrentGossipMenu->GetItem(Id); IntId = item.IntId; } GossipSelectOption(pObject, Plr, Id , IntId, EnteredCode); } void GossipScript::OnEnd(Object* pObject, Player* Plr) { GossipEnd(pObject, Plr); } /* Hook Implementations */ bool HookInterface::OnNewCharacter(uint32 Race, uint32 Class, WorldSession* Session, const char* Name) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_NEW_CHARACTER]; bool ret_val = true; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) { bool rv = ((tOnNewCharacter) * itr)(Race, Class, Session, Name); if(rv == false) // never set ret_val back to true, once it's false ret_val = false; } return ret_val; } void HookInterface::OnKillPlayer(Player* pPlayer, Player* pVictim) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_KILL_PLAYER]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnKillPlayer)*itr)(pPlayer, pVictim); } void HookInterface::OnFirstEnterWorld(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_FIRST_ENTER_WORLD]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnFirstEnterWorld)*itr)(pPlayer); } void HookInterface::OnCharacterCreate(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_CHARACTER_CREATE]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOCharacterCreate)*itr)(pPlayer); } void HookInterface::OnEnterWorld(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ENTER_WORLD]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnEnterWorld)*itr)(pPlayer); } void HookInterface::OnGuildCreate(Player* pLeader, Guild* pGuild) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_GUILD_CREATE]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnGuildCreate)*itr)(pLeader, pGuild); } void HookInterface::OnGuildJoin(Player* pPlayer, Guild* pGuild) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_GUILD_JOIN]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnGuildJoin)*itr)(pPlayer, pGuild); } void HookInterface::OnDeath(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_DEATH]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnDeath)*itr)(pPlayer); } bool HookInterface::OnRepop(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_REPOP]; bool ret_val = true; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) { bool rv = ((tOnRepop) * itr)(pPlayer); if(rv == false) // never set ret_val back to true, once it's false ret_val = false; } return ret_val; } void HookInterface::OnEmote(Player* pPlayer, uint32 Emote, Unit* pUnit) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_EMOTE]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnEmote)*itr)(pPlayer, Emote, pUnit); } void HookInterface::OnEnterCombat(Player* pPlayer, Unit* pTarget) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ENTER_COMBAT]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnEnterCombat)*itr)(pPlayer, pTarget); } bool HookInterface::OnCastSpell(Player* pPlayer, SpellEntry* pSpell, Spell* spell) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_CAST_SPELL]; bool ret_val = true; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) { bool rv = ((tOnCastSpell) * itr)(pPlayer, pSpell, spell); if(rv == false) // never set ret_val back to true, once it's false ret_val = false; } return ret_val; } bool HookInterface::OnLogoutRequest(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_LOGOUT_REQUEST]; bool ret_val = true; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) { bool rv = ((tOnLogoutRequest) * itr)(pPlayer); if(rv == false) // never set ret_val back to true, once it's false ret_val = false; } return ret_val; } void HookInterface::OnLogout(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_LOGOUT]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnLogout)*itr)(pPlayer); } void HookInterface::OnQuestAccept(Player* pPlayer, Quest* pQuest, Object* pQuestGiver) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_QUEST_ACCEPT]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnQuestAccept)*itr)(pPlayer, pQuest, pQuestGiver); } void HookInterface::OnZone(Player* pPlayer, uint32 zone, uint32 oldZone) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ZONE]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnZone)*itr)(pPlayer, zone, oldZone); } bool HookInterface::OnChat(Player* pPlayer, uint32 type, uint32 lang, const char* message, const char* misc) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_CHAT]; bool ret_val = true; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) { bool rv = ((tOnChat) * itr)(pPlayer, type, lang, message, misc); if(rv == false) // never set ret_val back to true, once it's false ret_val = false; } return ret_val; } void HookInterface::OnLoot(Player* pPlayer, Unit* pTarget, uint32 money, uint32 itemId) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_LOOT]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnLoot)*itr)(pPlayer, pTarget, money, itemId); } void HookInterface::OnObjectLoot(Player* pPlayer, Object* pTarget, uint32 money, uint32 itemId) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_OBJECTLOOT]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnObjectLoot)*itr)(pPlayer, pTarget, money, itemId); } void HookInterface::OnFullLogin(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_FULL_LOGIN]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnEnterWorld)*itr)(pPlayer); } void HookInterface::OnQuestCancelled(Player* pPlayer, Quest* pQuest) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_QUEST_CANCELLED]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnQuestCancel)*itr)(pPlayer, pQuest); } void HookInterface::OnQuestFinished(Player* pPlayer, Quest* pQuest, Object* pQuestGiver) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_QUEST_FINISHED]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnQuestFinished)*itr)(pPlayer, pQuest, pQuestGiver); } void HookInterface::OnHonorableKill(Player* pPlayer, Player* pKilled) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_HONORABLE_KILL]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnHonorableKill)*itr)(pPlayer, pKilled); } void HookInterface::OnArenaFinish(Player* pPlayer, ArenaTeam* pTeam, bool victory, bool rated) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ARENA_FINISH]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnArenaFinish)*itr)(pPlayer, pTeam, victory, rated); } void HookInterface::OnAreaTrigger(Player* pPlayer, uint32 areaTrigger) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_AREATRIGGER]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnAreaTrigger)*itr)(pPlayer, areaTrigger); } void HookInterface::OnPostLevelUp(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_POST_LEVELUP]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnPostLevelUp)*itr)(pPlayer); } bool HookInterface::OnPreUnitDie(Unit* killer, Unit* victim) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_PRE_DIE]; bool ret_val = true; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) { bool rv = ((tOnPreUnitDie) * itr)(killer, victim); if(rv == false) // never set ret_val back to true, once it's false ret_val = false; } return ret_val; } void HookInterface::OnAdvanceSkillLine(Player* pPlayer, uint32 skillLine, uint32 current) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ADVANCE_SKILLLINE]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnAdvanceSkillLine)*itr)(pPlayer, skillLine, current); } void HookInterface::OnDuelFinished(Player* Winner, Player* Looser) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_DUEL_FINISHED]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnDuelFinished)*itr)(Winner, Looser); } void HookInterface::OnAuraRemove(Aura* aura) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_AURA_REMOVE]; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) ((tOnAuraRemove)*itr)(aura); } bool HookInterface::OnResurrect(Player* pPlayer) { ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_RESURRECT]; bool ret_val = true; for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr) { bool rv = ((tOnResurrect) * itr)(pPlayer); if(rv == false) // never set ret_val back to true, once it's false ret_val = false; } return ret_val; }
30.25625
174
0.741051
499453466
87ff0fe2e6931d5ab67336efe927a2c045ad694d
1,584
cpp
C++
Cpp-Projects/Part_02_Foundation/L4_writing_multiple_programs/13_Classes_and_OOP/1_Code_without_Objects/main.cpp
selfbeing/selfdriving
8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9
[ "MIT" ]
null
null
null
Cpp-Projects/Part_02_Foundation/L4_writing_multiple_programs/13_Classes_and_OOP/1_Code_without_Objects/main.cpp
selfbeing/selfdriving
8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9
[ "MIT" ]
null
null
null
Cpp-Projects/Part_02_Foundation/L4_writing_multiple_programs/13_Classes_and_OOP/1_Code_without_Objects/main.cpp
selfbeing/selfdriving
8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9
[ "MIT" ]
null
null
null
/* Code without Objects Suppose you were writing a program to model several cars. In your program, you want to keep track of each car's color and the distance the car has traveled, and you want to be able to increment this distance and print out the car's properties. You could write something like the code below to accomplish this: */ #include <iostream> #include <string> using std::string; using std::cout; int main() { // Variables to hold each car's color. string car_1_color = "green"; string car_2_color = "red"; string car_3_color = "blue"; // Variables to hold each car's initial position. int car_1_distance = 0; int car_2_distance = 0; int car_3_distance = 0; // Increment car_1's position by 1. car_1_distance++; // Print out the position and color of each car. cout << "The distance that the " << car_1_color << " car 1 has traveled is: " << car_1_distance << "\n"; cout << "The distance that the " << car_2_color << " car 2 has traveled is: " << car_2_distance << "\n"; cout << "The distance that the " << car_3_color << " car 3 has traveled is: " << car_3_distance << "\n"; } /* This works for the few cars that are defined in the program, but if you wanted the program to keep track of many cars this would be cumbersome. You would need to create a new variables for every car, and the code would quickly become cluttered. One way to fix this would be to define a Car class with those variables as attributes, along with a few class methods to increment the distance traveled and print out car data. */
36
108
0.705177
selfbeing
e2008f873e49dc817c7bbea2579cd98fb7e09b25
4,792
cpp
C++
sdh/crc.cpp
ipab-slmc/SDHLibrary-CPP
0217d4edf82f34292750240bd7a3d9c63feb7e33
[ "Apache-2.0" ]
2
2021-11-12T09:28:45.000Z
2021-12-22T09:09:31.000Z
sdh/crc.cpp
ipab-slmc/SDHLibrary-CPP
0217d4edf82f34292750240bd7a3d9c63feb7e33
[ "Apache-2.0" ]
null
null
null
sdh/crc.cpp
ipab-slmc/SDHLibrary-CPP
0217d4edf82f34292750240bd7a3d9c63feb7e33
[ "Apache-2.0" ]
2
2019-05-02T20:03:29.000Z
2019-06-24T14:50:42.000Z
//====================================================================== /*! \file \section sdhlibrary_cpp_crc_cpp_general General file information \author Dirk Osswald \date 2007-02-19 \brief Implementation of class #SDH::cCRC_DSACON32m (actually only the static members all other is derived). \section sdhlibrary_cpp_crc_cpp_copyright Copyright - Copyright (c) 2008 SCHUNK GmbH & Co. KG <HR> \internal \subsection sdhlibrary_cpp_crc_cpp_details SVN related, detailed file specific information: $LastChangedBy: Osswald2 $ $LastChangedDate: 2008-10-08 10:48:38 +0200 (Mi, 08 Okt 2008) $ \par SVN file revision: $Id: crc.cpp 3659 2008-10-08 08:48:38Z Osswald2 $ \subsection sdhlibrary_cpp_crc_cpp_changelog Changelog of this file: \include crc.cpp.log */ //====================================================================== #include "sdhlibrary_settings.h" //---------------------------------------------------------------------- // System Includes - include with <> //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Project Includes - include with "" //---------------------------------------------------------------------- #include "crc.h" USING_NAMESPACE_SDH //---------------------------------------------------------------------- // Defines, enums, unions, structs, //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Global variables //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Function implementation (function definitions) //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Class member definitions //---------------------------------------------------------------------- tCRCValue const cCRC_DSACON32m::crc_table_dsacon32m[256] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 }; //====================================================================== /* Here are some settings for the emacs/xemacs editor (and can be safely ignored): (e.g. to explicitely set C++ mode for *.h header files) Local Variables: mode:C++ mode:ELSE End: */ //======================================================================
42.785714
105
0.515442
ipab-slmc
e207034aa51177b9803721c97bffdf7abe9ae688
279
hpp
C++
include/RED4ext/Scripting/Natives/Generated/rend/WindShapeAnchorPointVert.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/rend/WindShapeAnchorPointVert.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/rend/WindShapeAnchorPointVert.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> namespace RED4ext { namespace rend { enum class WindShapeAnchorPointVert : uint32_t { AP_CENTER = 0, AP_TOP = 1, AP_BOTTOM = 2, }; } // namespace rend } // namespace RED4ext
16.411765
57
0.698925
jackhumbert
e20737d3135a49e21df6882d87d3d9136988046b
786
hpp
C++
source/gui/LogEntry.hpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
1
2021-12-26T12:48:18.000Z
2021-12-26T12:48:18.000Z
source/gui/LogEntry.hpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
null
null
null
source/gui/LogEntry.hpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
1
2021-12-26T12:48:25.000Z
2021-12-26T12:48:25.000Z
#pragma once #include <VehicleID.hpp> class LogEntry { public: std::string timestamp; std::string source; std::string text; uint8_t color[3]; /** * @brief Create a log entry. * @param [in] timestamp The UTC second of the day. * @param [in] source Source of the log message. * @param [in] text Text of the log message. * @param [in] r Red component for text color. * @param [in] g Green component for text color. * @param [in] b Blue component for text color. */ LogEntry(double timestamp, const VehicleID& source, std::string& text, uint8_t r, uint8_t g, uint8_t b); /** * @brief Delete the log entry. */ ~LogEntry(); };
25.354839
112
0.554707
RobertDamerius
e208cd81c87125355ee128e641604a7199345678
1,545
cpp
C++
libpigpiodpp/test/pihardwaremanagerfactorytests.cpp
freesurfer-rge/linesidecabinet
8944c67fa7d340aa792e3a6e681113a4676bfbad
[ "MIT" ]
null
null
null
libpigpiodpp/test/pihardwaremanagerfactorytests.cpp
freesurfer-rge/linesidecabinet
8944c67fa7d340aa792e3a6e681113a4676bfbad
[ "MIT" ]
14
2019-11-17T14:46:25.000Z
2021-03-10T02:48:40.000Z
libpigpiodpp/test/pihardwaremanagerfactorytests.cpp
freesurfer-rge/linesidecabinet
8944c67fa7d340aa792e3a6e681113a4676bfbad
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include "tendril/devices/i2cdevicedata.hpp" #include "tendril/devices/pca9685.hpp" #include "pigpiodpp/pihardwaremanagerfactory.hpp" BOOST_AUTO_TEST_SUITE( PiHardwareManagerFactory ) BOOST_AUTO_TEST_CASE( Smoke ) { Tendril::HardwareManagerData config; auto hwm = PiGPIOdpp::GetHardwareManager(config); BOOST_REQUIRE( hwm ); BOOST_CHECK( hwm->bipProviderRegistrar.Retrieve("GPIO") ); BOOST_CHECK( hwm->bopProviderRegistrar.Retrieve("GPIO") ); BOOST_CHECK( hwm->bopArrayProviderRegistrar.Retrieve("GPIO") ); BOOST_CHECK( hwm->i2cCommProviderRegistrar.Retrieve("0") ); BOOST_CHECK( hwm->i2cCommProviderRegistrar.Retrieve("1") ); } BOOST_AUTO_TEST_CASE( WithPCA9685 ) { const std::string devName = "MyServoProvider"; auto some9685 = std::make_shared< Tendril::Devices::I2CDeviceData<Tendril::Devices::PCA9685>>(); some9685->i2cCommsRequest.providerName = "1"; some9685->i2cCommsRequest.idOnProvider = "0x10"; some9685->name = devName; some9685->settings["referenceClock"] = "25e6"; some9685->settings["pwmFrequency"] = "60"; Tendril::HardwareManagerData config; config.devices.push_back(some9685); auto hwm = PiGPIOdpp::GetHardwareManager(config); BOOST_REQUIRE( hwm ); BOOST_CHECK( hwm->bipProviderRegistrar.Retrieve("GPIO") ); BOOST_CHECK( hwm->bopProviderRegistrar.Retrieve("GPIO") ); BOOST_CHECK( hwm->bopArrayProviderRegistrar.Retrieve("GPIO") ); BOOST_CHECK( hwm->pwmcProviderRegistrar.Retrieve( devName ) ); } BOOST_AUTO_TEST_SUITE_END()
32.1875
66
0.756634
freesurfer-rge
e20a1779c288f36bf771964a87d0f79255b286bb
10,634
cpp
C++
Quickhaptics/examples/ShapeDepthFeedback/ShapeDepthFeedbackGLUT/src/main.cpp
Stalpaard/SensoHapt
74c90f1f4b1a17bd94109bc6543a864006849c75
[ "MIT" ]
null
null
null
Quickhaptics/examples/ShapeDepthFeedback/ShapeDepthFeedbackGLUT/src/main.cpp
Stalpaard/SensoHapt
74c90f1f4b1a17bd94109bc6543a864006849c75
[ "MIT" ]
null
null
null
Quickhaptics/examples/ShapeDepthFeedback/ShapeDepthFeedbackGLUT/src/main.cpp
Stalpaard/SensoHapt
74c90f1f4b1a17bd94109bc6543a864006849c75
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// //OpenHaptics QuickHaptics - Depth and Feedback Buffer Example //SensAble Technologies, Woburn, MA //September 03, 2008 //Programmer: Hari Vasudevan ////////////////////////////////////////////////////////////////////////////// #include <QHHeadersGLUT.h>//Include all necessary headers void glutMenuFunction(int MenuID); int main(int argc, char *argv[]) { QHGLUT* DisplayObject = new QHGLUT(argc,argv);//create a display window DeviceSpace* OmniSpace = new DeviceSpace;//get the default device DisplayObject->tell(OmniSpace);//Tell QuickHaptics about it TriMesh* Bunny = new TriMesh("Models/BunnyRep.ply");//Load the Bunny Models Bunny->setName("Bunny");//give it a name Bunny->setTranslation(0.25,-1.0,0.0);//Position the model Bunny->setScale(10.0);//make the model 2 times as large Bunny->setStiffness(0.5); Bunny->setDamping(0.3); Bunny->setFriction(0.3, 0.5);//Give the Bunny some friction on the surface Bunny->setShapeColor(205.0/255.0,133.0/255.0,63.0/255.0);//Set a brown color for the bunny DisplayObject->tell(Bunny);//Tell Quickhaptics about the bunny TriMesh* WheelLowRes = new TriMesh("Models/wheel-lo.obj");//Load the low resolution Wheel model WheelLowRes->setName("WheelLowRes");//give it a name WheelLowRes->setScale(1/12.0);//This model is too big compared to the bunnt model.. So we have to scale it down WheelLowRes->setStiffness(1.0); WheelLowRes->setFriction(0.5,0.3);//Give the Wheel some friction on the surface WheelLowRes->setShapeColor(0.65,0.65,0.65);//Give the Wheel a green color DisplayObject->tell(WheelLowRes);//Tell Quickhaptics about the low resolution Wheel TriMesh* WheelHighRes = new TriMesh("Models/wheel-hi.obj");//Load the High resolution Wheel model WheelHighRes->setName("WheelHighRes");//give it a name WheelHighRes->setScale(1/12.0);//Scale the Wheel model WheelHighRes->setStiffness(1.0); WheelHighRes->setFriction(0.5,0.3);//Give the Wheel some friction on the surface WheelHighRes->setRenderModeDepth();//Set the rendering mode to Depth Buffer. This is because the High resolution mode contains more than 65536 vertices WheelHighRes->setShapeColor(0.65,0.65,0.65);//Set the color of the shape to green DisplayObject->tell(WheelHighRes);//Tell Quickhaptics about the WheelHighRes Text* RenderModeMsg = new Text(30, "Render Mode: Feedback Buffer", 0.0, 0.95);//Set the message to be displayed on screen, with it's position in //normalised coordinates. (0,0) is the lower left corner of the screen and (1,1) is the upper right corner. RenderModeMsg->setShapeColor(0.0,0.0,0.0);//Set the color as black. RenderModeMsg->setName("RenderModemessage");//Give the message a name DisplayObject->tell(RenderModeMsg);//Tell QuickHaptics about the text message Text* ModelStatMsg = new Text(24, "Stanford Bunny: 35,947 vertices",0.0, 0.875);//Create a text message and position it. ModelStatMsg->setShapeColor(0.0,0.0,0.0);//Set the color as black. ModelStatMsg->setName("ModelStatMessage");//Give the message a name DisplayObject->tell(ModelStatMsg);//Tell QuickHaptics about the text message Text* InstMsg = new Text(24, "Right click on screen to bring up the menu",0.0, 0.05); InstMsg->setShapeColor(0.0,0.0,0.0);//Set the color as black. InstMsg->setName("ModelStatMessage");//Tell QuickHaptics about the text message DisplayObject->tell(InstMsg);//Tell QuickHaptics about the text message Cursor* OmniCursor = new Cursor("Models/pencil.3DS");//Declare a new cursor OmniCursor->scaleCursor(0.002);//Scale the cursor because it is too large TriMesh* ModelTriMeshPointer = OmniCursor->getTriMeshPointer(); ModelTriMeshPointer->setTexture("Models/pencil.JPG"); DisplayObject->tell(OmniCursor);//tell QuickHaptics about the cursor //Make the The Hight and Low Res Wheels both haptically and graphically invisible ///////////////////////////////////////////////////////////////////////////////// WheelLowRes->setHapticVisibility(false); WheelLowRes->setGraphicVisibility(false); WheelHighRes->setHapticVisibility(false); WheelHighRes->setGraphicVisibility(false); ///////////////////////////////////////////////////////////////////////////////// //Create the GLUT menu glutCreateMenu(glutMenuFunction); //Add entries glutAddMenuEntry("Stanford Bunny - Feedback Buffer", 0); glutAddMenuEntry("Stanford Bunny - Depth Buffer", 1); glutAddMenuEntry("Wheel Low Resolution - Feedback Buffer", 2); glutAddMenuEntry("Wheel Low Resolution - Depth Buffer", 3); glutAddMenuEntry("Wheel High Resolution - Depth Buffer", 4); //Attach the menu to the right mouse button glutAttachMenu(GLUT_RIGHT_BUTTON); qhStart();//Set everything in motion return 0; } void glutMenuFunction(int MenuID) { static TriMesh* BunnyPointer = TriMesh::searchTriMesh("Bunny");//Search for a Pointer to the model static TriMesh* WheelLowRes = TriMesh::searchTriMesh("WheelLowRes");//Search for a Pointer to the model static TriMesh* WheelHighRes = TriMesh::searchTriMesh("WheelHighRes");//Search for a Pointer to the model static Text* RenderModeMsgPointer = Text::searchText("RenderModemessage");//Search for a Pointer to the Text static Text* ModelStatMsgPointer = Text::searchText("ModelStatMessage");//Search for a Pointer to the Text if(!(BunnyPointer && WheelLowRes && WheelHighRes && RenderModeMsgPointer && ModelStatMsgPointer))//If any of the models cannot be found then return return; ////////////////////////// ////////////////////////// if(MenuID == 0)//If the Bunny is clicked on { BunnyPointer->setHapticVisibility(true);//Make the Bunny Haptically visible BunnyPointer->setGraphicVisibility(true);//Make the Bunny Graphically visible //////////////////////////////////////////////////////////// //Make the other models graphically and haptically invisible //////////////////////////////////////////////////////////// WheelLowRes->setHapticVisibility(false); WheelLowRes->setGraphicVisibility(false); WheelHighRes->setHapticVisibility(false); WheelHighRes->setGraphicVisibility(false); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// BunnyPointer->setRenderModeFeedback(); WheelLowRes->setRenderModeFeedback(); WheelHighRes->setRenderModeDepth(); RenderModeMsgPointer->setText("Render Mode: Feedback Buffer");//For any other model change the message to feedback buffer ModelStatMsgPointer->setText("Stanford Bunny: 35,947 vertices");//Display message /////////////////////// /////////////////////// } else if(MenuID == 1)//If the low resolution Wheel is clicked on { BunnyPointer->setHapticVisibility(true);//Make the Bunny Haptically visible BunnyPointer->setGraphicVisibility(true);//Make the Bunny Graphically visible //////////////////////////////////////////////////////////// //Make the other models graphically and haptically invisible //////////////////////////////////////////////////////////// WheelLowRes->setHapticVisibility(false); WheelLowRes->setGraphicVisibility(false); WheelHighRes->setHapticVisibility(false); WheelHighRes->setGraphicVisibility(false); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// BunnyPointer->setRenderModeDepth(); WheelLowRes->setRenderModeDepth(); WheelHighRes->setRenderModeDepth(); RenderModeMsgPointer->setText("Render Mode: Depth Buffer"); ModelStatMsgPointer->setText("Stanford Bunny: 35,947 vertices");//Display message /////////////////////// /////////////////////// } else if(MenuID == 2)//If the high resolution Wheel is clicked on { WheelLowRes->setHapticVisibility(true);//Make the Low Res Wheel Haptically visible WheelLowRes->setGraphicVisibility(true);//Make the Low Res Wheel Graphically visible //////////////////////////////////////////////////////////// //Make the other models graphically and haptically invisible //////////////////////////////////////////////////////////// BunnyPointer->setHapticVisibility(false); BunnyPointer->setGraphicVisibility(false); WheelHighRes->setHapticVisibility(false); WheelHighRes->setGraphicVisibility(false); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// BunnyPointer->setRenderModeFeedback(); WheelLowRes->setRenderModeFeedback(); WheelHighRes->setRenderModeDepth(); RenderModeMsgPointer->setText("Render Mode: Feedback Buffer"); ModelStatMsgPointer->setText("Wheel - Low Resolution: 49,989 vertices"); } else if(MenuID == 3) { WheelLowRes->setHapticVisibility(true);//Make the Low Res Wheel Haptically visible; WheelLowRes->setGraphicVisibility(true);//Make the Low Res Wheel Graphically visible //////////////////////////////////////////////////////////// //Make the other models graphically and haptically invisible //////////////////////////////////////////////////////////// BunnyPointer->setHapticVisibility(false); BunnyPointer->setGraphicVisibility(false); WheelHighRes->setHapticVisibility(false); WheelHighRes->setGraphicVisibility(false); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// BunnyPointer->setRenderModeDepth(); WheelLowRes->setRenderModeDepth(); WheelHighRes->setRenderModeDepth(); RenderModeMsgPointer->setText("Render Mode: Depth Buffer"); ModelStatMsgPointer->setText("Wheel - Low Resolution: 49,989 vertices"); } else if(MenuID == 4) { WheelHighRes->setHapticVisibility(true);//Make the High Res Wheel Haptically visible; WheelHighRes->setGraphicVisibility(true);//Make the High Res Wheel Graphically visible; //////////////////////////////////////////////////////////// //Make the other models graphically and haptically invisible //////////////////////////////////////////////////////////// BunnyPointer->setHapticVisibility(false); BunnyPointer->setGraphicVisibility(false); WheelLowRes->setHapticVisibility(false); WheelLowRes->setGraphicVisibility(false); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// BunnyPointer->setRenderModeDepth(); WheelLowRes->setRenderModeDepth(); WheelHighRes->setRenderModeDepth(); RenderModeMsgPointer->setText("Render Mode: Depth Buffer"); ModelStatMsgPointer->setText("Wheel - High Resolution: 147,489 vertices"); } }
43.227642
152
0.639552
Stalpaard
e2149b5c91c3ba0cb374d5e5506b3b243b969ff1
1,709
hpp
C++
src/core/Math.hpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
1
2021-11-12T08:42:43.000Z
2021-11-12T08:42:43.000Z
src/core/Math.hpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
null
null
null
src/core/Math.hpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include "math.h" namespace lucent { constexpr float kPi = 3.14159265358979323846; constexpr float k2Pi = kPi * 2.0f; constexpr float kHalfPi = kPi / 2.0f; // Math wrapper functions: inline float Sqrt(float x) { return std::sqrt(x); } inline float Sin(float radians) { return std::sin(radians); } inline float Asin(float x) { return std::asin(x); } inline float Cos(float radians) { return std::cos(radians); } inline float Acos(float x) { return std::acos(x); } inline float Tan(float radians) { return std::tan(radians); } inline float Atan(float x) { return std::atan(x); } inline float Atan2(float x, float y) { return std::atan2(x, y); } inline float Clamp(float value, float min, float max) { return value > min ? (value < max ? value : max) : min; } inline float Ceil(float value) { return std::ceil(value); } inline float Floor(float value) { return std::floor(value); } inline float Round(float value) { return Floor(value + 0.5f); } inline float Mod(float value, float by) { return std::fmod(value, by); } inline float Exp(float value) { return std::exp(value); } inline float Pow(float base, float exp) { return std::powf(base, exp); } inline float Abs(float x) { return std::abs(x); } inline float CopySign(float value, float sign) { return std::copysign(value, sign); } inline bool Approximately(float x, float y, float epsilon = FLT_EPSILON) { return Abs(x - y) <= epsilon; } inline float Log2(float x) { return std::log2(x); } template<typename T> T Min(T a, T b) { return a < b ? a : b; } template<typename T> T Max(T a, T b) { return a < b ? b : a; } }
14.008197
72
0.647162
bferan
e216b026375f1dfdaeeb490f3eeb344d5e13abb4
1,052
cpp
C++
control/examples/pegel/main.cpp
devfix/b15f
5a49a37e69cca99359a98e1ef29a83043afed5e5
[ "MIT" ]
1
2019-10-26T18:37:49.000Z
2019-10-26T18:37:49.000Z
control/examples/pegel/main.cpp
devfix/b15f
5a49a37e69cca99359a98e1ef29a83043afed5e5
[ "MIT" ]
null
null
null
control/examples/pegel/main.cpp
devfix/b15f
5a49a37e69cca99359a98e1ef29a83043afed5e5
[ "MIT" ]
1
2022-03-26T16:06:23.000Z
2022-03-26T16:06:23.000Z
#include <iostream> #include <cmath> #include <b15f/b15f.h> #include <b15f/plottyfile.h> /* * Inkrementiert DAC 0 von 0 bis 1023 und speichert zu jeder Ausgabe den Wert von ADC 0 in einem Puffer. * Die Funktion ADC 0 abhängig von DAC 0 wird als Graph geplottet. */ const char PLOT_FILE[] = "plot.bin"; int main() { B15F& drv = B15F::getInstance(); PlottyFile pf; uint16_t buf[1024]; const uint16_t count = 1024; const uint16_t delta = 1; const uint16_t start = 0; pf.setUnitX("V"); pf.setUnitY("V"); pf.setUnitPara("V"); pf.setDescX("U_{OUT}"); pf.setDescY("U_{IN}"); pf.setDescPara(""); pf.setRefX(5); pf.setRefY(5); pf.setParaFirstCurve(0); pf.setParaStepWidth(0); const uint8_t curve = 0; drv.analogSequence(0, &buf[0], 0, 1, nullptr, 0, start, delta, count); for(uint16_t x = 0; x < count; x++) { std::cout << x << " - " << buf[x] << std::endl; pf.addDot(Dot(x, buf[x], curve)); } // speichern und plotty starten pf.writeToFile(PLOT_FILE); pf.startPlotty(PLOT_FILE); }
21.04
104
0.635932
devfix
e21babaa579368d6960e67e4357583b0514be73d
17,289
cpp
C++
engine/hltvclient.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
cstrike15_src/engine/hltvclient.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
cstrike15_src/engine/hltvclient.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
//===== Copyright (c) Valve Corporation, All rights reserved. ======// // // hltvclient.cpp: implementation of the CHLTVClient class. // // $NoKeywords: $ // //==================================================================// #include <tier0/vprof.h> #include "hltvclient.h" #include "netmessages.h" #include "hltvserver.h" #include "framesnapshot.h" #include "networkstringtable.h" #include "dt_send_eng.h" #include "GameEventManager.h" #include "cmd.h" #include "ihltvdirector.h" #include "host.h" #include "sv_steamauth.h" #include "fmtstr.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" static ConVar tv_maxrate( "tv_maxrate", STRINGIFY( DEFAULT_RATE ), FCVAR_RELEASE, "Max GOTV spectator bandwidth rate allowed, 0 == unlimited" ); static ConVar tv_relaypassword( "tv_relaypassword", "", FCVAR_NOTIFY | FCVAR_PROTECTED | FCVAR_DONTRECORD | FCVAR_RELEASE, "GOTV password for relay proxies" ); static ConVar tv_chattimelimit( "tv_chattimelimit", "8", FCVAR_RELEASE, "Limits spectators to chat only every n seconds" ); static ConVar tv_chatgroupsize( "tv_chatgroupsize", "0", FCVAR_RELEASE, "Set the default chat group size" ); extern ConVar replay_debug; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CHLTVClient::CHLTVClient(int slot, CBaseServer *pServer) { Clear(); m_nClientSlot = slot; m_Server = pServer; m_pHLTV = dynamic_cast<CHLTVServer*>(pServer); Assert( g_pHltvServer[ m_pHLTV->GetInstanceIndex() ] == pServer ); m_nEntityIndex = slot < 0 ? slot : m_pHLTV->GetHLTVSlot() + 1; m_nLastSendTick = 0; m_fLastSendTime = 0.0f; m_flLastChatTime = 0.0f; m_bNoChat = false; if ( tv_chatgroupsize.GetInt() > 0 ) { Q_snprintf( m_szChatGroup, sizeof(m_szChatGroup), "group%d", slot%tv_chatgroupsize.GetInt() ); } else { Q_strncpy( m_szChatGroup, "all", sizeof(m_szChatGroup) ); } } CHLTVClient::~CHLTVClient() { } bool CHLTVClient::SendSignonData( void ) { // check class table CRCs if ( m_nSendtableCRC != SendTable_GetCRC() ) { Disconnect( "Server uses different class tables" ); return false; } else { // use your class infos, CRC is correct CSVCMsg_ClassInfo_t classmsg; classmsg.set_create_on_client( true ); m_NetChannel->SendNetMsg( classmsg ); } return CBaseClient::SendSignonData(); } bool CHLTVClient::ProcessSignonStateMsg(int state, int spawncount) { if ( !CBaseClient::ProcessSignonStateMsg( state, spawncount ) ) return false; if ( state == SIGNONSTATE_FULL ) { // Send all the delayed avatar data to the fully connected client if ( INetChannel *pMyNetChannel = GetNetChannel() ) { FOR_EACH_MAP_FAST( m_pHLTV->m_mapPlayerAvatarData, iData ) { pMyNetChannel->EnqueueVeryLargeAsyncTransfer( *m_pHLTV->m_mapPlayerAvatarData.Element( iData ) ); } } } return true; } bool CHLTVClient::CLCMsg_ClientInfo( const CCLCMsg_ClientInfo& msg ) { if ( !CBaseClient::CLCMsg_ClientInfo( msg ) ) return false; return true; } bool CHLTVClient::CLCMsg_Move( const CCLCMsg_Move& msg ) { // HLTV clients can't move return true; } bool CHLTVClient::CLCMsg_ListenEvents( const CCLCMsg_ListenEvents& msg ) { // HLTV clients can't subscribe to events, we just send them return true; } bool CHLTVClient::CLCMsg_RespondCvarValue( const CCLCMsg_RespondCvarValue& msg ) { return true; } bool CHLTVClient::CLCMsg_FileCRCCheck( const CCLCMsg_FileCRCCheck& msg ) { return true; } bool CHLTVClient::CLCMsg_VoiceData(const CCLCMsg_VoiceData& msg) { // HLTV clients can't speak return true; } void CHLTVClient::ConnectionClosing(const char *reason) { Disconnect ( (reason!=NULL)?reason:"Connection closing" ); } void CHLTVClient::ConnectionCrashed(const char *reason) { Disconnect ( (reason!=NULL)?reason:"Connection lost" ); } void CHLTVClient::PacketStart(int incoming_sequence, int outgoing_acknowledged) { // During connection, only respond if client sends a packet m_bReceivedPacket = true; } void CHLTVClient::PacketEnd() { } void CHLTVClient::FileRequested(const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ ) { DevMsg( "CHLTVClient::FileRequested: %s.\n", fileName ); m_NetChannel->DenyFile( fileName, transferID, bIsReplayDemoFile ); } void CHLTVClient::FileDenied(const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ ) { DevMsg( "CHLTVClient::FileDenied: %s.\n", fileName ); } void CHLTVClient::FileReceived( const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ ) { DevMsg( "CHLTVClient::FileReceived: %s.\n", fileName ); } void CHLTVClient::FileSent( const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ ) { DevMsg( "CHLTVClient::FileSent: %s.\n", fileName ); } CClientFrame *CHLTVClient::GetDeltaFrame( int nTick ) { return m_pHLTV->GetDeltaFrame( nTick ); } bool CHLTVClient::ExecuteStringCommand( const char *pCommandString ) { // first let the baseclass handle it if ( CBaseClient::ExecuteStringCommand( pCommandString ) ) return true; if ( !pCommandString || !pCommandString[0] ) return true; CCommand args; if ( !args.Tokenize( pCommandString, kCommandSrcNetServer ) ) return true; const char *cmd = args[ 0 ]; if ( !Q_stricmp( cmd, "spec_next" ) || !Q_stricmp( cmd, "spec_prev" ) || !Q_stricmp( cmd, "spec_mode" ) || !Q_stricmp( cmd, "spec_goto" ) || !Q_stricmp( cmd, "spec_lerpto" ) ) { ClientPrintf("Camera settings can't be changed during a live broadcast.\n"); return true; } if ( !Q_stricmp( cmd, "say" ) && args.ArgC() > 1 ) { // if tv_chattimelimit = 0, chat is turned off if ( tv_chattimelimit.GetFloat() <= 0 ) return true; if ( (m_flLastChatTime + tv_chattimelimit.GetFloat()) > net_time ) return true; m_flLastChatTime = net_time; // Check if chat is non-empty string bool bValidText = false; for ( char const *szChatMsg = args[1]; szChatMsg && *szChatMsg; ++ szChatMsg ) { if ( !V_isspace( *szChatMsg ) ) { bValidText = true; break; } } if ( !bValidText ) return true; char chattext[128]; V_sprintf_safe( chattext, "%s : %s", GetClientName(), args[1] ); m_pHLTV->BroadcastLocalChat( chattext, m_szChatGroup ); return true; } else if ( !Q_strcmp( cmd, "tv_chatgroup" ) ) { if ( args.ArgC() > 1 ) { Q_strncpy( m_szChatGroup, args[1], sizeof(m_szChatGroup) ); } else { ClientPrintf("Your current chat group is \"%s\"\n", m_szChatGroup ); } return true; } else if ( !Q_strcmp( cmd, "status" ) ) { int slots, proxies, clients; char gd[MAX_OSPATH]; Q_FileBase( com_gamedir, gd, sizeof( gd ) ); if ( m_pHLTV->IsMasterProxy() ) { ClientPrintf("GOTV Master \"%s\", delay %.0f\n", m_pHLTV->GetName(), m_pHLTV->GetDirector()->GetDelay() ); } else // if ( m_Server->IsRelayProxy() ) { if ( m_pHLTV->GetRelayAddress() ) { ClientPrintf("GOTV Relay \"%s\", connected.\n", m_pHLTV->GetName() ); } else { ClientPrintf("GOTV Relay \"%s\", not connect.\n", m_pHLTV->GetName() ); } } ClientPrintf("IP %s:%i, Online %s, Version %i (%s)\n", net_local_adr.ToString( true ), m_pHLTV->GetUDPPort(), COM_FormatSeconds( m_pHLTV->GetOnlineTime() ), build_number(), #ifdef _WIN32 "Win32" ); #else "Linux" ); #endif ClientPrintf("Game Time %s, Mod \"%s\", Map \"%s\", Players %i\n", COM_FormatSeconds( m_pHLTV->GetTime() ), gd, m_pHLTV->GetMapName(), m_pHLTV->GetNumPlayers() ); m_pHLTV->GetLocalStats( proxies, slots, clients ); ClientPrintf("Local Slots %i, Spectators %i, Proxies %i\n", slots, clients-proxies, proxies ); m_pHLTV->GetGlobalStats( proxies, slots, clients); ClientPrintf("Total Slots %i, Spectators %i, Proxies %i\n", slots, clients-proxies, proxies); m_pHLTV->GetExternalStats( slots, clients ); if ( slots > 0 ) { if ( clients > 0 ) ClientPrintf( "Streaming spectators %i, linked to Steam %i\n", slots, clients ); else ClientPrintf( "Streaming spectators %i\n", slots ); } } else { DevMsg( "CHLTVClient::ExecuteStringCommand: Unknown command %s.\n", pCommandString ); } return true; } bool CHLTVClient::ShouldSendMessages( void ) { if ( !IsActive() ) { // during signon behave like normal client return CBaseClient::ShouldSendMessages(); } // HLTV clients use snapshot rate used by HLTV server, not given by HLTV client // if the reliable message overflowed, drop the client if ( m_NetChannel->IsOverflowed() ) { m_NetChannel->Reset(); Disconnect( CFmtStr( "%s overflowed reliable buffer", m_Name ) ); return false; } // send a packet if server has a new tick we didn't already send bool bSendMessage = ( m_nLastSendTick != m_Server->m_nTickCount ); // send a packet at least every 2 seconds if ( !bSendMessage && (m_fLastSendTime + 2.0f) < net_time ) { bSendMessage = true; // force sending a message even if server didn't update } if ( bSendMessage && !m_NetChannel->CanPacket() ) { // we would like to send a message, but bandwidth isn't available yet // in HLTV we don't send choke information, doesn't matter bSendMessage = false; } return bSendMessage; } void CHLTVClient::SpawnPlayer( void ) { // set view entity CSVCMsg_SetView_t setView; setView.set_entity_index( m_pHLTV->m_nViewEntity ); SendNetMsg( setView ); m_pHLTV->BroadcastLocalTitle( this ); m_flLastChatTime = net_time; CBaseClient::SpawnPlayer(); } void CHLTVClient::SetRate(int nRate, bool bForce ) { if ( !bForce ) { if ( m_bIsHLTV ) { // allow higher bandwidth rates for HLTV proxies nRate = clamp( nRate, MIN_RATE, MAX_RATE ); } else if ( tv_maxrate.GetInt() > 0 ) { // restrict rate for normal clients to hltv_maxrate nRate = clamp( nRate, MIN_RATE, tv_maxrate.GetInt() ); } } CBaseClient::SetRate( nRate, bForce ); } void CHLTVClient::SetUpdateRate( float fUpdateRate, bool bForce) { // for HLTV clients ignore update rate settings, speed is tv_snapshotrate m_fSnapshotInterval = 1.0f / m_pHLTV->GetSnapshotRate(); } bool CHLTVClient::NETMsg_SetConVar(const CNETMsg_SetConVar& msg) { if ( !CBaseClient::NETMsg_SetConVar( msg ) ) return false; // if this is the first time we get user settings, check password etc if ( GetSignonState() == SIGNONSTATE_CONNECTED ) { // Note: the master client of HLTV server will replace the rate ConVars for us. It's necessary so that demo recorder can take those frames from the master client and write them with values already modified m_bIsHLTV = m_ConVars->GetInt( "tv_relay", 0 ) != 0; if ( m_bIsHLTV ) { // The connecting client is a TV relay // Check if this relay address is whitelisted by IP range mask and bypasses all checks extern bool IsHltvRelayProxyWhitelisted( ns_address const &adr ); if ( IsHltvRelayProxyWhitelisted( m_NetChannel->GetRemoteAddress() ) ) { Msg( "Accepted GOTV relay proxy from whitelisted IP address: %s\n", m_NetChannel->GetAddress() ); } // if the connecting client is a TV relay, check the password else if ( !m_pHLTV->CheckHltvPasswordMatch( m_szPassword, m_pHLTV->GetHltvRelayPassword(), CSteamID() ) ) { Disconnect("Bad relay password"); return false; } } else { // if client is a normal spectator, check if we can to forward him to other relays if ( m_pHLTV->DispatchToRelay( this ) ) { return false; } // if we are not dispatching the client to other relay and we are the master server then validate // the number of non-proxy clients extern ConVar tv_maxclients_relayreserved; if ( tv_maxclients_relayreserved.GetInt() ) { int numActualNonProxyAccounts = 0; for (int i=0; i < m_pHLTV->GetClientCount(); i++ ) { CBaseClient *pProxy = static_cast< CBaseClient * >( m_pHLTV->GetClient( i ) ); // check if this is a proxy if ( !pProxy->IsConnected() || pProxy->IsHLTV() || (this == pProxy) ) continue; ++ numActualNonProxyAccounts; } if ( numActualNonProxyAccounts > m_pHLTV->GetMaxClients() - tv_maxclients_relayreserved.GetInt() ) { this->Disconnect( "No GOTV relays available" ); return false; } } // if client stays here, check the normal password // additionally if the first variable is client accountid then use that to validate personalized password CSteamID steamUserAccountID; if ( Steam3Server().SteamGameServerUtils() && ( msg.convars().cvars_size() > 1 ) && !Q_strcmp( NetMsgGetCVarUsingDictionary( msg.convars().cvars( 0 ) ), "accountid" ) ) steamUserAccountID = CSteamID( Q_atoi( msg.convars().cvars( 0 ).value().c_str() ), Steam3Server().SteamGameServerUtils()->GetConnectedUniverse(), k_EAccountTypeIndividual ); if ( !m_pHLTV->CheckHltvPasswordMatch( m_szPassword, m_pHLTV->GetPassword(), steamUserAccountID ) ) { Disconnect("Bad spectator password"); return false; } // check if server is LAN only if ( !m_pHLTV->CheckIPRestrictions( m_NetChannel->GetRemoteAddress(), PROTOCOL_HASHEDCDKEY ) ) { Disconnect( "GOTV server is restricted to local spectators (class C).\n" ); return false; } } } return true; } void CHLTVClient::UpdateUserSettings() { // set voice loopback m_bNoChat = m_ConVars->GetInt( "tv_nochat", 0 ) != 0; CBaseClient::UpdateUserSettings(); } bool CHLTVClient::SendSnapshot( CClientFrame * pFrame ) { VPROF_BUDGET( "CHLTVClient::SendSnapshot", "HLTV" ); byte buf[NET_MAX_PAYLOAD]; bf_write msg( "CHLTVClient::SendSnapshot", buf, sizeof(buf) ); // if we send a full snapshot (no delta-compression) before, wait until client // received and acknowledge that update. don't spam client with full updates if ( m_pLastSnapshot == pFrame->GetSnapshot() ) { // never send the same snapshot twice m_NetChannel->Transmit(); return false; } if ( m_nForceWaitForTick > 0 ) { // just continue transmitting reliable data Assert( !m_bFakePlayer ); // Should never happen m_NetChannel->Transmit(); return false; } CClientFrame *pDeltaFrame = GetDeltaFrame( m_nDeltaTick ); // NULL if delta_tick is not found CHLTVFrame *pLastFrame = (CHLTVFrame*) GetDeltaFrame( m_nLastSendTick ); if ( pLastFrame ) { // start first frame after last send pLastFrame = (CHLTVFrame*) pLastFrame->m_pNext; } // add all reliable messages between ]lastframe,currentframe] // add all tempent & sound messages between ]lastframe,currentframe] while ( pLastFrame && pLastFrame->tick_count <= pFrame->tick_count ) { m_NetChannel->SendData( pLastFrame->m_Messages[HLTV_BUFFER_RELIABLE], true ); if ( pDeltaFrame ) { // if we send entities delta compressed, also send unreliable data m_NetChannel->SendData( pLastFrame->m_Messages[HLTV_BUFFER_UNRELIABLE], false ); m_NetChannel->SendData( pLastFrame->m_Messages[ HLTV_BUFFER_VOICE ], false ); // we separate voice, even though it's simply more unreliable data, because we don't send it in replay } pLastFrame = (CHLTVFrame*) pLastFrame->m_pNext; } // now create client snapshot packet // send tick time CNETMsg_Tick_t tickmsg( pFrame->tick_count, host_frameendtime_computationduration, host_frametime_stddeviation, host_framestarttime_stddeviation ); tickmsg.WriteToBuffer( msg ); // Update shared client/server string tables. Must be done before sending entities m_Server->m_StringTables->WriteUpdateMessage( NULL, GetMaxAckTickCount(), msg ); // TODO delta cache whole snapshots, not just packet entities. then use net_Align // send entity update, delta compressed if deltaFrame != NULL { CSVCMsg_PacketEntities_t packetmsg; m_Server->WriteDeltaEntities( this, pFrame, pDeltaFrame, packetmsg ); packetmsg.WriteToBuffer( msg ); } // write message to packet and check for overflow if ( msg.IsOverflowed() ) { if ( !pDeltaFrame ) { // if this is a reliable snapshot, drop the client Disconnect( "ERROR! Reliable snapshot overflow." ); return false; } else { // unreliable snapshots may be dropped ConMsg ("WARNING: msg overflowed for %s\n", m_Name); msg.Reset(); } } // remember this snapshot m_pLastSnapshot = pFrame->GetSnapshot(); m_nLastSendTick = pFrame->tick_count; // Don't send the datagram to fakeplayers if ( m_bFakePlayer ) { m_nDeltaTick = pFrame->tick_count; return true; } bool bSendOK; // is this is a full entity update (no delta) ? if ( !pDeltaFrame ) { if ( replay_debug.GetInt() >= 10 ) Msg( "HLTV send full frame %d bytes\n", ( msg.m_iCurBit + 7 ) / 8 ); // transmit snapshot as reliable data chunk bSendOK = m_NetChannel->SendData( msg ); bSendOK = bSendOK && m_NetChannel->Transmit(); // remember this tickcount we send the reliable snapshot // so we can continue sending other updates if this has been acknowledged m_nForceWaitForTick = pFrame->tick_count; } else { if ( replay_debug.GetInt() >= 10 ) Msg( "HLTV send datagram %d bytes\n", ( msg.m_iCurBit + 7 ) / 8 ); // just send it as unreliable snapshot bSendOK = m_NetChannel->SendDatagram( &msg ) > 0; } if ( !bSendOK ) { Disconnect( "ERROR! Couldn't send snapshot." ); return false; } return true; }
28.066558
208
0.692116
DannyParker0001
e21c6fa48127900170983abd4d0f273513c10bf7
44,201
cpp
C++
deprecated-code/Ajisai/Integrators/BidirectionalPath.cpp
siyuanpan/ajisai_render
203d79235bf698c1a4a747be291c0f3050b213da
[ "MIT" ]
null
null
null
deprecated-code/Ajisai/Integrators/BidirectionalPath.cpp
siyuanpan/ajisai_render
203d79235bf698c1a4a747be291c0f3050b213da
[ "MIT" ]
null
null
null
deprecated-code/Ajisai/Integrators/BidirectionalPath.cpp
siyuanpan/ajisai_render
203d79235bf698c1a4a747be291c0f3050b213da
[ "MIT" ]
null
null
null
/* Copyright 2021 Siyuan Pan <[email protected]> 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 <Ajisai/Core/BSDF.h> #include <Ajisai/Core/Geometry.h> #include <Ajisai/Integrators/Integrator.h> #include <Ajisai/Integrators/BidirectionalPath.h> #include <cstring> // using Ajisai::Core::CameraSamplingRecord; // using Ajisai::Core::Intersect; // using Ajisai::Core::LightSamplingRecord; // using Ajisai::Core::SurfaceInteraction; // using Ajisai::Core::VisibilityTester; using namespace Ajisai::Math; using namespace Ajisai::Core; namespace Ajisai::Integrators { // template <typename T> // class ScopedAssignment { // T* target = nullptr; // T backup; // public: // ScopedAssignment() : target(nullptr), backup(T()) {} // ScopedAssignment(T* target, T value) : target(target) { // if (target) { // backup = *target; // *target = value; // } // } // ~ScopedAssignment() { // if (target) *target = backup; // } // ScopedAssignment(ScopedAssignment&&) = delete; // ScopedAssignment(const ScopedAssignment&) = delete; // ScopedAssignment& operator=(const ScopedAssignment&) = delete; // ScopedAssignment& operator=(ScopedAssignment&& other) noexcept { // if (target) *target = backup; // target = other.target; // backup = other.backup; // other.target = nullptr; // return *this; // } // }; // struct EndpointInteraction : Intersect { // using Intersect::Intersect; // // Math::Vector3f p; // union { // const Core::Camera* camera; // const Core::AreaLight* light; // }; // EndpointInteraction() : light{nullptr} {} // EndpointInteraction(const Core::Ray& ray) // : Intersect(ray.Point(1)), light(nullptr) {} // EndpointInteraction(const Core::Camera* camera, const Core::Ray& ray) // : Intersect(ray.o), camera(camera) {} // EndpointInteraction(const Core::AreaLight* light, const Core::Ray& ray) // : Intersect(ray.o), light(light) {} // // EndpointInteraction(const Core::Camera* camera, const Math::Vector3f& p) // // : Intersect(p), camera(camera) {} // EndpointInteraction(const Core::AreaLight* light, const Core::Ray& r, // const Math::Vector3f& nl) // : Intersect(r.o), light(light) { // Ng = nl; // } // }; // enum class VertexType { Camera, Light, Surface }; // enum class TransportMode { Radiance, Importance }; // struct PathVertex { // VertexType type; // Math::Spectrum beta; // union { // EndpointInteraction ei; // SurfaceInteraction si; // }; // bool delta = false; // float pdfFwd = 0, pdfRev = 0; // PathVertex() : ei() {} // PathVertex(VertexType type, const EndpointInteraction& ei, // const Math::Spectrum& beta) // : type(type), beta(beta), ei(ei) {} // PathVertex(const SurfaceInteraction& si, const Math::Spectrum& beta) // : type(VertexType::Surface), beta(beta), si(si) {} // ~PathVertex() {} // PathVertex(const PathVertex& v) { memcpy(this, &v, sizeof(PathVertex)); } // PathVertex& operator=(const PathVertex& v) { // memcpy(this, &v, sizeof(PathVertex)); // return *this; // } // const Intersect& GetInteraction() const { // switch (type) { // case VertexType::Surface: // return si; // default: // return ei; // } // } // const auto& p() const { return GetInteraction().p; } // const auto& ng() const { return GetInteraction().Ng; } // [[nodiscard]] Math::Vector3f Ns() const { // if (type == VertexType::Surface) { // return si.Ns; // } else if (type == VertexType::Light || type == VertexType::Camera) { // return ei.Ng; // } else { // return {}; // } // } // bool IsOnSurface() const { return ng() != Math::Vector3f{0.f}; } // bool IsConnectible() const { // switch (type) { // case VertexType::Light: // return true; // case VertexType::Camera: // return true; // case VertexType::Surface: // return !delta; // } // return false; // NOTREACHED // } // float PdfLightOrigin(const Core::Scene& scene, const PathVertex& next) { // const Core::AreaLight* light = ei.light; // if (!light) { // return 0.0f; // } // auto w = next.p() - p(); // w = w.normalized(); // float pdfPos = 0, pdfDir = 0; // light->Pdf_Le(Core::Ray(p(), w), &pdfPos, &pdfDir); // return scene.PdfLight(light) * pdfPos; // } // Math::Spectrum Le(const PathVertex& next) const { // switch (type) { // case VertexType::Surface: { // auto wo = (next.p() - p()).normalized(); // return si.Le(wo); // } // case VertexType::Light: { // auto* light = ei.light; // auto wo = (next.p() - p()).normalized(); // return light->Li(wo); // } // case VertexType::Camera: // default: // return Math::Spectrum{0.f}; // } // } // float Pdf(const Core::Scene& scene, const PathVertex* prev, // const PathVertex& next) { // if (type == VertexType::Light) { // return PdfLight(scene, next); // } // auto wn = next.p() - p(); // if (Math::dot(wn, wn) == 0) return 0; // wn = wn.normalized(); // Math::Vector3f wp; // if (prev) { // wp = prev->p() - p(); // if (Math::dot(wp, wp) == 0) return 0; // wp = wp.normalized(); // } else { // assert(type == VertexType::Camera); // } // float pdf = 0; // if (type == VertexType::Surface) { // auto wo = si.bsdf->toLocal(-wp); // auto wi = si.bsdf->toLocal(wn); // pdf = si.bsdf->EvaluatePdf(wo, wi); // } else if (type == VertexType::Camera) { // auto* camera = ei.camera; // float _; // camera->Pdf_We(ei.SpawnRay(wn), &_, &pdf); // } else { // std::exit(1); // } // return ConvertDensity(pdf, next); // } // float PdfLight(const Core::Scene& scene, const PathVertex& next) { // const Core::AreaLight* light = ei.light; // if (!light) { // return 0; // } // auto w = next.p() - p(); // float invDist2 = 1 / Math::dot(w, w); // w = w.normalized(); // float pdf; // float pdfPos = 0, pdfDir = 0; // light->Pdf_Le(Core::Ray(p(), w), &pdfPos, &pdfDir); // pdf = pdfDir * invDist2; // if (next.IsOnSurface()) { // pdf *= std::abs(Math::dot(next.ng(), w)); // } // return pdf; // } // Math::Spectrum f(const PathVertex& next) const { // auto wi = (next.p() - p()).normalized(); // switch (type) { // case VertexType::Surface: { // return si.bsdf->Evaluate(si.wo, wi); // } // default: // return {}; // } // } // float ConvertDensity(float pdf, const PathVertex& next) const { // // Return solid angle density if _next_ is an infinite area light // // if (next.IsInfiniteLight()) return pdf; // auto w = next.p() - p(); // if (Math::dot(w, w) == 0) return 0; // float invDist2 = 1 / Math::dot(w, w); // w = w.normalized(); // if (next.IsOnSurface()) pdf *= std::abs(Math::dot(next.ng(), w)); // // pdf *= std::abs(Math::dot(next.ng(), w * std::sqrt(invDist2))); // return pdf * invDist2; // } // static inline PathVertex CreateCamera(const Core::Camera* camera, // const Core::Ray& ray, // const Math::Spectrum& beta); // static inline PathVertex CreateLight(const EndpointInteraction& ei, // const Math::Spectrum& beta, float // pdf); // static inline PathVertex CreateSurface(const SurfaceInteraction& si, // const Math::Spectrum& beta, float // pdf, const PathVertex& prev); // static inline PathVertex CreateLight(const Core::AreaLight* light, // const Core::Ray& ray, // const Math::Vector3f& N, // const Math::Spectrum& Le, float pdf); // static inline PathVertex CreateCamera(const Core::Camera* camera, // const Math::Vector3f& p, // const Math::Spectrum& beta); // static Math::Spectrum G(const Core::Scene& scene, const PathVertex& v0, // const PathVertex& v1) { // auto d = v0.p() - v1.p(); // float g = 1 / Math::dot(d, d); // // d *= std::sqrt(g); // d = d.normalized(); // if (v0.IsOnSurface()) g *= std::abs(Math::dot(v0.Ns(), d)); // if (v1.IsOnSurface()) g *= std::abs(Math::dot(v1.Ns(), d)); // VisibilityTester vis(v0.GetInteraction(), v1.GetInteraction()); // return g * vis.Tr(scene); // } // }; // inline PathVertex PathVertex::CreateCamera(const Core::Camera* camera, // const Core::Ray& ray, // const Math::Spectrum& beta) { // return PathVertex(VertexType::Camera, EndpointInteraction(camera, ray), // beta); // } // inline PathVertex PathVertex::CreateLight(const EndpointInteraction& ei, // const Math::Spectrum& beta, // float pdf) { // PathVertex v(VertexType::Light, ei, beta); // v.pdfFwd = pdf; // return v; // } // inline PathVertex PathVertex::CreateSurface(const SurfaceInteraction& si, // const Math::Spectrum& beta, // float pdf, const PathVertex& // prev) { // PathVertex v(si, beta); // v.pdfFwd = prev.ConvertDensity(pdf, v); // return v; // } // inline PathVertex PathVertex::CreateLight(const Core::AreaLight* light, // const Core::Ray& ray, // const Math::Vector3f& N, // const Math::Spectrum& Le, float // pdf) { // PathVertex v(VertexType::Light, EndpointInteraction(light, ray, N), Le); // v.pdfFwd = pdf; // return v; // } // inline PathVertex PathVertex::CreateCamera(const Core::Camera* camera, // const Math::Vector3f& p, // const Math::Spectrum& beta) { // return PathVertex(VertexType::Camera, EndpointInteraction(camera, p), // beta); // } // class BDPTIntegrator : public Integrator { // public: // explicit BDPTIntegrator(PluginManager::AbstractManager& manager, // const std::string plugin) // : Integrator{manager, plugin} {} // struct Vertex { // Spectrum throughput; // uint32_t length; // SurfaceInteraction si; // Vector3f inDir; // float DVCM; // float DVC; // }; // struct PathState { // Vector3f origin; // Vector3f direction; // Spectrum throughput; // uint PathLength : 30; // bool isFiniteLight : 1; // bool SpecularPath : 1; // float DVCM; // float DVC; // }; // size_t RandomWalk(const Core::Scene& scene, Core::Sampler& sampler, // Core::Ray& ray, Math::Spectrum& beta, float pdf, // size_t depth, TransportMode mode, PathVertex* path) const // { // using Core::BSDFSamplingRecord; // using Core::BSDFType; // if (depth == 0) return 0; // int bounces = 0; // float pdfFwd = pdf, pdfRev = 0.f; // while (true) { // Core::Intersection isect; // bool foundIntersection = scene.Intersect(ray, &isect); // if (beta.isBlack()) break; // auto& vertex = path[bounces]; // auto& prev = path[bounces - 1]; // if (!foundIntersection) { // // if (mode == TransportMode::Radiance) { // // vertex = // // PathVertex::CreateLight(EndpointInteraction(ray), beta, // // pdfFwd); // // ++bounces; // // } // break; // } // Core::Triangle triangle{}; // isect.mesh->GetTriangle(isect.triId, &triangle); // auto p = ray.Point(isect.t); // SurfaceInteraction si(-ray.d, p, triangle, isect); // isect.mesh->GetMaterial()->ComputeScatteringFunction(&si); // vertex = PathVertex::CreateSurface(si, beta, pdfFwd, prev); // if (++bounces >= depth) break; // Math::Vector3f wi, wo = si.wo; // BSDFSamplingRecord bRec(si, sampler.Next2D()); // si.bsdf->Sample(bRec); // if (bRec.pdf <= 0.f) break; // pdfFwd = bRec.pdf; // wi = si.bsdf->toWorld(bRec.wi); // beta *= bRec.f * std::abs(Math::dot(wi, si.Ns)) / bRec.pdf; // pdfRev = si.bsdf->EvaluatePdf(bRec.wi, bRec.wo); // if (bRec.type & BSDFType::BSDF_SPECULAR) { // vertex.delta = true; // pdfFwd = pdfRev = 0.f; // } // ray = si.SpawnRay(wi); // prev.pdfRev = vertex.ConvertDensity(pdfRev, prev); // } // return bounces; // } // size_t GenerateCameraSubpath(const Core::Scene& scene, // const Core::Camera& camera, // const Math::Vector2i& raster, // Core::Sampler& sampler, size_t depth, // PathVertex* path) const { // if (depth == 0) return 0; // // const float u = // // (raster.x() + sampler.Next1D()) / // camera.GetFilm()->Dimension().x(); // // const float v = // // (raster.y() + sampler.Next1D()) / // camera.GetFilm()->Dimension().y(); // // auto ray = camera.GenerateRay(u, v); // auto ray = camera.GenerateRay(sampler.Next2D(), sampler.Next2D(), // raster); auto beta = Math::Spectrum(1); // float pdfPos, pdfDir; // path[0] = PathVertex::CreateCamera(&camera, ray, beta); // camera.Pdf_We(ray, &pdfPos, &pdfDir); // if (pdfDir <= 0 || pdfPos <= 0) { // return 0; // } // return RandomWalk(scene, sampler, ray, beta, pdfDir, depth - 1, // TransportMode::Importance, path + 1) + // 1; // } // size_t GenerateLightSubpath(const Core::Scene& scene, Core::Sampler& // sampler, // size_t depth, PathVertex* path) const { // if (depth == 0) return 0; // float lightPdf = 0.f; // auto sampleLight = scene.SampleOneLight(sampler.Next1D(), &lightPdf); // Core::Ray ray; // Math::Vector3f nLight; // float pdfPos, pdfDir; // Math::Spectrum Le; // sampleLight->Sample_Le(sampler.Next2D(), sampler.Next2D(), &ray, nLight, // &pdfPos, &pdfDir, Le); // if (lightPdf <= 0 || pdfPos <= 0 || pdfDir <= 0 || Le.isBlack()) { // return 0; // } // path[0] = PathVertex::CreateLight(sampleLight, ray, nLight, Le, // pdfPos * lightPdf); // Math::Spectrum beta = // Le * std::abs(Math::dot(nLight, ray.d)) / (lightPdf * pdfPos * // pdfDir); // return 1 + RandomWalk(scene, sampler, ray, beta, pdfDir, depth - 1, // TransportMode::Radiance, path + 1); // } // template <int Power> // float MisWeight(const Core::Scene& scene, Core::Sampler& sampler, // PathVertex* cameraVertices, size_t t, // PathVertex* lightVertices, size_t s, // PathVertex& sampled) const { // if (s + t == 2) return 1; // auto remap0 = [](float x) -> float { // return x != 0 ? std::pow(x, Power) : 1.0f; // }; // (void)remap0; // float sumRi = 0; // // p_0 ... pt qs ... q_0 // auto* pt = t > 0 ? &cameraVertices[t - 1] : nullptr; // auto* qs = s > 0 ? &lightVertices[s - 1] : nullptr; // auto* ptMinus = t > 1 ? &cameraVertices[t - 2] : nullptr; // auto* qsMinus = s > 1 ? &lightVertices[s - 2] : nullptr; // ScopedAssignment<PathVertex> _a1; // if (s == 1) // _a1 = {qs, sampled}; // else if (t == 1) // _a1 = {pt, sampled}; // // if (s == 1) { // // printf("b %f\n", lightVertices[s - 1].pdfFwd); // // } // ScopedAssignment<bool> _a2, _a3; // if (pt) _a2 = {&pt->delta, false}; // if (qs) _a3 = {&qs->delta, false}; // // now connect pt to qs // // we need to compute pt->pdfRev // // segfault ? // ScopedAssignment<float> _a4; // if (pt) { // float pdfRev; // if (s > 0) { // pdfRev = qs->Pdf(scene, qsMinus, *pt); // } else { // pdfRev = pt->PdfLightOrigin(scene, *ptMinus); // } // // if (s != 0) // // printf("before rev %f s %d pdfRev %f\n", pt->pdfRev, (int)s, // pdfRev); _a4 = {&pt->pdfRev, pdfRev}; // } // // if (pt) printf("after rev %f\n", pt->pdfRev); // // now ptMinus->pdfRev // ScopedAssignment<float> _a5; // // if (ptMinus) printf("before rev %f\n", ptMinus->pdfRev); // if (ptMinus) { // float pdfRev; // if (s > 0) { // pdfRev = pt->Pdf(scene, qs, *ptMinus); // } else { // pdfRev = pt->PdfLight(scene, *ptMinus); // } // _a5 = {&ptMinus->pdfRev, pdfRev}; // } // // if (ptMinus) printf("after rev %f\n", ptMinus->pdfRev); // // now qs // ScopedAssignment<float> _a6; // if (qs) { // _a6 = {&qs->pdfRev, pt->Pdf(scene, ptMinus, *qs)}; // } // // printf("%f\n", sampled.pdfFwd); // // now qsMinus // ScopedAssignment<float> _a7; // if (qsMinus) { // _a7 = {&qsMinus->pdfRev, qs->Pdf(scene, pt, *qsMinus)}; // } // float ri = 1; // for (int i = (int)t - 1; i > 0; i--) { // ri *= remap0(cameraVertices[i].pdfRev) / // remap0(cameraVertices[i].pdfFwd); if (!cameraVertices[i].delta && // !cameraVertices[i - 1].delta) { // sumRi += ri; // } // } // ri = 1; // for (int i = (int)s - 1; i >= 0; i--) { // ri *= remap0(lightVertices[i].pdfRev) / // remap0(lightVertices[i].pdfFwd); bool delta = i > 0 ? lightVertices[i - // 1].delta // : false /*lightVertices[i].IsDeltaLight()*/; // if (!lightVertices[i].delta && !delta) { // sumRi += ri; // } // } // return 1.0 / (1.0 + sumRi); // } // Math::Spectrum ConnectPath(const Core::Scene& scene, Core::Sampler& // sampler, // PathVertex* cameraVertices, size_t t, // PathVertex* lightVertices, size_t s, // Math::Vector2f* pRaster) const { // if (t > 1 && s != 0 && cameraVertices[t - 1].type == VertexType::Light) // return Math::Spectrum(0.f); // Math::Spectrum L(0.f); // PathVertex sampled{}; // if (s == 0) { // const PathVertex& pt = cameraVertices[t - 1]; // L = pt.Le(cameraVertices[t - 2]) * pt.beta; // } else if (t == 1) { // const PathVertex& qs = lightVertices[s - 1]; // auto camera = cameraVertices[0].ei.camera; // if (qs.IsConnectible()) { // VisibilityTester vis; // CameraSamplingRecord cRec; // camera->Sample_Wi(sampler.Next2D(), qs.GetInteraction(), &cRec, // &vis); *pRaster = cRec.pos; if (cRec.pdf > 0 && !cRec.I.isBlack()) { // // Initialize dynamically sampled vertex and _L_ for $t=1$ case // sampled = PathVertex::CreateCamera(camera, vis.shadowRay, // cRec.I / cRec.pdf); // L = qs.beta * qs.f(sampled) * sampled.beta; // if (qs.IsOnSurface()) L *= std::abs(Math::dot(cRec.wi, qs.Ns())); // // Only check visibility after we know that the path would // // make a non-zero contribution. // if (!L.isBlack()) L *= vis.Tr(scene); // } // } // } else if (s == 1) { // // Sample a point on a light and connect it to the camera subpath // const PathVertex& pt = cameraVertices[t - 1]; // auto& lightVertex = lightVertices[0]; // if (pt.IsConnectible()) { // float lightPdf; // VisibilityTester vis; // LightSamplingRecord lRec; // lightVertex.ei.light->Sample_Li(sampler.Next2D(), // pt.GetInteraction(), // lRec, vis); // const Core::AreaLight* light = lightVertex.ei.light; // if (lRec.pdf > 0 && !lRec.Li.isBlack()) { // EndpointInteraction ei(light, vis.shadowRay); // sampled = PathVertex::CreateLight( // ei, lRec.Li / (scene.PdfLight(light) * lRec.pdf), 0); // sampled.pdfFwd = sampled.PdfLightOrigin(scene, pt); // L = pt.beta * pt.f(sampled) * sampled.beta; // if (pt.IsOnSurface()) L *= std::abs(Math::dot(lRec.wi, pt.Ns())); // // Only check visibility if the path would carry radiance. // if (!L.isBlack()) L *= vis.Tr(scene); // } // } // } else { // // Handle all other bidirectional connection cases // const PathVertex &qs = lightVertices[s - 1], &pt = cameraVertices[t - // 1]; if (qs.IsConnectible() && pt.IsConnectible()) { // L = qs.beta * qs.f(pt) * pt.f(qs) * pt.beta; // // VLOG(2) << "General connect s: " << s << ", t: " << t << " qs: " // << // // qs // // << ", pt: " << pt // // << ", qs.f(pt): " << qs.f(pt, TransportMode::Importance) // // << ", pt.f(qs): " << pt.f(qs, TransportMode::Radiance) // // << ", G: " << G(scene, sampler, qs, pt) // // << ", dist^2: " << DistanceSquared(qs.p(), pt.p()); // if (!L.isBlack()) L *= PathVertex::G(scene, qs, pt); // } // } // if (L.isBlack()) return {}; // float misWeight = 1.0f / (s + t); // // if (s == 1) printf("t %d s %d\n", (int)t, (int)s); // misWeight = MisWeight<1>(scene, sampler, cameraVertices, t, // lightVertices, // s, sampled); // assert(misWeight >= 0); // L *= misWeight; // return L.removeNaN(); // } template <int pow> float MIS(float fVal) { // Use power heuristic return std::pow(fVal, pow); } BDPTIntegrator::PathState BDPTIntegrator::SampleLightSource(Scene* scene, Sampler* sampler) { PathState ret; float lightPdf = 0.f; auto sampleLight = scene->SampleOneLight(sampler->Next1D(), &lightPdf); // printf("lightPdf %f\n", lightPdf); Ray lightRay; Vector3f nLight; float posPdf, dirPdf; sampleLight->Sample_Le(sampler->Next2D(), sampler->Next2D(), &lightRay, nLight, &posPdf, &dirPdf, ret.throughput); // printf( // "ray.o (%f %f %f) ray.d (%f %f %f) nLight (%f %f %f) posPdf (%f) " // "dirPdf(%f) E (%f %f %f)\n", // lightRay.o[0], lightRay.o[1], lightRay.o[2], lightRay.d[0], // lightRay.d[1], lightRay.d[2], nLight.x(), nLight.y(), nLight.z(), // posPdf, dirPdf, ret.throughput[0], ret.throughput[1], // ret.throughput[2]); if ((posPdf * dirPdf) == 0.0f) return ret; // dirPdf *= lightPdf; // posPdf *= lightPdf; // printf("dirPdf %f, posPdf %f, lightPdf %f emitPdf %f\n", dirPdf, posPdf, // lightPdf, dirPdf * posPdf * lightPdf); float emitPdf = dirPdf * posPdf * lightPdf; ret.throughput /= emitPdf; ret.isFiniteLight = sampleLight->isFinite(); ret.SpecularPath = true; ret.PathLength = 1; ret.direction = lightRay.d.normalized(); ret.origin = lightRay.o; float emitCos = dot(nLight, lightRay.d); ret.DVCM = MIS<pow>((posPdf * lightPdf) / emitPdf); ret.DVC = sampleLight->isDelta() ? 0.f : (sampleLight->isFinite() ? MIS<pow>(emitCos / (dirPdf * posPdf * lightPdf)) : MIS<pow>(1.f / (dirPdf * posPdf * lightPdf))); // printf("dirPdf %f, posPdf %f, lightPdf %f emitPdf %f\n", dirPdf, posPdf, // lightPdf, emitPdf); // printf("E (%f %f %f), emitCos %f, DVCM %f DVC %f\n", ret.throughput[0], // ret.throughput[1], ret.throughput[2], emitCos, ret.DVCM, ret.DVC); return ret; } Spectrum BDPTIntegrator::ConnectToCamera(Scene* scene, Camera* camera, Sampler* sampler, SurfaceInteraction& si, Vertex& lightVertex, Vector2f& pRaster) { Vector3f dirToCamera; // Vector2f pRaster; if (!camera->ToRaster(sampler->Next2D(), si, dirToCamera, pRaster)) return {}; float distToCamera = dirToCamera.length(); dirToCamera = dirToCamera.normalized(); // printf("(%f %f %f) (%f %f)\n", lightVertex.throughput[0], // lightVertex.throughput[1], lightVertex.throughput[2], pRaster[0], // pRaster[1]); Spectrum f = si.bsdf->Evaluate(dirToCamera, lightVertex.inDir) * std::abs(dot(lightVertex.inDir, si.Ns)) / std::abs(dot(lightVertex.inDir, si.Ng)); // printf("(%f %f %f) (%f %f %f) %f %f (%f %f %f)\n", dirToCamera[0], // dirToCamera[1], dirToCamera[2], // si.bsdf->Evaluate(dirToCamera, lightVertex.inDir)[0], // si.bsdf->Evaluate(dirToCamera, lightVertex.inDir)[1], // si.bsdf->Evaluate(dirToCamera, lightVertex.inDir)[2], // std::abs(dot(lightVertex.inDir, si.Ns)), // std::abs(dot(lightVertex.inDir, si.Ng)), f[0], f[1], f[2]); if (f.isBlack()) return {}; // printf("(%f %f %f)\n", f[0], f[1], f[2]); float pdf = si.bsdf->EvaluatePdf(si.bsdf->toLocal(lightVertex.inDir), si.bsdf->toLocal(dirToCamera)); float revPdf = si.bsdf->EvaluatePdf(si.bsdf->toLocal(dirToCamera), si.bsdf->toLocal(lightVertex.inDir)); // printf("%f %f\n", pdf, revPdf); if (pdf == 0.f || revPdf == 0.f) return {}; float cosToCam = dot(si.Ng, dirToCamera); CameraSamplingRecord cRec; VisibilityTester tester; camera->Sample_Wi(sampler->Next2D(), si, &cRec, &tester); (void)tester; // printf("%f\n", cRec.pdf); float cameraPdfA = cRec.pdf * std::abs(cosToCam) / (distToCamera * distToCamera); // printf("%d\n", camera->GetPixelCount()); float WLight = MIS<pow>( cameraPdfA / camera->GetPixelCount() //(float)camera->GetPixelCount() ) * (lightVertex.DVCM + lightVertex.DVC * MIS<pow>(revPdf)); float MISWeight = 1.f / (WLight + 1.f); // printf("%f\n", MISWeight); Spectrum contrib = MISWeight * lightVertex.throughput * f * cameraPdfA / camera->GetPixelCount(); // (float)camera->GetPixelCount(); // printf("%f %f %f\n", contrib[0], contrib[1], contrib[2]); // printf("(%f %f %f) MISWeight %f f (%f %f %f) cameraPdfA %f A %f\n", // lightVertex.throughput[0], lightVertex.throughput[1], // lightVertex.throughput[2], MISWeight, f[0], f[1], f[2], // cameraPdfA, camera->A()); Ray rayToCam = Ray(si.p, dirToCamera, Ray::Eps(), distToCamera * (1.f - Ray::Eps())); if (!contrib.isBlack() && !scene->Occlude(rayToCam)) { // printf("%f %f %f\n", contrib[0], contrib[1], contrib[2]); return contrib; } return {}; } int BDPTIntegrator::GenerateLightPath(Scene* scene, Sampler* sampler, const int maxDepth, Vertex* lightVertices, Camera* camera, int* vertexCount, const int rrDepth, const bool connectToCamera) { if (maxDepth == 0) { *vertexCount = 0; return 0; } PathState lightPathState = SampleLightSource(scene, sampler); if (lightPathState.throughput.isBlack()) return 0; // printf("(%f %f %f) \n", lightPathState.throughput[0], // lightPathState.throughput[1], lightPathState.throughput[2]); if (lightPathState.PathLength >= maxDepth) { *vertexCount = 0; return lightPathState.PathLength; } *vertexCount = 0; while (true) { Ray pathRay(lightPathState.origin, lightPathState.direction); // printf("(%f %f %f) (%f %f %f)\n", pathRay.o[0], pathRay.o[1], // pathRay.o[2], pathRay.d[0], pathRay.d[1], pathRay.d[2]); Intersection isect; if (!scene->Intersect(pathRay, &isect)) { return lightPathState.PathLength; } if (lightPathState.PathLength > 1 || lightPathState.isFiniteLight) { // printf("1 %f %f\n", lightPathState.DVCM, isect.t); lightPathState.DVCM *= MIS<pow>(isect.t * isect.t); // printf("(%f) (%f)\n", (pathRay.Point(isect.t) - pathRay.o).length(), // isect.t); // printf("2 %f\n", lightPathState.DVCM); } float cosIn = std::abs(dot(isect.Ng, -pathRay.d)); lightPathState.DVCM /= MIS<pow>(cosIn); lightPathState.DVC /= MIS<pow>(cosIn); // printf("cosIn %f DVCM %f DVC %f\n", cosIn, lightPathState.DVCM, // lightPathState.DVC); Triangle triangle{}; isect.mesh->GetTriangle(isect.triId, &triangle); auto p = pathRay.Point(isect.t); SurfaceInteraction si(-pathRay.d, p, triangle, isect); isect.mesh->GetMaterial()->ComputeScatteringFunction( &si, Core::TransportMode::eRadiance); BSDFSamplingRecord bRec(si, sampler->Next2D()); si.bsdf->Sample(bRec); // if (bRec.pdf <= 0.f) break; auto specular = bRec.type & BxDFType::BSDF_SPECULAR; if (!specular) { Vertex& lightVertex = lightVertices[(*vertexCount)++]; lightVertex.throughput = lightPathState.throughput; lightVertex.length = lightPathState.PathLength + 1; lightVertex.si = si; lightVertex.inDir = -lightPathState.direction; lightVertex.DVCM = lightPathState.DVCM; lightVertex.DVC = lightPathState.DVC; // printf("(%f %f %f) \n", lightVertex.throughput[0], // lightVertex.throughput[1], lightVertex.throughput[2]); // connect to camera if (connectToCamera) { Vector2f ptRaster; Spectrum connectRadiance = ConnectToCamera(scene, camera, sampler, si, lightVertex, ptRaster); // if (connectRadiance.isBlack()) break; // printf("(%f %f %f) (%f %f)\n", connectRadiance[0], // connectRadiance[1], // connectRadiance[2], ptRaster[0], ptRaster[1]); camera->GetFilm()->AddSplat(connectRadiance, ptRaster); } } if (++lightPathState.PathLength >= maxDepth) break; // if (!SampleScattering()) break; Spectrum f = bRec.f; Vector3f wi = bRec.wi; float scatteredPdf = bRec.pdf; float revPdf = si.bsdf->EvaluatePdf(wi, si.bsdf->toLocal(-pathRay.d)); if (f.isBlack() || scatteredPdf == 0.f) break; // printf("(%f %f %f) %f\n", f[0], f[1], f[2], scatteredPdf); if (!specular && rrDepth != -1 && lightPathState.PathLength > rrDepth) { float q = std::min(0.95f, lightPathState.throughput.max()); if (sampler->Next1D() >= q) break; lightPathState.throughput /= q; } lightPathState.origin = si.p; lightPathState.direction = si.bsdf->toWorld(bRec.wi); float cosOut = std::abs(dot(si.Ns, si.bsdf->toWorld(bRec.wi))); if (!specular) { lightPathState.SpecularPath &= 0; lightPathState.DVCM = MIS<pow>(cosOut / scatteredPdf) * (lightPathState.DVC * MIS<pow>(revPdf) + lightPathState.DVCM); lightPathState.DVC = MIS<pow>(1.0f / scatteredPdf); // printf("%f %f\n", lightPathState.DVCM, lightPathState.DVC); } else { lightPathState.SpecularPath &= 1; lightPathState.DVCM = 0.f; lightPathState.DVC *= MIS<pow>(cosOut); // printf("%f %f\n", lightPathState.DVCM, lightPathState.DVC); } lightPathState.throughput *= f * cosOut / scatteredPdf; // printf("(%f %f %f) \n", lightPathState.throughput[0], // lightPathState.throughput[1], lightPathState.throughput[2]); } return lightPathState.PathLength; } // bool SampleScattering() const {} void BDPTIntegrator::SampleCamera(Camera* camera, Ray& ray, Sampler* sampler, PathState& initPathState) { // CameraSamplingRecord cRec; // VisibilityTester tester; // SurfaceInteraction si; // ray.d = ray.d.normalized(); // si.p = ray.Point(camera->GetFocusDistance()); // camera->Sample_Wi(sampler->Next2D(), si, &cRec, &tester); // (void)tester; // float cosAtCam = Math::Dot(pCamera->mDir, primRay.mDir); // float rasterToCamDist = pCamera->GetImagePlaneDistance() / cosAtCam; // float cameraPdfW = rasterToCamDist * rasterToCamDist / cosAtCam; float virtualImagePlaneDistance = camera->GetImagePlaneDist(); float cosThetaCamera = dot(camera->GetDir(), ray.d.normalized()); float imagePointToCameraDistance = virtualImagePlaneDistance / cosThetaCamera; float invSolidAngleMeasure = imagePointToCameraDistance * imagePointToCameraDistance / cosThetaCamera; float revCameraPdfW = (1.0f / invSolidAngleMeasure); // printf("%f %f %f %f %f\n", virtualImagePlaneDistance, cosThetaCamera, // imagePointToCameraDistance, invSolidAngleMeasure, revCameraPdfW); initPathState.origin = ray.o; initPathState.direction = ray.d.normalized(); initPathState.throughput = Spectrum{1.f}; initPathState.PathLength = 1; initPathState.SpecularPath = true; initPathState.DVC = 0.f; initPathState.DVCM = MIS<pow>(revCameraPdfW * camera->GetPixelCount()); // initPathState.DVCM = MIS<pow>( // camera->GetPixelCount() // camera->A() / cRec.pdf); // printf("%d %f %f\n", camera->GetPixelCount(), cRec.pdf, // initPathState.DVCM); } Spectrum BDPTIntegrator::HittingLightSource(Scene* scene, Ray& ray, Intersection& isect, AreaLight* light, PathState& cameraPathState) { float pickPdf = scene->PdfLight(light); float emitPdfW, directPdfA; Spectrum emittedRadiance = light->Emit(-ray.d, isect.Ng, &emitPdfW, &directPdfA); // printf("(%f %f %f) %f %f\n", emittedRadiance[0], emittedRadiance[1], // emittedRadiance[2], emitPdfW, directPdfA); if (emittedRadiance.isBlack()) return {}; // printf("%d\n", cameraPathState.PathLength); if (cameraPathState.PathLength == 2) { return emittedRadiance; } directPdfA *= pickPdf; emitPdfW *= pickPdf; float WCamera = MIS<pow>(directPdfA) * cameraPathState.DVCM + MIS<pow>(emitPdfW) * cameraPathState.DVC; float MISWeight = 1.0f / (1.0f + WCamera); // printf("%f %f %f %f %f\n", directPdfA, emitPdfW, cameraPathState.DVCM, // cameraPathState.DVC, WCamera); return MISWeight * emittedRadiance; } Spectrum BDPTIntegrator::ConnectToLight(const Scene* scene, Ray& pathRay, const SurfaceInteraction& si, Sampler* sampler, PathState& cameraPathState) { // Sample light source and get radiance float lightPdf = 0.f; auto sampleLight = scene->SampleOneLight(sampler->Next1D(), &lightPdf); const Vector3f& pos = si.p; Vector3f vIn; VisibilityTester visibility; float lightPdfW; float cosAtLight; float emitPdfW; Spectrum radiance = sampleLight->Illuminate(si, sampler->Next2D(), vIn, visibility, &lightPdfW, &cosAtLight, &emitPdfW); // printf("(%f %f %f) %f %f %f\n", radiance[0], radiance[1], radiance[2], // lightPdfW, cosAtLight, emitPdfW); if (radiance.isBlack() || lightPdfW == 0.0f) { return {}; } Vector3f vOut = -pathRay.d; Spectrum bsdfFac = si.bsdf->Evaluate(vOut, vIn); if (bsdfFac.isBlack()) { return {}; } float bsdfPdfW = si.bsdf->EvaluatePdf(vOut, vIn); if (bsdfPdfW == 0.f) return {}; if (sampleLight->isDelta()) bsdfPdfW = 0.f; float bsdfRevPdfW = si.bsdf->EvaluatePdf(vIn, vOut); float WLight = MIS<pow>(bsdfPdfW / (lightPdfW * lightPdf)); // printf("%f\n", WLight); float cosToLight = std::abs(Math::dot(si.Ns, vIn)); float WCamera = MIS<pow>(emitPdfW * cosToLight / (lightPdfW * cosAtLight)) * (cameraPathState.DVCM + cameraPathState.DVC * MIS<pow>(bsdfRevPdfW)); // printf("%f\n", WCamera); float fMISWeight = 1.0f / (WLight + 1.0f + WCamera); Spectrum contribution = (fMISWeight * cosToLight / (lightPdfW * lightPdf)) * bsdfFac * radiance; if (contribution.isBlack() || !visibility.visible(*scene)) { return {}; } // printf("%f %f %f\n", contribution[0], contribution[1], contribution[2]); return contribution; } Spectrum BDPTIntegrator::ConnectVertex(Scene* scene, SurfaceInteraction& si, const Vertex& lightVertex, PathState& cameraState) { const Vector3f& cameraPos = si.p; auto dirToLight = lightVertex.si.p - cameraPos; float distToLightSqr = dot(dirToLight, dirToLight); float distToLight = dirToLight.length(); auto vOutCam = -cameraState.direction; Spectrum cameraBsdfFac = si.bsdf->Evaluate(vOutCam, dirToLight); float cosAtCam = dot(si.Ns, dirToLight); auto cameraDirPdfW = si.bsdf->EvaluatePdf(vOutCam, dirToLight); float cameraReversePdfW = si.bsdf->EvaluatePdf(dirToLight, vOutCam); if (cameraBsdfFac.isBlack() || cameraDirPdfW == 0.0f || cameraReversePdfW == 0.0f) return {}; Vector3f dirToCamera = -dirToLight; Spectrum lightBsdfFac = lightVertex.si.bsdf->Evaluate(lightVertex.inDir, dirToCamera); float cosAtLight = Math::dot(lightVertex.si.Ns, dirToCamera); float lightDirPdfW = lightVertex.si.bsdf->EvaluatePdf(lightVertex.inDir, dirToCamera); float lightRevPdfW = lightVertex.si.bsdf->EvaluatePdf(dirToCamera, lightVertex.inDir); if (lightBsdfFac.isBlack() || lightDirPdfW == 0.0f || lightRevPdfW == 0.0f) return {}; // printf("%f %f %f %f\n", cameraDirPdfW, cameraReversePdfW, lightDirPdfW, // lightRevPdfW); float geometryTerm = cosAtLight * cosAtCam / distToLightSqr; if (geometryTerm < 0.0f) { return {}; } // printf("%f\n", geometryTerm); float cameraDirPdfA = cameraDirPdfW * std::abs(cosAtLight) / (distToLight * distToLight); float lightDirPdfA = lightDirPdfW * std::abs(cosAtCam) / (distToLight * distToLight); float WLight = MIS<pow>(cameraDirPdfA) * (lightVertex.DVCM + lightVertex.DVC * MIS<pow>(lightRevPdfW)); float WCamera = MIS<pow>(lightDirPdfA) * (cameraState.DVCM + cameraState.DVC * MIS<pow>(cameraReversePdfW)); float fMISWeight = 1.0f / (WLight + 1.0f + WCamera); // printf("%f %f %f\n", fMISWeight, WLight, WCamera); Spectrum contribution = (fMISWeight * geometryTerm) * lightBsdfFac * cameraBsdfFac; Ray rayToLight = Ray(cameraPos, dirToLight, Ray::Eps(), distToLight * (1.f - Ray::Eps())); if (contribution.isBlack() || scene->Occlude(rayToLight)) { // printf("%f %f %f\n", contribution[0], contribution[1], // contribution[2]); return {}; } // printf("%f %f %f\n", contribution[0], contribution[1], contribution[2]); return contribution; } Math::Spectrum BDPTIntegrator::Li(Core::Scene* scene, Core::Camera* camera, const Math::Vector2i& raster, Core::Sampler* sampler) const { Vertex* lightVertices = (Vertex*)calloc(maxDepth, sizeof(Vertex)); int numLightVertex; int lightPathLen = GenerateLightPath(scene, sampler, maxDepth + 1, lightVertices, camera, &numLightVertex); const float u = (raster.x() + sampler->Next1D()) / camera->GetFilm()->Dimension().x(); const float v = (raster.y() + sampler->Next1D()) / camera->GetFilm()->Dimension().y(); // auto ray = camera->GenerateRay(u, v); auto ray = camera->GenerateRay(sampler->Next2D(), sampler->Next2D(), raster); PathState cameraPathState; SampleCamera(camera, ray, sampler, cameraPathState); Math::Spectrum L(0.f); while (true) { Ray pathRay(cameraPathState.origin, cameraPathState.direction); Intersection isect; if (!scene->Intersect(pathRay, &isect)) { break; } float cosIn = std::abs(dot(isect.Ng, -pathRay.d)); cameraPathState.DVCM *= MIS<pow>(isect.t * isect.t); cameraPathState.DVCM /= MIS<pow>(cosIn); cameraPathState.DVC /= MIS<pow>(cosIn); // printf("%f %f\n", cameraPathState.DVCM, cameraPathState.DVC); if (isect.mesh->IsEmitter()) { cameraPathState.PathLength++; L += cameraPathState.throughput * HittingLightSource(scene, pathRay, isect, isect.mesh->GetLight(isect.triId).get(), cameraPathState); break; } if (++cameraPathState.PathLength >= maxDepth + 2) { break; } Triangle triangle{}; isect.mesh->GetTriangle(isect.triId, &triangle); auto p = pathRay.Point(isect.t); SurfaceInteraction si(-pathRay.d, p, triangle, isect); isect.mesh->GetMaterial()->ComputeScatteringFunction( &si, Core::TransportMode::eImportance); BSDFSamplingRecord bRec(si, sampler->Next2D()); si.bsdf->Sample(bRec); if (bRec.pdf <= 0.f) break; auto specular = bRec.type & BxDFType::BSDF_SPECULAR; if (!specular) { L += cameraPathState.throughput * ConnectToLight(scene, pathRay, si, sampler, cameraPathState); for (int i = 0; i < numLightVertex; i++) { const Vertex& lightVertex = lightVertices[i]; if (lightVertex.length + cameraPathState.PathLength - 2 > maxDepth) { break; } L += lightVertex.throughput * cameraPathState.throughput * ConnectVertex(scene, si, lightVertex, cameraPathState); } } Spectrum f = bRec.f; Vector3f wi = bRec.wi; float scatteredPdf = bRec.pdf; float revPdf = si.bsdf->EvaluatePdf(wi, si.bsdf->toLocal(-pathRay.d)); if (f.isBlack() || scatteredPdf == 0.f) break; // printf("(%f %f %f) %f\n", f[0], f[1], f[2], scatteredPdf); if (!specular && rrDepth != -1 && cameraPathState.PathLength > rrDepth) { float q = std::min(0.95f, cameraPathState.throughput.max()); if (sampler->Next1D() >= q) break; cameraPathState.throughput /= q; } cameraPathState.origin = si.p; cameraPathState.direction = si.bsdf->toWorld(bRec.wi); float cosOut = std::abs(dot(si.Ns, si.bsdf->toWorld(bRec.wi))); if (!specular) { cameraPathState.SpecularPath &= 0; cameraPathState.DVCM = MIS<pow>(cosOut / scatteredPdf) * (cameraPathState.DVC * MIS<pow>(revPdf) + cameraPathState.DVCM); cameraPathState.DVC = MIS<pow>(1.0f / scatteredPdf); } else { cameraPathState.SpecularPath &= 1; cameraPathState.DVCM = 0.f; cameraPathState.DVC *= MIS<pow>(cosOut); } cameraPathState.throughput *= f * cosOut / scatteredPdf; } free((void*)lightVertices); return L; } void BDPTIntegrator::Render(Core::Scene* scene, Core::Camera* camera, Core::Sampler* sampler) const {} // private: // // int rrDepth = 5, maxDepth = 16; // int rrDepth = 5, maxDepth = 16; // // heuristic // static constexpr int pow = 1; // }; } // namespace Ajisai::Integrators AJISAI_PLUGIN_REGISTER(BDPTIntegrator, Ajisai::Integrators::BDPTIntegrator, "ajisai.integrators.Integrator/0.0.1")
36.111928
80
0.573878
siyuanpan
e2228f6754b8bbf31357a6f7086c29b17ac48b84
6,380
hpp
C++
libctrpf/include/CTRPluginFrameworkImpl/Menu/KeyboardImpl.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
libctrpf/include/CTRPluginFrameworkImpl/Menu/KeyboardImpl.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
libctrpf/include/CTRPluginFrameworkImpl/Menu/KeyboardImpl.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
#ifndef CTRPLUGINFRAMEWORKIMPL_KEYBOARD_HPP #define CTRPLUGINFRAMEWORKIMPL_KEYBOARD_HPP #include "CTRPluginFrameworkImpl/Graphics.hpp" #include "CTRPluginFramework/Graphics/CustomIcon.hpp" #include "CTRPluginFrameworkImpl/Graphics/TouchKey.hpp" #include "CTRPluginFrameworkImpl/Graphics/TouchKeyString.hpp" #include "CTRPluginFramework/Menu/Keyboard.hpp" #include "CTRPluginFrameworkImpl/System.hpp" #include "CTRPluginFramework/Sound.hpp" #include <vector> #include <string> namespace CTRPluginFramework { enum Layout { QWERTY, DECIMAL, HEXADECIMAL }; class Keyboard; class KeyboardImpl { using CompareCallback = bool (*)(const void *, std::string&); using ConvertCallback = void *(*)(std::string&, bool); using OnEventCallback = void(*)(Keyboard&, KeyboardEvent&); using FrameCallback = void (*)(Time); using KeyIter = std::vector<TouchKey>::iterator; using KeyStringIter = std::vector<TouchKeyString>::iterator; public: KeyboardImpl(const std::string &text = ""); explicit KeyboardImpl(Keyboard *kb, const std::string &text = ""); ~KeyboardImpl(void); void SetLayout(Layout layout); void SetHexadecimal(bool isHex); bool IsHexadecimal(void) const; void SetMaxInput(u32 max); void CanAbort(bool canAbort); void CanChangeLayout(bool canChange); std::string &GetInput(void); std::string &GetMessage(void); std::string &GetTitle(void); void SetError(std::string &error); void SetConvertCallback(ConvertCallback callback); void SetCompareCallback(CompareCallback callback); void OnKeyboardEvent(OnEventCallback callback); static void OnNewFrame(FrameCallback callback); void ChangeSelectedEntry(int entry); int GetSelectedEntry() {return _manualKey;} void ChangeEntrySound(int entry, SoundEngine::Event soundEvent); void Populate(const std::vector<std::string>& input, bool resetScroll); void Populate(const std::vector<CustomIcon>& input, bool resetScroll); void Clear(void); int Run(void); void Close(void); bool operator()(int &out); bool DisplayTopScreen; private: friend class HexEditor; friend class ARCodeEditor; void _RenderTop(void); void _RenderBottom(void); void _ProcessEvent(Event &event); void _UpdateScroll(float delta, bool ignoreTouch); void _Update(float delta); // Keyboard layout constructor void _Qwerty(void); void _QwertyLowCase(void); void _QwertyUpCase(void); void _QwertySymbols(void); void _QwertyNintendo(void); static void _DigitKeyboard(std::vector<TouchKey> &keys); void _Decimal(void); void _Hexadecimal(void); void _ScrollUp(void); void _ScrollDown(void); void _UpdateScrollInfos(void); bool _CheckKeys(void); //<- Return if input have changed bool _CheckInput(void); //<- Call compare callback, return true if the input is valid bool _CheckButtons(int &ret); //<- for string button void _HandleManualKeyPress(Key key); void _ClearKeyboardEvent(); void _ChangeManualKey(int newVal, bool playSound = true); Keyboard *_owner{nullptr}; std::string _title; std::string _text; std::string _error; std::string _userInput; bool _canChangeLayout{false}; bool _canAbort{true}; bool _isOpen{false}; bool _askForExit{false}; bool _errorMessage{false}; bool _userAbort{false}; bool _isHex{true}; bool _mustRelease{false}; bool _useCaps{false}; bool _useSymbols{false}; bool _useNintendo{false}; float _offset{0.f}; u32 _max{0}; u8 _symbolsPage{0}; u8 _nintendoPage{0}; Layout _layout{HEXADECIMAL}; Clock _blinkingClock; int _cursorPositionInString{0}; int _cursorPositionOnScreen{0}; bool _showCursor{true}; CompareCallback _compare{nullptr}; ConvertCallback _convert{nullptr}; OnEventCallback _onKeyboardEvent{nullptr}; static FrameCallback _onNewFrame; KeyboardEvent _KeyboardEvent{}; std::vector<TouchKey> *_keys{nullptr}; static std::vector<TouchKey> _DecimalKeys; static std::vector<TouchKey> _HexaDecimalKeys; static std::vector<TouchKey> _QwertyKeys; // Custom keyboard stuff int _manualKey{0}; int _prevManualKey{-2}; bool _manualScrollUpdate{false}; bool _userSelectedKey{false}; bool _customKeyboard{false}; bool _displayScrollbar{false}; bool _isIconKeyboard{false}; int _currentPosition{0}; u32 _scrollbarSize{0}; u32 _scrollCursorSize{0}; float _scrollSize{0.f}; float _scrollPosition{0.f}; float _scrollPadding{0.f}; float _scrollJump{0.f}; float _inertialVelocity{0.f}; float _scrollStart{0.f}; float _scrollEnd{0.f}; IntVector _lastTouch; Clock _touchTimer; std::vector<TouchKeyString *> _strKeys; }; } #endif
38.902439
96
0.54185
MirayXS
e224e709d74a393c04acd3371847fe9ca1d0b0e3
704
cpp
C++
152-maxProductSubarray.cpp
riasood02/leetcoding-problems
568bb4e323acb57e274b87c07969a772f011259e
[ "Unlicense" ]
5
2020-10-06T13:10:04.000Z
2021-06-07T02:07:59.000Z
152-maxProductSubarray.cpp
riasood02/leetcoding-problems
568bb4e323acb57e274b87c07969a772f011259e
[ "Unlicense" ]
5
2020-10-05T17:23:57.000Z
2020-10-10T12:56:15.000Z
152-maxProductSubarray.cpp
riasood02/leetcoding-problems
568bb4e323acb57e274b87c07969a772f011259e
[ "Unlicense" ]
43
2020-10-05T17:31:56.000Z
2020-10-29T23:47:53.000Z
// https://leetcode.com/problems/maximum-product-subarray/ class Solution { public: int maxProduct(vector<int>& nums) { int cur = INT_MIN; vector<int> a(nums.size(),0); vector<int> b(nums.size(),0); a[0] = nums[0]; b[0] = nums[0]; int ma = a[0]; for(int i = 1 ;i<nums.size();i++){ if(nums[i]<0){ a[i] = max(nums[i],b[i-1]*nums[i]); b[i] = min(nums[i],a[i-1]*nums[i]); } else{ a[i] = max(nums[i],a[i-1]*nums[i]); b[i] = min(nums[i],b[i-1]*nums[i]); } ma = max(a[i],ma); } return ma; } };
27.076923
58
0.400568
riasood02
e2338d870195e71b2e20868ca3757af7d5680636
5,493
cpp
C++
src/uavpc/Pose/PoseService.cpp
filipdutescu/uavpc
050bd19b103f2cf7cdac9fd167d8965d0032c5ec
[ "Apache-2.0" ]
2
2021-10-11T02:54:08.000Z
2021-10-11T09:29:59.000Z
src/uavpc/Pose/PoseService.cpp
filipdutescu/uavpc
050bd19b103f2cf7cdac9fd167d8965d0032c5ec
[ "Apache-2.0" ]
null
null
null
src/uavpc/Pose/PoseService.cpp
filipdutescu/uavpc
050bd19b103f2cf7cdac9fd167d8965d0032c5ec
[ "Apache-2.0" ]
null
null
null
#include "uavpc/Pose/PoseService.hpp" #include <ctime> #include <iostream> #include <stdexcept> #include <string> #include <opencv2/core/types.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/videoio.hpp> #include <openpose/core/matrix.hpp> #include <openpose/core/point.hpp> #include <openpose/thread/enumClasses.hpp> namespace uavpc::Pose { PoseService::PoseService() noexcept : m_OpenPoseWrapper(op::ThreadManagerMode::Asynchronous), m_ShouldRun(false), m_WithRecognition(false), m_SaveVideoStream(false) { } PoseService::~PoseService() { if (m_ShouldRun) { while (!m_RecognitionMutex.try_lock()) { std::this_thread::sleep_for(s_MutexTryLockWaitTime); } m_ShouldRun = false; m_RecognitionMutex.unlock(); while (!m_RecognitionThread.joinable()) { std::this_thread::sleep_for(s_MutexTryLockWaitTime); } if (m_RecognitionThread.joinable()) { m_RecognitionThread.join(); } m_RecognitionMutex.unlock(); if (m_SaveVideoStream) { ToggleSaveVideoStream(); } } } TDatumsSP PoseService::DetectPoseFromFrame(const cv::Mat &frame) noexcept { const auto rawImage = OP_CV2OPCONSTMAT(frame); return m_OpenPoseWrapper.emplaceAndPop(rawImage); } void PoseService::DisplayFrameWithPose(const TDatumsSP &frame) noexcept { try { if (frame != nullptr && !frame->empty()) { const auto image = OP_OP2CVCONSTMAT(frame->at(0U)->cvOutputData); if (!image.empty()) { cv::imshow("UAVPC", image); } } } catch (const std::exception &e) { std::cerr << "Could not display frame with pose: " << e.what(); } } void PoseService::ToggleRecognition() noexcept { m_WithRecognition = !m_WithRecognition; } void PoseService::ToggleSaveVideoStream() noexcept { m_SaveVideoStream = !m_SaveVideoStream; if (m_ShouldRun) { if (m_SaveVideoStream) { while (m_RecognitionMutex.try_lock()) { std::this_thread::sleep_for(s_MutexTryLockWaitTime); } constexpr auto format = "uavpc_%Y%m%d_%H%M%S.mp4"; constexpr auto bufferSize = 30U; char buffer[bufferSize]{ '\0' }; std::strftime(buffer, bufferSize, format, std::localtime(nullptr)); m_PersistentVideoStream.open( std::string(buffer), cv::VideoWriter::fourcc('M', 'P', '4', 'V'), -1, m_VideoStreamSize); m_RecognitionMutex.unlock(); } else { while (m_RecognitionMutex.try_lock()) { std::this_thread::sleep_for(s_MutexTryLockWaitTime); } m_PersistentVideoStream.release(); m_RecognitionMutex.unlock(); } } } void PoseService::StartDisplay(cv::VideoCapture &videoStream) { m_ShouldRun = true; if (!videoStream.isOpened()) { throw std::runtime_error("Video stream closed."); } m_RecognitionThread = std::thread( [&] { auto width = static_cast<int>(videoStream.get(cv::CAP_PROP_FRAME_WIDTH) / 2); auto height = static_cast<int>(videoStream.get(cv::CAP_PROP_FRAME_HEIGHT) / 2); auto opWidth = (width / (16 * 3) + 1) * 16; auto opHeight = (width / (16 * 3) + 1) * 16; cv::Mat frame; op::WrapperStructPose poseConfig{}; poseConfig.netInputSize = op::Point<int>(opWidth, opHeight); poseConfig.poseModel = op::PoseModel::MPI_15_4; m_OpenPoseWrapper.configure(poseConfig); m_OpenPoseWrapper.start(); while (m_ShouldRun) { if (videoStream.read(frame)) { if (!frame.empty()) { cv::Mat resizedFrame; cv::resize(frame, resizedFrame, cv::Size(width, height)); cv::Mat persistentFrame = resizedFrame; if (m_WithRecognition) { auto processedFrame = DetectPoseFromFrame(resizedFrame); DisplayFrameWithPose(processedFrame); persistentFrame = OP_OP2CVCONSTMAT(processedFrame->at(0U)->cvOutputData); } else { cv::imshow("UAVPC", resizedFrame); } if (m_SaveVideoStream) { while (m_RecognitionMutex.try_lock()) { std::this_thread::sleep_for(s_MutexTryLockWaitTime); } m_PersistentVideoStream.write(persistentFrame); m_RecognitionMutex.unlock(); } } } else { std::cout << "could not read frame" << std::endl; } cv::waitKey(1); } }); } void PoseService::StopDisplay() noexcept { while (!m_RecognitionMutex.try_lock()) { std::this_thread::sleep_for(s_MutexTryLockWaitTime); } m_ShouldRun = false; m_RecognitionMutex.unlock(); while (!m_RecognitionThread.joinable()) { std::this_thread::sleep_for(s_MutexTryLockWaitTime); } if (m_RecognitionThread.joinable()) { m_RecognitionThread.join(); } m_RecognitionMutex.unlock(); m_OpenPoseWrapper.stop(); } } // namespace uavpc::Pose
25.910377
101
0.57728
filipdutescu
e23ab9f821e9f74c8baa4061e876516778c0842a
422
cpp
C++
CanadianExperience/CanadianExperience/Testing/CAnimChannelAngleTest.cpp
NicholsTyler/cse_335
b8a46522c15a9881cb681ae94b4a5f737817b05e
[ "MIT" ]
null
null
null
CanadianExperience/CanadianExperience/Testing/CAnimChannelAngleTest.cpp
NicholsTyler/cse_335
b8a46522c15a9881cb681ae94b4a5f737817b05e
[ "MIT" ]
null
null
null
CanadianExperience/CanadianExperience/Testing/CAnimChannelAngleTest.cpp
NicholsTyler/cse_335
b8a46522c15a9881cb681ae94b4a5f737817b05e
[ "MIT" ]
null
null
null
#include "pch.h" #include "CppUnitTest.h" #include "AnimChannelAngle.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace Testing { TEST_CLASS(CAnimChannelAngleTest) { public: TEST_METHOD(TestCAnimChannelAngleName) { CAnimChannelAngle channel; channel.SetName(L"abcdexx"); Assert::AreEqual(std::wstring(L"abcdexx"), channel.GetName()); } }; }
16.230769
74
0.687204
NicholsTyler
e249cc60aa888d14c8688687992cf22d8f83ba50
1,069
hpp
C++
include/gclib/gc_delete.hpp
axilmar/gclib
1d2707238b549d889a7c9b097d599a36e3841da4
[ "Apache-2.0" ]
2
2021-11-24T18:49:09.000Z
2022-01-11T04:30:43.000Z
include/gclib/gc_delete.hpp
axilmar/gclib
1d2707238b549d889a7c9b097d599a36e3841da4
[ "Apache-2.0" ]
null
null
null
include/gclib/gc_delete.hpp
axilmar/gclib
1d2707238b549d889a7c9b097d599a36e3841da4
[ "Apache-2.0" ]
1
2020-10-27T09:51:06.000Z
2020-10-27T09:51:06.000Z
#ifndef GCLIB_GC_DELETE_HPP #define GCLIB_GC_DELETE_HPP #include "gc_new_array.hpp" namespace gclib { /** * Deletes an object pointed to by the given pointer. * @param p pointer to object to delete; can be null; if not null, then it should have a value returned by gc_new, * otherwise the operation will have undefined results. */ template <class T> void gc_delete(const gc_ptr<T>& p) { if (!p) { return; } class delete_object { public: delete_object(void* obj) : m_block(gc::object_to_block(obj)) { gc::begin_remove(m_block); m_block->vtable->finalize(m_block + 1, m_block->end()); } ~delete_object() { gc::end_remove(m_block); m_block->vtable->deallocate(m_block); } private: gc::block* m_block; }; const delete_object delete_object_var(p.get()); } } //namespace gclib #endif //GCLIB_GC_DELETE_HPP
22.270833
118
0.558466
axilmar
f46d513866d62800e662f5381531cf2cd4b82e88
2,430
cpp
C++
control/groupsform.cpp
TheMrButcher/offline-mentor
15c362710fc993b21ed2d23adfc98e797e2380db
[ "MIT" ]
null
null
null
control/groupsform.cpp
TheMrButcher/offline-mentor
15c362710fc993b21ed2d23adfc98e797e2380db
[ "MIT" ]
101
2017-03-11T19:09:46.000Z
2017-09-04T17:37:55.000Z
control/groupsform.cpp
TheMrButcher/offline-mentor
15c362710fc993b21ed2d23adfc98e797e2380db
[ "MIT" ]
1
2018-03-13T03:47:15.000Z
2018-03-13T03:47:15.000Z
#include "groupsform.h" #include "ui_groupsform.h" #include "group_utils.h" #include "groupdialog.h" GroupsForm::GroupsForm(QWidget *parent) : QWidget(parent), ui(new Ui::GroupsForm) { ui->setupUi(this); } GroupsForm::~GroupsForm() { delete ui; } void GroupsForm::load() { ui->listWidget->clear(); ui->listWidget->selectionModel()->clear(); for (const auto& group : getGroups()) { QListWidgetItem* item = new QListWidgetItem(group.name, ui->listWidget); item->setData(Qt::UserRole, group.id); } } void GroupsForm::onGroupsPathChanged() { loadGroups(); load(); emit groupCollectionChanged(); } void GroupsForm::createGroup() { if (!groupDialog) groupDialog = new GroupDialog(this); groupDialog->init(Group::createGroup()); if (groupDialog->exec() == QDialog::Accepted) { auto newGroup = groupDialog->result(); QListWidgetItem* item = new QListWidgetItem(newGroup.name, ui->listWidget); item->setData(Qt::UserRole, newGroup.id); addGroup(newGroup); emit groupAdded(newGroup.id); } } void GroupsForm::editGroupInRow(int row) { if (!groupDialog) groupDialog = new GroupDialog(this); auto item = ui->listWidget->item(row); const auto& group = getGroup(item->data(Qt::UserRole).toUuid()); groupDialog->init(group); if (groupDialog->exec() == QDialog::Accepted) { auto newGroup = groupDialog->result(); item->setText(newGroup.name); addGroup(newGroup); emit groupCollectionChanged(); } } void GroupsForm::on_addButton_clicked() { createGroup(); } void GroupsForm::on_editButton_clicked() { editGroupInRow(ui->listWidget->selectionModel()->selectedRows()[0].row()); } void GroupsForm::on_removeButton_clicked() { int row = ui->listWidget->selectionModel()->selectedRows()[0].row(); auto item = ui->listWidget->item(row); removeGroup(item->data(Qt::UserRole).toUuid()); delete item; ui->listWidget->selectionModel()->clear(); emit groupCollectionChanged(); } void GroupsForm::on_listWidget_doubleClicked(const QModelIndex &index) { editGroupInRow(index.row()); } void GroupsForm::on_listWidget_itemSelectionChanged() { bool isRowSelected = ui->listWidget->selectionModel()->selectedRows().size() == 1; ui->editButton->setEnabled(isRowSelected); ui->removeButton->setEnabled(isRowSelected); }
25.578947
86
0.671605
TheMrButcher
f46e2fffcd01d3db771283a05a6a14e9cb327b97
432
cpp
C++
ArkEngineTest/ArkEngineTest.cpp
gamedevboy/ArkEngine
1fb1fb153ac73fcbfa75f8e02eb5a26e8993ff01
[ "MIT" ]
null
null
null
ArkEngineTest/ArkEngineTest.cpp
gamedevboy/ArkEngine
1fb1fb153ac73fcbfa75f8e02eb5a26e8993ff01
[ "MIT" ]
null
null
null
ArkEngineTest/ArkEngineTest.cpp
gamedevboy/ArkEngine
1fb1fb153ac73fcbfa75f8e02eb5a26e8993ff01
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CppUnitTest.h" #include "../ArkEngine/include/ArkEngine/AEModuleManager.h" #include "../ArkEngine/include/ArkEngine/gfx/AEGFXDevice.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace ArkEngineTest { TEST_CLASS(ArkEngineTest) { public: TEST_METHOD(ModuleTest) { ArkEngine::GFX::AEGFXDevice device; ArkEngine::AEModuleManager::Get()->Initialize(); } }; }
19.636364
62
0.743056
gamedevboy
f472b7a520d86afbd6c1e38b9fa9230bfe2880da
3,156
cpp
C++
day11/day11.cpp
throx/advent2020
071dee09e6bb2596c3f78c19f9c97d076798c8b3
[ "Unlicense" ]
null
null
null
day11/day11.cpp
throx/advent2020
071dee09e6bb2596c3f78c19f9c97d076798c8b3
[ "Unlicense" ]
null
null
null
day11/day11.cpp
throx/advent2020
071dee09e6bb2596c3f78c19f9c97d076798c8b3
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <numeric> using namespace std; int NumOcc(const vector<string>& seats, int x, int y) { int maxx = seats[0].length(); int maxy = seats.size(); int numocc = 0; for (int x1 = max(0, x - 1); x1 < min(maxx, x + 2); ++x1) { for (int y1 = max(0, y - 1); y1 < min(maxy, y + 2); ++y1) { if (x != x1 || y != y1) { if (seats[y1][x1] == '#') { ++numocc; } } } } return numocc; } int NumOccSeen(const vector<string>& seats, int x, int y) { int maxx = seats[0].length(); int maxy = seats.size(); int numocc = 0; for (int dx = -1; dx <= 1; ++dx) { for (int dy = -1; dy <= 1; ++dy) { if (dx != 0 || dy != 0) { int x1 = x + dx; int y1 = y + dy; while (x1 >= 0 && x1 < maxx && y1 >= 0 && y1 < maxy) { if (seats[y1][x1] == '#') { ++numocc; break; } else if (seats[y1][x1] == 'L') { break; } x1 += dx; y1 += dy; } } } } return numocc; } void DoRound(vector<string>& seats, int maxocc = 4, int occfn(const vector<string>&, int, int) = NumOcc) { int maxx = seats[0].length(); int maxy = seats.size(); vector<string> newseats; for (int y = 0; y < maxy; ++y) { string s; for (int x = 0; x < maxx; ++x) { if (seats[y][x] != '.') { int n = occfn(seats, x, y); if (n == 0) { s.push_back('#'); } else if (n >= maxocc) { s.push_back('L'); } else { s.push_back(seats[y][x]); } } else { s.push_back('.'); } } newseats.push_back(s); } seats = newseats; } void Dump(const vector<string>& seats) { for (auto v : seats) { cout << v << endl; } cout << endl; } int Occupancy(const vector<string>& seats) { int occ = 0; for (auto s : seats) { for (auto c : s) { if (c == '#') ++occ; } } return occ; } int main() { vector<string> seats; string s; while (getline(cin, s)) { seats.push_back(s); } auto base = seats; vector<string> prev; int rounds = 0; while (prev != seats) { prev = seats; DoRound(seats); ++rounds; //Dump(seats); } cout << "Rounds to stable = " << rounds - 1 << endl; cout << "Occupancy = " << Occupancy(seats) << endl << endl; seats = base; rounds = 0; while (prev != seats) { prev = seats; DoRound(seats, 5, NumOccSeen); ++rounds; //Dump(seats); } cout << "Rounds to stable = " << rounds - 1 << endl; cout << "Occupancy = " << Occupancy(seats) << endl; }
21.616438
104
0.398289
throx
f47e2107c702f649175447aec68f6acf7eaff645
254
hpp
C++
pythran/pythonic/include/operator_/__itruediv__.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/operator_/__itruediv__.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/operator_/__itruediv__.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_OPERATOR_ITRUEDIV__HPP #define PYTHONIC_INCLUDE_OPERATOR_ITRUEDIV__HPP #include "pythonic/include/operator_/itruediv.hpp" namespace pythonic { namespace operator_ { USING_FUNCTOR(__itruediv__, itruediv); } } #endif
15.875
50
0.807087
xmar
f4858b21356f076b7544d53c05055b358c718911
3,229
hpp
C++
src/Zv8/V8Engine.hpp
indie-zen/zen-server
deb4485fe462d6c88eeeadb09c62e6024e06ff67
[ "MIT" ]
null
null
null
src/Zv8/V8Engine.hpp
indie-zen/zen-server
deb4485fe462d6c88eeeadb09c62e6024e06ff67
[ "MIT" ]
8
2016-12-06T15:55:28.000Z
2016-12-18T17:31:36.000Z
src/Zv8/V8Engine.hpp
indie-zen/zen-server
deb4485fe462d6c88eeeadb09c62e6024e06ff67
[ "MIT" ]
null
null
null
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // V8 plugin for Zen Scripting // // Copyright (C) 2001 - 2016 Raymond A. Richards //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #pragma once #include <Zen/Scripting/I_ScriptEngine.hpp> #include <memory> #include <v8.h> //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ namespace Zen { namespace Zv8 { //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ class V8Engine : public Zen::Scripting::I_ScriptEngine , public std::enable_shared_from_this<V8Engine> { /// @name I_ScriptEngine implementation /// @{ public: virtual void initialize(pConfiguration_type _pConfiguration = nullptr); virtual Scripting::I_ObjectHeap& heap(); virtual bool executeScript(const std::string& _fileName); virtual void executeMethod(boost::any& _object, boost::any& _method, std::vector<boost::any>& _parms); virtual pScriptModule_type createScriptModule(const std::string& _moduleName, const std::string& _docString); /// @} /// @name V8Engine implementation /// @{ public: /// Implementation of managed_self_ref from Zen 1.x std::shared_ptr<V8Engine> getSelfReference(); /// Execute a script that is embedded in a string /// @param _source - String to execute /// @param _name - Name of the string (usually the URI where the string /// was loaded from) /// @param _printResult - output the results of the script to std::cout /// @param _reportExceptions - output an exception report if the script throws /// an uncaught exception. bool executeString(v8::Local<v8::String> _source, v8::Local<v8::Value> _name, bool _printResult, bool _reportExecptions); /// Read a file into a (maybe local) string /// @todo Zen Server should not support direct file access; instead, all /// source must be loaded from a container local segment of Zen Spaces. /// This is only being supported as a temporary measure until Zen Spaces /// integration is complete. v8::MaybeLocal<v8::String> readFile(const std::string& _scriptName); /// Report an exception /// Output an exception to std::cout (maybe it should be std::cerr?) void reportException(v8::TryCatch* _pTryCatch); /// Convert a v8 string to a C string const char* toCString(const v8::String::Utf8Value& value); v8::Isolate* getIsolate(); /// @} /// @name 'Structors /// @{ public: V8Engine(); virtual ~V8Engine(); /// @} /// @name Member variables /// @{ private: v8::Platform* m_pPlatform; v8::Isolate* m_pIsolate; v8::Isolate::Scope* m_pGlobalScope; v8::HandleScope* m_pHandleScope; // v8::Global<v8::ObjectTemplate> m_global; v8::Global<v8::Context> m_context; /// @} }; // class V8Engine //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ } // namespace Zv8 } // namespace Zen //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
35.483516
113
0.549396
indie-zen
f498dc62d5bebae3e8bd7c1efbc82658400f67d4
2,051
cpp
C++
Semester1/Homeworks/HW7.Lists/7.3/7.3/list.cpp
PavelSaltykov/Course1
68920c4a4679b6dd0e0b83cb8109d3c52d2cf076
[ "Apache-2.0" ]
null
null
null
Semester1/Homeworks/HW7.Lists/7.3/7.3/list.cpp
PavelSaltykov/Course1
68920c4a4679b6dd0e0b83cb8109d3c52d2cf076
[ "Apache-2.0" ]
2
2019-12-17T11:58:46.000Z
2019-12-21T20:08:01.000Z
Semester1/Homeworks/HW7.Lists/7.3/7.3/list.cpp
PavelSaltykov/Course1
68920c4a4679b6dd0e0b83cb8109d3c52d2cf076
[ "Apache-2.0" ]
1
2020-02-24T18:28:00.000Z
2020-02-24T18:28:00.000Z
#include <stdio.h> #include <string.h> #include "list.h" struct Entry { char *name = nullptr; char *phone = nullptr; Entry *next = nullptr; }; struct List { int length = 0; Entry *head = nullptr; Entry *tail = nullptr; }; List *createList() { return new List; } bool isEmpty(List *list) { return list->head == nullptr; } void addEntry(List *list, char *name, char *phone) { list->length++; char *newName = new char[strlen(name) + 1]; char *newPhone = new char[strlen(phone) + 1]; strcpy(newName, name); strcpy(newPhone, phone); Entry *newEntry = new Entry {newName, newPhone, nullptr}; if (isEmpty(list)) { list->head = newEntry; list->tail = list->head; return; } list->tail->next = newEntry; list->tail = list->tail->next; } char *returnNameFromHead(List *list) { return list->head->name; } char *returnPhoneFromHead(List *list) { return list->head->phone; } int listLength(List *list) { return list->length; } void deleteHead(List *list) { if (isEmpty(list)) { return; } list->length--; Entry *temp = list->head->next; delete list->head->name; delete list->head->phone; delete list->head; list->head = temp; } bool checkSort(List *list, bool byName) { if (isEmpty(list)) { return true; } Entry *current = list->head->next; Entry *previous = list->head; while (current != nullptr) { int comparison = 0; if (byName) { comparison = strcmp(current->name, previous->name); } else { comparison = strcmp(current->phone, previous->phone); } if (comparison < 0) { return false; } previous = current; current = current->next; } return true; } void printList(List *list) { if (isEmpty(list)) { return; } Entry *current = list->head; while (current != nullptr) { printf("%s - %s\n", current->name, current->phone); current = current->next; } } void deleteList(List *list) { while (!isEmpty(list)) { Entry *temp = list->head->next; delete list->head->name; delete list->head->phone; delete list->head; list->head = temp; } delete list; }
15.537879
58
0.641151
PavelSaltykov
f4ab84cd87a1853294e48fc98a7110a2fd1a11f9
6,507
hpp
C++
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_StdClass.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_StdClass.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_StdClass.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDMacroEng_StdClass.hpp // // AUTHOR: Dean Roddey // // CREATED: 01/24/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header file for the CIDMacroEng_StdClass.cpp file, which // implements derivates of the class info and class value classes that are // used by the compiler for compiled macros from user code. These classes // are all the same except for the classpath of the class. The members of // such a class are all dynamically controlled and added as method, var, // import, and so forth objects. The invocation is just a passthrough to // the targeted method object. // // The value class is just a dummy, since we don't need any actual C++ // level data members, but we must have an instance data class. At some // point, it might be used to keep some housekeeping, instrumentation, or // debugging info. The macro level member objects are handled by the common // base value class. Any classes which only need macro level members objects // can use this class for their value object, which is all macro level // defined classes, but also any wrapped C++ classes which store their // data as standard macro level value objects (and they all should if they // can.) // // Copying to and from involves copying the contents of each defined // variable for that class. We initially set the class as copyable, but // if any non-coypable member is added, it becomes non-copyable. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) class TMEngStdClassInfo; // --------------------------------------------------------------------------- // CLASS: TMEngStdClassVal // PREFIX: mecv // --------------------------------------------------------------------------- class CIDMACROENGEXP TMEngStdClassVal : public TMEngClassVal { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TMEngStdClassVal ( const TString& strName , const tCIDLib::TCard2 c2ClassId , const tCIDMacroEng::EConstTypes eConst ); TMEngStdClassVal(const TMEngStdClassVal&) = delete; ~TMEngStdClassVal(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TMEngStdClassVal& operator=(const TMEngStdClassVal&) = delete; // ------------------------------------------------------------------- // Public, inherited methods // ------------------------------------------------------------------- tCIDLib::TBoolean bDbgFormat ( TTextOutStream& strmTarget , const TMEngClassInfo& meciThis , const tCIDMacroEng::EDbgFmts eFormat , const tCIDLib::ERadices eRadix , const TCIDMacroEngine& meOwner ) const override; tCIDLib::TVoid CopyFrom ( const TMEngClassVal& mecvToCopy , TCIDMacroEngine& meOwner ) override; protected : // ------------------------------------------------------------------- // Declare our friends. We want our info class to be our friend so // that, when he creates a new instance, he can load us up with // value objects for our members. // ------------------------------------------------------------------- friend class TMEngStdClassInfo; private : // ------------------------------------------------------------------- // Do any needed magic macros // ------------------------------------------------------------------- RTTIDefs(TMEngStdClassVal,TMEngClassVal) }; // --------------------------------------------------------------------------- // CLASS: TMEngStdClassInfo // PREFIX: meci // --------------------------------------------------------------------------- class CIDMACROENGEXP TMEngStdClassInfo : public TMEngClassInfo { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TMEngStdClassInfo ( const TString& strName , const TString& strBasePath , TCIDMacroEngine& meOwner , const TString& strParentClassPath ); TMEngStdClassInfo(const TMEngStdClassInfo&) = delete; ~TMEngStdClassInfo(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TMEngStdClassInfo& operator=(const TMEngStdClassInfo&) = delete; // ------------------------------------------------------------------- // Public, inherited methods // ------------------------------------------------------------------- TMEngClassVal* pmecvMakeStorage ( const TString& strName , TCIDMacroEngine& meOwner , const tCIDMacroEng::EConstTypes eConst ) const override; protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TBoolean bInvokeMethod ( TCIDMacroEngine& meOwner , const TMEngMethodInfo& methiTarget , TMEngClassVal& mecvInstance ) override; private : // ------------------------------------------------------------------- // Do any needed magic macros // ------------------------------------------------------------------- RTTIDefs(TMEngStdClassInfo,TMEngClassInfo) }; #pragma CIDLIB_POPPACK
35.950276
78
0.442908
MarkStega
f4ac64b514f7a6a1259d2da3562e3034220407b8
16,221
cc
C++
swap-ssdb-1.9.2/tests/qa/integration/hash_test.cc
TimothyZhang023/swapdb
e40c1ddf46892e698acf54f26b02927f0505ea84
[ "BSD-2-Clause" ]
242
2017-12-14T00:31:28.000Z
2022-02-16T02:00:15.000Z
swap-ssdb-1.9.2/tests/qa/integration/hash_test.cc
javaperson/swapdb
66efd9f919dfaa56dcefd9b39a8bdabe57624546
[ "BSD-2-Clause" ]
7
2017-12-14T08:34:43.000Z
2020-12-19T02:53:03.000Z
swap-ssdb-1.9.2/tests/qa/integration/hash_test.cc
javaperson/swapdb
66efd9f919dfaa56dcefd9b39a8bdabe57624546
[ "BSD-2-Clause" ]
47
2017-12-26T03:11:26.000Z
2022-01-26T07:46:45.000Z
#include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <sstream> #include "SSDB_client.h" #include "gtest/gtest.h" #include "ssdb_test.h" using namespace std; class HashTest : public SSDBTest { public: ssdb::Status s; std::vector<std::string> list, keys, kvs2; std::map<std::string, std::string> kvs; string key, val, getVal, field; uint16_t keysNum; int64_t ret; }; TEST_F(HashTest, Test_hash_hset) { #define OKHset s = client->hset(key, field, val);\ ASSERT_TRUE(s.ok())<<"fail to hset key!"<<endl;\ s = client->hget(key, field, &getVal);\ ASSERT_TRUE(s.ok()&&(val == getVal))<<"fail to hget key val!"<<s.code()<<key<<endl; #define FalseHset s = client->hset(key, field, val);\ ASSERT_TRUE(s.error())<<"this key should set fail!"<<s.code()<<endl; // Some special keys for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++) { key = *it; field = GetRandomField_(); val = GetRandomVal_(); s = client->multi_del(key); OKHset // set exsit key field = GetRandomField_(); val = GetRandomVal_(); OKHset s = client->multi_del(key); } // Some random keys keysNum = 100; val = ""; key = GetRandomKey_(); field = GetRandomField_(); s = client->multi_del(key); for(int n = 0; n < keysNum; n++) { field = field+itoa(n); OKHset } s = client->hsize(key, &ret); ASSERT_EQ(keysNum, ret); s = client->multi_del(key); //other types key field = GetRandomField_(); val = GetRandomVal_(); client->multi_del(key); s = client->set(key, val); FalseHset client->multi_del(key); client->sadd(key, val); FalseHset client->multi_del(key); client->qpush_front(key, val); FalseHset client->multi_del(key); client->zset(key, field, 1.0); FalseHset client->multi_del(key); } TEST_F(HashTest, Test_hash_hget) { #define NotFoundHget s = client->hget(key, field, &getVal);\ ASSERT_TRUE(s.not_found())<<"this key should be not found!"<<endl; // Some random keys for(int n = 0; n < 5; n++) { key = GetRandomKey_(); val = GetRandomVal_(); field = GetRandomField_(); s = client->multi_del(key); NotFoundHget } keysNum = 100; for(int n = 0; n < keysNum; n++) { field = field+itoa(n); s = client->hset(key, field, val); } field = field+itoa(keysNum); NotFoundHget s = client->multi_del(key); } TEST_F(HashTest, Test_hash_hdel) { #define OKHdel s = client->multi_hdel(key, field);\ ASSERT_TRUE(s.ok())<<"fail to delete key!"<<key<<endl;\ s = client->hget(key, field, &getVal);\ ASSERT_TRUE(s.not_found())<<"this key should be deleted!"<<key<<endl; #define NotFoundHdel s = client->multi_hdel(key, field);\ ASSERT_TRUE(s.not_found())<<"this key should be not found!"<<endl; //Some special keys for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++) { key = *it; client->multi_del(key); val = GetRandomVal_(); field = GetRandomField_(); s = client->hset(key, field, val); OKHdel // NotFoundHdel } keysNum = 100; val = ""; for(int n = 0; n < keysNum; n++) { field = field+itoa(n); s = client->hset(key, field, val); OKHdel // NotFoundHdel } } TEST_F(HashTest, Test_hash_hincrby) { #define OKHincr incr = GetRandomInt64_();\ s = client->multi_del(key);\ s = client->hincr(key, field, incr, &ret);\ ASSERT_TRUE(s.ok());\ s = client->hget(key, field, &getVal);\ ASSERT_EQ(to_string(incr), getVal);\ \ s = client->hincr(key, field, n, &ret);\ ASSERT_TRUE(s.ok());\ s = client->hget(key, field, &getVal);\ ASSERT_EQ(to_string(incr+n), getVal);\ s = client->multi_hdel(key, field); #define FalseHincr s = client->hincr(key, field, 1, &ret);\ ASSERT_TRUE(s.error())<<"this key should hincr fail!"<<endl; int64_t incr, ret, n = 0; //Some special keys for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++) { n++; key = *it; field = GetRandomField_(); OKHincr client->multi_del(key); } //Some random keys keysNum = 10; val = ""; for(n = 0; n < keysNum; n++) { key = GetRandomKey_(); field = GetRandomField_(); OKHincr client->multi_del(key); } s = client->multi_del(key); s = client->hincr(key, field, MAX_INT64, &ret); s = client->hget(key, field, &getVal); ASSERT_EQ(i64toa(MAX_INT64), getVal); s = client->hincr(key, field, 1, &ret); ASSERT_TRUE(s.error()); s = client->hget(key, field, &getVal); ASSERT_EQ(i64toa(MAX_INT64), getVal); s = client->multi_del(key); s = client->hincr(key, field, MIN_INT64, &ret); ASSERT_EQ((MIN_INT64), ret); s = client->hget(key, field, &getVal); ASSERT_EQ(i64toa(MIN_INT64), getVal); s = client->hincr(key, field, -1, &ret); ASSERT_TRUE(s.error()); s = client->hget(key, field, &getVal); ASSERT_EQ(i64toa(MIN_INT64), getVal); s = client->multi_hdel(key, field); //other types key field = GetRandomField_(); val = GetRandomVal_(); client->multi_del(key); s = client->set(key, val); FalseHincr client->multi_del(key); client->sadd(key, val); FalseHincr client->multi_del(key); client->qpush_front(key, val); FalseHincr client->multi_del(key); client->zset(key, field, 1.0); FalseHincr client->multi_del(key); } //hdecr removed //TEST_F(HashTest, Test_hash_hdecrby) { //#define OKHdecr decr = GetRandomInt64_();\ // s = client->multi_del(key);\ // s = client->hdecr(key, field, decr, &ret);\ // ASSERT_TRUE(s.ok());\ // s = client->hget(key, field, &getVal);\ // ASSERT_EQ(to_string(-1*decr), getVal);\ // \ // s = client->hdecr(key, field, n, &ret);\ // ASSERT_TRUE(s.ok());\ // s = client->hget(key, field, &getVal);\ // ASSERT_EQ(to_string(-1*(decr+n)), getVal);\ // s = client->multi_hdel(key, field); // // int64_t decr, ret, n = 0; // //Some special keys // for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++) // { // n++; // key = *it; // field = GetRandomField_(); // OKHdecr // client->multi_del(key); // } //} TEST_F(HashTest, Test_hash_hgetall) { #define NotExsitHgetall s = client->hgetall(key, &list);\ ASSERT_TRUE(s.ok());\ ASSERT_EQ(0, list.size())<<"get list should be empty!"<<endl; // EXPECT_TRUE(s.not_found())<<"this key should be not found!"<<endl; key = GetRandomKey_(); val = GetRandomVal_(); field = GetRandomField_(); s = client->multi_del(key); NotExsitHgetall keysNum = 10; for(int n = 0; n < keysNum; n++) { field = field+itoa(n); val = val+itoa(n); kvs.insert(std::make_pair(field, val)); s = client->hset(key, field, val); } s = client->hgetall(key, &list); for(int n = 0; n < keysNum; n += 2) { EXPECT_EQ(kvs[list[n]], list[n+1]); } s = client->multi_del(key); } TEST_F(HashTest, Test_hash_hsize) { #define OKHsize(num) s = client->hsize(key, &ret);\ ASSERT_EQ(ret, num)<<"fail to hsize key!"<<key<<endl;\ ASSERT_TRUE(s.ok())<<"hsize key not ok!"<<endl; // Some special keys for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++) { key = *it; field = GetRandomField_(); val = GetRandomVal_(); s = client->multi_del(key); OKHsize(0) s = client->hset(key, field, val); OKHsize(1) s = client->multi_hdel(key, field); } key = GetRandomKey_(); field = GetRandomField_(); val = GetRandomVal_(); s = client->multi_del(key); for(int n = 0; n < 10; n++) { field = field+itoa(n); val = val+itoa(n); client->hset(key, field, val); OKHsize(n+1) } s = client->multi_del(key); } //use del instead of hclear,and hclear cannot clear 100 elements hash key now. /* TEST_F(HashTest, Test_hash_hclear) { #define OKHclear(num) s = client->hclear(key, &ret);\ ASSERT_EQ(ret , num)<<"fail to hclear key!"<<key<<endl;\ s = client->hsize(key, &ret);\ ASSERT_EQ(ret, 0)<<"key is not null!"<<key<<endl; // Some special keys for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++) { key = *it; field = GetRandomField_(); val = GetRandomVal_(); s = client->multi_del(key); OKHclear(0) s = client->hset(key, field, val); OKHclear(1) } key = GetRandomKey_(); field = GetRandomField_(); val = GetRandomVal_(); s = client->multi_del(key); for(int n = 0; n < 100; n++) { field = field+itoa(n); val = val+itoa(n); client->hset(key, field, val); } OKHclear(100) } */ TEST_F(HashTest, Test_hash_hkeys) { key = GetRandomKey_(); s = client->hkeys(key, "", "", 5, &list); ASSERT_TRUE(s.ok() && list.size() == 0); list.clear(); client->hset(key, "000000001",""); client->hset(key, "000000002",""); client->hset(key, "000000003",""); //TODO HKEYS command changed s = client->hkeys(key, "000000000", "000000002", 5, &list); ASSERT_TRUE(s.ok() && list.size() == 3); ASSERT_EQ("000000001", list[0]); ASSERT_EQ("000000002", list[1]); list.clear(); s = client->hkeys(key, "000000000", "000000003", 5, &list); ASSERT_TRUE(s.ok() && list.size() == 3); ASSERT_EQ("000000003", list[2]); list.clear(); s = client->hkeys(key, "000000000", "000000003", 2, &list); ASSERT_TRUE(s.ok() && list.size() == 3); s = client->multi_del(key); } TEST_F(HashTest, DISABLED_Test_hash_hscan) { key = GetRandomKey_(); s = client->hscan(key, "", "", 2, &list); ASSERT_TRUE(s.ok() && list.size() <= 4); list.clear(); client->multi_del("key"); client->hset("key", "00000000f1","v1"); client->hset("key", "00000000f2","v2"); s = client->hscan("key", "00000000f0", "00000000f2", 2, &list); ASSERT_TRUE(s.ok() && list.size() == 4); ASSERT_EQ("00000000f1", list[0]); ASSERT_EQ("v1", list[1]); ASSERT_EQ("00000000f2", list[2]); ASSERT_EQ("v2", list[3]); list.clear(); s = client->hscan("key", "00000000f2", "00000000f0", 2, &list); ASSERT_EQ(0, list.size()); s = client->multi_del("key"); s = client->hscan("key", "00000000f0", "00000000f2", 2, &list); ASSERT_EQ(0, list.size()); } //remove hrscan /* TEST_F(HashTest, Test_hash_hrscan) { key = GetRandomKey_(); s = client->hrscan(key, "", "", 2, &list); ASSERT_TRUE(s.ok() && list.size() <= 4); list.clear(); client->multi_del("key"); client->hset("key", "00000000f1","v1"); client->hset("key", "00000000f2","v2"); s = client->hrscan("key", "00000000f3", "00000000f1", 2, &list); ASSERT_TRUE(s.ok() && list.size() == 4); ASSERT_EQ("00000000f2", list[0]); ASSERT_EQ("v2", list[1]); ASSERT_EQ("00000000f1", list[2]); ASSERT_EQ("v1", list[3]); list.clear(); s = client->hrscan("key", "00000000f1", "00000000f3", 2, &list); ASSERT_EQ(0, list.size()); s = client->multi_del("key"); s = client->hrscan("key", "00000000f3", "00000000f1", 2, &list); ASSERT_EQ(0, list.size()); } */ TEST_F(HashTest, Test_hash_hmset_hmget_hdel) { //Redis hmset/hmget/hdel string key, field1, field2, field3, val1, val2, val3; key = GetRandomKey_(); field1 = GetRandomField_(); field2 = field1+'2'; field3 = field1+'3'; val1 = GetRandomVal_(); val2 = val1+'2'; val3 = val1+'3'; kvs.clear(); keys.clear(); list.clear(); kvs.insert(std::make_pair(field1, val1)); kvs.insert(std::make_pair(field2, val2)); keys.push_back(field1); keys.push_back(field2); keys.push_back(field3); //all keys not exist s = client->multi_hdel(key, keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(0, ret); s = client->multi_hget(key, keys, &list); ASSERT_EQ(0, list.size()); s = client->multi_hset(key, kvs); ASSERT_TRUE(s.ok()); s = client->multi_hget(key, keys, &list); ASSERT_EQ(4, list.size()); ASSERT_EQ(field1, list[0]); ASSERT_EQ(val1, list[1]); ASSERT_EQ(field2, list[2]); ASSERT_EQ(val2, list[3]); kvs.insert(std::make_pair(field3, val3)); //one key not exist, two keys exist s = client->multi_hset(key, kvs); ASSERT_TRUE(s.ok()); list.clear(); s = client->multi_hget(key, keys, &list); ASSERT_EQ(6, list.size()); kvs.clear(); val1 = val1+'1'; val2 = val2+'2'; val3 = val3+'3'; kvs.insert(std::make_pair(field1, val1)); kvs.insert(std::make_pair(field2, val2)); kvs.insert(std::make_pair(field3, val3)); //all keys exist, update their vals s = client->multi_hset(key, kvs); ASSERT_TRUE(s.ok()); list.clear(); s = client->multi_hget(key, keys, &list); ASSERT_EQ(6, list.size()); ASSERT_EQ(field1, list[0]); ASSERT_EQ(val1, list[1]); ASSERT_EQ(field2, list[2]); ASSERT_EQ(val2, list[3]); ASSERT_EQ(field3, list[4]); ASSERT_EQ(val3, list[5]); s = client->multi_hdel(key, keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); list.clear(); s = client->multi_hget(key, keys, &list); ASSERT_EQ(0, list.size()); kvs.clear(); list.clear(); keys.clear(); int fieldNum = 10; for(int n = 0; n < fieldNum; n++) { kvs.insert(std::make_pair(field1 + itoa(n), val1 + itoa(n))); keys.push_back(field1 + itoa(n)); } s = client->multi_hset(key, kvs); ASSERT_TRUE(s.ok()); s = client->multi_hget(key, keys, &list); ASSERT_EQ(fieldNum*2, list.size()); for(int n = 0; n < fieldNum; n++) { ASSERT_EQ(field1 + itoa(n), list[n*2]); ASSERT_EQ(val1 + itoa(n), list[n*2+1]); } s = client->multi_hdel(key, keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(fieldNum, ret); list.clear(); s = client->multi_hget(key, keys, &list); ASSERT_EQ(0, list.size()); client->sadd(key, "val"); s = client->multi_hdel(key, keys, &ret); ASSERT_TRUE(s.error()); s = client->multi_hget(key, keys, &list); ASSERT_TRUE(s.error()); s = client->multi_hset(key, kvs); ASSERT_TRUE(s.error()); client->multi_del(key); } TEST_F(HashTest, Test_hash_samefields_hmset_hmget_hdel) { //simulate process same fields at one time. key = "hkey"; field = "hfield_"; val = "hval_"; keysNum = 1; kvs2.clear(); keys.clear(); for(int m = 0;m < 2;m++){ for(int n = 0;n < keysNum;n++) { keys.push_back(field+itoa(n)); kvs2.push_back(field+itoa(n)); kvs2.push_back(val+itoa(n)); } } //all keys not exist client->multi_del(key); s = client->multi_hdel(key, keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(0, ret); list.clear(); s = client->multi_hget(key, keys, &list); ASSERT_EQ(0, list.size()); //same field same value hmset s = client->multi_hset(key, kvs2); ASSERT_TRUE(s.ok()); s = client->multi_hget(key, keys, &list); ASSERT_EQ(keys.size()*2, list.size()); for(int n = 0;n < 2*keysNum;n++) { ASSERT_EQ(field+itoa(n%keysNum), list[2*n]); ASSERT_EQ(val+itoa(n%keysNum), list[2*n+1]); } //same key diff value mset for(int n = 0;n < keysNum;n++) { keys.push_back(field+itoa(n)); kvs2.push_back(field+itoa(n)); kvs2.push_back(val+itoa(n*2)); } s = client->multi_hset(key, kvs2); ASSERT_TRUE(s.ok()); list.clear(); s = client->multi_hget(key, keys, &list); ASSERT_EQ(keys.size()*2, list.size()); for(int n = 0;n < 3*keysNum;n++) { ASSERT_EQ(field+itoa(n%keysNum), list[2*n]); ASSERT_EQ(val+itoa(n%keysNum*2), list[2*n+1]); } client->multi_hdel(key, keys, &ret); ASSERT_EQ(keysNum, ret); }
28.308901
87
0.573208
TimothyZhang023
f4acf5c25709d692fda58cf417492ad69f05621d
3,227
cpp
C++
src/HandGunC.cpp
pablojor/mood
779af33ae3fc596c1749901917f67c0d8a14d63f
[ "MIT" ]
null
null
null
src/HandGunC.cpp
pablojor/mood
779af33ae3fc596c1749901917f67c0d8a14d63f
[ "MIT" ]
2
2020-04-12T14:01:00.000Z
2020-05-20T12:53:11.000Z
src/HandGunC.cpp
NoVariableGlobal/mood
e3446857a1d309dfac71beaf6407bb905f02a912
[ "MIT" ]
1
2020-10-07T15:09:45.000Z
2020-10-07T15:09:45.000Z
#include "HandGunC.h" #include "BulletC.h" #include "ComponentsManager.h" #include "Entity.h" #include "FactoriesFactory.h" #include "Ogre.h" #include "OgreQuaternion.h" #include "RigidbodyPC.h" #include "Scene.h" #include "TransformComponent.h" #include <json.h> void HandGunC::onShoot(TransformComponent* transform, RigidbodyPC* rigidBody) { Ogre::Quaternion quat = getOrientation(); transform->setPosition(myTransform_->getPosition() + (quat * Ogre::Vector3::UNIT_Y) * 25 + (quat * Ogre::Vector3::UNIT_Z) * 10); transform->setOrientation(myTransform_->getOrientation()); rigidBody->setLinearVelocity((quat * Ogre::Vector3::UNIT_Z) * bulletSpeed_); GunC::onShoot(transform, rigidBody); } // FACTORY INFRASTRUCTURE HandGunCFactory::HandGunCFactory() = default; Component* HandGunCFactory::create(Entity* _father, Json::Value& _data, Scene* _scene) { HandGunC* hg = new HandGunC(); _scene->getComponentsManager()->addDC(hg); hg->setFather(_father); hg->setScene(_scene); hg->setSoundManager(); if (!_data["bulletTag"].isString()) throw std::exception("HandGunC: bulletTag is not a string"); hg->setBulletTag(_data["bulletTag"].asString()); if (!_data["bulletchamberMax"].isInt()) throw std::exception("HandGunC: bulletchamberMax is not an int"); hg->setbulletchamber(_data["bulletchamberMax"].asInt()); if (!_data["munition"].isInt()) throw std::exception("HandGunC: munition is not an int"); hg->setmunition(_data["munition"].asInt()); if (!_data["bulletDamage"].isDouble()) throw std::exception("HandGunC: bulletDamage is not a double"); hg->setbulletdamage(_data["bulletDamage"].asDouble()); if (!_data["bulletSpeed"].isDouble()) throw std::exception("HandGunC: bulletSpeed is not a double"); hg->setbulletspeed(_data["bulletSpeed"].asDouble()); if (!_data["cadence"].isDouble()) throw std::exception("HandGunC: cadence is not an int"); hg->setcadence(_data["cadence"].asFloat()); if (!_data["automatic"].isBool()) throw std::exception("HandGunC: semiautomatic is not an bool"); hg->setautomatic(_data["automatic"].asBool()); if (!_data["instakill"].isBool()) throw std::exception("HandGunC: instakill is not an bool"); hg->setInstakill(_data["instakill"].asBool()); if (_data["infiniteAmmo"].isBool()) hg->setInfiniteAmmo(_data["infiniteAmmo"].asBool()); if (!_data["bulletType"].isString()) throw std::exception("HandGunC: bulletType is not a string"); hg->setBulletType(_data["bulletType"].asString()); if (!_data["shotSound"].isString()) throw std::exception("HandGunC: shotSound is not a string"); hg->setShotSound(_data["shotSound"].asString()); if (!_data["bulletComponent"].isString()) throw std::exception("HandGunC: bulletComponent is not a string"); hg->setBulletComponentName(_data["bulletComponent"].asString()); hg->setTransform(reinterpret_cast<TransformComponent*>( _father->getComponent("TransformComponent"))); return hg; }; DEFINE_FACTORY(HandGunC);
35.076087
80
0.662845
pablojor
f4ad65e4c0e2b702c324528a34702eec26bceafb
6,137
cpp
C++
opt_kappa.cpp
dokyum/tiLDA
7dc3a2c8023bfc92b777fa9a2f50ace65209fccc
[ "Apache-2.0" ]
2
2016-01-21T02:40:42.000Z
2018-12-22T18:07:02.000Z
opt_kappa.cpp
vineelpratap/tiLDA
7dc3a2c8023bfc92b777fa9a2f50ace65209fccc
[ "Apache-2.0" ]
null
null
null
opt_kappa.cpp
vineelpratap/tiLDA
7dc3a2c8023bfc92b777fa9a2f50ace65209fccc
[ "Apache-2.0" ]
2
2015-02-13T20:53:34.000Z
2021-01-30T17:11:51.000Z
#include "opt_kappa.h" #define KAPPA_NEWTON_THRESH 1e-6 #define KAPPA_MAX_ITER 5000 #define LIKELIHOOD_DECREASE_ALLOWANCE 1e-5 extern double oneoverk; double opt_kappa(double* kappa, int ntopics, int nchildren, double* dirichlet_prior, double alpha, double tau, double* digamma_sum_over_children, int node_index) { double* g = NULL; double* h = NULL; double* delta_kappa = NULL; double* new_kappa = NULL; g = zero_init_double_array(ntopics); h = zero_init_double_array(ntopics); delta_kappa = zero_init_double_array(ntopics); new_kappa = zero_init_double_array(ntopics); for (int i = 0; i < ntopics; ++i) { kappa[i] = oneoverk; } #ifdef _DEBUG // printf("kappa opt start %d : nchildren %d \t alpha %5.15f \t tau %5.15f \n", // node_index, nchildren, alpha, tau); // for (int i = 0; i < ntopics; ++i) { // printf("kappa opt start %d %d : dirichlet_prior %5.15f \t kappa %5.15f \n", // node_index, i, dirichlet_prior[i], kappa[i]); // } #endif double invhsum = 0; double goverhsum = 0; double coefficient = 0; double old_likelihood = 0; // double likelihood = 0; double sqr_newton_decrement = 0; double step_size; double indep_new_likelihood = 0; double dep_new_likelihood = 0; double new_likelihood; double expected_increase; #ifdef _DEBUG double initial_likelihood; #endif int iter = 0; for (int i = 0; i < ntopics; ++i) { double const taukappai = tau * kappa[i]; double const alphakappai = alpha * kappa[i]; double const common = dirichlet_prior[i] + nchildren * (1 - alphakappai) - taukappai; double const digammataukappai = digamma(taukappai); double const logkappai = log(kappa[i]); dep_new_likelihood += digammataukappai * common; indep_new_likelihood -= nchildren * (lgamma(alphakappai) + (1 - alphakappai) * logkappai); indep_new_likelihood += alphakappai * digamma_sum_over_children[i]; dep_new_likelihood += lgamma(taukappai); } new_likelihood = indep_new_likelihood + dep_new_likelihood; #ifdef _DEBUG initial_likelihood = new_likelihood; #endif do { iter++; invhsum = 0; goverhsum = 0; coefficient = 0; for (int i = 0; i < ntopics; ++i) { double const taukappai = tau * kappa[i]; double const alphakappai = alpha * kappa[i]; double const common = dirichlet_prior[i] + nchildren * (1 - alphakappai) - taukappai; double const digammataukappai = digamma(taukappai); double const trigammataukappai = trigamma(taukappai); double const logkappai = log(kappa[i]); g[i] = tau * trigammataukappai * common - nchildren * alpha * (digamma(alphakappai) - logkappai + digammataukappai - 1) - nchildren / kappa[i] + alpha * digamma_sum_over_children[i]; h[i] = tau * tau * tetragamma(taukappai) * common - tau * trigammataukappai * (tau + 2 * alpha * nchildren) - alpha * alpha * trigamma(alphakappai) * nchildren + alpha * nchildren / kappa[i] + nchildren / (kappa[i] * kappa[i]); invhsum += 1 / h[i]; goverhsum += g[i] / h[i]; } old_likelihood = new_likelihood; coefficient = goverhsum / invhsum; sqr_newton_decrement = 0; expected_increase = 0; step_size = 1; for (int i = 0; i < ntopics; ++i) { delta_kappa[i] = (coefficient - g[i]) / h[i]; sqr_newton_decrement -= h[i] * delta_kappa[i] * delta_kappa[i]; // this one is maximization expected_increase += g[i] * delta_kappa[i]; //sqr_newton_decrement += g[i] * delta_kappa[i]; if (delta_kappa[i] < 0) { double limit = (kappa[i] - 1e-10) / -(delta_kappa[i]); if (step_size > limit) { step_size = limit; } } } #ifdef _DEBUG printf("kappa maximization %d : L %5.15f \t dL %5.15f \t indL %5.15f \t newton %5.15f \t %5.15f\n", node_index, old_likelihood, dep_new_likelihood, indep_new_likelihood, sqr_newton_decrement / 2, step_size); // for (int i = 0; i < ntopics; ++i) { // printf("kappa maximization %d %d: delta_kappa %5.15f \n", // node_index, i, delta_kappa[i]); // } #endif if (sqr_newton_decrement < KAPPA_NEWTON_THRESH * 2 || step_size < 1e-8 ) { break; } // backtracking line search while(1) { // double sum_new_kappa = 0.0; indep_new_likelihood = 0.0; dep_new_likelihood = 0.0; for (int i = 0; i < ntopics; ++i) { new_kappa[i] = kappa[i] + step_size * delta_kappa[i]; double const taukappai = tau * new_kappa[i]; double const alphakappai = alpha * new_kappa[i]; double const common = dirichlet_prior[i] + nchildren * (1 - alphakappai) - taukappai; double const logkappai = log(new_kappa[i]); dep_new_likelihood += digamma(taukappai) * common; indep_new_likelihood -= nchildren * (lgamma(alphakappai) + (1 - alphakappai) * logkappai); indep_new_likelihood += alphakappai * digamma_sum_over_children[i]; dep_new_likelihood += lgamma(taukappai); } new_likelihood = indep_new_likelihood + dep_new_likelihood; #ifdef _DEBUG printf("line search %d : nL: %5.15f \t bound: %5.15f \t step_size: %5.15f \n", node_index, new_likelihood, old_likelihood + 0.4 * step_size * expected_increase, step_size); #endif if (new_likelihood > old_likelihood + 0.4 * step_size * expected_increase) { // if (new_likelihood > old_likelihood + 0.4 * step_size * sqr_newton_decrement) { break; } step_size *= 0.9; if (step_size < 1e-8) break; } if (step_size < 1e-8) break; for (int i = 0; i < ntopics; ++i) { kappa[i] = new_kappa[i]; assert(!std::isnan(kappa[i])); assert(kappa[i] > 0); } } while (iter < KAPPA_MAX_ITER); if (iter >= KAPPA_MAX_ITER) { printf("KAPPA_MAX_ITER reached\n"); exit(-1); } #ifdef _DEBUG printf("%d TL %5.15f \t IL %5.15f \n", node_index, new_likelihood, initial_likelihood); assert(new_likelihood >= initial_likelihood || ( ((initial_likelihood - new_likelihood) / fabs(initial_likelihood) < LIKELIHOOD_DECREASE_ALLOWANCE) && (iter >= 3) ) ); #endif free(new_kappa); free(delta_kappa); free(g); free(h); return new_likelihood; }
31.311224
112
0.653577
dokyum
f4aef88cf32cde12ced412931608263def713ce6
1,686
cpp
C++
Utility/lib/src/utility/math_utils.cpp
tdenis8/S3DR
fb8f4c0c98b5571abb12a51e03229978115b099b
[ "MIT" ]
1
2019-07-10T04:25:45.000Z
2019-07-10T04:25:45.000Z
Utility/lib/src/utility/math_utils.cpp
tdenis8/S3DR
fb8f4c0c98b5571abb12a51e03229978115b099b
[ "MIT" ]
null
null
null
Utility/lib/src/utility/math_utils.cpp
tdenis8/S3DR
fb8f4c0c98b5571abb12a51e03229978115b099b
[ "MIT" ]
null
null
null
#include "math_utils.hpp" #include <cmath> glm::vec3 MeanPoint(const std::vector<glm::vec3> & points){ glm::vec3 result(0.0, 0.0, 0.0); auto size=points.size(); for(auto it=points.begin(); it<points.end(); ++it){ result += *it; } if(size>0){ result /= size; } return result; } float DegToRad(float angle_deg) { const float deg_to_rad = 3.14159f * 2.0f / 360.0f; return angle_deg * deg_to_rad; } bool IsNull(float value){ if(value < 0.000000001){ return true; } return false; } glm::vec3 CircleCenterFromCirclePoints(const std::vector<glm::vec3> & points){ if(points.size()!=3){ return glm::vec3(0.0, 0.0, 0.0); } const glm::vec3 & p1 = points[0]; const glm::vec3 & p2 = points[1]; const glm::vec3 & p3 = points[2]; auto tmp = glm::length(glm::cross(p1-p2, p2-p3)); if(IsNull(tmp)){ return glm::vec3(0.0, 0.0, 0.0); } auto k = 1/(2*tmp*tmp); tmp = glm::length(p2-p3); glm::vec3 a = (tmp*tmp) * glm::cross(p1-p2,p1-p3) * k; tmp = glm::length(p1-p3); glm::vec3 b = (tmp*tmp) * glm::cross(p2-p1,p2-p3) * k; tmp = glm::length(p1-p2); glm::vec3 c = (tmp*tmp) * glm::cross(p3-p1,p3-p2) * k; return a*p1 + b*p2 + c*p3; } float CircleRadiusFromCirclePoints(const std::vector<glm::vec3> & points){ if(points.size()!=3){ return 0.0;; } const glm::vec3 & p1 = points[0]; const glm::vec3 & p2 = points[1]; const glm::vec3 & p3 = points[2]; float tmp1 = glm::length(p1-p2) * glm::length(p2-p3) * glm::length(p3-p1); float tmp2 = 2 * glm::length(glm::cross(p1-p2, p2-p3)); if(IsNull(tmp2)){ return 0.0; } return tmp1/tmp2; }
21.896104
78
0.578885
tdenis8
f4b9f8ed45470d551028eb05368f1f2c8ae8d057
2,856
cpp
C++
naklibsrc/src/core/MessageHash/Base58EncDec.cpp
murphyj8/testNakStructure
fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a
[ "Unlicense" ]
1
2021-07-01T02:01:27.000Z
2021-07-01T02:01:27.000Z
naklibsrc/src/core/MessageHash/Base58EncDec.cpp
murphyj8/testNakStructure
fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a
[ "Unlicense" ]
1
2020-09-23T12:34:34.000Z
2020-09-23T12:34:34.000Z
naklibsrc/src/core/MessageHash/Base58EncDec.cpp
murphyj8/testNakStructure
fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a
[ "Unlicense" ]
null
null
null
#include "MessageHash/Base58EncDec.h" #include "MessageHash/Base58EncDecImpl.h" Base58EncDec::Base58EncDec() : m_pImpl(new Base58EncDecImpl){ return ; } Base58EncDec::~Base58EncDec(){ return ; } std::string Base58EncDec::encode (const std::vector<uint8_t>& vch){ return (m_pImpl->encode(vch)); } std::string Base58EncDec::encodeCheck (const std::vector<uint8_t>& vch){ return (m_pImpl->encodeCheck(vch)); } messageVec Base58EncDec::decode (const std::string& msg){ return (m_pImpl->decode(msg)); } messageVec Base58EncDec::decodeCheck(const std::string& msg){ return (m_pImpl->decodeCheck(msg)); } std::string EncodeBase58 (const std::string& msg) { std::vector<uint8_t> vec; for (std::string::const_iterator iter = msg.begin(); iter != msg.end(); ++ iter) { vec.push_back(*iter); } Base58EncDec encdec ; std::string encVal = encdec.encode (vec); return encVal ; } std::string DecodeBase58 (const std::string& msg) { std::string nonConstMsg ( msg ); nonConstMsg = nonConstMsg.erase(nonConstMsg.find_last_not_of("\t\n\v\f\r ")+1); std::unique_ptr<unsigned char[]> msgPtr ( new unsigned char [nonConstMsg.length()+1]); std::fill_n(msgPtr.get(), msg.length()+1, 0x00); std::string::const_iterator iter = nonConstMsg.begin(); for (unsigned int i = 0; i < nonConstMsg.size();++i) { msgPtr.get()[i] = *iter ; ++ iter ; } Base58EncDec encdec; std::vector<uint8_t> decodedVal = encdec.decode(nonConstMsg); std::string retVal; for(std::vector<uint8_t>::const_iterator iter = decodedVal.begin();iter != decodedVal.end(); ++ iter) { retVal.push_back(*iter); } return retVal ; } std::string EncodeBase58Checked (const std::string& msg) { std::vector<uint8_t> vec; for (std::string::const_iterator iter = msg.begin(); iter != msg.end(); ++ iter) { vec.push_back(*iter); } Base58EncDec encdec ; std::string encVal = encdec.encodeCheck (vec); return encVal ; } std::string DecodeBase58Checked (const std::string& msg) { std::string nonConstMsg ( msg ); nonConstMsg = nonConstMsg.erase(nonConstMsg.find_last_not_of("\t\n\v\f\r ")+1); std::unique_ptr<unsigned char> msgPtr ( new unsigned char [nonConstMsg.length()+1]); std::fill_n(msgPtr.get(), msg.length()+1, 0x00); std::string::const_iterator iter = nonConstMsg.begin(); for (unsigned int i = 0; i < nonConstMsg.size();++i) { msgPtr.get()[i] = *iter ; ++ iter ; } Base58EncDec encdec; std::vector<uint8_t> decodedVal = encdec.decodeCheck(nonConstMsg); std::string retVal; for(std::vector<uint8_t>::const_iterator iter = decodedVal.begin();iter != decodedVal.end(); ++ iter) { retVal.push_back(*iter); } return retVal ; }
30.382979
105
0.644258
murphyj8
f4bafce0eb4329174202ea4c22b8e6b84b9afafe
94,230
cpp
C++
src/raven_src/src/StandardOutput.cpp
Okanagan-Basin-Water-Board/obwb-hydro-modelling
91ee6b914e344de65a495093c3b9427986182ef2
[ "Artistic-2.0" ]
null
null
null
src/raven_src/src/StandardOutput.cpp
Okanagan-Basin-Water-Board/obwb-hydro-modelling
91ee6b914e344de65a495093c3b9427986182ef2
[ "Artistic-2.0" ]
null
null
null
src/raven_src/src/StandardOutput.cpp
Okanagan-Basin-Water-Board/obwb-hydro-modelling
91ee6b914e344de65a495093c3b9427986182ef2
[ "Artistic-2.0" ]
null
null
null
/*---------------------------------------------------------------- Raven Library Source Code Copyright (c) 2008-2020 the Raven Development Team Includes CModel routines for writing output headers and contents: CModel::CloseOutputStreams() CModel::WriteOutputFileHeaders() CModel::WriteMinorOutput() CModel::WriteMajorOutput() CModel::SummarizeToScreen() CModel::RunDiagnostics() Ensim output routines NetCDF output routines ----------------------------------------------------------------*/ #include "Model.h" #include "StateVariables.h" #if defined(_WIN32) #include <direct.h> #elif defined(__linux__) #include <sys/stat.h> #endif int NetCDFAddMetadata (const int fileid,const int time_dimid, string shortname,string longname,string units); int NetCDFAddMetadata2D(const int fileid,const int time_dimid,int nbasins_dimid,string shortname,string longname,string units); void WriteNetCDFGlobalAttributes(const int out_ncid,const optStruct &Options,const string descript); void AddSingleValueToNetCDF (const int out_ncid,const string &label,const size_t time_index,const double &value); ////////////////////////////////////////////////////////////////// /// \brief returns true if specified observation time series is the flow series for subbasin SBID /// \param pObs [in] observation time series /// \param SBID [in] subbasin ID // bool IsContinuousFlowObs(CTimeSeriesABC *pObs,long SBID) { // clears up terribly ugly repeated if statements if(pObs==NULL){return false;} if (s_to_l(pObs->GetTag().c_str()) != SBID){ return false; }//SBID is correct if(pObs->GetType() != CTimeSeriesABC::TS_REGULAR){ return false; } return (!strcmp(pObs->GetName().c_str(),"HYDROGRAPH")); //name ="HYDROGRAPH" } ////////////////////////////////////////////////////////////////// /// \brief returns true if specified observation time series is the reservoir stage series for subbasin SBID /// \param pObs [in] observation time series /// \param SBID [in] subbasin ID // bool IsContinuousStageObs(CTimeSeriesABC *pObs,long SBID) { // clears up terribly ugly repeated if statements if(pObs==NULL){return false;} return ( (!strcmp(pObs->GetName().c_str(),"RESERVOIR_STAGE")) && (s_to_l(pObs->GetTag().c_str()) == SBID) && (pObs->GetType() == CTimeSeriesABC::TS_REGULAR) ); } ////////////////////////////////////////////////////////////////// /// \brief returns true if specified observation time series is the reservoir inflow series for subbasin SBID /// \param pObs [in] observation time series /// \param SBID [in] subbasin ID // bool IsContinuousInflowObs(CTimeSeriesABC *pObs, long SBID) { // clears up terribly ugly repeated if statements if (pObs == NULL) { return false; } return ( (!strcmp(pObs->GetName().c_str(), "RESERVOIR_INFLOW")) && (s_to_l(pObs->GetTag().c_str()) == SBID) && (pObs->GetType() == CTimeSeriesABC::TS_REGULAR) ); } ////////////////////////////////////////////////////////////////// /// \brief returns true if specified observation time series is the reservoir inflow series for subbasin SBID /// \param pObs [in] observation time series /// \param SBID [in] subbasin ID // bool IsContinuousNetInflowObs(CTimeSeriesABC *pObs, long SBID) { // clears up terribly ugly repeated if statements if (pObs == NULL) { return false; } return ( (!strcmp(pObs->GetName().c_str(), "RESERVOIR_NETINFLOW")) && (s_to_l(pObs->GetTag().c_str()) == SBID) && (pObs->GetType() == CTimeSeriesABC::TS_REGULAR) ); } ////////////////////////////////////////////////////////////////// /// \brief Adds output directory & prefix to base file name /// \param filebase [in] base filename, with extension, no directory information /// \param &Options [in] Global model options information // string FilenamePrepare(string filebase, const optStruct &Options) { string fn; if (Options.run_name==""){fn=Options.output_dir+filebase;} else {fn=Options.output_dir+Options.run_name+"_"+filebase;} return fn; } ////////////////////////////////////////////////////////////////// /// \brief Closes output file streams /// \details after end of simulation from Main() or in ExitGracefully; All file streams are opened in WriteOutputFileHeaders() routine // void CModel::CloseOutputStreams() { for (int c=0;c<_nCustomOutputs;c++){ _pCustomOutputs[c]->CloseFiles(); } _pTransModel->CloseOutputFiles(); if(_pGWModel!=NULL) { _pGWModel->CloseOutputFiles(); } if ( _STORAGE.is_open()){ _STORAGE.close();} if ( _HYDRO.is_open()){ _HYDRO.close();} if (_FORCINGS.is_open()){_FORCINGS.close();} if (_RESSTAGE.is_open()){_RESSTAGE.close();} if ( _DEMANDS.is_open()){ _DEMANDS.close();} #ifdef _RVNETCDF_ /* close netcdfs */ int retval; // error value for NetCDF routines if (_HYDRO_ncid != -9) {retval = nc_close(_HYDRO_ncid); HandleNetCDFErrors(retval); } _HYDRO_ncid = -9; if (_STORAGE_ncid != -9) {retval = nc_close(_STORAGE_ncid); HandleNetCDFErrors(retval); } _STORAGE_ncid = -9; if (_FORCINGS_ncid != -9) {retval = nc_close(_FORCINGS_ncid); HandleNetCDFErrors(retval); } _FORCINGS_ncid = -9; #endif // end compilation if NetCDF library is available } ////////////////////////////////////////////////////////////////// /// \brief Write output file headers /// \details Called prior to simulation (but after initialization) from CModel::Initialize() /// \param &Options [in] Global model options information // void CModel::WriteOutputFileHeaders(const optStruct &Options) { int i,j,p; string tmpFilename; if(!Options.silent) { cout<<" Writing Output File Headers..."<<endl; } if (Options.output_format==OUTPUT_STANDARD) { //WatershedStorage.csv //-------------------------------------------------------------- if (Options.write_watershed_storage) { tmpFilename=FilenamePrepare("WatershedStorage.csv",Options); _STORAGE.open(tmpFilename.c_str()); if (_STORAGE.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP); _STORAGE<<"time [d],date,hour,rainfall [mm/day],snowfall [mm/d SWE],Channel Storage [mm],Reservoir Storage [mm],Rivulet Storage [mm]"; for (i=0;i<GetNumStateVars();i++){ if (CStateVariable::IsWaterStorage(_aStateVarType[i])){ if (i!=iAtmPrecip){ _STORAGE<<","<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]"; //_STORAGE<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]"; } } } _STORAGE<<", Total [mm], Cum. Inputs [mm], Cum. Outflow [mm], MB Error [mm]"<<endl; } //Hydrographs.csv //-------------------------------------------------------------- tmpFilename=FilenamePrepare("Hydrographs.csv",Options); _HYDRO.open(tmpFilename.c_str()); if (_HYDRO.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } _HYDRO<<"time,date,hour"; _HYDRO<<",precip [mm/day]"; for (p=0;p<_nSubBasins;p++){ if (_pSubBasins[p]->IsGauged() && _pSubBasins[p]->IsEnabled()){ string name; if (_pSubBasins[p]->GetName()==""){_HYDRO<<",ID="<<_pSubBasins[p]->GetID() <<" [m3/s]";} else {_HYDRO<<"," <<_pSubBasins[p]->GetName()<<" [m3/s]";} //if (Options.print_obs_hydro) { for (i = 0; i < _nObservedTS; i++){ if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID())) { if (_pSubBasins[p]->GetName()==""){_HYDRO<<",ID="<<_pSubBasins[p]->GetID() <<" (observed) [m3/s]";} else {_HYDRO<<"," <<_pSubBasins[p]->GetName()<<" (observed) [m3/s]";} } } } if (_pSubBasins[p]->GetReservoir() != NULL){ if (_pSubBasins[p]->GetName()==""){_HYDRO<<",ID="<<_pSubBasins[p]->GetID() <<" (res. inflow) [m3/s]";} else {_HYDRO<<"," <<_pSubBasins[p]->GetName()<<" (res. inflow) [m3/s]";} } } } _HYDRO<<endl; } else if (Options.output_format==OUTPUT_ENSIM) { WriteEnsimStandardHeaders(Options); } else if (Options.output_format==OUTPUT_NETCDF) { WriteNetcdfStandardHeaders(Options); // creates NetCDF files, writes dimensions and creates variables (without writing actual values) } //WatershedEnergyStorage.csv //-------------------------------------------------------------- if (Options.write_energy) { ofstream EN_STORAGE; tmpFilename=FilenamePrepare("WatershedEnergyStorage.csv",Options); EN_STORAGE.open(tmpFilename.c_str()); if (EN_STORAGE.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } EN_STORAGE<<"time[d],date,hour,temp[C],net incoming [MJ/m2/d]"; for (i=0;i<GetNumStateVars();i++){ if (CStateVariable::IsEnergyStorage(_aStateVarType[i])){ EN_STORAGE<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i])<<" [MJ/m2]"; } } EN_STORAGE<<", Total [MJ/m2], Cum. In [MJ/m2], Cum. Out [MJ/m2], EB Error [MJ/m2]"<<endl; EN_STORAGE.close(); } //ReservoirStages.csv //-------------------------------------------------------------- if((Options.write_reservoir) && (Options.output_format!=OUTPUT_NONE)) { tmpFilename=FilenamePrepare("ReservoirStages.csv",Options); _RESSTAGE.open(tmpFilename.c_str()); if(_RESSTAGE.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } _RESSTAGE<<"time,date,hour"; _RESSTAGE<<",precip [mm/day]"; for(p=0;p<_nSubBasins;p++){ if((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) { string name; if(_pSubBasins[p]->GetName()==""){ _RESSTAGE<<",ID="<<_pSubBasins[p]->GetID() <<" "; } else { _RESSTAGE<<"," <<_pSubBasins[p]->GetName()<<" "; } } //if (Options.print_obs_hydro) { for(i = 0; i < _nObservedTS; i++){ if(IsContinuousStageObs(_pObservedTS[i],_pSubBasins[p]->GetID())) { if(_pSubBasins[p]->GetName()==""){ _RESSTAGE<<",ID="<<_pSubBasins[p]->GetID() <<" (observed) [m3/s]"; } else { _RESSTAGE<<"," <<_pSubBasins[p]->GetName()<<" (observed) [m3/s]"; } } } } } _RESSTAGE<<endl; } //ReservoirStages.csv //-------------------------------------------------------------- if((Options.write_demandfile) && (Options.output_format!=OUTPUT_NONE)) { tmpFilename=FilenamePrepare("Demands.csv",Options); _DEMANDS.open(tmpFilename.c_str()); if(_DEMANDS.fail()) { ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } _DEMANDS<<"time,date,hour"; for(p=0;p<_nSubBasins;p++) { if((_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->HasIrrigationDemand())) { string name; if(_pSubBasins[p]->GetName()=="") { name="ID="+to_string(_pSubBasins[p]->GetID()); } else { name=_pSubBasins[p]->GetName(); } _DEMANDS<<","<<name<<" [m3/s]"; _DEMANDS<<","<<name<<" (demand) [m3/s]"; _DEMANDS<<","<<name<<" (min.) [m3/s]"; _DEMANDS<<","<<name<<" (unmet) [m3/s]"; } } _DEMANDS<<endl; } //ReservoirMassBalance.csv //-------------------------------------------------------------- if ((Options.write_reservoirMB) && (Options.output_format!=OUTPUT_NONE)) { ofstream RES_MB; string name; tmpFilename=FilenamePrepare("ReservoirMassBalance.csv",Options); RES_MB.open(tmpFilename.c_str()); if (RES_MB.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } RES_MB<<"time,date,hour"; RES_MB<<",precip [mm/day]"; for(p=0;p<_nSubBasins;p++){ if((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) { if(_pSubBasins[p]->GetName()==""){ name=to_string(_pSubBasins[p]->GetID())+"="+to_string(_pSubBasins[p]->GetID()); } else { name=_pSubBasins[p]->GetName(); } RES_MB<<"," <<name<<" inflow [m3]"; RES_MB<<"," <<name<<" outflow [m3]"; RES_MB<<"," <<name<<" volume [m3]"; RES_MB<<"," <<name<<" losses [m3]"; RES_MB<<"," <<name<<" MB error [m3]"; RES_MB<<"," <<name<<" constraint"; } } RES_MB<<endl; RES_MB.close(); } //WatershedMassEnergyBalance.csv //-------------------------------------------------------------- if (Options.write_mass_bal) { ofstream MB; tmpFilename=FilenamePrepare("WatershedMassEnergyBalance.csv",Options); MB.open(tmpFilename.c_str()); if (MB.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } MB<<"time [d],date,hour"; for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType()); MB<<"["<<CStateVariable::GetStateVarUnits(_aStateVarType[_pProcesses[j]->GetFromIndices()[q]])<<"]"; } } MB<<endl; MB<<",,from:"; for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ sv_type typ=GetStateVarType (_pProcesses[j]->GetFromIndices()[q]); int ind=GetStateVarLayer(_pProcesses[j]->GetFromIndices()[q]); MB<<","<<CStateVariable::SVTypeToString(typ,ind); } } MB<<endl; MB<<",,to:"; for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ sv_type typ=GetStateVarType (_pProcesses[j]->GetToIndices()[q]); int ind=GetStateVarLayer(_pProcesses[j]->GetToIndices()[q]); MB<<","<<CStateVariable::SVTypeToString(typ,ind); } } MB<<endl; MB.close(); } //WatershedMassEnergyBalance.csv //-------------------------------------------------------------- if (Options.write_group_mb!=DOESNT_EXIST) { int kk=Options.write_group_mb; ofstream HGMB; tmpFilename=FilenamePrepare(_pHRUGroups[kk]->GetName()+"_MassEnergyBalance.csv",Options); HGMB.open(tmpFilename.c_str()); if (HGMB.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } HGMB<<"time [d],date,hour"; for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ HGMB<<","<<GetProcessName(_pProcesses[j]->GetProcessType()); HGMB<<"["<<CStateVariable::GetStateVarUnits(_aStateVarType[_pProcesses[j]->GetFromIndices()[q]])<<"]"; } } HGMB<<endl; HGMB<<",,from:"; for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ sv_type typ=GetStateVarType (_pProcesses[j]->GetFromIndices()[q]); int ind=GetStateVarLayer(_pProcesses[j]->GetFromIndices()[q]); HGMB<<","<<CStateVariable::SVTypeToString(typ,ind); } } HGMB<<endl; HGMB<<",,to:"; for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ sv_type typ=GetStateVarType (_pProcesses[j]->GetToIndices()[q]); int ind=GetStateVarLayer(_pProcesses[j]->GetToIndices()[q]); HGMB<<","<<CStateVariable::SVTypeToString(typ,ind); } } HGMB<<endl; HGMB.close(); } //ExhaustiveMassBalance.csv //-------------------------------------------------------------- if (Options.write_exhaustiveMB) { ofstream MB; tmpFilename=FilenamePrepare("ExhaustiveMassBalance.csv",Options); MB.open(tmpFilename.c_str()); if (MB.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } MB<<"time[d],date,hour"; bool first; for (i=0;i<_nStateVars;i++){ if (CStateVariable::IsWaterStorage(_aStateVarType[i])) { MB<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i]); first=true; for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ if (_pProcesses[j]->GetFromIndices()[q]==i){ if (!first){MB<<",";}first=false; } } } for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ if (_pProcesses[j]->GetToIndices()[q]==i){ if (!first){MB<<",";}first=false; } } } for(j=0;j<_nProcesses;j++){ for(int q=0;q<_pProcesses[j]->GetNumLatConnections();q++){ CLateralExchangeProcessABC *pProc=static_cast<CLateralExchangeProcessABC *>(_pProcesses[j]); if(pProc->GetLateralToIndices()[q]==i){ if(!first){ MB<<","; }first=false;break; } if (pProc->GetLateralFromIndices()[q]==i){ if (!first){MB<<",";}first=false;break; } } } MB<<",,,";//cum, stor, error } } MB<<endl; MB<<",,";//time,date,hour for (i=0;i<_nStateVars;i++){ if (CStateVariable::IsWaterStorage(_aStateVarType[i])) { for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ if (_pProcesses[j]->GetFromIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());} } } for (j=0;j<_nProcesses;j++){ for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){ if (_pProcesses[j]->GetToIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());} } } for(j=0;j<_nProcesses;j++){ for(int q=0;q<_pProcesses[j]->GetNumLatConnections();q++){ CLateralExchangeProcessABC *pProc=static_cast<CLateralExchangeProcessABC *>(_pProcesses[j]); if (pProc->GetLateralToIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());break;} if (pProc->GetLateralFromIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());break;} } } MB<<",cumulative,storage,error"; } } MB<<endl; MB.close(); } //ForcingFunctions.csv //-------------------------------------------------------------- if (Options.write_forcings) { tmpFilename=FilenamePrepare("ForcingFunctions.csv",Options); _FORCINGS.open(tmpFilename.c_str()); if (_FORCINGS.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } _FORCINGS<<"time [d],date,hour,day_angle,"; _FORCINGS<<" rain [mm/d], snow [mm/d], temp [C], temp_daily_min [C], temp_daily_max [C],temp_daily_ave [C],temp_monthly_min [C],temp_monthly_max [C],"; _FORCINGS<<" air dens. [kg/m3], air pres. [KPa], rel hum. [-],"; _FORCINGS<<" cloud cover [-],"; _FORCINGS<<" ET radiation [MJ/m2/d], SW radiation [MJ/m2/d], net SW radiation [MJ/m2/d], LW radiation [MJ/m2/d], wind vel. [m/s],"; _FORCINGS<<" PET [mm/d], OW PET [mm/d],"; _FORCINGS<<" daily correction [-], potential melt [mm/d]"; _FORCINGS<<endl; } // HRU Storage files //-------------------------------------------------------------- if (_pOutputGroup!=NULL){ for (int kk=0; kk<_pOutputGroup->GetNumHRUs();kk++) { ofstream HRUSTOR; tmpFilename="HRUStorage_"+to_string(_pOutputGroup->GetHRU(kk)->GetID())+".csv"; tmpFilename=FilenamePrepare(tmpFilename,Options); HRUSTOR.open(tmpFilename.c_str()); if (HRUSTOR.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP); HRUSTOR<<"time [d],date,hour,rainfall [mm/day],snowfall [mm/d SWE]"; for (i=0;i<GetNumStateVars();i++){ if (CStateVariable::IsWaterStorage(_aStateVarType[i])){ if (i!=iAtmPrecip){ HRUSTOR<<","<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]"; //HRUSTOR<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]"; } } } HRUSTOR<<", Total [mm]"<<endl; HRUSTOR.close(); } } // Custom output files //-------------------------------------------------------------- for (int c=0;c<_nCustomOutputs;c++) { _pCustomOutputs[c]->WriteFileHeader(Options); } // Transport output files //-------------------------------------------------------------- if (Options.output_format==OUTPUT_STANDARD) { _pTransModel->WriteOutputFileHeaders(Options); } else if (Options.output_format==OUTPUT_ENSIM) { _pTransModel->WriteEnsimOutputFileHeaders(Options); } // Groundwater output files //------------------------------------------------------------- _pGWModel->WriteOutputFileHeaders(Options); //raven_debug.csv //-------------------------------------------------------------- if (Options.debug_mode) { ofstream DEBUG; tmpFilename=FilenamePrepare("raven_debug.csv",Options); DEBUG.open(tmpFilename.c_str()); if (DEBUG.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } DEBUG<<"time[d],date,hour,debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10"<<endl; DEBUG.close(); } //opens and closes diagnostics.csv so that this warning doesn't show up at end of simulation //-------------------------------------------------------------- if ((_nObservedTS>0) && (_nDiagnostics>0)) { ofstream DIAG; tmpFilename=FilenamePrepare("Diagnostics.csv",Options); DIAG.open(tmpFilename.c_str()); if(DIAG.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } DIAG.close(); } } ////////////////////////////////////////////////////////////////// /// \brief Writes minor output to file at the end of each timestep (or multiple thereof) /// \note only thing this modifies should be output streams /// \param &Options [in] Global model options information /// \param &tt [in] Local (model) time *at the end of* the pertinent time step // void CModel::WriteMinorOutput(const optStruct &Options,const time_struct &tt) { int i,iCumPrecip,k; double output_int = 0.0; double mod_final = 0.0; double S,currentWater; string thisdate; string thishour; bool silent=true; bool quiet=true; double t; string tmpFilename; if ((tt.model_time==0) && (Options.suppressICs)){return;} //converts the 'write every x timesteps' into a 'write at time y' value output_int = Options.output_interval * Options.timestep; mod_final = ffmod(tt.model_time,output_int); iCumPrecip=GetStateVarIndex(ATMOS_PRECIP); if(fabs(mod_final) <= 0.5*Options.timestep) //checks to see if sufficiently close to timestep //(this should account for any roundoff error in timestep calcs) { thisdate=tt.date_string; //refers to date and time at END of time step thishour=DecDaysToHours(tt.julian_day); t =tt.model_time; time_struct prev; JulianConvert(t-Options.timestep,Options.julian_start_day,Options.julian_start_year,Options.calendar,prev); //get start of time step, prev double usetime=tt.model_time; string usedate=thisdate; string usehour=thishour; if(Options.period_starting){ usedate=prev.date_string; usehour=DecDaysToHours(prev.julian_day); usetime=tt.model_time-Options.timestep; } // Console output //---------------------------------------------------------------- if ((quiet) && (!Options.silent) && (tt.day_of_month==1) && ((tt.julian_day)-floor(tt.julian_day+TIME_CORRECTION)<Options.timestep/2)) { cout<<thisdate <<endl; } if(!silent) { cout <<thisdate<<" "<<thishour<<":"; if (t!=0){cout <<" | P: "<< setw(6)<<setiosflags(ios::fixed) << setprecision(2)<<GetAveragePrecip();} else {cout <<" | P: ------";} } //Write current state of water storage in system to WatershedStorage.csv (ALWAYS DONE if not switched OFF) //---------------------------------------------------------------- if (Options.output_format==OUTPUT_STANDARD) { if (Options.write_watershed_storage) { double snowfall =GetAverageSnowfall(); double precip =GetAveragePrecip(); double channel_stor =GetTotalChannelStorage(); double reservoir_stor=GetTotalReservoirStorage(); double rivulet_stor =GetTotalRivuletStorage(); _STORAGE<<tt.model_time <<","<<thisdate<<","<<thishour; //instantaneous, so thishour rather than usehour used. if (t!=0){_STORAGE<<","<<precip-snowfall<<","<<snowfall;}//precip else {_STORAGE<<",---,---";} _STORAGE<<","<<channel_stor<<","<<reservoir_stor<<","<<rivulet_stor; currentWater=0.0; for (i=0;i<GetNumStateVars();i++) { if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iCumPrecip)) { S=GetAvgStateVar(i); if (!silent){cout<<" |"<< setw(6)<<setiosflags(ios::fixed) << setprecision(2)<<S;} _STORAGE<<","<<FormatDouble(S); currentWater+=S; } } currentWater+=channel_stor+rivulet_stor+reservoir_stor; if(t==0){ // \todo [fix]: this fixes a mass balance bug in reservoir simulations, but there is certainly a more proper way to do it // JRC: I think somehow this is being double counted in the delta V calculations in the first timestep for(int p=0;p<_nSubBasins;p++){ if(_pSubBasins[p]->GetReservoir()!=NULL){ currentWater+=_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2; currentWater-=_pSubBasins[p]->GetIntegratedOutflow (Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2; } } } _STORAGE<<","<<currentWater<<","<<_CumulInput<<","<<_CumulOutput<<","<<FormatDouble((currentWater-_initWater)+(_CumulOutput-_CumulInput)); _STORAGE<<endl; } //Write hydrographs for gauged watersheds (ALWAYS DONE) //---------------------------------------------------------------- if ((Options.ave_hydrograph) && (t!=0.0)) { _HYDRO<<usetime<<","<<usedate<<","<<usehour<<","<<GetAveragePrecip(); for (int p=0;p<_nSubBasins;p++){ if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())) { _HYDRO<<","<<_pSubBasins[p]->GetIntegratedOutflow(Options.timestep)/(Options.timestep*SEC_PER_DAY); //if (Options.print_obs_hydro) { for (i = 0; i < _nObservedTS; i++) { if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID())) { double val = _pObservedTS[i]->GetAvgValue(tt.model_time,Options.timestep); //time shift handled in CTimeSeries::Parse if ((val != RAV_BLANK_DATA) && (tt.model_time>0)){ _HYDRO << "," << val; } else { _HYDRO << ","; } } } } if (_pSubBasins[p]->GetReservoir() != NULL){ _HYDRO<<","<<_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/(Options.timestep*SEC_PER_DAY); } } } _HYDRO<<endl; } else //point value hydrograph or t==0 { if((Options.period_starting) && (t==0)){}//don't write anything at time zero else{ _HYDRO<<t<<","<<thisdate<<","<<thishour; if(t!=0){ _HYDRO<<","<<GetAveragePrecip(); }//watershed-wide precip else { _HYDRO<<",---"; } for(int p=0;p<_nSubBasins;p++){ if(_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())) { _HYDRO<<","<<_pSubBasins[p]->GetOutflowRate(); //if (Options.print_obs_hydro) { for(i = 0; i < _nObservedTS; i++){ if(IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID())) { double val = _pObservedTS[i]->GetAvgValue(tt.model_time,Options.timestep); if((val != RAV_BLANK_DATA) && (tt.model_time>0)){ _HYDRO << "," << val; } else { _HYDRO << ","; } } } } if(_pSubBasins[p]->GetReservoir() != NULL){ _HYDRO<<","<<_pSubBasins[p]->GetReservoirInflow(); } } } _HYDRO<<endl; } } } else if (Options.output_format==OUTPUT_ENSIM) { WriteEnsimMinorOutput(Options,tt); } else if (Options.output_format==OUTPUT_NETCDF) { WriteNetcdfMinorOutput(Options,tt); } //Write cumulative mass balance info to HRUGroup_MassEnergyBalance.csv //---------------------------------------------------------------- if (Options.write_group_mb!=DOESNT_EXIST) { if((Options.period_starting) && (t==0)){}//don't write anything at time zero else{ double sum; int kk=Options.write_group_mb; ofstream HGMB; tmpFilename=FilenamePrepare(_pHRUGroups[kk]->GetName()+"_MassEnergyBalance.csv",Options); HGMB.open(tmpFilename.c_str(),ios::app); HGMB<<usetime<<","<<usedate<<","<<usehour; double areasum=0.0; for(k = 0; k < _nHydroUnits; k++){ if(_pHRUGroups[kk]->IsInGroup(k)){ areasum+=_pHydroUnits[k]->GetArea(); } } for(int js=0;js<_nTotalConnections;js++) { sum=0.0; for(k = 0; k < _nHydroUnits; k++){ if(_pHRUGroups[kk]->IsInGroup(k)){ sum += _aCumulativeBal[k][js] * _pHydroUnits[k]->GetArea(); } } HGMB<<","<<sum/areasum; } HGMB<<endl; HGMB.close(); } } //Write cumulative mass balance info to WatershedMassEnergyBalance.csv //---------------------------------------------------------------- if (Options.write_mass_bal) { if((Options.period_starting) && (t==0)){}//don't write anything at time zero else{ double sum; ofstream MB; tmpFilename=FilenamePrepare("WatershedMassEnergyBalance.csv",Options); MB.open(tmpFilename.c_str(),ios::app); MB<<usetime<<","<<usedate<<","<<usehour; for(int js=0;js<_nTotalConnections;js++) { sum=0.0; for(k=0;k<_nHydroUnits;k++){ if(_pHydroUnits[k]->IsEnabled()) { sum+=_aCumulativeBal[k][js]*_pHydroUnits[k]->GetArea(); } } MB<<","<<sum/_WatershedArea; } MB<<endl; MB.close(); } } //ReservoirStages.csv //-------------------------------------------------------------- if ((Options.write_reservoir) && (Options.output_format!=OUTPUT_NONE)) { if((Options.period_starting) && (t==0)){}//don't write anything at time zero else{ _RESSTAGE<< t<<","<<thisdate<<","<<thishour<<","<<GetAveragePrecip(); for (int p=0;p<_nSubBasins;p++){ if ((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) { _RESSTAGE<<","<<_pSubBasins[p]->GetReservoir()->GetResStage(); } //if (Options.print_obs_hydro) { for (i = 0; i < _nObservedTS; i++){ if (IsContinuousStageObs(_pObservedTS[i],_pSubBasins[p]->GetID())) { double val = _pObservedTS[i]->GetAvgValue(tt.model_time,Options.timestep); if ((val != RAV_BLANK_DATA) && (tt.model_time>0)){ _RESSTAGE << "," << val; } else { _RESSTAGE << ","; } } } } } _RESSTAGE<<endl; } } //Demands.csv //---------------------------------------------------------------- if((Options.write_demandfile) && (Options.output_format!=OUTPUT_NONE)) { if((Options.period_starting) && (t==0)) {}//don't write anything at time zero else { _DEMANDS<< t<<","<<thisdate<<","<<thishour; for(int p=0;p<_nSubBasins;p++) { if((_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->HasIrrigationDemand())) { double irr =_pSubBasins[p]->GetIrrigationDemand(tt.model_time); double eF =_pSubBasins[p]->GetEnviroMinFlow (tt.model_time); double Q =_pSubBasins[p]->GetOutflowRate (); //AFTER irrigation removed double Qirr=_pSubBasins[p]->GetIrrigationRate (); double unmet=max(irr-Qirr,0.0); _DEMANDS<<","<<Q<<","<<irr<<","<<eF<<","<<unmet; } } _DEMANDS<<endl; } } //ReservoirMassBalance.csv //---------------------------------------------------------------- if((Options.write_reservoirMB) && (Options.output_format!=OUTPUT_NONE)) { if((Options.period_starting) && (t==0)){}//don't write anything at time zero else{ ofstream RES_MB; tmpFilename=FilenamePrepare("ReservoirMassBalance.csv",Options); RES_MB.open(tmpFilename.c_str(),ios::app); if(RES_MB.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } RES_MB<< usetime<<","<<usedate<<","<<usehour<<","<<GetAveragePrecip(); double in,out,loss,stor,oldstor; for(int p=0;p<_nSubBasins;p++){ if((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) { string name,constraint_str; if(_pSubBasins[p]->GetName()==""){ name=to_string(_pSubBasins[p]->GetID())+"="+to_string(_pSubBasins[p]->GetID()); } else { name=_pSubBasins[p]->GetName(); } in =_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep);//m3 out =_pSubBasins[p]->GetIntegratedOutflow(Options.timestep);//m3 stor =_pSubBasins[p]->GetReservoir()->GetStorage();//m3 oldstor=_pSubBasins[p]->GetReservoir()->GetOldStorage();//m3 loss =_pSubBasins[p]->GetReservoir()->GetReservoirLosses(Options.timestep);//m3 constraint_str=_pSubBasins[p]->GetReservoir()->GetCurrentConstraint(); if(tt.model_time==0.0){ in=0.0; } RES_MB<<","<<in<<","<<out<<","<<stor<<","<<loss<<","<<in-out-loss-(stor-oldstor)<<","<<constraint_str; } } RES_MB<<endl; RES_MB.close(); } } // WatershedEnergyStorage.csv //---------------------------------------------------------------- double sum=0.0; if (Options.write_energy) { force_struct F=GetAverageForcings(); ofstream EN_STORAGE; tmpFilename=FilenamePrepare("WatershedEnergyStorage.csv",Options); EN_STORAGE.open(tmpFilename.c_str(),ios::app); EN_STORAGE<<t<<","<<thisdate<<","<<thishour; EN_STORAGE<<","<<F.temp_ave; EN_STORAGE<<",TMP_DEBUG"; // STOR<<","<<GetAverageNetRadiation();//TMP DEBUG for (i=0;i<GetNumStateVars();i++) { if (CStateVariable::IsEnergyStorage(_aStateVarType[i])) { S=GetAvgStateVar(i); if (!silent){cout<<" |"<< setw(6)<<setiosflags(ios::fixed) << setprecision(2)<<S;} EN_STORAGE<<","<<S; sum+=S; } } EN_STORAGE<<","<<sum<<","<<_CumEnergyGain<<","<<_CumEnergyLoss<<","<<_CumEnergyGain-sum-_CumEnergyLoss; EN_STORAGE<<endl; EN_STORAGE.close(); } if (!silent){cout<<endl;} // ExhaustiveMassBalance.csv //-------------------------------------------------------------- if (Options.write_exhaustiveMB) { if((Options.period_starting) && (t==0)){}//don't write anything at time zero else{ int j,js,q; double cumsum; ofstream MB; tmpFilename=FilenamePrepare("ExhaustiveMassBalance.csv",Options); MB.open(tmpFilename.c_str(),ios::app); MB<<usetime<<","<<usedate<<","<<usehour; for(i=0;i<_nStateVars;i++) { if(CStateVariable::IsWaterStorage(_aStateVarType[i])) { cumsum=0.0; js=0; for(j=0;j<_nProcesses;j++){ for(q=0;q<_pProcesses[j]->GetNumConnections();q++){ if(_pProcesses[j]->GetFromIndices()[q]==i) { sum=0.0; for(k=0;k<_nHydroUnits;k++){ if(_pHydroUnits[k]->IsEnabled()) { sum+=_aCumulativeBal[k][js]*_pHydroUnits[k]->GetArea(); } } MB<<","<<-sum/_WatershedArea; cumsum-=sum/_WatershedArea; } js++; } } js=0; for(j=0;j<_nProcesses;j++){ for(q=0;q<_pProcesses[j]->GetNumConnections();q++){ if(_pProcesses[j]->GetToIndices()[q]==i) { sum=0.0; for(k=0;k<_nHydroUnits;k++){ if(_pHydroUnits[k]->IsEnabled()) { sum+=_aCumulativeBal[k][js]*_pHydroUnits[k]->GetArea(); } } MB<<","<<sum/_WatershedArea; cumsum+=sum/_WatershedArea; } js++; } } js=0; bool found; for(j=0;j<_nProcesses;j++){ sum=0; found=false; for(q=0;q<_pProcesses[j]->GetNumLatConnections();q++){ CLateralExchangeProcessABC *pProc=static_cast<CLateralExchangeProcessABC *>(_pProcesses[j]); if (pProc->GetLateralToIndices()[q]==i){ sum+=_aCumulativeLatBal[js];found=true; } if (pProc->GetLateralFromIndices()[q]==i){ sum-=_aCumulativeLatBal[js];found=true; } js++; } if((_pProcesses[j]->GetNumLatConnections()>0) && (found==true)){ MB<<","<<sum/_WatershedArea; cumsum+=sum/_WatershedArea; } } //Cumulative, storage, error double Initial_i=0.0; //< \todo [bug] need to evaluate and store initial storage actross watershed!!! MB<<","<<cumsum<<","<<GetAvgStateVar(i)<<","<<cumsum-GetAvgStateVar(i)-Initial_i; } } MB<<endl; MB.close(); } } // ForcingFunctions.csv //---------------------------------------------------------------- if (Options.write_forcings) { if((Options.period_starting) && (t==0)){}//don't write anything at time zero else{ force_struct *pFave; force_struct faveStruct = GetAverageForcings(); pFave = &faveStruct; _FORCINGS<<usetime<<","<<usedate<<","<<usehour<<","; _FORCINGS<<pFave->day_angle<<","; _FORCINGS<<pFave->precip*(1-pFave->snow_frac) <<","; _FORCINGS<<pFave->precip*(pFave->snow_frac) <<","; _FORCINGS<<pFave->temp_ave<<","; _FORCINGS<<pFave->temp_daily_min<<","; _FORCINGS<<pFave->temp_daily_max<<","; _FORCINGS<<pFave->temp_daily_ave<<","; _FORCINGS<<pFave->temp_month_min<<","; _FORCINGS<<pFave->temp_month_max<<","; _FORCINGS<<pFave->air_dens<<","; _FORCINGS<<pFave->air_pres<<","; _FORCINGS<<pFave->rel_humidity<<","; _FORCINGS<<pFave->cloud_cover<<","; _FORCINGS<<pFave->ET_radia<<","; _FORCINGS<<pFave->SW_radia<<","; _FORCINGS<<pFave->SW_radia_net<<","; //_FORCINGS<<pFave->LW_incoming<<","; _FORCINGS<<pFave->LW_radia_net<<","; _FORCINGS<<pFave->wind_vel<<","; _FORCINGS<<pFave->PET<<","; _FORCINGS<<pFave->OW_PET<<","; _FORCINGS<<pFave->subdaily_corr<<","; _FORCINGS<<pFave->potential_melt; _FORCINGS<<endl; } } // Transport output files //-------------------------------------------------------------- if (Options.output_format==OUTPUT_STANDARD) { _pTransModel->WriteMinorOutput(Options,tt); } else if (Options.output_format==OUTPUT_ENSIM) { _pTransModel->WriteEnsimMinorOutput(Options,tt); } // Groundwater output files //-------------------------------------------------------------- _pGWModel->WriteMinorOutput(Options,tt); // raven_debug.csv //-------------------------------------------------------------- if (Options.debug_mode) { ofstream DEBUG; tmpFilename=FilenamePrepare("raven_debug.csv",Options); DEBUG.open(tmpFilename.c_str(),ios::app); DEBUG<<t<<","<<thisdate<<","<<thishour; for(i=0;i<10;i++){DEBUG<<","<<g_debug_vars[i];} DEBUG<<endl; DEBUG.close(); } // HRU storage output //-------------------------------------------------------------- if (_pOutputGroup!=NULL) { for (int kk=0;kk<_pOutputGroup->GetNumHRUs();kk++) { ofstream HRUSTOR; tmpFilename="HRUStorage_"+to_string(_pOutputGroup->GetHRU(kk)->GetID())+".csv"; tmpFilename=FilenamePrepare(tmpFilename,Options); HRUSTOR.open(tmpFilename.c_str(),ios::app); const force_struct *F=_pOutputGroup->GetHRU(kk)->GetForcingFunctions(); HRUSTOR<<tt.model_time <<","<<thisdate<<","<<thishour;//instantaneous -no period starting correction if (t!=0){HRUSTOR<<","<<F->precip*(1-F->snow_frac)<<","<<F->precip*(F->snow_frac);}//precip else {HRUSTOR<<",---,---";} currentWater=0; for (i=0;i<GetNumStateVars();i++) { if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iCumPrecip)) { S=_pOutputGroup->GetHRU(kk)->GetStateVarValue(i); HRUSTOR<<","<<S; currentWater+=S; } } HRUSTOR<<","<<currentWater; HRUSTOR<<endl; HRUSTOR.close(); } } } // end of write output interval if statement // Custom output files //-------------------------------------------------------------- for (int c=0;c<_nCustomOutputs;c++) { _pCustomOutputs[c]->WriteCustomOutput(tt,Options); } // Write major output, if necessary //-------------------------------------------------------------- if ((_nOutputTimes>0) && (tt.model_time>_aOutputTimes[_currOutputTimeInd]-0.5*Options.timestep)) { _currOutputTimeInd++; tmpFilename="state_"+tt.date_string; WriteMajorOutput(tmpFilename,Options,tt,false); } } ////////////////////////////////////////////////////////////////// /// \brief Writes major output to file at the end of simulation /// \details Writes: /// - Solution file of all state variables; and /// - Autogenerated parameters /// /// \param &Options [in] Global model options information // void CModel::WriteMajorOutput(string solfile, const optStruct &Options, const time_struct &tt, bool final) const { int i,k; string tmpFilename; // WRITE {RunName}_solution.rvc - final state variables file ofstream OUT; tmpFilename=FilenamePrepare(solfile+".rvc",Options); OUT.open(tmpFilename.c_str()); if (OUT.fail()){ WriteWarning(("CModel::WriteMajorOutput: Unable to open output file "+tmpFilename+" for writing.").c_str(),Options.noisy); } OUT<<":TimeStamp "<<tt.date_string<<" "<<DecDaysToHours(tt.julian_day)<<endl; //Header-------------------------- OUT<<":HRUStateVariableTable"<<endl; OUT<<" :Attributes,"; for (i=0;i<GetNumStateVars();i++) { OUT<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i]); if (i!=GetNumStateVars()-1){OUT<<",";} } OUT<<endl; OUT<<" :Units,"; for (i=0;i<GetNumStateVars();i++) { OUT<<CStateVariable::GetStateVarUnits(_aStateVarType[i]); if (i!=GetNumStateVars()-1){OUT<<",";} } OUT<<endl; //Data---------------------------- for (k=0;k<_nHydroUnits;k++) { OUT<<std::fixed; OUT.precision(5); OUT<<" "<<_pHydroUnits[k]->GetID()<<","; for (i=0;i<GetNumStateVars();i++) { OUT<<_pHydroUnits[k]->GetStateVarValue(i); if (i!=GetNumStateVars()-1){OUT<<",";} } OUT<<endl; } OUT<<":EndHRUStateVariableTable"<<endl; //By basin------------------------ OUT<<":BasinStateVariables"<<endl; for (int p=0;p<_nSubBasins;p++){ OUT<<" :BasinIndex "<<_pSubBasins[p]->GetID()<<","; _pSubBasins[p]->WriteToSolutionFile(OUT); } OUT<<":EndBasinStateVariables"<<endl; OUT.close(); if(Options.write_channels){ CChannelXSect::WriteRatingCurves(); } if(Options.write_basinfile) { ofstream BASIN; tmpFilename=FilenamePrepare("SubbasinParams.csv",Options); BASIN.open(tmpFilename.c_str()); if(BASIN.fail()) { WriteWarning(("CModel::WriteMajorOutput: Unable to open output file "+tmpFilename+" for writing.").c_str(),Options.noisy); } BASIN<<"SBID,Reference Discharge [m3/s],Reach Length [m],Reach Celerity [m/s],Reach Diffusivity [m2/s]"<<endl; for(int p=0;p<_nSubBasins;p++) { BASIN<<_pSubBasins[p]->GetID()<<","<<_pSubBasins[p]->GetReferenceFlow()<<","<<_pSubBasins[p]->GetReachLength()<<","; BASIN<<_pSubBasins[p]->GetReferenceCelerity()<<","<<_pSubBasins[p]->GetDiffusivity()<<endl; } BASIN.close(); } } ////////////////////////////////////////////////////////////////// /// \brief Writes progress file in JSON format (mainly for PAVICS runs) /// Looks like: /// { /// "% progress": 65, /// "seconds remaining": 123 /// } /// /// \note Does not account for initialization (reading) and final writing of model outputs. Only pure modeling time. /// /// \param &Options [in] Global model options information /// \param &elapsed_time [in] elapsed time (computational time markers) /// \param elapsed_steps [in] elapsed number of simulation steps to perform (to determine % progress) /// \param total_steps [in] total number of simulation steps to perform (to determine % progress) // void CModel::WriteProgressOutput(const optStruct &Options, clock_t elapsed_time, int elapsed_steps, int total_steps) { if (Options.pavics) { ofstream PROGRESS; PROGRESS.open((Options.main_output_dir+"Raven_progress.txt").c_str()); if (PROGRESS.fail()){ PROGRESS.close(); ExitGracefully("ParseInput:: Unable to open Raven_progress.txt. Bad output directory specified?",RUNTIME_ERR); } float total_time = (float(total_steps) * float(elapsed_time) / float(elapsed_steps)) / CLOCKS_PER_SEC; if (Options.benchmarking){ total_time =float(elapsed_time);} PROGRESS<<"{"<<endl; PROGRESS<<" \"% progress\": " << int( float(elapsed_steps) * 100.0 / float(total_steps) ) <<","<< endl; PROGRESS<<" \"seconds remaining\": "<< total_time - float(elapsed_time) / CLOCKS_PER_SEC <<endl; PROGRESS<<"}"<<endl; PROGRESS.close(); } } ////////////////////////////////////////////////////////////////// /// \brief Writes model summary information to screen /// \param &Options [in] Global model options information // void CModel::SummarizeToScreen (const optStruct &Options) const { int rescount=0; for (int p = 0; p < _nSubBasins; p++){ if (_pSubBasins[p]->GetReservoir() != NULL){rescount++;} } int disablecount=0; double allarea=0.0; for(int k=0;k<_nHydroUnits; k++){ if(!_pHydroUnits[k]->IsEnabled()){disablecount++;} allarea+=_pHydroUnits[k]->GetArea(); } int SBdisablecount=0; for(int p=0;p<_nSubBasins; p++){ if(!_pSubBasins[p]->IsEnabled()){SBdisablecount++;} } if(!Options.silent){ cout <<"==MODEL SUMMARY======================================="<<endl; cout <<" Model Run: "<<Options.run_name <<endl; cout <<" rvi filename: "<<Options.rvi_filename<<endl; cout <<"Output Directory: "<<Options.main_output_dir <<endl; cout <<" # SubBasins: "<<GetNumSubBasins() << " ("<< rescount << " reservoirs) ("<<SBdisablecount<<" disabled)"<<endl; cout <<" # HRUs: "<<GetNumHRUs() << " ("<<disablecount<<" disabled)"<<endl; cout <<" # Gauges: "<<GetNumGauges() <<endl; cout <<"#State Variables: "<<GetNumStateVars() <<endl; for (int i=0;i<GetNumStateVars();i++){ //don't write if convolution storage or advection storage? cout<<" - "; cout<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<" ("; cout<<CStateVariable::SVTypeToString (_aStateVarType[i],_aStateVarLayer[i])<<")"<<endl; } cout <<" # Processes: "<<GetNumProcesses() <<endl; for (int j=0;j<GetNumProcesses();j++) { cout<<" - "; cout<<GetProcessName(GetProcessType(j))<<endl; } cout <<" #Connections: "<<_nTotalConnections <<endl; cout <<"#Lat.Connections: "<<_nTotalLatConnections <<endl; cout <<" Duration: "<<Options.duration <<" d"<<endl; cout <<" Time step: "<<Options.timestep <<" d"<<endl; cout <<" Watershed Area: "<<_WatershedArea <<" km2 (simulated) of "<<allarea<<" km2"<<endl; cout <<"======================================================"<<endl; cout <<endl; if((Options.modeltype == MODELTYPE_COUPLED) || (Options.modeltype == MODELTYPE_GROUNDWATER)) { cout <<"==GROUNDWATER SUMMARY================================"<<endl; //CAquiferStack::SummarizeToScreen(); CGWGeometryClass::SummarizeToScreen(); CGWStressPeriodClass::SummarizeToScreen(); COverlapExchangeClass::SummarizeToScreen(); cout <<"====================================================="<<endl; } } } ////////////////////////////////////////////////////////////////// /// \brief run model diagnostics (at end of simulation) /// /// \param &Options [in] global model options // void CModel::RunDiagnostics (const optStruct &Options) { if ((_nObservedTS==0) || (_nDiagnostics==0)) {return;} ofstream DIAG; string tmpFilename; tmpFilename=FilenamePrepare("Diagnostics.csv",Options); DIAG.open(tmpFilename.c_str()); if (DIAG.fail()){ ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } //header DIAG<<"observed data series,filename,"; for (int j=0; j<_nDiagnostics;j++){ DIAG<<_pDiagnostics[j]->GetName()<<","; } DIAG<<endl; //body for (int i=0;i<_nObservedTS;i++) { DIAG<<_pObservedTS[i]->GetName()<<","<<_pObservedTS[i]->GetSourceFile() <<","; for (int j=0; j<_nDiagnostics;j++){ DIAG<<_pDiagnostics[j]->CalculateDiagnostic(_pModeledTS[i],_pObservedTS[i],_pObsWeightTS[i],Options)<<","; } DIAG<<endl; } DIAG.close(); } ////////////////////////////////////////////////////////////////// /// \brief Writes output headers for WatershedStorage.tb0 and Hydrographs.tb0 /// /// \param &Options [in] global model options // void CModel::WriteEnsimStandardHeaders(const optStruct &Options) { int i; time_struct tt, tt2; JulianConvert(0.0, Options.julian_start_day, Options.julian_start_year, Options.calendar, tt);//start of the timestep JulianConvert(Options.timestep, Options.julian_start_day, Options.julian_start_year, Options.calendar, tt2);//end of the timestep //WatershedStorage.tb0 //-------------------------------------------------------------- int iAtmPrecip = GetStateVarIndex(ATMOS_PRECIP); string tmpFilename; if (Options.write_watershed_storage) { tmpFilename = FilenamePrepare("WatershedStorage.tb0", Options); _STORAGE.open(tmpFilename.c_str()); if (_STORAGE.fail()){ ExitGracefully(("CModel::WriteEnsimStandardHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } _STORAGE << "#########################################################################" << endl; _STORAGE << ":FileType tb0 ASCII EnSim 1.0" << endl; _STORAGE << "#" << endl; _STORAGE << ":Application Raven" << endl; if(!Options.benchmarking){ _STORAGE << ":Version " << Options.version << endl; _STORAGE << ":CreationDate " << GetCurrentTime() << endl; } _STORAGE << "#" << endl; _STORAGE << "#------------------------------------------------------------------------" << endl; _STORAGE << "#" << endl; _STORAGE << ":RunName " << Options.run_name << endl; _STORAGE << ":Format Instantaneous" << endl; _STORAGE << "#" << endl; if (Options.suppressICs){ _STORAGE << ":StartTime " << tt2.date_string << " " << DecDaysToHours(tt2.julian_day) << endl; } else{ _STORAGE << ":StartTime " << tt.date_string << " " << DecDaysToHours(tt.julian_day) << endl; } if (Options.timestep != 1.0){ _STORAGE << ":DeltaT " << DecDaysToHours(Options.timestep) << endl; } else { _STORAGE << ":DeltaT 24:00:00.00" << endl; } _STORAGE << "#" << endl; _STORAGE<<":ColumnMetaData"<<endl; _STORAGE<<" :ColumnName rainfall snowfall \"Channel storage\" \"Rivulet storage\""; for (i=0;i<GetNumStateVars();i++){ if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){ _STORAGE<<" \""<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<"\"";}} _STORAGE<<" \"Total storage\" \"Cum. precip\" \"Cum. outflow\" \"MB error\""<<endl; _STORAGE<<" :ColumnUnits mm/d mm/d mm mm "; for (i=0;i<GetNumStateVars();i++){ if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){_STORAGE<<" mm";}} _STORAGE<<" mm mm mm mm"<<endl; _STORAGE<<" :ColumnType float float float float"; for (i=0;i<GetNumStateVars();i++){ if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){_STORAGE<<" float";}} _STORAGE<<" float float float float"<<endl; _STORAGE << " :ColumnFormat -1 -1 0 0"; for (i = 0; i < GetNumStateVars(); i++){ if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i != iAtmPrecip)){ _STORAGE << " 0"; } } _STORAGE << " 0 0 0 0" << endl; _STORAGE << ":EndColumnMetaData" << endl; _STORAGE << ":EndHeader" << endl; } //Hydrographs.tb0 //-------------------------------------------------------------- tmpFilename = FilenamePrepare("Hydrographs.tb0", Options); _HYDRO.open(tmpFilename.c_str()); if (_HYDRO.fail()){ ExitGracefully(("CModel::WriteEnsimStandardHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR); } _HYDRO << "#########################################################################" << endl; _HYDRO << ":FileType tb0 ASCII EnSim 1.0" << endl; _HYDRO << "#" << endl; _HYDRO << ":Application Raven" << endl; if(!Options.benchmarking){ _HYDRO << ":Version " << Options.version << endl; _HYDRO << ":CreationDate " << GetCurrentTime() << endl; } _HYDRO << "#" << endl; _HYDRO << "#------------------------------------------------------------------------" << endl; _HYDRO << "#" << endl; _HYDRO << ":RunName " << Options.run_name << endl; _HYDRO << "#" << endl; if (Options.ave_hydrograph){ _HYDRO << ":Format PeriodEnding" << endl; } else{ _HYDRO << ":Format Instantaneous" << endl; } if (((Options.period_ending) && (Options.ave_hydrograph)) || (Options.suppressICs )){ _HYDRO << ":StartTime " << tt2.date_string << " " << DecDaysToHours(tt2.julian_day) << endl; } else{ _HYDRO << ":StartTime " << tt.date_string << " " << DecDaysToHours(tt.julian_day) << endl; } if (Options.timestep!=1.0){_HYDRO<<":DeltaT " <<DecDaysToHours(Options.timestep)<<endl;} else {_HYDRO<<":DeltaT 24:00:00.00" <<endl;} _HYDRO<<"#"<<endl; double val = 0; //snapshot hydrograph double val2=1; if (Options.ave_hydrograph){ val = 1; } //continuous hydrograph if (Options.period_ending) { val *= -1; val2*=-1;}//period ending _HYDRO<<":ColumnMetaData"<<endl; _HYDRO<<" :ColumnName precip"; for (int p=0;p<_nSubBasins;p++){_HYDRO<<" Q_"<<_pSubBasins[p]->GetID();}_HYDRO<<endl; _HYDRO<<" :ColumnUnits mm/d"; for (int p=0;p<_nSubBasins;p++){_HYDRO<<" m3/s";}_HYDRO<<endl; _HYDRO<<" :ColumnType float"; for (int p=0;p<_nSubBasins;p++){_HYDRO<<" float";}_HYDRO<<endl; _HYDRO<<" :ColumnFormat "<<val2; for (int p=0;p<_nSubBasins;p++){_HYDRO<<" "<<val;}_HYDRO<<endl; _HYDRO<<":EndColumnMetaData"<<endl; _HYDRO<<":EndHeader"<<endl; } ////////////////////////////////////////////////////////////////// /// \brief Writes output headers for WatershedStorage.nc and Hydrographs.nc /// /// \param &Options [in] global model options /// original code developed by J. Mai // void CModel::WriteNetcdfStandardHeaders(const optStruct &Options) { #ifdef _RVNETCDF_ time_struct tt; // start time structure const int ndims1 = 1; const int ndims2 = 2; int dimids1[ndims1]; // array which will contain all dimension ids for a variable int ncid, varid_pre; // When we create netCDF variables and dimensions, we get back an ID for each one. int time_dimid, varid_time; // dimension ID (holds number of time steps) and variable ID (holds time values) for time int nSim, nbasins_dimid, varid_bsim; // # of sub-basins with simulated outflow, dimension ID, and // // variable to write basin IDs for simulated outflows int varid_qsim; // variable ID for simulated outflows int varid_qobs; // variable ID for observed outflows int varid_qin; // variable ID for observed inflows int retval; // error value for NetCDF routines string tmpFilename; int ibasin, p; // loop over all sub-basins size_t start[1], count[1]; // determines where and how much will be written to NetCDF const char *current_basin_name[1]; // current time in days since start time string tmp,tmp2,tmp3; // initialize all potential file IDs with -9 == "not existing and hence not opened" _HYDRO_ncid = -9; // output file ID for Hydrographs.nc (-9 --> not opened) _STORAGE_ncid = -9; // output file ID for WatershedStorage.nc (-9 --> not opened) _FORCINGS_ncid = -9; // output file ID for ForcingFunctions.nc (-9 --> not opened) //converts start day into "days since YYYY-MM-DD HH:MM:SS" (model start time) char starttime[200]; // start time string in format 'days since YYY-MM-DD HH:MM:SS' JulianConvert( 0.0,Options.julian_start_day, Options.julian_start_year, Options.calendar, tt); strcpy(starttime, "days since ") ; strcat(starttime, tt.date_string.c_str()) ; strcat(starttime, " "); strcat(starttime, DecDaysToHours(tt.julian_day,true).c_str()); if(Options.time_zone!=0) { strcat(starttime,TimeZoneToString(Options.time_zone).c_str()); } //==================================================================== // Hydrographs.nc //==================================================================== // Create the file. tmpFilename = FilenamePrepare("Hydrographs.nc", Options); retval = nc_create(tmpFilename.c_str(), NC_CLOBBER|NC_NETCDF4, &ncid); HandleNetCDFErrors(retval); _HYDRO_ncid = ncid; // ---------------------------------------------------------- // global attributes // ---------------------------------------------------------- WriteNetCDFGlobalAttributes(_HYDRO_ncid,Options,"Standard Output"); // ---------------------------------------------------------- // time // ---------------------------------------------------------- // (a) Define the DIMENSIONS. NetCDF will hand back an ID retval = nc_def_dim(_HYDRO_ncid, "time", NC_UNLIMITED, &time_dimid); HandleNetCDFErrors(retval); /// Define the time variable. Assign units attributes to the netCDF VARIABLES. dimids1[0] = time_dimid; retval = nc_def_var(_HYDRO_ncid, "time", NC_DOUBLE, ndims1,dimids1, &varid_time); HandleNetCDFErrors(retval); retval = nc_put_att_text(_HYDRO_ncid, varid_time, "units" , strlen(starttime) , starttime); HandleNetCDFErrors(retval); retval = nc_put_att_text(_HYDRO_ncid, varid_time, "calendar", strlen("gregorian"), "gregorian"); HandleNetCDFErrors(retval); retval = nc_put_att_text(_HYDRO_ncid, varid_time, "standard_name", strlen("time"), "time"); HandleNetCDFErrors(retval); // define precipitation variable varid_pre= NetCDFAddMetadata(_HYDRO_ncid, time_dimid,"precip","Precipitation","mm d**-1"); // ---------------------------------------------------------- // simulated/observed outflows // ---------------------------------------------------------- // (a) count number of simulated outflows "nSim" nSim = 0; for (p=0;p<_nSubBasins;p++){ if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){nSim++;} } if (nSim > 0) { // (b) create dimension "nbasins" retval = nc_def_dim(_HYDRO_ncid, "nbasins", nSim, &nbasins_dimid); HandleNetCDFErrors(retval); // (c) create variable and set attributes for"basin_name" dimids1[0] = nbasins_dimid; retval = nc_def_var(_HYDRO_ncid, "basin_name", NC_STRING, ndims1, dimids1, &varid_bsim); HandleNetCDFErrors(retval); tmp ="Name/ID of sub-basins with simulated outflows"; tmp2="timeseries_id"; tmp3="1"; retval = nc_put_att_text(_HYDRO_ncid, varid_bsim, "long_name", tmp.length(), tmp.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_text(_HYDRO_ncid, varid_bsim, "cf_role" , tmp2.length(),tmp2.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_text(_HYDRO_ncid, varid_bsim, "units" , tmp3.length(),tmp3.c_str()); HandleNetCDFErrors(retval); varid_qsim= NetCDFAddMetadata2D(_HYDRO_ncid, time_dimid,nbasins_dimid,"q_sim","Simulated outflows","m**3 s**-1"); varid_qobs= NetCDFAddMetadata2D(_HYDRO_ncid, time_dimid,nbasins_dimid,"q_obs","Observed outflows" ,"m**3 s**-1"); varid_qin = NetCDFAddMetadata2D(_HYDRO_ncid, time_dimid,nbasins_dimid,"q_in" ,"Observed inflows" ,"m**3 s**-1"); }// end if nSim>0 // End define mode. This tells netCDF we are done defining metadata. retval = nc_enddef(_HYDRO_ncid); HandleNetCDFErrors(retval); // write values to NetCDF // (a) write gauged basin names/IDs to variable "basin_name" ibasin = 0; for(p=0;p<_nSubBasins;p++){ if(_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){ if(_pSubBasins[p]->GetName()==""){ current_basin_name[0] = (to_string(_pSubBasins[p]->GetID())).c_str(); } else { current_basin_name[0] = (_pSubBasins[p]->GetName()).c_str(); } // write sub-basin name start[0] = ibasin; count[0] = 1; retval = nc_put_vara_string(_HYDRO_ncid,varid_bsim,start,count,&current_basin_name[0]); HandleNetCDFErrors(retval); ibasin++; } } //==================================================================== // WatershedStorage.nc //==================================================================== if (Options.write_watershed_storage) { tmpFilename = FilenamePrepare("WatershedStorage.nc", Options); retval = nc_create(tmpFilename.c_str(), NC_CLOBBER|NC_NETCDF4, &ncid); HandleNetCDFErrors(retval); _STORAGE_ncid = ncid; // ---------------------------------------------------------- // global attributes // ---------------------------------------------------------- WriteNetCDFGlobalAttributes(_STORAGE_ncid,Options,"Standard Output"); // ---------------------------------------------------------- // time vector // ---------------------------------------------------------- // Define the DIMENSIONS. NetCDF will hand back an ID retval = nc_def_dim(_STORAGE_ncid, "time", NC_UNLIMITED, &time_dimid); HandleNetCDFErrors(retval); /// Define the time variable. dimids1[0] = time_dimid; retval = nc_def_var(_STORAGE_ncid, "time", NC_DOUBLE, ndims1,dimids1, &varid_time); HandleNetCDFErrors(retval); retval = nc_put_att_text(_STORAGE_ncid, varid_time, "units" , strlen(starttime) , starttime); HandleNetCDFErrors(retval); retval = nc_put_att_text(_STORAGE_ncid, varid_time, "calendar", strlen("gregorian"), "gregorian"); HandleNetCDFErrors(retval); // ---------------------------------------------------------- // precipitation / channel storage / state vars / MB diagnostics // ---------------------------------------------------------- int varid; varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"rainfall","rainfall","mm d**-1"); varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"snowfall","snowfall","mm d**-1"); varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Channel Storage","Channel Storage","mm"); varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Reservoir Storage","Reservoir Storage","mm"); varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Rivulet Storage","Rivulet Storage","mm"); int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP); for(int i=0;i<_nStateVars;i++){ if((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){ string name =CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i]); varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,name,name,"mm"); } } varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Total","total water storage","mm"); varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Cum. Input","cumulative water input","mm"); varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Cum. Outflow","cumulative water output","mm"); varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"MB Error","mass balance error","mm"); // End define mode. This tells netCDF we are done defining metadata. retval = nc_enddef(_STORAGE_ncid); HandleNetCDFErrors(retval); } //==================================================================== // ForcingFunctions.nc //==================================================================== if(Options.write_forcings) { tmpFilename = FilenamePrepare("ForcingFunctions.nc",Options); retval = nc_create(tmpFilename.c_str(),NC_CLOBBER|NC_NETCDF4,&ncid); HandleNetCDFErrors(retval); _FORCINGS_ncid = ncid; WriteNetCDFGlobalAttributes(_FORCINGS_ncid,Options,"Standard Output"); // ---------------------------------------------------------- // time vector // ---------------------------------------------------------- retval = nc_def_dim(_FORCINGS_ncid,"time",NC_UNLIMITED,&time_dimid); HandleNetCDFErrors(retval); dimids1[0] = time_dimid; retval = nc_def_var(_FORCINGS_ncid,"time",NC_DOUBLE,ndims1,dimids1,&varid_time); HandleNetCDFErrors(retval); retval = nc_put_att_text(_FORCINGS_ncid,varid_time,"units",strlen(starttime),starttime); HandleNetCDFErrors(retval); retval = nc_put_att_text(_FORCINGS_ncid,varid_time,"calendar",strlen("gregorian"),"gregorian"); HandleNetCDFErrors(retval); // ---------------------------------------------------------- int varid; varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"rainfall","rainfall","mm d**-1"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"snowfall","snowfall","mm d**-1"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp","temp","C"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp_daily_min","temp_daily_min","C"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp_daily_max","temp_daily_max","C"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp_daily_ave","temp_daily_ave","C"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"air density","air density","kg m**-3"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"air pressure","air pressure","kPa"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"relative humidity","relative humidity",""); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"cloud cover","cloud cover",""); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"ET radiation","ET radiation","MJ m**-2 d**-1"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"SW radiation","SW radiation","MJ m**-2 d**-1"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"net SW radiation","net SW radiation","MJ m**-2 d**-1"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"LW radiation","LW radiation","MJ m**-2 d**-1"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"wind velocity","wind velocity","m s**-1"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"PET","PET","mm d**-1"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"OW PET","OW PET","mm d**-1"); varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"potential melt","potential melt","mm d**-1"); // End define mode. This tells netCDF we are done defining metadata. retval = nc_enddef(_FORCINGS_ncid); HandleNetCDFErrors(retval); } #endif // end compilation if NetCDF library is available } ////////////////////////////////////////////////////////////////// /// \brief Writes minor output data to WatershedStorage.tb0 and Hydrographs.tb0 /// /// \param &Options [in] global model options /// \param &tt [in] current time structure /// \todo [reorg] merge with WriteMinorOutput - too much complex code repetition here when only difference is (1) delimeter and (2) timestep info included in the .csv file // void CModel::WriteEnsimMinorOutput (const optStruct &Options, const time_struct &tt) { double currentWater; double S; int i; int iCumPrecip=GetStateVarIndex(ATMOS_PRECIP); double snowfall =GetAverageSnowfall(); double precip =GetAveragePrecip(); double channel_stor =GetTotalChannelStorage(); double reservoir_stor=GetTotalReservoirStorage(); double rivulet_stor =GetTotalRivuletStorage(); if ((tt.model_time==0) && (Options.suppressICs==true) && (Options.period_ending)){return;} //---------------------------------------------------------------- // write watershed state variables (WatershedStorage.tb0) if (Options.write_watershed_storage) { if (tt.model_time!=0){_STORAGE<<" "<<precip-snowfall<<" "<<snowfall;}//precip else {_STORAGE<<" 0.0 0.0";} _STORAGE<<" "<<channel_stor+reservoir_stor<<" "<<rivulet_stor; currentWater=0.0; for (i=0;i<GetNumStateVars();i++){ if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iCumPrecip)){ S=GetAvgStateVar(i);_STORAGE<<" "<<FormatDouble(S);currentWater+=S; } } currentWater+=channel_stor+rivulet_stor; if(tt.model_time==0){ // \todo [fix]: this fixes a mass balance bug in reservoir simulations, but there is certainly a more proper way to do it // JRC: I think somehow this is being double counted in the delta V calculations in the first timestep for(int p=0;p<_nSubBasins;p++){ if(_pSubBasins[p]->GetReservoir()!=NULL){ currentWater+=_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2; currentWater-=_pSubBasins[p]->GetIntegratedOutflow (Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2; } } } _STORAGE<<" "<<currentWater<<" "<<_CumulInput<<" "<<_CumulOutput<<" "<<FormatDouble((currentWater-_initWater)+(_CumulOutput-_CumulInput)); _STORAGE<<endl; } //---------------------------------------------------------------- //Write hydrographs for gauged watersheds (ALWAYS DONE) (Hydrographs.tb0) if ((Options.ave_hydrograph) && (tt.model_time!=0)) { _HYDRO<<" "<<GetAveragePrecip(); for (int p=0;p<_nSubBasins;p++){ if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())) { _HYDRO<<" "<<_pSubBasins[p]->GetIntegratedOutflow(Options.timestep)/(Options.timestep*SEC_PER_DAY); } } _HYDRO<<endl; } else { if (tt.model_time!=0){_HYDRO<<" "<<GetAveragePrecip();} else {_HYDRO<<" 0.0";} for (int p=0;p<_nSubBasins;p++){ if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())) { _HYDRO<<" "<<_pSubBasins[p]->GetOutflowRate(); } } _HYDRO<<endl; } } ////////////////////////////////////////////////////////////////// /// \brief Writes minor output data to WatershedStorage.nc and Hydrographs.nc /// /// \param &Options [in] global model options /// \param &tt [in] current time structure // void CModel::WriteNetcdfMinorOutput ( const optStruct &Options, const time_struct &tt) { #ifdef _RVNETCDF_ int retval; // error value for NetCDF routines int time_id; // variable id in NetCDF for time size_t time_index[1], count1[1]; // determines where and how much will be written to NetCDF; 1D variable (pre, time) size_t start2[2], count2[2]; // determines where and how much will be written to NetCDF; 2D variable (qsim, qobs, qin) double current_time[1]; // current time in days since start time double current_prec[1]; // precipitation of current time step size_t time_ind2; current_time[0] = tt.model_time; time_index [0] = int(round(tt.model_time/Options.timestep)); // element of NetCDF array that will be written time_ind2 =int(round(tt.model_time/Options.timestep)); count1[0] = 1; // writes exactly one time step //==================================================================== // Hydrographs.nc //==================================================================== int precip_id; // variable id in NetCDF for precipitation int qsim_id; // variable id in NetCDF for simulated outflow int qobs_id; // variable id in NetCDF for observed outflow int qin_id; // variable id in NetCDF for observed inflow // (a) count how many values need to be written for q_obs, q_sim, q_in int iSim, nSim; // current and total # of sub-basins with simulated outflows nSim = 0; for (int p=0;p<_nSubBasins;p++){ if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){nSim++;} } // (b) allocate memory if necessary double *outflow_obs=NULL; // q_obs double *outflow_sim=NULL; // q_sim double *inflow_obs =NULL; // q_in if(nSim>0){ outflow_sim=new double[nSim]; outflow_obs=new double[nSim]; inflow_obs =new double[nSim]; } // (c) obtain data iSim = 0; current_prec[0] = NETCDF_BLANK_VALUE; if ((Options.ave_hydrograph) && (current_time[0] != 0.0)) { current_prec[0] = GetAveragePrecip(); for (int p=0;p<_nSubBasins;p++) { if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){ outflow_sim[iSim] = _pSubBasins[p]->GetIntegratedOutflow(Options.timestep)/(Options.timestep*SEC_PER_DAY); outflow_obs[iSim] = NETCDF_BLANK_VALUE; for (int i = 0; i < _nObservedTS; i++){ if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID())) { double val = _pObservedTS[i]->GetAvgValue(current_time[0],Options.timestep); //time shift handled in CTimeSeries::Parse if ((val != RAV_BLANK_DATA) && (current_time[0]>0)){ outflow_obs[iSim] = val; } } } inflow_obs[iSim] =NETCDF_BLANK_VALUE; if (_pSubBasins[p]->GetReservoir() != NULL){ inflow_obs[iSim] = _pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/(Options.timestep*SEC_PER_DAY); } iSim++; } } } else { // point-value hydrograph if (current_time[0] != 0.0){current_prec[0] = GetAveragePrecip();} //watershed-wide precip else {current_prec[0] = NETCDF_BLANK_VALUE;} // was originally '---' for (int p=0;p<_nSubBasins;p++) { if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){ outflow_sim[iSim] = _pSubBasins[p]->GetOutflowRate(); outflow_obs[iSim] = NETCDF_BLANK_VALUE; for (int i = 0; i < _nObservedTS; i++){ if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID())) { double val = _pObservedTS[i]->GetAvgValue(current_time[0],Options.timestep); if ((val != RAV_BLANK_DATA) && (current_time[0]>0)){ outflow_obs[iSim] = val; } } } inflow_obs[iSim] =NETCDF_BLANK_VALUE; if (_pSubBasins[p]->GetReservoir() != NULL){ inflow_obs[iSim] = _pSubBasins[p]->GetReservoirInflow(); } iSim++; } } } // write new time step retval = nc_inq_varid (_HYDRO_ncid, "time", &time_id); HandleNetCDFErrors(retval); retval = nc_put_vara_double(_HYDRO_ncid, time_id, time_index, count1, &current_time[0]); HandleNetCDFErrors(retval); // write precipitation values retval = nc_inq_varid (_HYDRO_ncid, "precip", &precip_id); HandleNetCDFErrors(retval); retval = nc_put_vara_double(_HYDRO_ncid,precip_id,time_index,count1,&current_prec[0]); HandleNetCDFErrors(retval); // write simulated outflow/obs outflow/obs inflow values if (nSim > 0){ start2[0] = int(round(current_time[0]/Options.timestep)); // element of NetCDF array that will be written start2[1] = 0; // element of NetCDF array that will be written count2[0] = 1; // writes exactly one time step count2[1] = nSim; // writes exactly nSim elements retval = nc_inq_varid (_HYDRO_ncid, "q_sim", &qsim_id); HandleNetCDFErrors(retval); retval = nc_inq_varid (_HYDRO_ncid, "q_obs", &qobs_id); HandleNetCDFErrors(retval); retval = nc_inq_varid (_HYDRO_ncid, "q_in", &qin_id); HandleNetCDFErrors(retval); retval = nc_put_vara_double(_HYDRO_ncid, qsim_id, start2, count2, &outflow_sim[0]); HandleNetCDFErrors(retval); retval = nc_put_vara_double(_HYDRO_ncid, qobs_id, start2, count2, &outflow_obs[0]); HandleNetCDFErrors(retval); retval = nc_put_vara_double(_HYDRO_ncid, qin_id, start2, count2, &inflow_obs[0]); HandleNetCDFErrors(retval); } delete[] outflow_obs; delete[] outflow_sim; delete[] inflow_obs; //==================================================================== // WatershedStorage.nc //==================================================================== if (Options.write_watershed_storage) { double snowfall =GetAverageSnowfall(); double precip =GetAveragePrecip(); double channel_stor =GetTotalChannelStorage(); double reservoir_stor=GetTotalReservoirStorage(); double rivulet_stor =GetTotalRivuletStorage(); // write new time step retval = nc_inq_varid (_STORAGE_ncid, "time", &time_id); HandleNetCDFErrors(retval); retval = nc_put_vara_double(_STORAGE_ncid, time_id, time_index, count1, &current_time[0]); HandleNetCDFErrors(retval); if(tt.model_time!=0){ AddSingleValueToNetCDF(_STORAGE_ncid,"rainfall" ,time_ind2,precip-snowfall); AddSingleValueToNetCDF(_STORAGE_ncid,"snowfall" ,time_ind2,snowfall); } AddSingleValueToNetCDF(_STORAGE_ncid,"Channel Storage" ,time_ind2,channel_stor); AddSingleValueToNetCDF(_STORAGE_ncid,"Reservoir Storage",time_ind2,reservoir_stor); AddSingleValueToNetCDF(_STORAGE_ncid,"Rivulet Storage" ,time_ind2,rivulet_stor); double currentWater=0.0; double S;string short_name; int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP); for (int i=0;i<GetNumStateVars();i++) { if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)) { S=FormatDouble(GetAvgStateVar(i)); short_name=CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i]); AddSingleValueToNetCDF(_STORAGE_ncid, short_name.c_str(),time_ind2,S); currentWater+=S; } } currentWater+=channel_stor+rivulet_stor+reservoir_stor; if(tt.model_time==0){ // \todo [fix]: this fixes a mass balance bug in reservoir simulations, but there is certainly a more proper way to do it // JRC: I think somehow this is being double counted in the delta V calculations in the first timestep for(int p=0;p<_nSubBasins;p++){ if(_pSubBasins[p]->GetReservoir()!=NULL){ currentWater+=_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2; currentWater-=_pSubBasins[p]->GetIntegratedOutflow (Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2; } } } AddSingleValueToNetCDF(_STORAGE_ncid,"Total" ,time_ind2,currentWater); AddSingleValueToNetCDF(_STORAGE_ncid,"Cum. Input" ,time_ind2,_CumulInput); AddSingleValueToNetCDF(_STORAGE_ncid,"Cum. Outflow" ,time_ind2,_CumulOutput); AddSingleValueToNetCDF(_STORAGE_ncid,"MB Error" ,time_ind2,FormatDouble((currentWater-_initWater)+(_CumulOutput-_CumulInput))); } //==================================================================== // ForcingFunctions.nc //==================================================================== if(Options.write_forcings) { force_struct *pFave; force_struct faveStruct = GetAverageForcings(); pFave = &faveStruct; // write new time step retval = nc_inq_varid (_FORCINGS_ncid, "time", &time_id); HandleNetCDFErrors(retval); retval = nc_put_vara_double(_FORCINGS_ncid, time_id, time_index, count1, &current_time[0]); HandleNetCDFErrors(retval); // write data AddSingleValueToNetCDF(_FORCINGS_ncid,"rainfall" ,time_ind2,pFave->precip*(1.0-pFave->snow_frac)); AddSingleValueToNetCDF(_FORCINGS_ncid,"snowfall" ,time_ind2,pFave->precip*( pFave->snow_frac)); AddSingleValueToNetCDF(_FORCINGS_ncid,"temp" ,time_ind2,pFave->temp_ave); AddSingleValueToNetCDF(_FORCINGS_ncid,"temp_daily_min" ,time_ind2,pFave->temp_daily_min); AddSingleValueToNetCDF(_FORCINGS_ncid,"temp_daily_max" ,time_ind2,pFave->temp_daily_max); AddSingleValueToNetCDF(_FORCINGS_ncid,"temp_daily_ave" ,time_ind2,pFave->temp_daily_ave); AddSingleValueToNetCDF(_FORCINGS_ncid,"air density" ,time_ind2,pFave->air_dens); AddSingleValueToNetCDF(_FORCINGS_ncid,"air pressure" ,time_ind2,pFave->air_pres); AddSingleValueToNetCDF(_FORCINGS_ncid,"relative humidity",time_ind2,pFave->rel_humidity); AddSingleValueToNetCDF(_FORCINGS_ncid,"cloud cover" ,time_ind2,pFave->cloud_cover); AddSingleValueToNetCDF(_FORCINGS_ncid,"ET radiation" ,time_ind2,pFave->ET_radia); AddSingleValueToNetCDF(_FORCINGS_ncid,"SW radiation" ,time_ind2,pFave->SW_radia); AddSingleValueToNetCDF(_FORCINGS_ncid,"net SW radiation" ,time_ind2,pFave->SW_radia_net); AddSingleValueToNetCDF(_FORCINGS_ncid,"LW radiation" ,time_ind2,pFave->cloud_cover); AddSingleValueToNetCDF(_FORCINGS_ncid,"wind velocity" ,time_ind2,pFave->wind_vel); AddSingleValueToNetCDF(_FORCINGS_ncid,"PET" ,time_ind2,pFave->PET); AddSingleValueToNetCDF(_FORCINGS_ncid,"OW PET" ,time_ind2,pFave->OW_PET); AddSingleValueToNetCDF(_FORCINGS_ncid,"potential melt" ,time_ind2,pFave->potential_melt); } #endif } ////////////////////////////////////////////////////////////////// /// \brief creates specified output directory, if needed /// /// \param &Options [in] global model options // void PrepareOutputdirectory(const optStruct &Options) { if (Options.output_dir!="") { #if defined(_WIN32) _mkdir(Options.output_dir.c_str()); #elif defined(__linux__) mkdir(Options.output_dir.c_str(), 0777); #endif } g_output_directory=Options.main_output_dir;//necessary evil } ////////////////////////////////////////////////////////////////// /// \brief returns directory path given filename /// /// \param fname [in] filename, e.g., C:\temp\thisfile.txt returns c:\temp // string GetDirectoryName(const string &fname) { size_t pos = fname.find_last_of("\\/"); if (std::string::npos == pos){ return ""; } else { return fname.substr(0, pos);} } ////////////////////////////////////////////////////////////////// /// \brief returns directory path given filename and relative path /// /// \param filename [in] filename, e.g., C:/temp/thisfile.txt returns c:/temp /// \param relfile [in] filename of reference file /// e.g., /// absolute path of reference file is adopted /// if filename = something.txt and relfile= c:/temp/myfile.rvi, returns c:/temp/something.txt /// /// relative path of reference file is adopted /// if filename = something.txt and relfile= ../dir/myfile.rvi, returns ../dir/something.txt /// /// if path of reference file is same as file, then nothing changes /// if filename = ../temp/something.txt and relfile= ../temp/myfile.rvi, returns ../temp/something.txt /// /// if absolute paths of file is given, nothing changes /// if filename = c:/temp/something.txt and relfile= ../temp/myfile.rvi, returns c:/temp/something.txt // string CorrectForRelativePath(const string filename,const string relfile) { string filedir = GetDirectoryName(relfile); //if a relative path name, e.g., "/path/model.rvt", only returns e.g., "/path" if (StringToUppercase(filename).find(StringToUppercase(filedir)) == string::npos)//checks to see if absolute dir already included in redirect filename { string firstchar = filename.substr(0, 1); // if '/' --> absolute path on UNIX systems string secondchar = filename.substr(1, 1); // if ':' --> absolute path on WINDOWS system if ( (firstchar.compare("/") != 0) && (secondchar.compare(":") != 0) ){ // cout << "This is not an absolute filename! --> " << filename << endl; //+"//" //cout << "StandardOutput: corrected filename: " << filedir + "//" + filename << endl; return filedir + "//" + filename; } } // cout << "StandardOutput: corrected filename: " << filename << endl; return filename; } ////////////////////////////////////////////////////////////////// /// \brief adds metadata of attribute to NetCDF file /// \param fileid [in] NetCDF output file id /// \param time_dimid [in], identifier of time attribute /// \param shortname [in] attribute short name /// \param longname [in] attribute long name /// \param units [in] attribute units as string // int NetCDFAddMetadata(const int fileid,const int time_dimid,string shortname,string longname,string units) { int varid(0); #ifdef _RVNETCDF_ int retval; int dimids[1]; dimids[0] = time_dimid; static double fill_val[] = {NETCDF_BLANK_VALUE}; static double miss_val[] = {NETCDF_BLANK_VALUE}; // (a) create variable precipitation retval = nc_def_var(fileid,shortname.c_str(),NC_DOUBLE,1,dimids,&varid); HandleNetCDFErrors(retval); // (b) add attributes to variable retval = nc_put_att_text (fileid,varid,"units",units.length(),units.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_text (fileid,varid,"long_name",longname.length(),longname.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_double(fileid,varid,"_FillValue",NC_DOUBLE,1,fill_val); HandleNetCDFErrors(retval); retval = nc_put_att_double(fileid,varid,"missing_value",NC_DOUBLE,1,miss_val); HandleNetCDFErrors(retval); #endif return varid; } ////////////////////////////////////////////////////////////////// /// \brief adds metadata of attribute to NetCDF file for 2D data (time,nbasins) /// \param fileid [in] NetCDF output file id /// \param time_dimid [in], identifier of time attribute /// \param nbasins_dimid [in], identifier of # basins attribute /// \param shortname [in] attribute short name /// \param longname [in] attribute long name /// \param units [in] attribute units as string // int NetCDFAddMetadata2D(const int fileid,const int time_dimid,int nbasins_dimid,string shortname,string longname,string units) { int varid(0); #ifdef _RVNETCDF_ int retval; int dimids2[2]; string tmp; static double fill_val[] = {NETCDF_BLANK_VALUE}; static double miss_val[] = {NETCDF_BLANK_VALUE}; dimids2[0] = time_dimid; dimids2[1] = nbasins_dimid; // (a) create variable retval = nc_def_var(fileid,shortname.c_str(),NC_DOUBLE,2,dimids2,&varid); HandleNetCDFErrors(retval); tmp = "basin_name"; // (b) add attributes to variable retval = nc_put_att_text( fileid,varid,"units", units.length(), units.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_text( fileid,varid,"long_name", longname.length(),longname.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_double(fileid,varid,"_FillValue", NC_DOUBLE,1, fill_val); HandleNetCDFErrors(retval); retval = nc_put_att_double(fileid,varid,"missing_value", NC_DOUBLE,1, miss_val); HandleNetCDFErrors(retval); retval = nc_put_att_text( fileid,varid,"coordinates", tmp.length(), tmp.c_str()); HandleNetCDFErrors(retval); #endif return varid; } ////////////////////////////////////////////////////////////////// /// \brief writes global attributes to netcdf file identified with out_ncid. Must be timeSeries featureType. /// \param out_ncid [in] NetCDF file identifier /// \param Options [in] model Options structure /// \param descript [in] contents of NetCDF description attribute // void WriteNetCDFGlobalAttributes(const int out_ncid,const optStruct &Options,const string descript) { ExitGracefullyIf(out_ncid==-9,"WriteNetCDFGlobalAttributes: netCDF file not open",RUNTIME_ERR); int retval(0); string att,val; #ifdef _RVNETCDF_ retval = nc_put_att_text(out_ncid, NC_GLOBAL, "Conventions", strlen("CF-1.6"), "CF-1.6"); HandleNetCDFErrors(retval); retval = nc_put_att_text(out_ncid, NC_GLOBAL, "featureType", strlen("timeSeries"), "timeSeries"); HandleNetCDFErrors(retval); retval = nc_put_att_text(out_ncid, NC_GLOBAL, "history", strlen("Created by Raven"),"Created by Raven"); HandleNetCDFErrors(retval); retval = nc_put_att_text(out_ncid, NC_GLOBAL, "description", strlen(descript.c_str()), descript.c_str()); HandleNetCDFErrors(retval); for(int i=0;i<Options.nNetCDFattribs;i++){ att=Options.aNetCDFattribs[i].attribute; val=Options.aNetCDFattribs[i].value; retval = nc_put_att_text(out_ncid,NC_GLOBAL,att.c_str(),strlen(val.c_str()),val.c_str()); HandleNetCDFErrors(retval); } #endif } ////////////////////////////////////////////////////////////////// /// \brief adds single value of attribute 'shortname' linked to time time_index to NetCDF file /// \param out_ncid [in] NetCDF file identifier /// \param shortname [in] short name of attribute (e.g., 'rainfall') /// \param time_index [in] index of current time step /// \param value [in] value of attribute at current time step // void AddSingleValueToNetCDF(const int out_ncid,const string &shortname,const size_t time_index,const double &value) { static size_t count1[1]; //static for speed of execution static size_t time_ind[1]; static double val[1]; int var_id(0),retval(0); time_ind[0]=time_index; count1[0]=1; val[0]=value; #ifdef _RVNETCDF_ retval = nc_inq_varid (out_ncid,shortname.c_str(),&var_id); HandleNetCDFErrors(retval); retval = nc_put_vara_double(out_ncid,var_id,time_ind,count1,&val[0]); HandleNetCDFErrors(retval); #endif }
43.10613
171
0.582575
Okanagan-Basin-Water-Board