hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
1636eed6a8a6ee6fb15e097dec74f26da3b5d807
2,705
cpp
C++
aws-cpp-sdk-ecs/source/model/InstanceHealthCheckState.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-ecs/source/model/InstanceHealthCheckState.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-ecs/source/model/InstanceHealthCheckState.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ecs/model/InstanceHealthCheckState.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace ECS { namespace Model { namespace InstanceHealthCheckStateMapper { static const int OK_HASH = HashingUtils::HashString("OK"); static const int IMPAIRED_HASH = HashingUtils::HashString("IMPAIRED"); static const int INSUFFICIENT_DATA_HASH = HashingUtils::HashString("INSUFFICIENT_DATA"); static const int INITIALIZING_HASH = HashingUtils::HashString("INITIALIZING"); InstanceHealthCheckState GetInstanceHealthCheckStateForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == OK_HASH) { return InstanceHealthCheckState::OK; } else if (hashCode == IMPAIRED_HASH) { return InstanceHealthCheckState::IMPAIRED; } else if (hashCode == INSUFFICIENT_DATA_HASH) { return InstanceHealthCheckState::INSUFFICIENT_DATA; } else if (hashCode == INITIALIZING_HASH) { return InstanceHealthCheckState::INITIALIZING; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<InstanceHealthCheckState>(hashCode); } return InstanceHealthCheckState::NOT_SET; } Aws::String GetNameForInstanceHealthCheckState(InstanceHealthCheckState enumValue) { switch(enumValue) { case InstanceHealthCheckState::OK: return "OK"; case InstanceHealthCheckState::IMPAIRED: return "IMPAIRED"; case InstanceHealthCheckState::INSUFFICIENT_DATA: return "INSUFFICIENT_DATA"; case InstanceHealthCheckState::INITIALIZING: return "INITIALIZING"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace InstanceHealthCheckStateMapper } // namespace Model } // namespace ECS } // namespace Aws
31.823529
96
0.63475
[ "model" ]
163d735fe121a640fb95a8de2d52842d2b8a4293
4,367
cpp
C++
Jit/compiler.cpp
brianherman/cinder
f1ed7bee94bd91e23b7b78038de5eb2fbb732678
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Jit/compiler.cpp
brianherman/cinder
f1ed7bee94bd91e23b7b78038de5eb2fbb732678
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Jit/compiler.cpp
brianherman/cinder
f1ed7bee94bd91e23b7b78038de5eb2fbb732678
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #include "Jit/compiler.h" #include "Jit/disassembler.h" #include "Jit/hir/builder.h" #include "Jit/hir/optimization.h" #include "Jit/hir/printer.h" #include "Jit/hir/ssa.h" #include "Jit/jit_x_options.h" #include "Jit/log.h" #include "Python.h" namespace jit { void CompiledFunction::Disassemble() const { JIT_CHECK(false, "Disassemble() cannot be called in a release build."); } void CompiledFunction::PrintHIR() const { JIT_CHECK(false, "PrintHIR() cannot be called in a release build."); } void CompiledFunctionDebug::Disassemble() const { disassemble( reinterpret_cast<const char*>(entry_point()), GetCodeSize(), reinterpret_cast<vma_t>(entry_point())); } void CompiledFunctionDebug::PrintHIR() const { jit::hir::HIRPrinter printer; printer.Print(*irfunc_.get()); } template <typename T> static void runPass(hir::Function& func) { T pass; JIT_LOGIF( g_dump_hir_passes, "HIR for %s before pass %s:\n%s", func.fullname, pass.name(), func); pass.Run(func); JIT_LOGIF( g_dump_hir_passes, "HIR for %s after pass %s:\n%s", func.fullname, pass.name(), func); JIT_DCHECK( checkFunc(func, std::cerr), "Function %s failed verification after pass %s:\n%s", func.fullname, pass.name(), func); } void Compiler::runPasses(jit::hir::Function& irfunc) { // SSAify must come first; nothing but SSAify should ever see non-SSA HIR runPass<jit::hir::SSAify>(irfunc); runPass<jit::hir::RedundantConversionElimination>(irfunc); runPass<jit::hir::LoadAttrSpecialization>(irfunc); runPass<jit::hir::NullCheckElimination>(irfunc); runPass<jit::hir::DynamicComparisonElimination>(irfunc); runPass<jit::hir::CallOptimization>(irfunc); runPass<jit::hir::PhiElimination>(irfunc); runPass<jit::hir::RefcountInsertion>(irfunc); JIT_LOGIF( g_dump_final_hir, "Optimized HIR for %s:\n%s", irfunc.fullname, irfunc); } std::unique_ptr<CompiledFunction> Compiler::Compile(PyObject* func) { if (!PyFunction_Check(func)) { auto repr = Ref<>::steal(PyObject_Repr(func)); if (repr == nullptr) { JIT_LOG( "Refusing to compile object of type '%.200s'", Py_TYPE(func)->tp_name); } else { JIT_LOG("Refusing to compile non-function %s", PyUnicode_AsUTF8(repr)); } return nullptr; } std::string fullname = funcFullname(reinterpret_cast<PyFunctionObject*>(func)); PyObject* globals = PyFunction_GetGlobals(func); if (!PyDict_CheckExact(globals)) { JIT_DLOG( "Refusing to compile %s: globals is a %.200s, not a dict", fullname, Py_TYPE(globals)->tp_name); return nullptr; } PyObject* builtins = PyEval_GetBuiltins(); if (!PyDict_CheckExact(builtins)) { JIT_DLOG( "Refusing to compile %s: builtins is a %.200s, not a dict", fullname, Py_TYPE(builtins)->tp_name); return nullptr; } JIT_DLOG("Compiling %s @ %p", fullname, func); jit::hir::HIRBuilder hir_builder; std::unique_ptr<jit::hir::Function> irfunc(hir_builder.BuildHIR(func)); if (irfunc == nullptr) { JIT_DLOG("Lowering to HIR failed %s", fullname); return nullptr; } if (g_dump_hir) { JIT_LOG("Initial HIR for %s:\n%s", fullname, *irfunc); } Compiler::runPasses(*irfunc); auto ngen = ngen_factory_(irfunc.get()); if (ngen == nullptr) { return nullptr; } auto entry = ngen->GetEntryPoint(); if (entry == nullptr) { JIT_DLOG("Generating native code for %s failed", fullname); return nullptr; } JIT_DLOG("Finished compiling %s", fullname); int func_size = ngen->GetCompiledFunctionSize(); int stack_size = ngen->GetCompiledFunctionStackSize(); int spill_stack_size = ngen->GetCompiledFunctionSpillStackSize(); if (g_debug) { return std::make_unique<CompiledFunctionDebug>( reinterpret_cast<vectorcallfunc>(entry), ngen->codeRuntime(), func_size, stack_size, spill_stack_size, std::move(irfunc), std::move(ngen)); } else { return std::make_unique<CompiledFunction>( reinterpret_cast<vectorcallfunc>(entry), ngen->codeRuntime(), func_size, stack_size, spill_stack_size); } } } // namespace jit
27.29375
78
0.6643
[ "object" ]
163dc44c6d18eec30a409426d6c04442a8350b9c
9,342
cpp
C++
src/gui/CTxDetailsDialog.cpp
gasteve/bitcoin
b5e79be9e7612c31403a2231ba03850f495ea9c1
[ "MIT" ]
1
2017-05-18T17:12:00.000Z
2017-05-18T17:12:00.000Z
src/gui/CTxDetailsDialog.cpp
gasteve/bitcoin
b5e79be9e7612c31403a2231ba03850f495ea9c1
[ "MIT" ]
null
null
null
src/gui/CTxDetailsDialog.cpp
gasteve/bitcoin
b5e79be9e7612c31403a2231ba03850f495ea9c1
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // CTxDetailsDialog // #include "CTxDetailsDialog.h" #include "main.h" #include "script.h" #include "base58.h" #include "CCriticalBlock.h" CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetailsDialogBase(parent) { CRITICAL_BLOCK(cs_mapAddressBook) { string strHTML; strHTML.reserve(4000); strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>"; int64 nTime = wtx.GetTxTime(); int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; strHTML += _("<b>Status:</b> ") + FormatTxStatus(wtx); int nRequests = wtx.GetRequestCount(); if (nRequests != -1) { if (nRequests == 0) strHTML += _(", has not been successfully broadcast yet"); else if (nRequests == 1) strHTML += strprintf(_(", broadcast through %d node"), nRequests); else strHTML += strprintf(_(", broadcast through %d nodes"), nRequests); } strHTML += "<br>"; strHTML += _("<b>Date:</b> ") + (nTime ? DateTimeStr(nTime) : "") + "<br>"; // // From // if (wtx.IsCoinBase()) { strHTML += _("<b>Source:</b> Generated<br>"); } else if (!wtx.mapValue["from"].empty()) { // Online transaction if (!wtx.mapValue["from"].empty()) strHTML += _("<b>From:</b> ") + HtmlEscape(wtx.mapValue["from"]) + "<br>"; } else { // Offline transaction if (nNet > 0) { // Credit foreach(const CTxOut& txout, wtx.vout) { if (txout.IsMine()) { vector<unsigned char> vchPubKey; if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey)) { string strAddress = PubKeyToAddress(vchPubKey); if (mapAddressBook.count(strAddress)) { strHTML += string() + _("<b>From:</b> ") + _("unknown") + "<br>"; strHTML += _("<b>To:</b> "); strHTML += HtmlEscape(strAddress); if (!mapAddressBook[strAddress].empty()) strHTML += _(" (yours, label: ") + mapAddressBook[strAddress] + ")"; else strHTML += _(" (yours)"); strHTML += "<br>"; } } break; } } } } // // To // string strAddress; if (!wtx.mapValue["to"].empty()) { // Online transaction strAddress = wtx.mapValue["to"]; strHTML += _("<b>To:</b> "); if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty()) strHTML += mapAddressBook[strAddress] + " "; strHTML += HtmlEscape(strAddress) + "<br>"; } // // Amount // if (wtx.IsCoinBase() && nCredit == 0) { // // Coinbase // int64 nUnmatured = 0; foreach(const CTxOut& txout, wtx.vout) nUnmatured += txout.GetCredit(); strHTML += _("<b>Credit:</b> "); if (wtx.IsInMainChain()) strHTML += strprintf(_("(%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity()); else strHTML += _("(not accepted)"); strHTML += "<br>"; } else if (nNet > 0) { // // Credit // strHTML += _("<b>Credit:</b> ") + FormatMoney(nNet) + "<br>"; } else { bool fAllFromMe = true; foreach(const CTxIn& txin, wtx.vin) fAllFromMe = fAllFromMe && txin.IsMine(); bool fAllToMe = true; foreach(const CTxOut& txout, wtx.vout) fAllToMe = fAllToMe && txout.IsMine(); if (fAllFromMe) { // // Debit // foreach(const CTxOut& txout, wtx.vout) { if (txout.IsMine()) continue; if (wtx.mapValue["to"].empty()) { // Offline transaction uint160 hash160; if (ExtractHash160(txout.scriptPubKey, hash160)) { string strAddress = Hash160ToAddress(hash160); strHTML += _("<b>To:</b> "); if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty()) strHTML += mapAddressBook[strAddress] + " "; strHTML += strAddress; strHTML += "<br>"; } } strHTML += _("<b>Debit:</b> ") + FormatMoney(-txout.nValue) + "<br>"; } if (fAllToMe) { // Payment to self int64 nChange = wtx.GetChange(); int64 nValue = nCredit - nChange; strHTML += _("<b>Debit:</b> ") + FormatMoney(-nValue) + "<br>"; strHTML += _("<b>Credit:</b> ") + FormatMoney(nValue) + "<br>"; } int64 nTxFee = nDebit - wtx.GetValueOut(); if (nTxFee > 0) strHTML += _("<b>Transaction fee:</b> ") + FormatMoney(-nTxFee) + "<br>"; } else { // // Mixed debit transaction // foreach(const CTxIn& txin, wtx.vin) if (txin.IsMine()) strHTML += _("<b>Debit:</b> ") + FormatMoney(-txin.GetDebit()) + "<br>"; foreach(const CTxOut& txout, wtx.vout) if (txout.IsMine()) strHTML += _("<b>Credit:</b> ") + FormatMoney(txout.GetCredit()) + "<br>"; } } strHTML += _("<b>Net amount:</b> ") + FormatMoney(nNet, true) + "<br>"; // // Message // if (!wtx.mapValue["message"].empty()) strHTML += string() + "<br><b>" + _("Message:") + "</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>"; if (!wtx.mapValue["comment"].empty()) strHTML += string() + "<br><b>" + _("Comment:") + "</b><br>" + HtmlEscape(wtx.mapValue["comment"], true) + "<br>"; if (wtx.IsCoinBase()) strHTML += string() + "<br>" + _("Generated coins must wait 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to \"not accepted\" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "<br>"; // // Debug view // if (fDebug) { strHTML += "<hr><br>debug print<br><br>"; foreach(const CTxIn& txin, wtx.vin) if (txin.IsMine()) strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>"; foreach(const CTxOut& txout, wtx.vout) if (txout.IsMine()) strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>"; strHTML += "<br><b>Transaction:</b><br>"; strHTML += HtmlEscape(wtx.ToString(), true); strHTML += "<br><b>Inputs:</b><br>"; CRITICAL_BLOCK(cs_mapWallet) { foreach(const CTxIn& txin, wtx.vin) { COutPoint prevout = txin.prevout; map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (prevout.n < prev.vout.size()) { strHTML += HtmlEscape(prev.ToString(), true); strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", "; strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>"; } } } } } strHTML += "</font></html>"; string(strHTML.begin(), strHTML.end()).swap(strHTML); m_htmlWin->SetPage(strHTML); m_buttonOK->SetFocus(); } } void CTxDetailsDialog::OnButtonOK(wxCommandEvent& event) { EndModal(false); }
35.930769
404
0.422929
[ "vector" ]
f38088d2c9d1127516c4d07bb77bb5873ff67b80
6,506
hpp
C++
source/redx/scripting/iproperty.hpp
clayne/CyberpunkSaveEditor
2069ea833ced56f549776179c2147b27d32d650c
[ "MIT" ]
276
2020-12-21T11:54:44.000Z
2022-03-28T16:49:44.000Z
source/redx/scripting/iproperty.hpp
13397729377/CyberpunkSaveEditor
2069ea833ced56f549776179c2147b27d32d650c
[ "MIT" ]
37
2020-12-21T18:25:12.000Z
2022-03-31T23:51:33.000Z
source/redx/scripting/iproperty.hpp
13397729377/CyberpunkSaveEditor
2069ea833ced56f549776179c2147b27d32d650c
[ "MIT" ]
36
2020-12-21T12:02:08.000Z
2022-03-21T10:47:43.000Z
#pragma once #include <iostream> #include <string> #include <memory> #include <list> #include <vector> #include <set> #include <array> #include <exception> #include "redx/core.hpp" #include "redx/ctypes.hpp" #include "redx/csav/node.hpp" #include "redx/csav/serializers.hpp" #include "CStringPool.hpp" #include "csystem_serctx.hpp" #ifndef DISABLE_CP_IMGUI_WIDGETS #include <appbase/widgets/list_widget.hpp> #include <appbase/extras/cpp_imgui.hpp> #include <appbase/extras/imgui_stdlib.h> #endif enum class EPropertyKind { None, Unknown, Bool, Integer, Float, Double, Combo, Array, DynArray, Handle, RaRef, Object, TweakDBID, CName, CRUID, NodeRef }; static inline std::string_view property_kind_to_display_name(EPropertyKind prop_kind) { switch (prop_kind) { case EPropertyKind::None: return "None"; case EPropertyKind::Unknown: return "Unknown"; case EPropertyKind::Bool: return "Bool"; case EPropertyKind::Integer: return "Integer"; case EPropertyKind::Float: return "Float"; case EPropertyKind::Double: return "Double"; case EPropertyKind::Combo: return "Combo"; case EPropertyKind::Array: return "Array"; case EPropertyKind::DynArray: return "DynArray"; case EPropertyKind::Handle: return "Handle"; case EPropertyKind::Object: return "Object"; } return "Invalid"; } enum class EPropertyEvent { data_edited, data_serialized_in }; struct CPropertyOwner { virtual ~CPropertyOwner() = default; virtual void on_cproperty_event(const CProperty& prop, EPropertyEvent evt) = 0; }; class CProperty { CPropertyOwner* m_owner; EPropertyKind m_kind; bool m_is_unskippable = false; bool m_is_freshly_constructed = true; protected: CProperty(CPropertyOwner* owner, EPropertyKind kind) : m_owner(owner), m_kind(kind) {} public: virtual ~CProperty() = default; CPropertyOwner* owner() const { return m_owner; } EPropertyKind kind() const { return m_kind; } virtual gname ctypename() const = 0; bool is_skippable_in_serialization() const { return !m_is_unskippable && (m_is_freshly_constructed || has_default_value()); } bool has_construction_value() const { return m_is_freshly_constructed; } // todo: dump them... virtual bool has_default_value() const { return false; } // serialization protected: // when called, a data_modified event is sent automatically by base class' serialize_in(..) virtual bool serialize_in_impl(std::istream& is, CSystemSerCtx& serctx) = 0; public: bool serialize_in(std::istream& is, CSystemSerCtx& serctx) { bool ok = serialize_in_impl(is, serctx); post_cproperty_event(EPropertyEvent::data_serialized_in); return ok; } virtual bool serialize_out(std::ostream& os, CSystemSerCtx& serctx) const = 0; // gui (define DISABLE_CP_IMGUI_WIDGETS to disable implementations) protected: // when returns true, a data_modified event is sent automatically by base class' imgui_widget(..) [[nodiscard]] virtual bool imgui_widget_impl(const char* label, bool editable) { #ifndef DISABLE_CP_IMGUI_WIDGETS ImGui::Text("widget not implemented"); return false; #endif } public: virtual bool imgui_is_one_liner() { return true; } static inline bool imgui_show_skipped = true; [[nodiscard]] bool imgui_widget(const char* label, bool editable) { //if (imgui_show_skipped && is_skippable_in_serialization()) // ImGui::Text("(default, may be skipped during serialization)"); if (imgui_show_skipped && (has_construction_value() && !m_is_unskippable)) { ImGui::Text("(!)"); ImGui::SameLine(); } bool modified = imgui_widget_impl(label, editable); if (modified) post_cproperty_event(EPropertyEvent::data_edited); return modified; } void imgui_widget(const char* label) const { std::ignore = const_cast<CProperty*>(this)->imgui_widget(label, false); } // events protected: void post_cproperty_event(EPropertyEvent evt) const { if (m_owner) m_owner->on_cproperty_event(*this, evt); auto nc_this = const_cast<CProperty*>(this); if (evt == EPropertyEvent::data_edited) { nc_this->m_is_freshly_constructed = false; nc_this->m_is_unskippable = false; } else if (evt == EPropertyEvent::data_serialized_in) { nc_this->m_is_unskippable = true; } } }; //------------------------------------------------------------------------------ // DEFAULT //------------------------------------------------------------------------------ class CUnknownProperty : public CProperty { protected: gname m_ctypename; std::vector<char> m_data; public: CUnknownProperty(CPropertyOwner* owner, gname ctypename) : CProperty(owner, EPropertyKind::Unknown) , m_ctypename(ctypename) { } ~CUnknownProperty() override = default; public: const std::vector<char>& raw_data() const { return m_data; }; // overrides gname ctypename() const override { return m_ctypename; }; bool serialize_in_impl(std::istream& is, CSystemSerCtx& serctx) override { std::streampos beg = is.tellg(); is.seekg(0, std::ios_base::end); const size_t size = (size_t)(is.tellg() - beg); is.seekg(beg); m_data.resize(size); is.read(m_data.data(), size); //std::istream_iterator<char> it(is), end; //m_data.assign(it, end); return is.good(); } virtual bool serialize_out(std::ostream& os, CSystemSerCtx& serctx) const { os.write(m_data.data(), m_data.size()); return true; } #ifndef DISABLE_CP_IMGUI_WIDGETS [[nodiscard]] bool imgui_widget_impl(const char* label, bool editable) override { ImGuiWindow* window = ImGui::GetCurrentWindow(); if (window->SkipItems) return false; bool modified = false; ImGui::BeginChild(label, ImVec2(0,0), true, ImGuiWindowFlags_AlwaysAutoResize); ImGui::Text("unsupported ctypename: %s", ctypename().c_str()); ImGui::Text("data size: %08X", m_data.size()); if (m_data.size() > 50) ImGui::Text("data: %s...", bytes_to_hex(m_data.data(), 50).c_str()); else ImGui::Text("data: %s", bytes_to_hex(m_data.data(), m_data.size()).c_str()); ImGui::EndChild(); return modified; } #endif };
25.119691
100
0.653397
[ "object", "vector" ]
f38276336ce814c5e1457794d5b20fd20eee6b5b
9,524
cpp
C++
main.cpp
ss840429/SP_Final_Project
afdb22d9b32d89994e0bd02943af93cb660a5930
[ "MIT" ]
null
null
null
main.cpp
ss840429/SP_Final_Project
afdb22d9b32d89994e0bd02943af93cb660a5930
[ "MIT" ]
null
null
null
main.cpp
ss840429/SP_Final_Project
afdb22d9b32d89994e0bd02943af93cb660a5930
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> #include <cstdio> #include <cstdlib> #include <fstream> #include <map> #include <sstream> #include <iomanip> #include <vector> #include <math.h> using namespace std ; #define MAXLINE 500 map<string,string>OPTAB = { {"STL","14"},{"LDB","68"},{"JSUB","48"},{"LDA","00"},{"COMP","28"},{"JEQ","30"} ,{"J","3C"},{"STA","0C"},{"CLEAR","B4"},{"LDT","74"},{"TD","E0"},{"RD","D8"},{"COMPR","A0"} ,{"STCH","54"},{"TIXR","B8"},{"JLT","38"},{"STX","10"},{"RSUB","4C"},{"LDCH","50"},{"WD","DC"} }; map<string,int>Register = { {"A",0},{"X",1},{"L",2},{"B",3},{"S",4},{"T",5} } ; map<string,int>SYMTAB ; void toupper( string& ss ) { for( int i = 0 ; i < ss.size() ; ++i ){ if( ss[i] >= 'a' && ss[i] <= 'z' ) ss[i] -= 'a' - 'A' ; } } int main( int argc , char* argv[] ) { /************ File Read **************/ string ob_file( "default.txt" ) ; if( argc == 2 ) ob_file = argv[1] ; else if( argc > 2 ) { cout << "Invalid command\n" ; return 0 ; } fstream fp( ob_file ) ; // Open File if( !fp ) { cout << "Cannot find input text file\n" ; return 0 ; } fstream ofp( "result.txt" , ios::out ) ; /************* PROGRAM ***************/ // For Header stringstream ss ; string FirstLine , name , tmp ; int START ; getline( fp , FirstLine ) ; ss << FirstLine ; ss >> name >> tmp >> START ; string command[MAXLINE] ; int address[MAXLINE] ; int numline = 0 ; while( getline(fp,command[numline++]) ) ; // Pass 1 int BASE = START , PC = BASE , count = 0 ; while( count != numline ) { ss.clear() ; address[count] = PC ; vector<string>S ; ss << command[count] ; while( ss >> tmp ) S.push_back(tmp) ; if( S.size() == 3 ) { SYMTAB[S[0]] = PC ; // add to symbol table } if( S.size() > 1 ) { if( S[S.size()-2] == "END" ) { numline = count+1 ; break ; } if( S[S.size()-2] == "RESW" ) { int n = atoi(S.back().c_str()) ; PC += n*3 ; } else if( S[S.size()-2] == "RESB" ) { int n = atoi(S.back().c_str()) ; PC += n ; } else if( S[S.size()-2] == "BYTE" ) { int n = S.back().size()-3 ; if( S.back()[0] == 'X' ) n/=2 ; PC += n ; } else if( S[S.size()-2] == "WORD" ) { PC += 3 ; } else if( S[S.size()-2] == "BASE" || S[S.size()-2] == "BASE" ) address[count] = -1 ; else if( S[S.size()-2][0] == '+' ) PC += 4 ; else if( S[S.size()-2] == "CLEAR" || S[S.size()-2] == "TIXR" || S[S.size()-2] == "COMPR" ) PC += 2 ; else PC += 3 ; } else PC += 3 ; S.clear(); count += 1 ; } for( int i = 0 ; i < numline ; i ++ ) { cout << hex << setfill('0') << setw(4) << address[i] << " " << command[i] << endl ; } cout << endl ; for( map<string,int>::iterator it = SYMTAB.begin() ; it != SYMTAB.end() ; it ++ ) { cout << it->first << " " << setw(4) << it->second << endl ; } int length = address[count]-START ; ofp << "H" << setw(6) << left << name << setfill('0') << hex << setw(6) << START << setw(6) << setfill('0') << hex << right << length << endl ; // Pass 2 stringstream object[MAXLINE] ; vector<int> jsubpos ; PC = BASE ; count = 0 ; while( count != numline ) { PC = address[count+1] ; int k = 1 ; while( PC == -1 ){ k ++ ; PC = address[count+k] ; } ss.clear() ; vector<string>S ; ss << command[count] ; while( ss >> tmp ) S.push_back(tmp) ; int n = 0 , i = 0 , x = 0 , b = 0 , p = 0 , e = 0; if( S.size() == 3 ) S.erase(S.begin()) ; if( S[0] == "JSUB" || S[0] == "+JSUB" ) jsubpos.push_back(address[count]+1) ; if( S[0] == "RESW" || S[0] == "RESB" ) { count += 1 ; continue ; } else if(S[0] == "RSUB" ) object[count] << "4F0000" ; else if(S[0] == "BASE" ){ BASE = SYMTAB[S[1]] ; } else if( S[0] == "CLEAR" ){ object[count] << OPTAB[S[0]] << Register[S[1]] << "0" ; } else if( S[0] == "BYTE" ){ if( S[1][0] == 'C' ){ for( int i = 2 ; i < S[1].size()-1 ; ++i ) object[count] << hex << static_cast<int>(S[1][i]) ; } else if(S[1][0] == 'X' ){ for( int i = 2 ; i < S[1].size()-1 ; ++i ) object[count] << S[1][i] ; } } else if( S[0] == "TIXR" ){ object[count] << OPTAB[S[0]] << Register[S[1]] << "0" ; } else if( S[0] == "COMPR" ){ string r1 , r2 ; r1+=S[1][0] , r2+= S[1][2] ; object[count] << OPTAB[S[0]] << Register[r1] << Register[r2] ; } else { if( S[0][0] == '+' ){ e = 1 ; // format 4 S[0].erase(S[0].begin()) ; } else e = 0 ; //format 3 if( S[1][0] == '#' ){ n = 0 , i = 1 ; S[1].erase(S[1].begin()) ; } else if( S[1][0] == '@' ){ n = 1 , i = 0 ; S[1].erase(S[1].begin()) ; } else{ n = 1 , i = 1 ; } if( S[1].size() >= 2 && S[1].substr( S[1].size()-2 , 2 ) == ",X" ){ x = 1 ; S[1].erase( S[1].end()-1 ) ; S[1].erase( S[1].end()-1 ) ; } string opcode = OPTAB[ S[0] ] ; opcode[1] += n*2+i ; if( opcode[1] > '9' && opcode[1] < 'A' ) { opcode[1] -= '9' - 'A' + 1 ; } else if( opcode[1] > 'F' ) { opcode[0] += 1 ; if( opcode[0] == '9'+1 ) opcode[0] = 'A' ; opcode[1] -= 'F' - '0' ; } object[count] << opcode ; if( e == 1 ){ object[count] << hex << e ; if( i && !n ) object[count] << setfill('0') << setw(5) << hex << atoi(S[1].c_str()) ; else object[count] << setfill('0') << setw(5) << SYMTAB[S[1]] ; } else{ if( SYMTAB.find(S[1]) != SYMTAB.end() ) { if( abs(SYMTAB[S[1]]-PC) < 2048 ){ p = 1 ; object[count] << hex << x*8+b*4+p*2+e ; stringstream zs ; zs << hex << setw(3) << setfill('0') << SYMTAB[S[1]] - PC ; string zst ; zs >> zst ; while( zst.size() > 3 ) zst.erase( zst.begin() ) ; object[count] << zst ; } else if ( abs(SYMTAB[S[1]]-BASE) < 4096 ){ b = 1 ; object[count] << hex << x*8+b*4+p*2+e ; object[count] << hex << setw(3) << setfill('0') << SYMTAB[S[1]] - BASE ; } else object[count] << "Error" ; } else { int shift = atoi( S[1].c_str() ) ; if( abs(shift) < 2048 ){ p = 1 ; object[count] << hex << x*8+b*4+p*2+e ; object[count] << hex << setw(3) << setfill('0') << shift ; } else if ( shift < 4096 ){ b = 1 ; object[count] << hex << x*8+b*4+p*2+e ; object[count] << hex << setw(3) << setfill('0') << shift ; } else object[count] << "Error" ; } } } count += 1 ; S.clear() ; } int tc = 0 , cc = 0 , last = 0 ; while( cc != numline ) { tc += object[cc++].str().size() ; if( tc > 70 || command[cc].find("RESW")!=string::npos|| command[cc].find("RESB")!=string::npos || cc == numline-1 ) { if( tc/2 == 0 ) continue ; string str ; while( object[last].str().size() <= 1 ) last ++ ; ofp << "T" << setw(6) << address[last] << hex << tc/2 ; for( int i = last ; i < cc ; ++i ){ object[i] >> str ; if( str.size() <= 1 ) continue ; toupper(str) ; ofp << str ; } ofp << endl ; tc = 0 ; last = cc ; } } // For M instruction for( auto& e : jsubpos ) ofp << "M" << setw(6) << e << "05" << endl ; // end ofp << "E" << setw(6) << setfill('0') << START ; return 0 ; }
29.949686
124
0.340823
[ "object", "vector" ]
f386c78b80aafd58e12fcebf2335192dd15235e6
2,861
cpp
C++
src/pValueLookUp.cpp
xuebingwu/xtools
b9078cb7228f0bc227e6eab917fbafe769f5ffc1
[ "MIT" ]
null
null
null
src/pValueLookUp.cpp
xuebingwu/xtools
b9078cb7228f0bc227e6eab917fbafe769f5ffc1
[ "MIT" ]
null
null
null
src/pValueLookUp.cpp
xuebingwu/xtools
b9078cb7228f0bc227e6eab917fbafe769f5ffc1
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include "utility.h" using namespace std; // load the top fraction of a list of ranked values, return the total number of data // col: start 0 int load_sorted_table(string filename, int col, vector<double> &table, double fraction) { //bool descending = true; ifstream fin; fin.open(filename.c_str()); string line; vector<string> flds; // save line 1 data getline(fin,line); flds = string_split(line,"\t"); //double first_data = stof(flds[col]); // save line 2 data getline(fin,line); flds = string_split(line,"\t"); //double second_data = stof(flds[col]); // cout << "first two data points = " << first_data << "," << second_data << endl; //if( first_data < second_data ) descending = false; int total = 1; // count total number of lines while(fin) { getline(fin,line); if(line.length()==0) continue; total ++; } fin.close(); // cout << total << " data points in total" << endl; // the line to stop int line_to_stop = total * fraction; // cout << "keep the top fraction " << fraction << endl; // cout << "keep the top lines " << line_to_stop << endl; int n = 0; fin.open(filename.c_str()); while(fin) { getline(fin,line); if(line.length()==0) continue; flds = string_split(line,"\t"); double v = stof(flds[col]); table.push_back(v); n++; if(n == line_to_stop) break; } fin.close(); // cout << "finished" << endl; return total; } // double lookup_table(double x, vector<double> table, int total) { int L = table.size(); bool descending = table[0] > table[1]; if ((descending == true && x < table[L-1]) || (descending == false && x > table[L-1])) return 1.0; int i=0; if (descending) { while(x<=table[i]) i++; } else { while(x>=table[i]) i++; } return (i+1.0)/total; } void calculate_p_from_file(string infile, string outfile, int col, vector<double> table, int total, double fraction) { ifstream fin; fin.open(infile.c_str()); ofstream fout; fout.open(outfile.c_str()); string line; vector<string> flds; while(fin) { getline(fin,line); if(line.length() == 0) continue; flds = string_split(line,"\t"); double p = lookup_table(stof(flds[col]),table,total) / fraction; if(p<1) fout << line << "\t" << p << endl; } fin.close(); fout.close(); } int main(int argc, char* argv[]) { string inputfile = argv[1]; int col1 = atoi(argv[2]); string tablefile = argv[3]; int col2 = atoi(argv[4]); double fraction = atof(argv[5]); string outputfile = argv[6]; vector<double> table; int total = load_sorted_table(tablefile, col2, table, fraction); // cout << table.size() << endl; // cout << total << " values in table" << endl; calculate_p_from_file(inputfile, outputfile, col1, table, total, fraction); return 0; }
20.883212
116
0.638937
[ "vector" ]
f38a1385de238845e490387e55bd59aef1c864bf
33,850
cpp
C++
omnn/math/Integer.cpp
iHateInventNames/openmind
2587b811e594daf9d9c235cb63eeae2950e93ff0
[ "BSD-3-Clause" ]
null
null
null
omnn/math/Integer.cpp
iHateInventNames/openmind
2587b811e594daf9d9c235cb63eeae2950e93ff0
[ "BSD-3-Clause" ]
4
2016-05-21T08:48:41.000Z
2017-02-22T19:37:03.000Z
omnn/math/Integer.cpp
iHateInventNames/openmind
2587b811e594daf9d9c235cb63eeae2950e93ff0
[ "BSD-3-Clause" ]
null
null
null
// // Created by Сергей Кривонос on 01.09.17. // #include "Integer.h" #include "i.h" #include "Infinity.h" #include "Exponentiation.h" #include "Fraction.h" #include "Modulo.h" #include "PrincipalSurd.h" #include "Product.h" #include "Sum.h" #include <rt/Prime.h> #include <rt/tasq.h> #include <algorithm> #include <codecvt> #include <cmath> #include <fstream> #include <iostream> #include <boost/archive/binary_oarchive.hpp> #if __cplusplus >= 201700 #include <random> #ifndef __GNUC__ namespace std { template< class It > void random_shuffle( It f, It l ) { std::random_device rd; std::mt19937 g(rd()); std::shuffle(f, l, g); } } #endif #endif #ifdef OPENMIND_USE_OPENCL #include <boost/compute.hpp> #endif #include <boost/functional/hash.hpp> #include <boost/numeric/conversion/converter.hpp> #include <boost/math/special_functions/prime.hpp> #include <boost/multiprecision/integer.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/detail/default_ops.hpp> #include <boost/multiprecision/detail/integer_ops.hpp> #include <boost/multiprecision/integer.hpp> #include <boost/multiprecision/miller_rabin.hpp> using boost::multiprecision::cpp_int; namespace omnn{ namespace math { const Integer::ranges_t Integer::empty_zero_zone; Integer::Integer(const Fraction& f) : arbitrary(f.getNumerator().ca() / f.getDenominator().ca()) { } Integer::operator a_int() const { return arbitrary; } a_int& Integer::a() { return arbitrary; } const a_int& Integer::ca() const { return arbitrary; } Integer::operator int64_t() const { return boost::numeric_cast<int64_t>(arbitrary); } Integer::operator uint64_t() const { return boost::numeric_cast<uint64_t>(arbitrary); } Valuable::YesNoMaybe Integer::IsEven() const { return (arbitrary >= 0 ? arbitrary : -arbitrary) & 1 ? YesNoMaybe::No : YesNoMaybe::Yes; } Valuable Integer::operator -() const { return Integer(-arbitrary); } Valuable& Integer::operator +=(const Valuable& v) { if (v.IsInt()) { arbitrary += v.ca(); hash = std::hash<base_int>()(arbitrary); } else { Become(v + *this); } return *this; } Valuable& Integer::operator +=(int v) { arbitrary += v; hash = std::hash<base_int>()(arbitrary); return *this; } Valuable& Integer::operator *=(const Valuable& v) { if (v.IsInt()) { arbitrary *= v.ca(); hash = std::hash<base_int>()(arbitrary); } else { // all other types should handle multiplication by Integer Become(v**this); } return *this; } bool Integer::MultiplyIfSimplifiable(const Valuable& v) { auto is = v.IsInt(); if(is) { arbitrary *= v.ca(); hash = std::hash<base_int>()(arbitrary); } else if (v.IsVa()) { } else { auto s = v.IsMultiplicationSimplifiable(*this); is = s.first; if(is) Become(std::move(s.second)); } return is; } std::pair<bool,Valuable> Integer::IsMultiplicationSimplifiable(const Valuable& v) const { std::pair<bool,Valuable> is; is.first = v.IsInt() || v.IsFraction(); if (is.first) { is.second = v * *this; if (is.second.Complexity() > v.Complexity()) IMPLEMENT; // TODO: not a simple fraction } else if (v.IsVa() || v.IsExponentiation()) { } else { is = v.IsMultiplicationSimplifiable(*this); } return is; } bool Integer::SumIfSimplifiable(const Valuable& v) { auto is = v.IsInt(); if(is) { arbitrary += v.ca(); hash = std::hash<base_int>()(arbitrary); } else { auto s = v.IsSummationSimplifiable(*this); is = s.first; if(is) Become(std::move(s.second)); } return is; } std::pair<bool,Valuable> Integer::IsSummationSimplifiable(const Valuable& v) const { std::pair<bool,Valuable> is; is.first = v.IsInt(); if (is.first) { is.second = v + *this; } else if (v.IsVa() || v.IsExponentiation()) { } else if (v.IsProduct()) { } else { is = v.IsSummationSimplifiable(*this); if (is.first && is.second.Complexity() > v.Complexity()) LOG_AND_IMPLEMENT("Simplification complexidy exceeds source complexity: " << v << " + " << str() << " = " << is.second); } return is; } Valuable& Integer::operator /=(const Valuable& v) { if (v.IsInt()) { auto& a = v.ca(); if (a == 0) { if (arbitrary < 0) { Become(MInfinity()); } else if (arbitrary > 0) { Become(Infinity()); } else { Become(NaN()); } } else if (arbitrary % a == 0) { arbitrary /= a; hash = std::hash<base_int>()(arbitrary); } else { Become(Fraction(*this, v)); } } else if(v.FindVa()) *this *= v^-1; else Become(Fraction(*this,v)); return *this; } Valuable& Integer::operator %=(const Valuable& v) { if (v.IsInt()) { arbitrary %= v.ca(); hash = std::hash<base_int>()(arbitrary); } else { Become(Modulo(*this, v)); } return *this; } Valuable& Integer::operator --() { arbitrary--; hash = std::hash<base_int>()(arbitrary); return *this; } Valuable& Integer::operator ++() { arbitrary++; hash = std::hash<base_int>()(arbitrary); return *this; } Integer::operator int() const { return boost::numeric_cast<int>(arbitrary); } Integer::operator uint32_t() const { return boost::numeric_cast<uint32_t>(arbitrary); } Integer::operator double() const { return boost::numeric_cast<double>(arbitrary); } Integer::operator long double() const { return boost::numeric_cast<long double>(arbitrary); } Integer::operator unsigned char() const { return boost::numeric_cast<unsigned char>(arbitrary); } Valuable Integer::bit(const Valuable& n) const { if (n.IsInt()) { if (arbitrary < 0) { if (arbitrary == -1) { return 1; } IMPLEMENT } unsigned N = static_cast<unsigned>(n); return static_cast<int>(bit_test(arbitrary, N)); } else IMPLEMENT; } Valuable& Integer::shl(const Valuable& n) { if (n.IsInt()) arbitrary = arbitrary << static_cast<int>(n); else base::shl(n); return *this; } Valuable& Integer::shr(const Valuable& n) { if (n.IsInt()) arbitrary = arbitrary >> static_cast<int>(n); else base::shl(n); return *this; } Valuable Integer::Shr() const { return Integer(decltype(arbitrary)(arbitrary>>1)); } Valuable Integer::Shr(const Valuable& n) const { if (!n.IsInt()) { IMPLEMENT } return Integer(decltype(arbitrary)(arbitrary>>static_cast<unsigned>(n))); } Valuable Integer::Or(const Valuable& n, const Valuable& v) const { IMPLEMENT } Valuable Integer::And(const Valuable& n, const Valuable& v) const { if (v.IsInt()) { auto mask = std::move(--((vo<2>() ^ n).a())); if (arbitrary < v.ca()) { mask &= arbitrary; mask &= v.ca(); } else { mask &= v.ca(); mask &= arbitrary; } return Valuable(std::move(mask)); } else return base::And(n, v); } Valuable Integer::Xor(const Valuable& n, const Valuable& v) const { IMPLEMENT } Valuable Integer::Not(const Valuable& n) const { return Integer(~arbitrary); } std::pair<Valuable,Valuable> Integer::GreatestCommonExp(const Valuable &e) const { // test : 50_v.GCE(2) == 5_v // 32_v.GCE(2) == 4_v // which is needed to be powered into 2 to get gretest devisor that may be powered into 2 to get devisor of the initial value if (e == constants::one) return {*this,*this}; auto xFactors = Facts(); std::sort(xFactors.begin(), xFactors.end()); while(xFactors.size() > 1) { auto&& xFactor = std::move(xFactors.back()); if(xFactor > constants::one) { if(e == constants::two){ Valuable v = boost::multiprecision::sqrt(xFactor.ca()); if((v^e) == xFactor) return {std::move(v),std::move(xFactor)}; } else if (e < constants::zero) { auto me = -e; IMPLEMENT } else { IMPLEMENT // auto v = boost::multiprecision::pow(xFactor, 1/e); } } xFactors.pop_back(); } return {constants::one, constants::one}; } Valuable& Integer::operator^=(const Valuable& v) { if(v == constants::one) return *this; if(arbitrary == 0 || (arbitrary == 1 && v.IsInt())) { if (v == 0) { IMPLEMENT; //NaN } return *this; } else if ((arbitrary == 1 || arbitrary == -1) && v.IsSimpleFraction()) { if(!v.as<Fraction>().getDenominator().IsEven()) return *this; else return Become(Exponentiation{*this,v}); } if(v.IsInt()) { // FIXME: arbitrary = boost::multiprecision::pow(a(), v.ca()); // hash = std::hash<base_int>()(arbitrary); // return *this; if (v != 0_v) { if (v > 1) { Valuable x = *this; Valuable n = v; if (n < 0_v) { x = 1_v / x; n = -n; } if (n == 0_v) { arbitrary = 1; hash = std::hash<base_int>()(arbitrary); return *this; } auto y = 1_v; while(n > 1) { auto nIsInt = n.IsInt(); if (!nIsInt) IMPLEMENT; if (n.ca() & 1) { y *= x; --n; } x.sq(); n /= 2; } x *= y; if (x.IsInt()) { arbitrary = std::move(x.a()); hash = std::hash<base_int>()(arbitrary); } else return Become(std::move(x)); } else if (v != 1) { return Become(Exponentiation{*this, v}); } } else { // zero if (arbitrary == 0) throw "NaN"; // feel free to handle this properly else { arbitrary = 1; hash = std::hash<base_int>()(arbitrary); } } } else if(v.IsSimpleFraction()) { auto& f = v.as<Fraction>(); auto& nu = f.getNumerator(); Valuable mn; auto nlz = nu < 0; if(nlz) mn = -nu; auto n = std::cref(nlz ? mn : nu); auto dn = nlz ? -f.getDenominator() : f.getDenominator(); auto numeratorIsOne = n == 1_v; if (!numeratorIsOne){ *this ^= n; n = std::cref(constants::one); } auto isNeg = operator<(0_v); auto signs = 0; //dimmensions while(dn.IsEven() == YesNoMaybe::Yes) { auto minus = arbitrary < 0; auto _ = boost::multiprecision::sqrt(minus ? -arbitrary : arbitrary); auto _sq = _ * _; if (_sq == boost::multiprecision::abs(arbitrary)){ arbitrary = _; // Become(isNeg ? -operator-().Sqrt() : Sqrt()); dn /= 2; ++signs; } else { // IMPLEMENT if(n!=1_v) IMPLEMENT; auto gce = GreatestCommonExp(dn); return Become(gce.first*Exponentiation{operator/=(gce.second),n/dn}); } } if(signs) hash = std::hash<base_int>()(arbitrary); auto dnSubZ = dn < 0; if(dnSubZ) dn = -dn; if(dn != 1_v) { auto even = dn.IsEven(); if(even == YesNoMaybe::Yes){ Valuable x = *this; if(x<0_v){ Valuable exp; if (!numeratorIsOne) { *this ^= n; exp = 1_v / dn; } auto& exponentiating = numeratorIsOne ? v : exp; auto xFactors = FactSet(); auto rb = xFactors.rbegin(), re = xFactors.rend(); for (auto it = rb; it != re; ++it) { auto& xFactor = *it; if(xFactor > 1_v /* && !operator==(xFactor) */){ auto e = xFactor ^ dn; if(operator==(e)) return Become(e*(1_v^exponentiating)); auto f = xFactor ^ exponentiating; if(!f.IsInt()) f /= 1_v ^ exponentiating; if(f.IsInt()) return Become(f*((x/xFactor)^exponentiating)); } } IMPLEMENT } } // else if(dn==2_v) { // return Become(Sqrt()*(1^(1_v/2))); // } Valuable nroot; bool rootFound = false; Valuable left =0, right = *this; while (!rootFound) { auto d = right - left; d -= d % 2; if (d!=0) { nroot = left + d / 2; auto result = nroot ^ dn; rootFound = result == *this; if (rootFound) break; else if (result > *this) right = nroot; else left = nroot; } else { nroot = Exponentiation(*this, 1_v/dn); break; } // *this ^ 1/dn == (nroot^dn + t)^ 1/dn // this == nroot^dn + // TODO : IMPLEMENT//return Become(Sum {nroot, (*this-(nroot^dn))^(1/dn)}); } return Become(std::move(nroot)); } if(dnSubZ) Become(1_v / *this); if(signs) { return operator*=((isNeg?-1_v:1_v)^(1_v/(2_v^signs))); } } else return Become(Exponentiation(*this, v)); optimize(); return *this; } Valuable& Integer::d(const Variable& x) { arbitrary = 0; return *this; } bool Integer::IsComesBefore(const Valuable& v) const { return v.IsInt() && *this > v; } Valuable Integer::InCommonWith(const Valuable& v) const { return (v.IsInt() && v!=0_v && *this!=0_v) ? boost::gcd(v.ca(),ca()) : 1_v; } // sqrt using boost Valuable Integer::Sqrt() const { auto minus = arbitrary < 0; auto _ = boost::multiprecision::sqrt(minus ? -arbitrary : arbitrary); // integer square root auto _sq = _ * _; if (_sq != boost::multiprecision::abs(arbitrary)){ // no integer square root auto d = GreatestCommonExp(2); if (d.second != 1) return (*this / d.second).Sqrt() * d.first; else { return Valuable(std::make_shared<PrincipalSurd>(*this)); LOG_AND_IMPLEMENT(str() << " integer square root is " << _ << " and " << _ << "^2=" << _sq); // implement radicals support } } return minus ? constant::i * _ : _; } // Sqrt using rational root test // Valuable Integer::Sqrt() const // { // auto minus = arbitrary < 0; // // // build an equation, find using RRT: // Variable x; // Valuable eq = *this; // auto _ = x.Sq(); // eq += minus ? _ : -_; // eq.SetView(View::Solving); // // auto esurrto = enforce_solve_using_rational_root_test_only; // enforce_solve_using_rational_root_test_only = true; // auto sols = eq.Solutions(x); // enforce_solve_using_rational_root_test_only = esurrto; // // if(!sols.size()){ // IMPLEMENT // } // auto it = sols.begin(); // if(*it < 0) // ++it; // _ = *it; // // return minus ? constant::i * _ : _; // } std::wstring Integer::save(const std::wstring& f) const { using namespace std; using convert_typeX = codecvt_utf8<wchar_t>; std::wstring_convert<convert_typeX, wchar_t> c; std::ofstream s(c.to_bytes(f)); boost::archive::binary_oarchive a(s); a & arbitrary; return f; } Valuable Integer::Sign() const { return arbitrary.sign(); } bool Integer::operator <(const Valuable& v) const { if (v.IsInt()) return arbitrary < v.ca(); else if (v.IsFraction()) return !(v < *this) && *this!=v; else if(v.IsMInfinity()) return {}; else if(v.IsInfinity()) return true; else if (!v.FindVa()) { double _1 = boost::numeric_cast<double>(arbitrary); double _2 = static_cast<double>(v); if(_1 == _2) { IMPLEMENT } return _1 < _2; } else return base::operator <(v); } bool Integer::operator ==(const Valuable& v) const { if (v.IsInt()) return Hash() == v.Hash() && arbitrary == v.ca(); else if(v.FindVa()) return false; else return v.operator==(*this); } std::ostream& Integer::print(std::ostream& out) const { return out << arbitrary; } std::wostream& Integer::print(std::wostream& out) const { return out << arbitrary.str().c_str(); } Valuable Integer::calcFreeMember() const { return *this; } std::deque<Valuable> Integer::Facts() const { std::deque<Valuable> f; Factorization([&](auto& v){ f.push_back(v); return false; }, abs()); return f; } void Integer::factorial() { if (arbitrary == 0) arbitrary = 1; else for (auto i = arbitrary; i-- > 1;) arbitrary *= i; hash = std::hash<base_int>()(arbitrary); } bool Integer::IsPrime() const { auto is = //boost::multiprecision::miller_rabin_test(boost::numeric_cast<uint64_t>(ca()), 3) && !Factorization( [&](auto& v) { auto isPrimeFactor = v == 0_v || v == 1_v || v == *this; auto stop = !isPrimeFactor; return stop; }, abs()); return is; } std::set<Valuable> Integer::SimpleFactsSet() const { std::set<Valuable> f; SimpleFactorization( [&](auto& v) { f.emplace(std::move(v)); return false; }, abs()); f.erase(0); return f; } std::set<Valuable> Integer::FactSet() const { std::set<Valuable> f; Factorization( [&](auto& v) { f.emplace(std::move(v)); return false; }, abs()); f.erase(0); return f; } bool Integer::SimpleFactorization(const std::function<bool(const Valuable&)>& f, const Valuable& max, const ranges_t& zz) const { auto h = arbitrary; if(h < 0) h = -h; if (f(0)) { return true; } bool scanz = zz.second.size(); auto scanIt = zz.second.end(); Valuable up = Integer(h); if (up > max) up = max; auto from = 1_v; if (scanz) { if (zz.first.second < up) { if(zz.first.second.IsInt()) up = zz.first.second; else up = static_cast<int>(static_cast<double>(zz.first.second)); } if (zz.first.first > from) { if(zz.first.first.IsInt()) from = zz.first.first; else from = static_cast<int>(static_cast<double>(zz.first.first)); } scanIt = zz.second.begin(); while (scanIt != zz.second.end() && scanIt->second < from) { ++scanIt; } } auto absolute = abs(); if(from==up) return f(up); else for (auto i = from; i < up; ++i) { auto a = absolute / i; if (a.IsInt()) { if(f(i) || f(a)) return true; if (a < up) { up = a; } } if (scanz && i > scanIt->second) { ++scanIt; if (scanIt == zz.second.end()) { break; } i = scanIt->first; if (!i.IsInt()) { IMPLEMENT; } } } return false; } namespace { StoringTasksQueue factorizationTasks; } bool Integer::Factorization(const std::function<bool(const Valuable&)>& f, const Valuable& max, const ranges_t& zz) const //{ // std::set<Integer> factors; // return Factorization(f, max, factors, zz); //} //bool Integer::Factorization(const std::function<bool(const Valuable&)>& f, // const Valuable& max, // std::set<Integer>& factors, // const ranges_t& zz) const { // check division by primes // iterate by primes to find factor and store it in factors set // togather with lowest factor found highest factor as result of division // the highest factor reduces the search range to its value exclusively (1) // after scan all the primes, need to scan permutations // // starting from smallest prime factor, // new set of non-prime factors is enreached with muiltiple multiplications to current prime to self and to each member of the new set // new set iterating starting from smallest too and until range out of upper bound (1) // ... // Multi-threaded way: // for devisible of thouse: isDevisible = (ResultOfDivision = This / iPrime).IsInt(): // add products of the Divisibles with factorization set numbers of result of division: // (add all [ResultOfDivision factors starting from iPrime inclusively] time iPrime) recursively auto absolute = arbitrary; if (absolute < 0) absolute = -absolute; decltype(arbitrary) from = 2; if (zz.first.first > from) { if(zz.first.first.IsInt()) from = zz.first.first.ca(); else from = static_cast<int>(static_cast<double>(zz.first.first)); // FIXME: precision issues } else if (f(0_v) || f(1_v)) { return true; } bool scanz = zz.second.size(); auto scanIt = zz.second.end(); Valuable up(absolute); if (up > max) up = max; auto primeIdx = 0; if (zz.first.first < zz.first.second) { if (zz.first.second < up) { if (zz.first.second.IsInt()) up = zz.first.second; else up = static_cast<int>(static_cast<double>(zz.first.second)); // FIXME: precision issues } } else { // assuming its current prime index stored primeIdx = boost::numeric_cast<decltype(primeIdx)>(zz.first.second.ca()); } if (absolute <= up && f(absolute)) { return true; } if (scanz) { scanIt = zz.second.begin(); while (scanIt != zz.second.end() && scanIt->second < from) { ++scanIt; } } if(from==up) return f(up); else { std::set<decltype(arbitrary)> primeFactors, nonPrimeFactors; auto maxPrimeIdx = omnn::rt::primes(); auto& primeUpmost = omnn::rt::prime(maxPrimeIdx); auto prime = omnn::rt::prime(primeIdx); while (prime < from) prime = omnn::rt::prime(++primeIdx); if (prime != from) { // from is not a prime number for (auto i = from; i < prime; ++i) { // slow scan till first prime if (absolute % i == 0) { auto a = absolute; a /= i; if (f(i) || f(a)) return true; if (a < up) { up = a; } nonPrimeFactors.emplace(a); } if (scanz && i > scanIt->second) { ++scanIt; if (scanIt == zz.second.end()) { break; } if (!scanIt->first.IsInt()) { IMPLEMENT; } i = scanIt->first.ca(); } } } // iterating by primes auto primeScanUp = up; while (from <= primeUpmost && primeScanUp >= prime && primeIdx < maxPrimeIdx) { if (absolute % prime == 0) { auto a = absolute; a /= prime; if(prime > a) break; if (f(prime) || f(a)) return true; primeFactors.emplace(prime); nonPrimeFactors.emplace(a); if (a < primeScanUp) primeScanUp = a; } prime = omnn::rt::prime(++primeIdx); } if (primeIdx == maxPrimeIdx) { #ifdef OPENMIND_PRIME_MINING static bool OutOfPrimesTableWarning = {}; if (!OutOfPrimesTableWarning) { std::cerr << primeUpmost << " is the biggest prime number in the hardcoaded primes table used for fast factorization to " "solve equations using RRT. Consider extending primes table to make this perform much " "quicker." << std::endl; OutOfPrimesTableWarning = true; //rt::GrowPrime(absolute, // [](const decltype(absolute)& v) { // return Integer(v).IsPrime(); // }); } #endif // Fallback algorithm for (auto i = from; i < up; ++i) { if (absolute % i == 0) { auto a = absolute; a /= i; if (f(i) || f(a)) return true; if (a < up) { up = a; } } if (scanz && i > scanIt->second) { ++scanIt; if (scanIt == zz.second.end()) { break; } if (!scanIt->first.IsInt()) { IMPLEMENT; } i = scanIt->first.ca(); } } return false; } for (auto& prime : primeFactors) { auto mul = prime; mul *= prime; decltype(primeFactors) addNonPrime; while (mul <= up) { if (absolute % mul == 0) { auto a = absolute; a /= mul; if (nonPrimeFactors.find(mul) == nonPrimeFactors.end() && addNonPrime.emplace(mul).second) { if (f(mul)) return true; if (nonPrimeFactors.find(a) == nonPrimeFactors.end() && addNonPrime.emplace(a).second) { if (f(a)) return true; } } } else { break; } mul *= prime; } for (auto& nonPrime : nonPrimeFactors) { mul = nonPrime; for (;;) { mul *= prime; if (mul > up) break; if (absolute % mul == 0) { auto a = absolute; a /= mul; if (nonPrimeFactors.find(mul) == nonPrimeFactors.end() && addNonPrime.emplace(mul).second) { if (f(mul)) return true; if (nonPrimeFactors.find(a) == nonPrimeFactors.end() && addNonPrime.emplace(a).second) { if (f(a)) return true; } } else { break; } } else { break; } } } nonPrimeFactors.merge(std::move(addNonPrime)); } } // } // else // { // // build OpenCL kernel // using namespace boost::compute; // auto copy = *this; // copy.optimize(); // std::stringstream source; // source << "__kernel void f(__global long16 a, __global long16 *c) {" // << " const uint i = get_global_id(0);" // << " c[i] = a/i;" // << ";}"; // // device cuwinner = system::default_device(); // for(auto& p: system::platforms()) // for(auto& d: p.devices()) // if (d.compute_units() > cuwinner.compute_units()) // cuwinner = d; // auto wgsz = cuwinner.max_work_group_size(); // context context(cuwinner); // // kernel k(program::build_with_source(source.str(), context), "f"); // auto sz = wgsz * sizeof(cl_long16); // buffer c(context, sz); // k.set_arg(0, c); // // command_queue queue(context, cuwinner); // // run the add kernel // queue.enqueue_1d_range_kernel(k, 0, wgsz, 0); // // // transfer results to the host array 'c' // std::vector<cl_long> z(wgsz); // queue.enqueue_read_buffer(c, 0, sz, &z[0]); // queue.finish(); // } //#pragma omp for return false; } }}
31.665108
144
0.427829
[ "vector" ]
f38e62f3f09ff5bff60058faf136cd6a130fb884
1,600
hxx
C++
libbutl/base64.hxx
build2/libbutl
405dfa3e28ab71d4f6b5210faba0e3600070a0f3
[ "MIT" ]
6
2018-05-31T06:16:37.000Z
2021-03-19T10:37:11.000Z
libbutl/base64.hxx
build2/libbutl
405dfa3e28ab71d4f6b5210faba0e3600070a0f3
[ "MIT" ]
3
2020-06-19T05:08:42.000Z
2021-09-29T05:23:07.000Z
libbutl/base64.hxx
build2/libbutl
405dfa3e28ab71d4f6b5210faba0e3600070a0f3
[ "MIT" ]
1
2020-06-16T14:56:48.000Z
2020-06-16T14:56:48.000Z
// file : libbutl/base64.hxx -*- C++ -*- // license : MIT; see accompanying LICENSE file #pragma once #include <iosfwd> #include <string> #include <vector> #include <libbutl/export.hxx> namespace butl { // Base64-encode a stream or a buffer. Split the output into 76 char-long // lines (new line is the 77th). If reading from a stream, check if it has // badbit, failbit, or eofbit set and throw invalid_argument if that's the // case. Otherwise, set eofbit on completion. If writing to a stream, check // if it has badbit, failbit, or eofbit set and throw invalid_argument if // that's the case. Otherwise set badbit if the write operation fails. // LIBBUTL_SYMEXPORT void base64_encode (std::ostream&, std::istream&); LIBBUTL_SYMEXPORT std::string base64_encode (std::istream&); LIBBUTL_SYMEXPORT std::string base64_encode (const std::vector<char>&); // Base64-decode a stream or a string. Throw invalid_argument if the input // is not a valid base64 representation. If reading from a stream, check if // it has badbit, failbit, or eofbit set and throw invalid_argument if // that's the case. Otherwise, set eofbit on completion. If writing to a // stream, check if it has badbit, failbit, or eofbit set and throw // invalid_argument if that's the case. Otherwise set badbit if the write // operation fails. // LIBBUTL_SYMEXPORT void base64_decode (std::ostream&, std::istream&); LIBBUTL_SYMEXPORT void base64_decode (std::ostream&, const std::string&); LIBBUTL_SYMEXPORT std::vector<char> base64_decode (const std::string&); }
34.042553
77
0.72125
[ "vector" ]
f39154a539bd0d03b44c6c921ce73c8221984ca8
7,753
cc
C++
content/public/browser/push_messaging_service.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
content/public/browser/push_messaging_service.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
content/public/browser/push_messaging_service.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/browser/push_messaging_service.h" #include "base/bind.h" #include "base/callback.h" #include "content/browser/push_messaging/push_messaging_manager.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" namespace content { namespace { void CallStringCallbackFromIO( PushMessagingService::RegistrationUserDataCallback callback, const std::vector<std::string>& data, blink::ServiceWorkerStatusCode service_worker_status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); bool success = service_worker_status == blink::ServiceWorkerStatusCode::kOk; GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(std::move(callback), success ? data : std::vector<std::string>())); } void CallClosureFromIO(base::OnceClosure callback, blink::ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(callback)); } void GetUserDataOnIO( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context_wrapper, int64_t service_worker_registration_id, const std::vector<std::string>& keys, PushMessagingService::RegistrationUserDataCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context_wrapper->GetRegistrationUserData( service_worker_registration_id, keys, base::BindOnce(&CallStringCallbackFromIO, std::move(callback))); } void ClearPushSubscriptionIdOnIO( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context, int64_t service_worker_registration_id, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context->ClearRegistrationUserData( service_worker_registration_id, {kPushRegistrationIdServiceWorkerKey}, base::BindOnce(&CallClosureFromIO, std::move(callback))); } void UpdatePushSubscriptionIdOnIO( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context, int64_t service_worker_registration_id, const GURL& origin, const std::string& subscription_id, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context->StoreRegistrationUserData( service_worker_registration_id, url::Origin::Create(origin), {{kPushRegistrationIdServiceWorkerKey, subscription_id}}, base::BindOnce(&CallClosureFromIO, std::move(callback))); } void StorePushSubscriptionOnIOForTesting( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context, int64_t service_worker_registration_id, const GURL& origin, const std::string& subscription_id, const std::string& sender_id, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context->StoreRegistrationUserData( service_worker_registration_id, url::Origin::Create(origin), {{kPushRegistrationIdServiceWorkerKey, subscription_id}, {kPushSenderIdServiceWorkerKey, sender_id}}, base::BindOnce(&CallClosureFromIO, std::move(callback))); } scoped_refptr<ServiceWorkerContextWrapper> GetServiceWorkerContext( BrowserContext* browser_context, const GURL& origin) { StoragePartition* partition = BrowserContext::GetStoragePartitionForUrl(browser_context, origin); return base::WrapRefCounted(static_cast<ServiceWorkerContextWrapper*>( partition->GetServiceWorkerContext())); } void GetSWDataCallback(PushMessagingService::SWDataCallback callback, const std::vector<std::string>& result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::string sender_id; std::string subscription_id; if (!result.empty()) { DCHECK_EQ(2u, result.size()); sender_id = result[0]; subscription_id = result[1]; } std::move(callback).Run(sender_id, subscription_id); } void GetSenderIdCallback(PushMessagingService::SenderIdCallback callback, const std::vector<std::string>& result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::string sender_id; if (!result.empty()) { DCHECK_EQ(1u, result.size()); sender_id = result[0]; } std::move(callback).Run(sender_id); } } // anonymous namespace // static void PushMessagingService::GetSenderId(BrowserContext* browser_context, const GURL& origin, int64_t service_worker_registration_id, SenderIdCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( &GetUserDataOnIO, GetServiceWorkerContext(browser_context, origin), service_worker_registration_id, std::vector<std::string>{kPushSenderIdServiceWorkerKey}, base::BindOnce(&GetSenderIdCallback, std::move(callback)))); } // static void PushMessagingService::GetSWData(BrowserContext* browser_context, const GURL& origin, int64_t service_worker_registration_id, SWDataCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( &GetUserDataOnIO, GetServiceWorkerContext(browser_context, origin), service_worker_registration_id, std::vector<std::string>{kPushSenderIdServiceWorkerKey, kPushRegistrationIdServiceWorkerKey}, base::BindOnce(&GetSWDataCallback, std::move(callback)))); } // static void PushMessagingService::ClearPushSubscriptionId( BrowserContext* browser_context, const GURL& origin, int64_t service_worker_registration_id, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&ClearPushSubscriptionIdOnIO, GetServiceWorkerContext(browser_context, origin), service_worker_registration_id, std::move(callback))); } // static void PushMessagingService::UpdatePushSubscriptionId( BrowserContext* browser_context, const GURL& origin, int64_t service_worker_registration_id, const std::string& subscription_id, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&UpdatePushSubscriptionIdOnIO, GetServiceWorkerContext(browser_context, origin), service_worker_registration_id, origin, subscription_id, std::move(callback))); } // static void PushMessagingService::StorePushSubscriptionForTesting( BrowserContext* browser_context, const GURL& origin, int64_t service_worker_registration_id, const std::string& subscription_id, const std::string& sender_id, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&StorePushSubscriptionOnIOForTesting, GetServiceWorkerContext(browser_context, origin), service_worker_registration_id, origin, subscription_id, sender_id, std::move(callback))); } } // namespace content
38.572139
78
0.721527
[ "vector" ]
f391b6d90d1aa83d6fb4ea3209e215dbcca3fcc5
1,553
cpp
C++
SMLMLib/StringUtils.cpp
qnano/simflux
4f149d4e6c997954ac862cc5a7a404855b2a0be9
[ "MIT" ]
2
2019-12-13T16:24:12.000Z
2021-03-13T04:02:51.000Z
SMLMLib/StringUtils.cpp
qnano/simflux
4f149d4e6c997954ac862cc5a7a404855b2a0be9
[ "MIT" ]
1
2021-01-25T13:32:43.000Z
2021-01-26T06:03:19.000Z
SMLMLib/StringUtils.cpp
qnano/simflux
4f149d4e6c997954ac862cc5a7a404855b2a0be9
[ "MIT" ]
null
null
null
#include "MemLeakDebug.h" #include "StringUtils.h" #include <cstdarg> #include <Windows.h> #include <mutex> std::mutex printMutex; void (*debugPrintCallback)(const char *msg)=0; DLL_EXPORT std::string SPrintf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); char buf[512]; VSNPRINTF(buf, sizeof(buf), fmt, ap); va_end(ap); return buf; } CDLL_EXPORT void DebugPrintf(const char* fmt, ...) { std::lock_guard<std::mutex> l(printMutex); va_list ap; va_start(ap, fmt); char buf[1024]; VSNPRINTF(buf, sizeof(buf), fmt, ap); OutputDebugString(buf); if (debugPrintCallback) debugPrintCallback(buf); fputs(buf, stdout); va_end(ap); } CDLL_EXPORT void SetDebugPrintCallback(void(*cb)(const char *msg)) { std::lock_guard<std::mutex> l(printMutex); debugPrintCallback = cb; } DLL_EXPORT std::vector<std::string> StringSplit(const std::string& str, char sep) { std::vector<std::string> r; std::string cur; for (int x = 0; x<str.size(); x++) { if (str[x] == sep) { r.push_back(cur); cur = ""; } else { cur += str[x]; } } if (cur.size()>0) r.push_back(cur); return r; } CDLL_EXPORT int FindIndexInSplitString(const char * str, const char * item, char seperator) { // TODO: fix this, this fails when doing complicated labels like FindIndexInSplitString("abc, ab", "ab", ','). // Should return 1 but returns 0 const char *found = strstr(str, item); if (!found) return -1; size_t pos = found - str; size_t i = 0; int n = 0; while (i<pos) { if (str[i] == seperator) n++; i++; } return n; }
19.4125
112
0.658081
[ "vector" ]
f3984bd6ff143bc600d6ef004e014d5adb2c74a3
853
cpp
C++
pg_answer/986eef90611543ec8ac5964988c4f17d.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
8
2019-10-09T14:33:42.000Z
2020-12-03T00:49:29.000Z
pg_answer/986eef90611543ec8ac5964988c4f17d.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
pg_answer/986eef90611543ec8ac5964988c4f17d.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <algorithm> int main() { int n, m; std::cin >> n >> m; std::vector<std::string> dict(n); for (auto& i : dict) { std::cin >> i; } int len{dict[0].size()}; while (m--) { std::string dest; std::cin >> dest; if (dest.size() % len != 0) { std::cout << "No" << std::endl; continue; } while (dest.size()) { std::string sub{dest.substr(dest.size() - len)}; auto it = std::find(dict.begin(), dict.end(), sub); if (it != dict.end()) { dest.erase(dest.size() - len); } else { std::cout << "No" << std::endl; goto next; } } std::cout << "Yes" << std::endl; next:; } }
25.088235
63
0.420868
[ "vector" ]
f39cd2c918a2b4d660c2ceffddc5967c1af6f08c
2,517
cpp
C++
os/fs/iso9660/iso9660Iterator.cpp
rvedam/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
2
2020-11-30T18:38:20.000Z
2021-06-07T07:44:03.000Z
os/fs/iso9660/iso9660Iterator.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
1
2019-01-14T03:09:45.000Z
2019-01-14T03:09:45.000Z
os/fs/iso9660/iso9660Iterator.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008, 2009 Google Inc. * Copyright 2006 Nintendo Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // ISO 9660 directory iterator #include <string.h> #include <es.h> #include <es/handle.h> #include "iso9660Stream.h" Iso9660Iterator:: Iso9660Iterator(Iso9660Stream* stream) : ref(1), stream(stream) { ASSERT(stream->isDirectory()); stream->addRef(); ipos = 0; } Iso9660Iterator:: ~Iso9660Iterator() { stream->release(); } bool Iso9660Iterator:: hasNext() { ASSERT(stream->isDirectory()); Handle<es::Stream> dir(stream->cache->getInputStream()); dir->setPosition(ipos); u8 record[255]; return stream->findNext(dir, record); } // Dot and dotdot entries are not reported. Object* Iso9660Iterator:: next() { ASSERT(stream->isDirectory()); Handle<es::Stream> dir(stream->cache->getInputStream()); dir->setPosition(ipos); u8 record[255]; if (!stream->findNext(dir, record)) { return 0; } ipos = dir->getPosition(); Iso9660Stream* next = stream->fileSystem->lookup(stream->location, ipos - record[DR_Length]); if (!next) { next = stream->fileSystem->createStream(stream->fileSystem, stream, ipos - record[DR_Length], record); } return static_cast<es::Binding*>(next); } int Iso9660Iterator:: remove() { return -1; } Object* Iso9660Iterator:: queryInterface(const char* riid) { Object* objectPtr; if (strcmp(riid, es::Iterator::iid()) == 0) { objectPtr = static_cast<es::Iterator*>(this); } else if (strcmp(riid, Object::iid()) == 0) { objectPtr = static_cast<es::Iterator*>(this); } else { return NULL; } objectPtr->addRef(); return objectPtr; } unsigned int Iso9660Iterator:: addRef() { return ref.addRef(); } unsigned int Iso9660Iterator:: release() { unsigned int count = ref.release(); if (count == 0) { delete this; return 0; } return count; }
21.512821
110
0.651172
[ "object" ]
f3a6c9d81d83713f3b88837df7e64a7f20fc3f63
3,658
cpp
C++
src/armnn/test/ModelAccuracyCheckerTest.cpp
sunshinemyson/armnn
a723ec5d2ac35948efb5dfd0c121a1a89cb977b7
[ "MIT" ]
1
2019-06-26T23:00:46.000Z
2019-06-26T23:00:46.000Z
src/armnn/test/ModelAccuracyCheckerTest.cpp
hessed99/armnn
a723ec5d2ac35948efb5dfd0c121a1a89cb977b7
[ "MIT" ]
null
null
null
src/armnn/test/ModelAccuracyCheckerTest.cpp
hessed99/armnn
a723ec5d2ac35948efb5dfd0c121a1a89cb977b7
[ "MIT" ]
null
null
null
// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "ModelAccuracyChecker.hpp" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <iostream> #include <string> #include <boost/log/core/core.hpp> #include <boost/filesystem.hpp> #include <boost/optional.hpp> #include <boost/variant.hpp> using namespace armnnUtils; struct TestHelper { const std::map<std::string, int> GetValidationLabelSet() { std::map<std::string, int> validationLabelSet; validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000001", 2)); validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000002", 9)); validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000003", 1)); validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000004", 6)); validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000005", 5)); validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000006", 0)); validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000007", 8)); validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000008", 4)); validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000009", 3)); validationLabelSet.insert( std::make_pair("ILSVRC2012_val_00000009", 7)); return validationLabelSet; } }; BOOST_AUTO_TEST_SUITE(ModelAccuracyCheckerTest) using TContainer = boost::variant<std::vector<float>, std::vector<int>, std::vector<unsigned char>>; BOOST_FIXTURE_TEST_CASE(TestFloat32OutputTensorAccuracy, TestHelper) { ModelAccuracyChecker checker(GetValidationLabelSet()); // Add image 1 and check accuracy std::vector<float> inferenceOutputVector1 = {0.05f, 0.10f, 0.70f, 0.15f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; TContainer inference1Container(inferenceOutputVector1); std::vector<TContainer> outputTensor1; outputTensor1.push_back(inference1Container); std::string imageName = "ILSVRC2012_val_00000001.JPEG"; checker.AddImageResult<TContainer>(imageName, outputTensor1); // Top 1 Accuracy float totalAccuracy = checker.GetAccuracy(1); BOOST_CHECK(totalAccuracy == 100.0f); // Add image 2 and check accuracy std::vector<float> inferenceOutputVector2 = {0.10f, 0.0f, 0.0f, 0.0f, 0.05f, 0.70f, 0.0f, 0.0f, 0.0f, 0.15f}; TContainer inference2Container(inferenceOutputVector2); std::vector<TContainer> outputTensor2; outputTensor2.push_back(inference2Container); imageName = "ILSVRC2012_val_00000002.JPEG"; checker.AddImageResult<TContainer>(imageName, outputTensor2); // Top 1 Accuracy totalAccuracy = checker.GetAccuracy(1); BOOST_CHECK(totalAccuracy == 50.0f); // Top 2 Accuracy totalAccuracy = checker.GetAccuracy(2); BOOST_CHECK(totalAccuracy == 100.0f); // Add image 3 and check accuracy std::vector<float> inferenceOutputVector3 = {0.0f, 0.10f, 0.0f, 0.0f, 0.05f, 0.70f, 0.0f, 0.0f, 0.0f, 0.15f}; TContainer inference3Container(inferenceOutputVector3); std::vector<TContainer> outputTensor3; outputTensor3.push_back(inference3Container); imageName = "ILSVRC2012_val_00000003.JPEG"; checker.AddImageResult<TContainer>(imageName, outputTensor3); // Top 1 Accuracy totalAccuracy = checker.GetAccuracy(1); BOOST_CHECK(totalAccuracy == 33.3333321f); // Top 2 Accuracy totalAccuracy = checker.GetAccuracy(2); BOOST_CHECK(totalAccuracy == 66.6666641f); // Top 3 Accuracy totalAccuracy = checker.GetAccuracy(3); BOOST_CHECK(totalAccuracy == 100.0f); } BOOST_AUTO_TEST_SUITE_END()
36.949495
113
0.726353
[ "vector" ]
f3ac822f51b77464c2f744a948b80e1d81621ece
28,673
cpp
C++
toonz/sources/tnzbase/tscanner/tscannerepson.cpp
areckx/opentoonz
a86fd8f80a1a07f97a8d230fda44fd1d6a7de576
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/tnzbase/tscanner/tscannerepson.cpp
areckx/opentoonz
a86fd8f80a1a07f97a8d230fda44fd1d6a7de576
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/tnzbase/tscanner/tscannerepson.cpp
areckx/opentoonz
a86fd8f80a1a07f97a8d230fda44fd1d6a7de576
[ "BSD-3-Clause" ]
null
null
null
#include <errno.h> #include "texception.h" #include "tscanner.h" #include "tscannerepson.h" #include "tscannerutil.h" #include "tsystem.h" #include "tconvert.h" #include "trop.h" #include "TScannerIO/TUSBScannerIO.h" #include <cassert> #include <memory> #include <fstream> #include <sstream> using namespace TScannerUtil; static void sense(bool) {} static int scsi_maxlen() { assert(0); return 0; } #define BW_USES_GRAYTONES #ifndef _WIN32 #define SWAPIT #endif #ifdef i386 #undef SWAPIT #endif /* Commands used to drive the scanner: cmd spec Level @ Reset B2 B3 B4 B5 A5 Q Sharpness B4 B5 A5 B Halftoning B1 B2 B3 B4 B5 A5 Z Gamma B2 B3 B4 B5 A5 L Brightness B2 B3 B4 B5 A5 t Threshold H Zoom B2 B3 B4 B5 A5 R Resolution B1 B2 B3 B4 B5 A5 A Set read Area B1 B2 B3 B4 B5 A5 C Linesequence Mode B1 B2 B3 B4 B5 A5 d Line count B4 B5 A5 D Dataformat B1 B2 B3 B4 B5 A5 g Scan speed B4 B5 A5 G Start Scan B1 B2 B3 B4 B5 e Activate ADF 0x19 Load from ADF 0x0C Unload from ADF */ /* NOTE: you can find these codes with "man ascii". */ static unsigned char STX = 0x02; static unsigned char ACK = 0x06; static unsigned char NAK = 0x15; static unsigned char CAN = 0x18; static unsigned char ESC = 0x1B; static unsigned char PF = 0x19; /* STATUS bit in readLineData */ static unsigned char FatalError = 1 << 7; static unsigned char NotReady = 1 << 6; //----------------------------------------------------------------------------- #define log class TScannerExpection final : public TException { TString m_scannerMsg; public: TScannerExpection(const std::vector<std::string> &notFatal, const std::string &fatal) : TException("Scanner Expection") { m_scannerMsg = ::to_wstring(fatal); for (int i = notFatal.size(); i; i--) m_scannerMsg += L"\n" + ::to_wstring(notFatal[i - 1]); log("Exception created: " + ::to_string(m_scannerMsg)); } TString getMessage() const override { return m_scannerMsg; } }; //----------------------------------------------------------------------------- namespace { /* void log(string s) { std::ofstream os("C:\\butta.txt", std::ios::app); os << s << std::endl; os.flush(); } */ } //----------------------------------------------------------------------------- TScannerEpson::TScannerEpson() : m_scannerIO(new TUSBScannerIO()), m_hasADF(false), m_isOpened(false) { log("Created"); } //----------------------------------------------------------------------------- void TScannerEpson::closeIO() { log("CloseIO."); if (m_scannerIO && m_isOpened) m_scannerIO->close(); m_isOpened = false; } //----------------------------------------------------------------------------- TScannerEpson::~TScannerEpson() { closeIO(); log("Destroyed"); } //----------------------------------------------------------------------------- void TScannerEpson::selectDevice() { log(std::string("selectDevice; isOpened=") + (m_isOpened ? "true" : "false")); if (!m_scannerIO->open()) { log("open() failed"); throw TException("unable to get handle to scanner"); } m_isOpened = true; /* char lev0, lev1; unsigned short lowRes, hiRes, hMax,vMax; collectInformation(&lev0, &lev1, &lowRes, &hiRes, &hMax, &vMax); string version = toString(lev0) + "." + toString(lev1); */ setName("Scanner EPSON (Internal driver)"); } //----------------------------------------------------------------------------- bool TScannerEpson::isDeviceAvailable() { return true; } //----------------------------------------------------------------------------- bool TScannerEpson::isDeviceSelected() { return m_isOpened; } //----------------------------------------------------------------------------- void TScannerEpson::updateParameters(TScannerParameters &parameters) { log("updateParameters()"); char lev0, lev1; unsigned short lowRes, hiRes, hMax, vMax; collectInformation(&lev0, &lev1, &lowRes, &hiRes, &hMax, &vMax); log("collected info. res = " + std::to_string(lowRes) + "/" + std::to_string(hiRes)); // non supportiamo black & white parameters.setSupportedTypes(true, true, true); // param.m_scanArea = TRectD(0, 0, 0, 0); parameters.setMaxPaperSize((25.4 * hMax) / (float)hiRes, (25.4 * vMax) / (float)hiRes); parameters.updatePaperFormat(); // cambio range, default, step, e supported. aggiorno, se necessario, il value // (n.b. non dovrebbe succedere // mai, perche' i range sono sempre gli stessi su tutti gli scanner TScanParam defaultEpsonParam(0., 255., 128., 1.); parameters.m_brightness.update(defaultEpsonParam); parameters.m_contrast.update(defaultEpsonParam); parameters.m_threshold.update(defaultEpsonParam); if (m_hasADF) { TScanParam defaultPaperFeederParam(0., 1., 0., 1.); parameters.m_paperFeeder.update(defaultPaperFeederParam); } else parameters.m_paperFeeder.m_supported = false; // cerco un default per il dpi. il piu' piccolo possibile nella forma 100+k50 float defaultDpi = 100; while (defaultDpi < lowRes) defaultDpi += 50; TScanParam defaultDpiParam(lowRes, hiRes, defaultDpi, hiRes > lowRes ? 1.F : 0.F); parameters.m_dpi.update(defaultDpiParam); // parameters.m_twainVersion = "NATIVE"; // parameters.m_manufacturer = "EPSON"; // parameters.m_version = toString(lev0) + "." + toString(lev1); log("end updateParameters()"); } //----------------------------------------------------------------------------- void TScannerEpson::acquire(const TScannerParameters &params, int paperCount) { log("acquire"); TRectD scanArea = params.getScanArea(); if (scanArea.isEmpty()) throw TException("Scan area is empty, select a paper size"); /* if ((scanArea.getSize().lx > params.m_maxPaperSize.lx) || (scanArea.getSize().ly > params.m_maxPaperSize.ly)) throw TException("Scan area too large, select a correct paper size"); */ for (int i = 0; i < paperCount; ++i) { log("paper " + std::to_string(i)); #ifdef _DEBUG m_scannerIO->trace(true); #endif doSettings(params, i == 0); unsigned int nTimes = 0; unsigned int bytes_to_read; bool rc; unsigned char stx; #ifdef _DEBUG m_scannerIO->trace(false); #endif TRasterP ras, rasBuffer; unsigned char *buffer = 0; log("Scan command"); rc = ESCI_command('G', false); /* 'SCAN' command */ if (!rc) throw TException("Start Scan failed"); log("Scan command OK"); unsigned short offsetx = 0, offsety = 0; unsigned short dimlx = 0, dimly = 0; TRectD scanArea = params.isPreview() ? params.getScanArea() : params.getCropBox(); scanArea2pix(params, offsetx, offsety, dimlx, dimly, scanArea); tswap(dimlx, dimly); unsigned int bytes; switch (params.getScanType()) { case TScannerParameters::BW: #ifdef BW_USES_GRAYTONES ras = TRasterGR8P(dimlx, dimly); bytes = dimlx * dimly; rasBuffer = TRasterGR8P(dimlx, dimly); buffer = rasBuffer->getRawData(); break; break; #else ras = TRasterGR8P(dimlx, dimly); bytes = tceil(dimlx / 8) * dimly; rasBuffer = TRasterGR8P(tceil(dimlx / 8), dimly); // bytes = (dimlx + 7) % 8 * dimly; // rasBuffer = TRasterGR8P((dimlx + 7) % 8,dimly); buffer = rasBuffer->getRawData(); break; #endif case TScannerParameters::GR8: #ifdef GRAYTONES_USES_RGB ras = TRasterGR8P(dimlx, dimly); bytes = dimlx * dimly * 3; rasBuffer = TRasterGR8P(dimlx * 3, dimly); buffer = rasBuffer->getRawData(); break; #else ras = TRasterGR8P(dimlx, dimly); bytes = dimlx * dimly; rasBuffer = TRasterGR8P(dimlx, dimly); buffer = rasBuffer->getRawData(); break; #endif case TScannerParameters::RGB24: ras = TRaster32P(dimlx, dimly); bytes = dimlx * dimly * 3; rasBuffer = TRasterGR8P(dimlx * 3, dimly); buffer = rasBuffer->getRawData(); break; default: throw TException("Unknown scanner mode"); break; } log("sleep"); TSystem::sleep(2000); log("reading data"); bool areaEnd = false; unsigned int bytes_read = 0; while (!areaEnd) { unsigned short lines, counter; unsigned char status = 0; unsigned int retryCount = 0; do { ESCI_readLineData(stx, status, counter, lines, areaEnd); if (status & FatalError) { retryCount++; if (retryCount == 1) throw TException("Error scanning"); } } while (status & FatalError); bytes_to_read = lines * counter; if (stx != 0x02) { std::stringstream os; os << "header corrupted (" << std::hex << stx << ")" << '\0'; throw TException(os.str()); } unsigned long reqBytes = bytes_to_read; std::unique_ptr<unsigned char[]> readBuffer = ESCI_read_data2(reqBytes); if (!readBuffer) throw TException("Error reading image data"); log("readline: OK"); /* if (params.getScanType() == TScannerParameters::BW ) { for (unsigned int i = 0; i< reqBytes;i++) readBuffer[i] = ~readBuffer[i]; } */ memcpy(buffer + bytes_read, readBuffer.get(), reqBytes); bytes_read += reqBytes; nTimes++; if (bytes_read == bytes) break; /* I've read enough bytes */ if (!(stx & 0x20)) sendACK(); } log("read: OK"); { /* FILE *myFile = fopen("C:\\temp\\prova.dmp", "w+"); fwrite(buffer, 1, bytes_to_read, myFile); fclose(myFile);*/ } if (params.m_paperFeeder.m_supported && (params.m_paperFeeder.m_value == 1.)) { log("Advance paper"); if (m_settingsMode == OLD_STYLE) ESCI_doADF(0); log("Advance paper: OK"); } switch (params.getScanType()) { case TScannerParameters::BW: #ifdef BW_USES_GRAYTONES copyGR8BufferToTRasterBW(buffer, dimlx, dimly, ras, true, params.m_threshold.m_value); // copyGR8BufferToTRasterGR8(buffer, dimlx, dimly, ras, true); break; #else copyBWBufferToTRasterGR8(buffer, dimlx, dimly, ras, true, true); break; #endif case TScannerParameters::GR8: #ifdef GRAYTONES_USES_RGB copyRGBBufferToTRasterGR8(buffer, dimlx, dimly, dimlx, ras); break; #else copyGR8BufferToTRasterGR8(buffer, dimlx, dimly, ras, true); break; #endif case TScannerParameters::RGB24: copyRGBBufferToTRaster32(buffer, dimlx, dimly, ras, true); break; default: throw TException("Unknown scanner mode"); break; } if (params.getCropBox() != params.getScanArea() && !params.isPreview()) { TRect scanRect( TPoint(offsetx, offsety), TDimension(dimly, dimlx)); // dimLx and ly was has been swapped scanArea2pix(params, offsetx, offsety, dimlx, dimly, params.getScanArea()); TRasterP app = ras->create(dimly, dimlx); TRaster32P app32(app); TRasterGR8P appGR8(app); if (app32) app32->fill(TPixel32::White); else if (appGR8) appGR8->fill(TPixelGR8::White); app->copy(ras, TPoint(dimly - scanRect.y1 - 1, dimlx - scanRect.x1 - 1)); ras = app; } TRasterImageP rasImg(ras); if (ras) { rasImg->setDpi(params.m_dpi.m_value, params.m_dpi.m_value); rasImg->setSavebox(ras->getBounds()); } log("notifying"); notifyImageDone(rasImg); if (!(params.m_paperFeeder.m_value == 1.) || params.isPreview()) // feeder here! { if ((paperCount - i) > 1) notifyNextPaper(); } else notifyAutomaticallyNextPaper(); if (isScanningCanceled()) break; } /*Unload Paper if need*/ if ((m_settingsMode == NEW_STYLE) && params.m_paperFeeder.m_supported && (params.m_paperFeeder.m_value == 1.)) { if (!ESCI_command_1b('e', 1, true)) { std::vector<std::string> notFatal; throw TScannerExpection(notFatal, "Scanner error (un)loading paper"); } unsigned char p = 0x0C; bool status = true; send(&p, 1); status = expectACK(); } log("acquire OK"); } //----------------------------------------------------------------------------- bool TScannerEpson::isAreaSupported() { return true; } //----------------------------------------------------------------------------- inline unsigned char B0(const unsigned int v) { return (v & 0x000000ff); } inline unsigned char B1(const unsigned int v) { return (v & 0x0000ff00) >> 8; } inline unsigned char B2(const unsigned int v) { return (v & 0x00ff0000) >> 16; } inline unsigned char B3(const unsigned int v) { return (v & 0xff000000) >> 24; } void TScannerEpson::doSettings(const TScannerParameters &params, bool firstSheet) { log("doSettings"); int retryCount = 3; std::vector<std::string> notFatal; while (retryCount--) { if (m_settingsMode == NEW_STYLE) { if (firstSheet) if (!resetScanner()) { notFatal.push_back("Scanner error resetting"); continue; } } else { if (!resetScanner()) { notFatal.push_back("Scanner error resetting"); continue; } } unsigned char cmd[64]; memset(&cmd, 0, 64); unsigned char brightness = 0x00; float bv = params.m_brightness.m_value; if (bv >= 0 && bv < 43) brightness = 0xFD; if (bv >= 43 && bv < 86) brightness = 0xFE; if (bv >= 86 && bv < 128) brightness = 0xFF; if (bv >= 128 && bv < 171) brightness = 0x00; if (bv >= 171 && bv < 214) brightness = 0x01; if (bv >= 214 && bv < 255) brightness = 0x02; if (bv == 255) brightness = 0x03; unsigned short dpi = (unsigned short)params.m_dpi.m_value; unsigned short offsetx, offsety; unsigned short sizelx, sizely; TRectD scanArea = params.isPreview() ? params.getScanArea() : params.getCropBox(); scanArea2pix(params, offsetx, offsety, sizelx, sizely, scanArea); // the main scan resolution (ESC R) cmd[0] = B0(dpi); cmd[1] = B1(dpi); cmd[2] = B2(dpi); cmd[3] = B3(dpi); // the sub scan resolution (ESC R) cmd[4] = B0(dpi); cmd[5] = B1(dpi); cmd[6] = B2(dpi); cmd[7] = B3(dpi); // skipping length of main scan (ESC A) cmd[8] = B0(offsetx); cmd[9] = B1(offsetx); cmd[10] = B2(offsetx); cmd[11] = B3(offsetx); // skipping length of sub scan (ESC A) cmd[12] = B0(offsety); cmd[13] = B1(offsety); cmd[14] = B2(offsety); cmd[15] = B3(offsety); // the length of main scanning (ESC A) cmd[16] = B0(sizelx); cmd[17] = B1(sizelx); cmd[18] = B2(sizelx); cmd[19] = B3(sizelx); // the length of sub scanning (ESC A) cmd[20] = B0(sizely); cmd[21] = B1(sizely); cmd[22] = B2(sizely); cmd[23] = B3(sizely); #ifdef GRAYTONES_USES_RGB cmd[24] = 0x13; // scanning color (ESC C) cmd[25] = 0x08; // data format (ESC D) #else switch (params.getScanType()) { case TScannerParameters::BW: cmd[24] = 0x00; // scanning BW/Gray (ESC C) #ifdef BW_USES_GRAYTONES cmd[25] = 0x08; // data format (ESC D) #else cmd[25] = 0x01; // data format (ESC D) break; #endif case TScannerParameters::GR8: cmd[24] = 0x00; // scanning BW/Gray (ESC C) cmd[25] = 0x08; // data format (ESC D) break; case TScannerParameters::RGB24: cmd[24] = 0x13; // scanning color (ESC C) cmd[25] = 0x08; // data format (ESC D) break; default: throw TException("Unknown scanner mode"); break; } // cmd[24] = (params.getScanType() == TScannerParameters::RGB24)?0x13:0x00; // //scanning color (ESC C) // cmd[25] = (params.getScanType() == TScannerParameters::RGB24)?0x08:0x08; // // data format (ESC D) #endif if (m_settingsMode == NEW_STYLE) cmd[26] = 0; else cmd[26] = (params.m_paperFeeder.m_supported && (params.m_paperFeeder.m_value == 1.)) ? 0x01 : 0x00; // option control (ESC e) cmd[27] = 0x00; // scanning mode (ESC g) cmd[28] = 0xFF; // the number of block line (ESC d) cmd[29] = 0x02; // gamma (ESC Z) cmd[30] = brightness; // brightness (ESC L) cmd[31] = 0x80; // color collection (ESC M) cmd[32] = 0x01; // half toning processing (ESC B) cmd[33] = (unsigned char)params.m_threshold.m_value; // threshold (ESC t) cmd[34] = 0x00; // separate of area (ESC s) cmd[35] = 0x01; // sharpness control (ESC Q) cmd[36] = 0x00; // mirroring (ESC K) cmd[37] = 0x00; // set film type (ESC N) // other bytes should be set to 0x00 ! if (m_settingsMode == NEW_STYLE) if (params.m_paperFeeder.m_supported && (params.m_paperFeeder.m_value == 1.)) { unsigned char v = (params.m_paperFeeder.m_value == 1.) ? 0x01 : 0x00; if (!ESCI_command_1b('e', v, true)) throw TScannerExpection(notFatal, "Scanner error (un)loading paper"); if (v) { unsigned char p = 0x19; bool status = true; send(&p, 1); status = expectACK(); } } unsigned char setParamCmd[2] = {0x1C, 0x57}; int wrote = send(&setParamCmd[0], 2); if (wrote != 2) throw TScannerExpection(notFatal, "Error setting scanner parameters - W -"); if (!expectACK()) { notFatal.push_back("Error setting scanner parameters - NAK on W -"); continue; } wrote = send(&cmd[0], 0x40); if (wrote != 0x40) throw TScannerExpection(notFatal, "Error setting scanner parameters - D -"); if (!expectACK()) { notFatal.push_back("Error setting scanner parameters - NAK on D -"); continue; } // if here, everything is ok, exit from loop break; } if (retryCount <= 0) throw TScannerExpection( notFatal, "Error setting scanner parameters, too many retries"); log("doSettings:OK"); } //----------------------------------------------------------------------------- void TScannerEpson::collectInformation(char *lev0, char *lev1, unsigned short *lowRes, unsigned short *hiRes, unsigned short *hMax, unsigned short *vMax) { log("collectInformation"); unsigned char stx; int pos = 0; unsigned short counter; unsigned char status; /* if (!resetScanner()) throw TException("Scanner error resetting"); */ if (!ESCI_command('I', false)) throw TException("Unable to get scanner info. Is it off ?"); unsigned long s = 4; // 4 bytes cfr Identity Data Block on ESCI Manual!!! std::unique_ptr<unsigned char[]> buffer2 = ESCI_read_data2(s); if (!buffer2 || (s != 4)) throw TException("Error reading scanner info"); memcpy(&stx, buffer2.get(), 1); memcpy(&counter, &(buffer2[2]), 2); #ifdef SWAPIT counter = swapUshort(counter); #endif #ifdef _DEBUG memcpy(&status, &(buffer2[1]), 1); std::stringstream os; os << "stx = " << stx << " status = " << status << " counter=" << counter << '\n' << '\0'; #endif s = counter; std::unique_ptr<unsigned char[]> buffer = ESCI_read_data2(s); int len = strlen((const char *)buffer.get()); /*printf("Level %c%c", buffer[0], buffer[1]);*/ if (len > 1) { *lev0 = buffer[0]; *lev1 = buffer[1]; } pos = 2; /* buffer[pos] contains 'R' */ if (len < 3 || buffer[pos] != 'R') { *lev0 = '0'; *lev1 = '0'; *lowRes = 0; *hiRes = 0; *vMax = 0; *hMax = 0; throw TException("unable to get information from scanner"); } *lowRes = (buffer[pos + 2] * 256) + buffer[pos + 1]; *hiRes = *lowRes; while (buffer[pos] == 'R') { *hiRes = (buffer[pos + 2] * 256) + buffer[pos + 1]; /* printf("Resolution %c %d", buffer[pos], *hiRes);*/ pos += 3; } if (buffer[pos] != 'A') { *lev0 = '0'; *lev1 = '0'; *lowRes = 0; *hiRes = 0; *vMax = 0; *hMax = 0; throw TException("unable to get information from scanner"); } *hMax = (buffer[pos + 2] * 256) + buffer[pos + 1]; *vMax = (buffer[pos + 4] * 256) + buffer[pos + 3]; ESCI_command('f', false); ESCI_readLineData2(stx, status, counter); if (status & FatalError) throw TException("Fatal error reading information from scanner"); s = counter; buffer = ESCI_read_data2(s); // name buffer+1A const char *name = (const char *)(buffer.get() + 0x1A); if (strncmp(name, "Perfection1640", strlen("Perfection1640"))) { m_settingsMode = NEW_STYLE; } else { m_settingsMode = OLD_STYLE; } #if 0 scsi_new_d("ESCI_extended_status"); scsi_len(42); /* main status*/ scsi_b00(0, "push_button_supported", 0); scsi_b11(0, "warming_up", 0); scsi_b33(0, "adf_load_sequence", 0); /* 1 from first sheet; 0 from last or not supp */ scsi_b44(0, "both_sides_on_adf", 0); scsi_b55(0, "adf_installed_main_status", 0); scsi_b66(0, "NFlatbed", 0); /*0 if scanner is flatbed else 1 */ scsi_b77(0, "system_error", 0); /* adf status */ scsi_b77(1, "adf_installed",0); /*... some other info.., refer to manual if needed*/ /**/ #endif m_hasADF = !!(buffer[1] & 0x80); log("collectInformation:OK"); } //----------------------------------------------------------------------------- bool TScannerEpson::resetScanner() { log("resetScanner"); bool ret = ESCI_command('@', true); log(std::string("resetScanner: ") + (ret ? "OK" : "FAILED")); return ret; } //----------------------------------------------------------------------------- int TScannerEpson::receive(unsigned char *buffer, int size) { return m_scannerIO->receive(buffer, size); } int TScannerEpson::send(unsigned char *buffer, int size) { return m_scannerIO->send(buffer, size); } int TScannerEpson::sendACK() { return send(&ACK, 1); } bool TScannerEpson::expectACK() { log("expectACK"); unsigned char ack = NAK; int nb = receive(&ack, 1); #ifdef _DEBUG if (ack != ACK) { std::stringstream os; os << "ack fails ret = 0x" << std::hex << (int)ack << '\n' << '\0'; TSystem::outputDebug(os.str()); } #endif log(std::string("expectACK: ") + (ack == ACK ? "ACK" : "FAILED")); return (ack == ACK); } char *TScannerEpson::ESCI_inquiry(char cmd) /* returns 0 if failed */ { assert(0); return 0; } bool TScannerEpson::ESCI_command(char cmd, bool checkACK) { unsigned char p[2]; p[0] = ESC; p[1] = cmd; bool status; int count = send(&(p[0]), 2); status = count == 2; if (checkACK) status = expectACK(); return status; } bool TScannerEpson::ESCI_command_1b(char cmd, unsigned char p0, bool checkACK) { bool status = false; if (ESCI_command(cmd, checkACK)) { unsigned char p = p0; status = true; send(&p, 1); if (checkACK) status = expectACK(); } return status; } bool TScannerEpson::ESCI_command_2b(char cmd, unsigned char p0, unsigned char p1, bool checkACK) { bool status = false; if (ESCI_command(cmd, checkACK)) { status = true; unsigned char p[2]; p[0] = p0; p[1] = p1; int timeout = 30000; send(&(p[0]), 2); if (checkACK) status = expectACK(); } return status; } bool TScannerEpson::ESCI_command_2w(char cmd, unsigned short p0, unsigned short p1, bool checkACK) { bool status = false; if (ESCI_command(cmd, checkACK)) { status = true; unsigned short p[2]; p[0] = p0; p[1] = p1; const int len = 1; int timeout = 30000; send((unsigned char *)(&(p[0])), 4); if (checkACK) status = expectACK(); } return status; } bool TScannerEpson::ESCI_command_4w(char cmd, unsigned short p0, unsigned short p1, unsigned short p2, unsigned short p3, bool checkACK) { bool status = false; if (ESCI_command(cmd, checkACK)) { status = true; unsigned char p[8]; p[0] = (unsigned char)p0; p[1] = (unsigned char)(p0 >> 8); p[2] = (unsigned char)p1; p[3] = (unsigned char)(p1 >> 8); p[4] = (unsigned char)p2; p[5] = (unsigned char)(p2 >> 8); p[6] = (unsigned char)(p3); p[7] = (unsigned char)(p3 >> 8); send((unsigned char *)&(p[0]), 8); if (checkACK) status = expectACK(); } return status; } std::unique_ptr<unsigned char[]> TScannerEpson::ESCI_read_data2( unsigned long &size) { std::unique_ptr<unsigned char[]> buffer(new unsigned char[size]); memset(buffer.get(), 0, size); unsigned long bytesToRead = size; size = receive(buffer.get(), bytesToRead); return buffer; } bool TScannerEpson::ESCI_doADF(bool on) { // check ref esci documentation page 3-64 unsigned char eject = 0x0c; int rc = send(&eject, 1); bool status1 = expectACK(); return status1; return 1; if (!ESCI_command_1b('e', 0x01, true)) { if (on) throw TException("Scanner error loading paper"); else throw TException("Scanner error unloading paper"); } unsigned char p = on ? 0x19 : 0x0C; send(&p, 1); bool status = expectACK(); return status; } void TScannerEpson::scanArea2pix(const TScannerParameters &params, unsigned short &offsetx, unsigned short &offsety, unsigned short &sizelx, unsigned short &sizely, const TRectD &scanArea) { const double f = 25.4; offsetx = (unsigned short)((scanArea.x0 * params.m_dpi.m_value) / f); offsety = (unsigned short)((scanArea.y0 * params.m_dpi.m_value) / f); sizelx = (unsigned short)(((scanArea.x1 - scanArea.x0) * params.m_dpi.m_value) / f); sizelx = (sizelx >> 3) << 3; // questo deve essere multiplo di 8 sizely = (unsigned short)(((scanArea.y1 - scanArea.y0) * params.m_dpi.m_value) / f); } void TScannerEpson::ESCI_readLineData(unsigned char &stx, unsigned char &status, unsigned short &counter, unsigned short &lines, bool &areaEnd) { unsigned long s = 6; std::unique_ptr<unsigned char[]> buffer = ESCI_read_data2(s); if (!buffer) throw TException("Error reading scanner info"); /* PACKET DATA LEN = 6 type offs descr byte 0 STX b77 1 fatal_error b66 1 not_ready b55 1 area_end b44 1 option_unit b33 1 col_attrib_bit_3 b22 1 col_attrib_bit_2 b11 1 extended_commands drow 2, counter drow 4 lines */ bool fatalError = !!(buffer[1] & 0x80); bool notReady = !!(buffer[1] & 0x40); areaEnd = !!(buffer[1] & 0x20); memcpy(&stx, buffer.get(), 1); memcpy(&counter, &(buffer[2]), 2); #ifdef SWAPIT counter = swapUshort(counter); #endif memcpy(&lines, &(buffer[4]), 2); #ifdef SWAPIT lines = swapUshort(lines); #endif status = buffer[1]; #ifdef _DEBUG std::stringstream os; os << "fatal=" << fatalError; os << " notReady=" << notReady; os << " areaEnd=" << areaEnd; os << " stx=" << stx; os << " counter=" << counter; os << " lines=" << lines; os << '\n' << '\0'; TSystem::outputDebug(os.str()); #endif } void TScannerEpson::ESCI_readLineData2(unsigned char &stx, unsigned char &status, unsigned short &counter) { unsigned long s = 4; std::unique_ptr<unsigned char[]> buffer = ESCI_read_data2(s); if (!buffer) throw TException("Error reading scanner info"); bool fatalError = !!(buffer[1] & 0x80); bool notReady = !!(buffer[1] & 0x40); memcpy(&stx, buffer.get(), 1); memcpy(&counter, &(buffer[2]), 2); #ifdef SWAPIT counter = swapUshort(counter); #endif status = buffer[1]; #ifdef _DEBUG std::stringstream os; os << "fatal=" << fatalError; os << " notReady=" << notReady; os << " stx=" << stx; os << " counter=" << counter; os << '\n' << '\0'; TSystem::outputDebug(os.str()); #endif }
29.109645
87
0.567224
[ "vector" ]
f3b16e2ae28a11eba5f2104000974d12a3eccb1c
6,332
hh
C++
gazebo/physics/ode/ODELink.hh
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
5
2017-07-14T19:36:51.000Z
2020-04-01T06:47:59.000Z
gazebo/physics/ode/ODELink.hh
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
20
2017-07-20T21:04:49.000Z
2017-10-19T19:32:38.000Z
gazebo/physics/ode/ODELink.hh
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012-2016 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* Desc: ODE Link class * Author: Nate Koenig */ #ifndef _ODELINK_HH_ #define _ODELINK_HH_ #include "gazebo/physics/ode/ode_inc.h" #include "gazebo/physics/ode/ODETypes.hh" #include "gazebo/physics/Link.hh" #include "gazebo/util/system.hh" namespace gazebo { namespace physics { /// \addtogroup gazebo_physics_ode /// \{ /// \brief ODE Link class. class GZ_PHYSICS_VISIBLE ODELink : public Link { /// \brief Constructor. /// \param[in] _parent Parent model. public: explicit ODELink(EntityPtr _parent); /// \brief Destructor. public: virtual ~ODELink(); // Documentation inherited public: virtual void Load(sdf::ElementPtr _sdf); // Documentation inherited public: virtual void Init(); // Documentation inherited public: virtual void Fini(); // Documentation inherited public: virtual void OnPoseChange(); // Documentation inherited public: virtual void SetEnabled(bool _enable) const; // Documentation inherited public: virtual bool GetEnabled() const; /// \brief Update location of collisions relative to center of mass. /// This used to be done only in the Init function, but was moved /// to a separate function to handle dynamic updates to the /// center of mass. public: void UpdateCollisionOffsets(); // Documentation inherited public: virtual void UpdateMass(); // Documentation inherited public: virtual void UpdateSurface(); // Documentation inherited public: virtual void SetLinearVel(const math::Vector3 &_vel); // Documentation inherited public: virtual void SetAngularVel(const math::Vector3 &_vel); // Documentation inherited public: virtual void SetForce(const math::Vector3 &_force); // Documentation inherited public: virtual void SetTorque(const math::Vector3 &_torque); // Documentation inherited public: virtual void AddForce(const math::Vector3 &_force); // Documentation inherited public: virtual void AddRelativeForce(const math::Vector3 &_force); // Documentation inherited public: virtual void AddForceAtWorldPosition(const math::Vector3 &_force, const math::Vector3 &_pos); // Documentation inherited public: virtual void AddForceAtRelativePosition( const math::Vector3 &_force, const math::Vector3 &_relpos); // Documentation inherited public: virtual void AddLinkForce(const math::Vector3 &_force, const math::Vector3 &_offset = math::Vector3::Zero); // Documentation inherited public: virtual void AddTorque(const math::Vector3 &_torque); // Documentation inherited public: virtual void AddRelativeTorque(const math::Vector3 &_torque); // Documentation inherited public: virtual math::Vector3 GetWorldLinearVel( const math::Vector3 &_offset) const; // Documentation inherited public: virtual math::Vector3 GetWorldLinearVel( const math::Vector3 &_offset, const math::Quaternion &_q) const; // Documentation inherited public: virtual math::Vector3 GetWorldCoGLinearVel() const; // Documentation inherited public: virtual math::Vector3 GetWorldAngularVel() const; // Documentation inherited public: virtual math::Vector3 GetWorldForce() const; // Documentation inherited public: virtual math::Vector3 GetWorldTorque() const; // Documentation inherited public: virtual void SetGravityMode(bool _mode); // Documentation inherited public: virtual bool GetGravityMode() const; // Documentation inherited public: void SetSelfCollide(bool _collide); // Documentation inherited public: virtual void SetLinearDamping(double _damping); // Documentation inherited public: virtual void SetAngularDamping(double _damping); // Documentation inherited public: virtual void SetKinematic(const bool &_state); // Documentation inherited public: virtual bool GetKinematic() const; // Documentation inherited public: virtual void SetAutoDisable(bool _disable); /// \brief Return the ID of this link /// \return ODE link id public: dBodyID GetODEId() const; /// \brief Get the ID of the collision space this link is in. /// \return The collision space ID for the link. public: dSpaceID GetSpaceId() const; /// \brief Set the ID of the collision space this link is in. /// \param[in] _spaceId The collision space ID for the link. public: void SetSpaceId(dSpaceID _spaceid); /// \brief Callback when ODE determines a body is disabled. /// \param[in] _id Id of the body. public: static void DisabledCallback(dBodyID _id); /// \brief when ODE updates dynamics bodies, this callback /// propagates the chagnes in pose back to Gazebo /// \param[in] _id Id of the body. public: static void MoveCallback(dBodyID _id); // Documentation inherited public: virtual void SetLinkStatic(bool _static); /// \brief ODE link handle private: dBodyID linkId; /// \brief Pointer to the ODE Physics engine private: ODEPhysicsPtr odePhysics; /// \brief Collision space id. private: dSpaceID spaceId; /// \brief Cache force applied on body private: math::Vector3 force; /// \brief Cache torque applied on body private: math::Vector3 torque; }; /// \} } } #endif
31.502488
79
0.667562
[ "model" ]
f3b3addaaabbfa9da04674961b8c39938b4d4591
22,157
hpp
C++
include/MasterServer/UserMessageHandler.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
23
2020-08-07T04:09:00.000Z
2022-03-31T22:10:29.000Z
include/MasterServer/UserMessageHandler.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
6
2021-09-29T23:47:31.000Z
2022-03-30T20:49:23.000Z
include/MasterServer/UserMessageHandler.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
17
2020-08-20T19:36:52.000Z
2022-03-30T18:28:24.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: MasterServer.BaseClientMessageHandler #include "MasterServer/BaseClientMessageHandler.hpp" // Including type: ConnectionFailedReason #include "GlobalNamespace/ConnectionFailedReason.hpp" // Including type: PublicServerInfo #include "GlobalNamespace/PublicServerInfo.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: MasterServer namespace MasterServer { // Forward declaring type: ITimeProvider class ITimeProvider; // Forward declaring type: BaseConnectToServerRequest class BaseConnectToServerRequest; // Forward declaring type: IUserMessage class IUserMessage; // Forward declaring type: IMasterServerAuthenticateRequest class IMasterServerAuthenticateRequest; } // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IAuthenticationTokenProvider class IAuthenticationTokenProvider; // Forward declaring type: IUnconnectedSenderReceiver class IUnconnectedSenderReceiver; // Forward declaring type: MasterServerEndPoint class MasterServerEndPoint; // Forward declaring type: ICertificateValidator class ICertificateValidator; // Forward declaring type: BeatmapLevelSelectionMask struct BeatmapLevelSelectionMask; // Forward declaring type: GameplayServerConfiguration struct GameplayServerConfiguration; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: Func`1<TResult> template<typename TResult> class Func_1; } // Forward declaring namespace: System::Threading namespace System::Threading { // Skipping declaration: CancellationToken because it is already included! } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IReadOnlyList`1<T> template<typename T> class IReadOnlyList_1; } // Forward declaring namespace: System::Threading::Tasks namespace System::Threading::Tasks { // Forward declaring type: Task class Task; // Forward declaring type: Task`1<TResult> template<typename TResult> class Task_1; } // Completed forward declares // Type namespace: MasterServer namespace MasterServer { // Forward declaring type: UserMessageHandler class UserMessageHandler; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(MasterServer::UserMessageHandler); DEFINE_IL2CPP_ARG_TYPE(MasterServer::UserMessageHandler*, "MasterServer", "UserMessageHandler"); // Type namespace: MasterServer namespace MasterServer { // Size: 0xC0 #pragma pack(push, 1) // Autogenerated type: MasterServer.UserMessageHandler // [TokenAttribute] Offset: FFFFFFFF class UserMessageHandler : public MasterServer::BaseClientMessageHandler { public: // Nested type: MasterServer::UserMessageHandler::ConnectToServerDelegate class ConnectToServerDelegate; // Nested type: MasterServer::UserMessageHandler::$GetAuthenticationRequest$d__9 struct $GetAuthenticationRequest$d__9; // Nested type: MasterServer::UserMessageHandler::$$c__DisplayClass12_0 class $$c__DisplayClass12_0; // Nested type: MasterServer::UserMessageHandler::$$c__DisplayClass13_0 class $$c__DisplayClass13_0; // Nested type: MasterServer::UserMessageHandler::$WithFailureHandler$d__14 struct $WithFailureHandler$d__14; #ifdef USE_CODEGEN_FIELDS public: #else protected: #endif // private System.Int64 _lastKeepaliveTime // Size: 0x8 // Offset: 0xB0 int64_t lastKeepaliveTime; // Field size check static_assert(sizeof(int64_t) == 0x8); // private readonly IAuthenticationTokenProvider _authenticationTokenProvider // Size: 0x8 // Offset: 0xB8 GlobalNamespace::IAuthenticationTokenProvider* authenticationTokenProvider; // Field size check static_assert(sizeof(GlobalNamespace::IAuthenticationTokenProvider*) == 0x8); public: // static field const value: static private System.Int64 kKeepaliveRequestIntervalMs static constexpr const int64_t kKeepaliveRequestIntervalMs = 60000; // Get static field: static private System.Int64 kKeepaliveRequestIntervalMs static int64_t _get_kKeepaliveRequestIntervalMs(); // Set static field: static private System.Int64 kKeepaliveRequestIntervalMs static void _set_kKeepaliveRequestIntervalMs(int64_t value); // Get instance field reference: private System.Int64 _lastKeepaliveTime int64_t& dyn__lastKeepaliveTime(); // Get instance field reference: private readonly IAuthenticationTokenProvider _authenticationTokenProvider GlobalNamespace::IAuthenticationTokenProvider*& dyn__authenticationTokenProvider(); // public IAuthenticationTokenProvider get_authenticationTokenProvider() // Offset: 0x12F5EE0 GlobalNamespace::IAuthenticationTokenProvider* get_authenticationTokenProvider(); // public System.Void .ctor(IUnconnectedSenderReceiver sender, MasterServerEndPoint endPoint, IAuthenticationTokenProvider authenticationTokenProvider, MasterServer.ITimeProvider timeProvider, ICertificateValidator certificateValidator) // Offset: 0x12F5EE8 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static UserMessageHandler* New_ctor(GlobalNamespace::IUnconnectedSenderReceiver* sender, GlobalNamespace::MasterServerEndPoint* endPoint, GlobalNamespace::IAuthenticationTokenProvider* authenticationTokenProvider, MasterServer::ITimeProvider* timeProvider, GlobalNamespace::ICertificateValidator* certificateValidator) { static auto ___internal__logger = ::Logger::get().WithContext("MasterServer::UserMessageHandler::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<UserMessageHandler*, creationType>(sender, endPoint, authenticationTokenProvider, timeProvider, certificateValidator))); } // private System.Void UpdateKeepalive() // Offset: 0x12F5F48 void UpdateKeepalive(); // public System.Void ConnectToServer(System.String userId, System.String userName, BeatmapLevelSelectionMask selectionMask, GameplayServerConfiguration configuration, System.String secret, System.String code, MasterServer.UserMessageHandler/MasterServer.ConnectToServerDelegate onSuccess, System.Action`1<ConnectionFailedReason> onConnectionFailed, System.Threading.CancellationToken cancellationToken) // Offset: 0x12F622C void ConnectToServer(::Il2CppString* userId, ::Il2CppString* userName, GlobalNamespace::BeatmapLevelSelectionMask selectionMask, GlobalNamespace::GameplayServerConfiguration configuration, ::Il2CppString* secret, ::Il2CppString* code, MasterServer::UserMessageHandler::ConnectToServerDelegate* onSuccess, System::Action_1<GlobalNamespace::ConnectionFailedReason>* onConnectionFailed, System::Threading::CancellationToken cancellationToken); // private System.Void SendConnectToServerRequest(MasterServer.BaseConnectToServerRequest request, MasterServer.UserMessageHandler/MasterServer.ConnectToServerDelegate onSuccess, System.Action`1<ConnectionFailedReason> onConnectionFailed, System.Threading.CancellationToken cancellationToken) // Offset: 0x12F638C void SendConnectToServerRequest(MasterServer::BaseConnectToServerRequest* request, MasterServer::UserMessageHandler::ConnectToServerDelegate* onSuccess, System::Action_1<GlobalNamespace::ConnectionFailedReason>* onConnectionFailed, System::Threading::CancellationToken cancellationToken); // public System.Void GetPublicServers(System.String userId, System.String userName, System.Int32 offset, System.Int32 count, BeatmapLevelSelectionMask selectionMask, GameplayServerConfiguration configuration, System.Action`1<System.Collections.Generic.IReadOnlyList`1<PublicServerInfo>> onSuccess, System.Action`1<ConnectionFailedReason> onFailure, System.Threading.CancellationToken cancellationToken) // Offset: 0x12F6524 void GetPublicServers(::Il2CppString* userId, ::Il2CppString* userName, int offset, int count, GlobalNamespace::BeatmapLevelSelectionMask selectionMask, GlobalNamespace::GameplayServerConfiguration configuration, System::Action_1<System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::PublicServerInfo>*>* onSuccess, System::Action_1<GlobalNamespace::ConnectionFailedReason>* onFailure, System::Threading::CancellationToken cancellationToken); // private System.Void WithFailureHandler(System.Action`1<ConnectionFailedReason> onFailure, System.Func`1<System.Threading.Tasks.Task> performTask) // Offset: 0x12F6460 void WithFailureHandler(System::Action_1<GlobalNamespace::ConnectionFailedReason>* onFailure, System::Func_1<System::Threading::Tasks::Task*>* performTask); // public override System.Void PollUpdate() // Offset: 0x12F5F24 // Implemented from: MasterServer.MessageHandler // Base method: System.Void MessageHandler::PollUpdate() void PollUpdate(); // protected override System.Boolean ShouldHandleUserMessage(MasterServer.IUserMessage packet, MasterServer.MessageHandler/MasterServer.MessageOrigin origin) // Offset: 0x12F60D0 // Implemented from: MasterServer.MessageHandler // Base method: System.Boolean MessageHandler::ShouldHandleUserMessage(MasterServer.IUserMessage packet, MasterServer.MessageHandler/MasterServer.MessageOrigin origin) bool ShouldHandleUserMessage(MasterServer::IUserMessage* packet, MasterServer::MessageHandler::MessageOrigin origin); // protected override System.Threading.Tasks.Task`1<MasterServer.IMasterServerAuthenticateRequest> GetAuthenticationRequest() // Offset: 0x12F612C // Implemented from: MasterServer.BaseClientMessageHandler // Base method: System.Threading.Tasks.Task`1<MasterServer.IMasterServerAuthenticateRequest> BaseClientMessageHandler::GetAuthenticationRequest() System::Threading::Tasks::Task_1<MasterServer::IMasterServerAuthenticateRequest*>* GetAuthenticationRequest(); // private System.Void HandshakeLog(System.String message) // Offset: 0x12F6648 // Implemented from: MasterServer.BaseClientMessageHandler // Base method: System.Void BaseClientMessageHandler::HandshakeLog(System.String message) void HandshakeLog(::Il2CppString* message); }; // MasterServer.UserMessageHandler #pragma pack(pop) static check_size<sizeof(UserMessageHandler), 184 + sizeof(GlobalNamespace::IAuthenticationTokenProvider*)> __MasterServer_UserMessageHandlerSizeCheck; static_assert(sizeof(UserMessageHandler) == 0xC0); } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: MasterServer::UserMessageHandler::get_authenticationTokenProvider // Il2CppName: get_authenticationTokenProvider template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IAuthenticationTokenProvider* (MasterServer::UserMessageHandler::*)()>(&MasterServer::UserMessageHandler::get_authenticationTokenProvider)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "get_authenticationTokenProvider", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: MasterServer::UserMessageHandler::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: MasterServer::UserMessageHandler::UpdateKeepalive // Il2CppName: UpdateKeepalive template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::UserMessageHandler::*)()>(&MasterServer::UserMessageHandler::UpdateKeepalive)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "UpdateKeepalive", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: MasterServer::UserMessageHandler::ConnectToServer // Il2CppName: ConnectToServer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::UserMessageHandler::*)(::Il2CppString*, ::Il2CppString*, GlobalNamespace::BeatmapLevelSelectionMask, GlobalNamespace::GameplayServerConfiguration, ::Il2CppString*, ::Il2CppString*, MasterServer::UserMessageHandler::ConnectToServerDelegate*, System::Action_1<GlobalNamespace::ConnectionFailedReason>*, System::Threading::CancellationToken)>(&MasterServer::UserMessageHandler::ConnectToServer)> { static const MethodInfo* get() { static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* userName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* selectionMask = &::il2cpp_utils::GetClassFromName("", "BeatmapLevelSelectionMask")->byval_arg; static auto* configuration = &::il2cpp_utils::GetClassFromName("", "GameplayServerConfiguration")->byval_arg; static auto* secret = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* code = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* onSuccess = &::il2cpp_utils::GetClassFromName("MasterServer", "UserMessageHandler/ConnectToServerDelegate")->byval_arg; static auto* onConnectionFailed = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg; static auto* cancellationToken = &::il2cpp_utils::GetClassFromName("System.Threading", "CancellationToken")->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "ConnectToServer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId, userName, selectionMask, configuration, secret, code, onSuccess, onConnectionFailed, cancellationToken}); } }; // Writing MetadataGetter for method: MasterServer::UserMessageHandler::SendConnectToServerRequest // Il2CppName: SendConnectToServerRequest template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::UserMessageHandler::*)(MasterServer::BaseConnectToServerRequest*, MasterServer::UserMessageHandler::ConnectToServerDelegate*, System::Action_1<GlobalNamespace::ConnectionFailedReason>*, System::Threading::CancellationToken)>(&MasterServer::UserMessageHandler::SendConnectToServerRequest)> { static const MethodInfo* get() { static auto* request = &::il2cpp_utils::GetClassFromName("MasterServer", "BaseConnectToServerRequest")->byval_arg; static auto* onSuccess = &::il2cpp_utils::GetClassFromName("MasterServer", "UserMessageHandler/ConnectToServerDelegate")->byval_arg; static auto* onConnectionFailed = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg; static auto* cancellationToken = &::il2cpp_utils::GetClassFromName("System.Threading", "CancellationToken")->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "SendConnectToServerRequest", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{request, onSuccess, onConnectionFailed, cancellationToken}); } }; // Writing MetadataGetter for method: MasterServer::UserMessageHandler::GetPublicServers // Il2CppName: GetPublicServers template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::UserMessageHandler::*)(::Il2CppString*, ::Il2CppString*, int, int, GlobalNamespace::BeatmapLevelSelectionMask, GlobalNamespace::GameplayServerConfiguration, System::Action_1<System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::PublicServerInfo>*>*, System::Action_1<GlobalNamespace::ConnectionFailedReason>*, System::Threading::CancellationToken)>(&MasterServer::UserMessageHandler::GetPublicServers)> { static const MethodInfo* get() { static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* userName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* selectionMask = &::il2cpp_utils::GetClassFromName("", "BeatmapLevelSelectionMask")->byval_arg; static auto* configuration = &::il2cpp_utils::GetClassFromName("", "GameplayServerConfiguration")->byval_arg; static auto* onSuccess = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "IReadOnlyList`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "PublicServerInfo")})})->byval_arg; static auto* onFailure = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg; static auto* cancellationToken = &::il2cpp_utils::GetClassFromName("System.Threading", "CancellationToken")->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "GetPublicServers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId, userName, offset, count, selectionMask, configuration, onSuccess, onFailure, cancellationToken}); } }; // Writing MetadataGetter for method: MasterServer::UserMessageHandler::WithFailureHandler // Il2CppName: WithFailureHandler template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::UserMessageHandler::*)(System::Action_1<GlobalNamespace::ConnectionFailedReason>*, System::Func_1<System::Threading::Tasks::Task*>*)>(&MasterServer::UserMessageHandler::WithFailureHandler)> { static const MethodInfo* get() { static auto* onFailure = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg; static auto* performTask = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Func`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System.Threading.Tasks", "Task")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "WithFailureHandler", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{onFailure, performTask}); } }; // Writing MetadataGetter for method: MasterServer::UserMessageHandler::PollUpdate // Il2CppName: PollUpdate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::UserMessageHandler::*)()>(&MasterServer::UserMessageHandler::PollUpdate)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "PollUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: MasterServer::UserMessageHandler::ShouldHandleUserMessage // Il2CppName: ShouldHandleUserMessage template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (MasterServer::UserMessageHandler::*)(MasterServer::IUserMessage*, MasterServer::MessageHandler::MessageOrigin)>(&MasterServer::UserMessageHandler::ShouldHandleUserMessage)> { static const MethodInfo* get() { static auto* packet = &::il2cpp_utils::GetClassFromName("MasterServer", "IUserMessage")->byval_arg; static auto* origin = &::il2cpp_utils::GetClassFromName("MasterServer", "MessageHandler/MessageOrigin")->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "ShouldHandleUserMessage", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{packet, origin}); } }; // Writing MetadataGetter for method: MasterServer::UserMessageHandler::GetAuthenticationRequest // Il2CppName: GetAuthenticationRequest template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Threading::Tasks::Task_1<MasterServer::IMasterServerAuthenticateRequest*>* (MasterServer::UserMessageHandler::*)()>(&MasterServer::UserMessageHandler::GetAuthenticationRequest)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "GetAuthenticationRequest", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: MasterServer::UserMessageHandler::HandshakeLog // Il2CppName: HandshakeLog template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (MasterServer::UserMessageHandler::*)(::Il2CppString*)>(&MasterServer::UserMessageHandler::HandshakeLog)> { static const MethodInfo* get() { static auto* message = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(MasterServer::UserMessageHandler*), "HandshakeLog", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{message}); } };
76.403448
503
0.78183
[ "vector" ]
f3b46abc33cd93cb7635d1de6622932dec4ff9f8
29,227
cpp
C++
src/test/logical_query_plan/jit_aware_lqp_translator_test.cpp
cmfcmf/hyrise
d3465dfc83039876c1800bf245e73874947da114
[ "MIT" ]
null
null
null
src/test/logical_query_plan/jit_aware_lqp_translator_test.cpp
cmfcmf/hyrise
d3465dfc83039876c1800bf245e73874947da114
[ "MIT" ]
17
2018-11-28T10:31:31.000Z
2019-03-06T10:28:12.000Z
src/test/logical_query_plan/jit_aware_lqp_translator_test.cpp
cmfcmf/hyrise
d3465dfc83039876c1800bf245e73874947da114
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "base_test.hpp" #include "expression/expression_functional.hpp" #include "logical_query_plan/jit_aware_lqp_translator.hpp" #include "logical_query_plan/predicate_node.hpp" #include "logical_query_plan/projection_node.hpp" #include "logical_query_plan/sort_node.hpp" #include "logical_query_plan/stored_table_node.hpp" #include "logical_query_plan/union_node.hpp" #include "logical_query_plan/validate_node.hpp" #include "operators/jit_operator/operators/jit_aggregate.hpp" #include "operators/jit_operator/operators/jit_compute.hpp" #include "operators/jit_operator/operators/jit_filter.hpp" #include "operators/jit_operator/operators/jit_limit.hpp" #include "operators/jit_operator/operators/jit_read_tuples.hpp" #include "operators/jit_operator/operators/jit_validate.hpp" #include "operators/jit_operator/operators/jit_write_references.hpp" #include "operators/jit_operator/operators/jit_write_tuples.hpp" #include "sql/sql_pipeline_builder.hpp" using namespace opossum::expression_functional; // NOLINT namespace opossum { class JitAwareLQPTranslatorTest : public BaseTest { protected: void SetUp() override { const auto int_int_int_table = load_table("resources/test_data/tbl/int_int_int.tbl"); const auto int_float_null_table = load_table("resources/test_data/tbl/int_float_null_sorted_asc.tbl"); StorageManager::get().add_table("table_a", int_int_int_table); StorageManager::get().add_table("table_b", int_float_null_table); stored_table_node_a = std::make_shared<StoredTableNode>("table_a"); stored_table_node_a2 = std::make_shared<StoredTableNode>("table_a"); stored_table_node_b = std::make_shared<StoredTableNode>("table_b"); a_a = stored_table_node_a->get_column("a"); a_b = stored_table_node_a->get_column("b"); a_c = stored_table_node_a->get_column("c"); } // Creates an (unoptimized) LQP from a given SQL query string and passes the LQP to the jit-aware translator. // This allows for creating different LQPs for testing with little code. The result of the translation // (which could be any AbstractOperator) is dynamically cast to a JitOperatorWrapper pointer. Thus, a simple nullptr // check can be used to test whether a JitOperatorWrapper has been created by the translator as the root node of the // PQP. std::shared_ptr<const JitOperatorWrapper> translate_query(const std::string& sql) const { const auto lqp = SQLPipelineBuilder(sql).create_pipeline_statement(nullptr).get_unoptimized_logical_plan(); return translate_lqp(lqp); } std::shared_ptr<const JitOperatorWrapper> translate_lqp(const std::shared_ptr<AbstractLQPNode>& lqp) const { JitAwareLQPTranslator lqp_translator; std::shared_ptr<const AbstractOperator> current_node = lqp_translator.translate_node(lqp); while (current_node && !std::dynamic_pointer_cast<const JitOperatorWrapper>(current_node)) { current_node = current_node->input_left(); } return std::dynamic_pointer_cast<const JitOperatorWrapper>(current_node); } std::shared_ptr<StoredTableNode> stored_table_node_a, stored_table_node_a2, stored_table_node_b; LQPColumnReference a_a, a_b, a_c; }; TEST_F(JitAwareLQPTranslatorTest, RequiresAtLeastTwoJittableOperators) { { const auto jit_operator_wrapper = translate_query("SELECT a FROM table_a"); ASSERT_EQ(jit_operator_wrapper, nullptr); } { const auto jit_operator_wrapper = translate_query("SELECT a FROM table_a WHERE a > 1"); ASSERT_NE(jit_operator_wrapper, nullptr); } } TEST_F(JitAwareLQPTranslatorTest, JitPipelineRequiresASingleInputNode) { { // A UnionNode with two distinct input nodes. If the jit-aware translator is not able to determine a single input // node to the (intended) operator pipeline, it should not create the pipeline in the first place. const auto union_node = std::make_shared<UnionNode>(UnionMode::Positions); union_node->set_left_input(stored_table_node_a); union_node->set_right_input(stored_table_node_a2); JitAwareLQPTranslator lqp_translator; const auto jit_operator_wrapper = std::dynamic_pointer_cast<JitOperatorWrapper>(lqp_translator.translate_node(union_node)); ASSERT_EQ(jit_operator_wrapper, nullptr); } { // Although both inputs of the UnionNode eventually lead to the same StoredTableNode (i.e., the LQP has a diamond // shape), one of the paths contains a non-jittable SortNode. Thus the jit-aware translator should reject the LQP // and not create an operator pipeline. const auto sort_node = std::make_shared<SortNode>(expression_vector(a_a), std::vector<OrderByMode>{OrderByMode::Ascending}); const auto union_node = std::make_shared<UnionNode>(UnionMode::Positions); sort_node->set_left_input(stored_table_node_a); union_node->set_left_input(stored_table_node_a); union_node->set_right_input(sort_node); JitAwareLQPTranslator lqp_translator; const auto jit_operator_wrapper = std::dynamic_pointer_cast<JitOperatorWrapper>(lqp_translator.translate_node(union_node)); ASSERT_EQ(jit_operator_wrapper, nullptr); } } TEST_F(JitAwareLQPTranslatorTest, JitOperatorsRejectIndexScan) { // The jit operators do not yet support index scans and should thus reject translating them const auto predicate_node_1 = std::make_shared<PredicateNode>(greater_than_(a_a, 1)); const auto predicate_node_2 = std::make_shared<PredicateNode>(less_than_(a_a, 10)); predicate_node_1->set_left_input(stored_table_node_a); predicate_node_2->set_left_input(predicate_node_1); JitAwareLQPTranslator lqp_translator; { const auto jit_operator_wrapper = std::dynamic_pointer_cast<JitOperatorWrapper>(lqp_translator.translate_node(predicate_node_2)); ASSERT_NE(jit_operator_wrapper, nullptr); } { predicate_node_1->scan_type = ScanType::IndexScan; const auto jit_operator_wrapper = std::dynamic_pointer_cast<JitOperatorWrapper>(lqp_translator.translate_node(predicate_node_1)); ASSERT_EQ(jit_operator_wrapper, nullptr); } } TEST_F(JitAwareLQPTranslatorTest, InputColumnsAreAddedToJitReadTupleAdapter) { // The query reads two columns from the input table. These input columns must be added to the JitReadTuples adapter to // make their data accessible by other JitOperators. // clang-format off const auto b_a = stored_table_node_b->get_column("a"); const auto b_b = stored_table_node_b->get_column("b"); const auto lqp = ProjectionNode::make(expression_vector(b_a, b_b), // SELECT a, b PredicateNode::make(greater_than_(b_b, value_(0)), PredicateNode::make(greater_than_(b_a, value_(1)), ValidateNode::make(stored_table_node_b)))); // clang-format on const auto jit_operator_wrapper = translate_lqp(lqp); ASSERT_TRUE(jit_operator_wrapper); const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operators.size(), 4u); // Check that the first operator is in fact a JitReadTuples instance const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); ASSERT_NE(jit_read_tuples, nullptr); // There should be two input columns const auto input_columns = jit_read_tuples->input_columns(); ASSERT_EQ(input_columns.size(), 2u); ASSERT_EQ(input_columns[0].column_id, ColumnID{0}); ASSERT_EQ(input_columns[0].tuple_entry.data_type(), DataType::Int); ASSERT_EQ(input_columns[0].tuple_entry.is_nullable(), true); ASSERT_EQ(input_columns[1].column_id, ColumnID{1}); ASSERT_EQ(input_columns[1].tuple_entry.data_type(), DataType::Float); ASSERT_EQ(input_columns[1].tuple_entry.is_nullable(), true); } TEST_F(JitAwareLQPTranslatorTest, LiteralValuesAreAddedToJitReadTupleAdapter) { // The query contains two literals. Literals are treated like values read from a column inside the operator pipeline. // The JitReadTuples adapter is responsible for making these literals available from within the pipeline. // clang-format off const auto b_a = stored_table_node_b->get_column("a"); const auto b_b = stored_table_node_b->get_column("b"); const auto lqp = ProjectionNode::make(expression_vector(b_a, b_b), // SELECT a, b PredicateNode::make(greater_than_(b_b, value_(1.2)), PredicateNode::make(greater_than_(b_a, value_(1)), ValidateNode::make(stored_table_node_b)))); // clang-format on const auto jit_operator_wrapper = translate_lqp(lqp); ASSERT_TRUE(jit_operator_wrapper); const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operators.size(), 4u); // Check that the first operator is in fact a JitReadTuples instance const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); ASSERT_NE(jit_read_tuples, nullptr); // There should be two literals read from the query const auto input_literals = jit_read_tuples->input_literals(); ASSERT_EQ(input_literals.size(), 2u); ASSERT_EQ(input_literals[0].value, AllTypeVariant(1)); ASSERT_EQ(input_literals[0].tuple_entry.data_type(), DataType::Int); ASSERT_EQ(input_literals[0].tuple_entry.is_nullable(), false); ASSERT_EQ(input_literals[1].value, AllTypeVariant(1.2)); ASSERT_EQ(input_literals[1].tuple_entry.data_type(), DataType::Double); ASSERT_EQ(input_literals[1].tuple_entry.is_nullable(), false); } TEST_F(JitAwareLQPTranslatorTest, ColumnSubsetIsOutputCorrectly) { // Select a subset of columns const auto jit_operator_wrapper = translate_query("SELECT a FROM table_a WHERE a > 1"); ASSERT_TRUE(jit_operator_wrapper); const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operators.size(), 4u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); ASSERT_NE(jit_read_tuples, nullptr); const auto jit_write_references = std::dynamic_pointer_cast<JitWriteReferences>(jit_operators[3]); ASSERT_NE(jit_write_references, nullptr); const auto output_columns = jit_write_references->output_columns(); ASSERT_EQ(output_columns.size(), 1u); ASSERT_EQ(output_columns[0].referenced_column_id, ColumnID{0}); } TEST_F(JitAwareLQPTranslatorTest, AllColumnsAreOutputCorrectly) { // Select all columns const auto jit_operator_wrapper = translate_query("SELECT * FROM table_a WHERE a > 1"); ASSERT_TRUE(jit_operator_wrapper); const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operators.size(), 4u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); ASSERT_NE(jit_read_tuples, nullptr); const auto jit_write_references = std::dynamic_pointer_cast<JitWriteReferences>(jit_operators[3]); ASSERT_NE(jit_write_references, nullptr); const auto output_columns = jit_write_references->output_columns(); ASSERT_EQ(output_columns.size(), 3u); ASSERT_EQ(output_columns[0].referenced_column_id, ColumnID{0}); ASSERT_EQ(output_columns[1].referenced_column_id, ColumnID{1}); ASSERT_EQ(output_columns[2].referenced_column_id, ColumnID{2}); } TEST_F(JitAwareLQPTranslatorTest, ReorderedColumnsAreOutputCorrectly) { // Select columns in different order const auto jit_operator_wrapper = translate_query("SELECT c, a FROM table_a WHERE a > 1"); ASSERT_TRUE(jit_operator_wrapper); const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operators.size(), 4u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); ASSERT_NE(jit_read_tuples, nullptr); const auto jit_write_references = std::dynamic_pointer_cast<JitWriteReferences>(jit_operators[3]); ASSERT_NE(jit_write_references, nullptr); const auto output_columns = jit_write_references->output_columns(); ASSERT_EQ(output_columns.size(), 2u); ASSERT_EQ(output_columns[0].referenced_column_id, ColumnID{2}); ASSERT_EQ(output_columns[1].referenced_column_id, ColumnID{0}); } TEST_F(JitAwareLQPTranslatorTest, OutputColumnNamesAndAlias) { const auto jit_operator_wrapper = translate_query("SELECT a, b as b_new FROM table_a WHERE a > 1"); ASSERT_TRUE(jit_operator_wrapper); const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operators.size(), 4u); const auto jit_write_references = std::dynamic_pointer_cast<JitWriteReferences>(jit_operators[3]); ASSERT_NE(jit_write_references, nullptr); const auto output_columns = jit_write_references->output_columns(); ASSERT_EQ(output_columns.size(), 2u); ASSERT_EQ(output_columns[0].column_name, "a"); ASSERT_EQ(output_columns[1].column_name, "b"); } TEST_F(JitAwareLQPTranslatorTest, ConsecutivePredicatesGetTransformedToConjunction) { // clang-format off const auto lqp = ProjectionNode::make(expression_vector(a_a, a_b, a_c), // SELECT a, b, c PredicateNode::make(greater_than_(a_c, a_a), PredicateNode::make(greater_than_(a_b, a_c), PredicateNode::make(greater_than_(a_a, a_b), ValidateNode::make(stored_table_node_a))))); // clang-format on const auto jit_operator_wrapper = translate_lqp(lqp); ASSERT_NE(jit_operator_wrapper, nullptr); // Check the type of jit operators in the operator pipeline const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operator_wrapper->jit_operators().size(), 4u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); const auto jit_validate = std::dynamic_pointer_cast<JitValidate>(jit_operators[1]); const auto jit_filter = std::dynamic_pointer_cast<JitFilter>(jit_operators[2]); const auto jit_write_references = std::dynamic_pointer_cast<JitWriteReferences>(jit_operators[3]); ASSERT_NE(jit_read_tuples, nullptr); ASSERT_NE(jit_validate, nullptr); ASSERT_NE(jit_filter, nullptr); ASSERT_NE(jit_write_references, nullptr); // Check the structure of the computed expression used for filtering const auto expression = jit_filter->expression(); ASSERT_EQ(expression->expression_type(), JitExpressionType::And); ASSERT_EQ(expression->right_child()->expression_type(), JitExpressionType::And); const auto b_gt_c = expression->right_child()->left_child(); const auto c_gt_a = expression->right_child()->right_child(); const auto a_gt_b = expression->left_child(); ASSERT_EQ(a_gt_b->expression_type(), JitExpressionType::GreaterThan); ASSERT_EQ(a_gt_b->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(a_gt_b->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(a_gt_b->left_child()->result_entry()), ColumnID{0}); ASSERT_EQ(*jit_read_tuples->find_input_column(a_gt_b->right_child()->result_entry()), ColumnID{1}); ASSERT_EQ(b_gt_c->expression_type(), JitExpressionType::GreaterThan); ASSERT_EQ(b_gt_c->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(b_gt_c->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(b_gt_c->left_child()->result_entry()), ColumnID{1}); ASSERT_EQ(*jit_read_tuples->find_input_column(b_gt_c->right_child()->result_entry()), ColumnID{2}); ASSERT_EQ(c_gt_a->expression_type(), JitExpressionType::GreaterThan); ASSERT_EQ(c_gt_a->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(c_gt_a->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(c_gt_a->left_child()->result_entry()), ColumnID{2}); ASSERT_EQ(*jit_read_tuples->find_input_column(c_gt_a->right_child()->result_entry()), ColumnID{0}); } TEST_F(JitAwareLQPTranslatorTest, UnionsGetTransformedToDisjunction) { // clang-format off const auto lqp = UnionNode::make(UnionMode::Positions, UnionNode::make(UnionMode::Positions, PredicateNode::make(greater_than_(a_a, a_b), stored_table_node_a), PredicateNode::make(greater_than_(a_b, a_c), stored_table_node_a)), PredicateNode::make(greater_than_(a_c, a_a), stored_table_node_a)); // clang-format on const auto jit_operator_wrapper = translate_lqp(lqp); ASSERT_NE(jit_operator_wrapper, nullptr); // Check the type of jit operators in the operator pipeline const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operator_wrapper->jit_operators().size(), 3u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); const auto jit_filter = std::dynamic_pointer_cast<JitFilter>(jit_operators[1]); const auto jit_write_references = std::dynamic_pointer_cast<JitWriteReferences>(jit_operators[2]); ASSERT_NE(jit_read_tuples, nullptr); ASSERT_NE(jit_filter, nullptr); ASSERT_NE(jit_write_references, nullptr); // Check the structure of the computed expression used for filtering const auto expression = jit_filter->expression(); ASSERT_EQ(expression->expression_type(), JitExpressionType::Or); ASSERT_EQ(expression->left_child()->expression_type(), JitExpressionType::Or); const auto a_gt_b = expression->left_child()->left_child(); const auto b_gt_c = expression->left_child()->right_child(); const auto c_gt_a = expression->right_child(); ASSERT_EQ(a_gt_b->expression_type(), JitExpressionType::GreaterThan); ASSERT_EQ(a_gt_b->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(a_gt_b->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(a_gt_b->left_child()->result_entry()), ColumnID{0}); ASSERT_EQ(*jit_read_tuples->find_input_column(a_gt_b->right_child()->result_entry()), ColumnID{1}); ASSERT_EQ(b_gt_c->expression_type(), JitExpressionType::GreaterThan); ASSERT_EQ(b_gt_c->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(b_gt_c->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(b_gt_c->left_child()->result_entry()), ColumnID{1}); ASSERT_EQ(*jit_read_tuples->find_input_column(b_gt_c->right_child()->result_entry()), ColumnID{2}); ASSERT_EQ(c_gt_a->expression_type(), JitExpressionType::GreaterThan); ASSERT_EQ(c_gt_a->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(c_gt_a->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(c_gt_a->left_child()->result_entry()), ColumnID{2}); ASSERT_EQ(*jit_read_tuples->find_input_column(c_gt_a->right_child()->result_entry()), ColumnID{0}); } TEST_F(JitAwareLQPTranslatorTest, CheckOperatorOrderValidateAfterFilter) { const auto lqp = ValidateNode::make( PredicateNode::make(greater_than_(a_a, a_b), PredicateNode::make(greater_than_(a_b, a_c), stored_table_node_a))); const auto jit_operator_wrapper = translate_lqp(lqp); ASSERT_NE(jit_operator_wrapper, nullptr); // Check the type of jit operators in the operator pipeline const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operators.size(), 4u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); const auto jit_filter = std::dynamic_pointer_cast<JitFilter>(jit_operators[1]); const auto jit_validate = std::dynamic_pointer_cast<JitValidate>(jit_operators[2]); const auto jit_write_references = std::dynamic_pointer_cast<JitWriteReferences>(jit_operators[3]); ASSERT_NE(jit_read_tuples, nullptr); ASSERT_NE(jit_filter, nullptr); ASSERT_NE(jit_validate, nullptr); ASSERT_NE(jit_write_references, nullptr); } TEST_F(JitAwareLQPTranslatorTest, CheckOperatorOrderValidateBeforeFilter) { const auto lqp = PredicateNode::make( greater_than_(a_a, a_b), PredicateNode::make(greater_than_(a_b, a_c), ValidateNode::make(stored_table_node_a))); const auto jit_operator_wrapper = translate_lqp(lqp); ASSERT_NE(jit_operator_wrapper, nullptr); // Check the type of jit operators in the operator pipeline const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operators.size(), 4u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); const auto jit_validate = std::dynamic_pointer_cast<JitValidate>(jit_operators[1]); const auto jit_filter = std::dynamic_pointer_cast<JitFilter>(jit_operators[2]); const auto jit_write_references = std::dynamic_pointer_cast<JitWriteReferences>(jit_operators[3]); ASSERT_NE(jit_read_tuples, nullptr); ASSERT_NE(jit_validate, nullptr); ASSERT_NE(jit_filter, nullptr); ASSERT_NE(jit_write_references, nullptr); } TEST_F(JitAwareLQPTranslatorTest, AMoreComplexQuery) { // clang-format off const auto lqp = ProjectionNode::make(expression_vector(a_a, mul_(add_(a_a, a_b), a_c)), // SELECT a, (a + b) * c PredicateNode::make(greater_than_(a_b, add_(a_a, a_c)), PredicateNode::make(less_than_equals_(a_a, a_b), ValidateNode::make(stored_table_node_a)))); // clang-format on const auto jit_operator_wrapper = translate_lqp(lqp); ASSERT_NE(jit_operator_wrapper, nullptr); // Check the type of jit operators in the operator pipeline const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operator_wrapper->jit_operators().size(), 5u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); const auto jit_validate = std::dynamic_pointer_cast<JitValidate>(jit_operators[1]); const auto jit_filter = std::dynamic_pointer_cast<JitFilter>(jit_operators[2]); const auto jit_compute = std::dynamic_pointer_cast<JitCompute>(jit_operators[3]); const auto jit_write_tuples = std::dynamic_pointer_cast<JitWriteTuples>(jit_operators[4]); ASSERT_NE(jit_read_tuples, nullptr); ASSERT_NE(jit_validate, nullptr); ASSERT_NE(jit_filter, nullptr); ASSERT_NE(jit_compute, nullptr); ASSERT_NE(jit_write_tuples, nullptr); // Check the structure of the computed filter expression const auto expression_1 = jit_filter->expression(); ASSERT_EQ(expression_1->expression_type(), JitExpressionType::And); const auto a_lte_b = expression_1->left_child(); ASSERT_EQ(a_lte_b->expression_type(), JitExpressionType::LessThanEquals); ASSERT_EQ(a_lte_b->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(a_lte_b->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(a_lte_b->left_child()->result_entry()), ColumnID{0}); ASSERT_EQ(*jit_read_tuples->find_input_column(a_lte_b->right_child()->result_entry()), ColumnID{1}); const auto b_gt_a_plus_c = expression_1->right_child(); ASSERT_EQ(b_gt_a_plus_c->expression_type(), JitExpressionType::GreaterThan); ASSERT_EQ(b_gt_a_plus_c->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(b_gt_a_plus_c->left_child()->result_entry()), ColumnID{1}); const auto a_plus_c = b_gt_a_plus_c->right_child(); ASSERT_EQ(a_plus_c->expression_type(), JitExpressionType::Addition); ASSERT_EQ(a_plus_c->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(a_plus_c->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(a_plus_c->left_child()->result_entry()), ColumnID{0}); ASSERT_EQ(*jit_read_tuples->find_input_column(a_plus_c->right_child()->result_entry()), ColumnID{2}); // Check the structure of the computed expression const auto expression_2 = jit_compute->expression(); ASSERT_EQ(expression_2->expression_type(), JitExpressionType::Multiplication); ASSERT_EQ(expression_2->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(expression_2->right_child()->result_entry()), ColumnID{2}); const auto a_plus_b = expression_2->left_child(); ASSERT_EQ(a_plus_b->expression_type(), JitExpressionType::Addition); ASSERT_EQ(a_plus_b->left_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(a_plus_b->right_child()->expression_type(), JitExpressionType::Column); ASSERT_EQ(*jit_read_tuples->find_input_column(a_plus_b->left_child()->result_entry()), ColumnID{0}); ASSERT_EQ(*jit_read_tuples->find_input_column(a_plus_b->right_child()->result_entry()), ColumnID{1}); const auto output_columns = jit_write_tuples->output_columns(); ASSERT_EQ(output_columns.size(), 2u); ASSERT_EQ(*jit_read_tuples->find_input_column(output_columns[0].tuple_entry), ColumnID{0}); ASSERT_EQ(expression_2->result_entry(), std::make_optional(output_columns[1].tuple_entry)); } TEST_F(JitAwareLQPTranslatorTest, AggregateOperator) { const auto jit_operator_wrapper = translate_query("SELECT COUNT(a), SUM(b), AVG(a + b), MIN(a), MAX(b), COUNT(*) FROM table_a GROUP BY a"); ASSERT_NE(jit_operator_wrapper, nullptr); // Check the type of jit operators in the operator pipeline const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operator_wrapper->jit_operators().size(), 4u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); const auto jit_validate = std::dynamic_pointer_cast<JitValidate>(jit_operators[1]); const auto jit_compute = std::dynamic_pointer_cast<JitCompute>(jit_operators[2]); const auto jit_aggregate = std::dynamic_pointer_cast<JitAggregate>(jit_operators[3]); ASSERT_NE(jit_read_tuples, nullptr); ASSERT_NE(jit_validate, nullptr); ASSERT_NE(jit_compute, nullptr); ASSERT_NE(jit_aggregate, nullptr); // Check the structure of the computed expression const auto expression = jit_compute->expression(); ASSERT_EQ(expression->expression_type(), JitExpressionType::Addition); ASSERT_EQ(*jit_read_tuples->find_input_column(expression->left_child()->result_entry()), ColumnID{0}); ASSERT_EQ(*jit_read_tuples->find_input_column(expression->right_child()->result_entry()), ColumnID{1}); // Check that the aggregate operator is configured with the correct group-by and aggregate columns const auto groupby_columns = jit_aggregate->groupby_columns(); ASSERT_EQ(groupby_columns.size(), 1u); ASSERT_EQ(groupby_columns[0].column_name, "a"); ASSERT_EQ(*jit_read_tuples->find_input_column(groupby_columns[0].tuple_entry), ColumnID{0}); const auto aggregate_columns = jit_aggregate->aggregate_columns(); ASSERT_EQ(aggregate_columns.size(), 6u); ASSERT_EQ(aggregate_columns[0].column_name, "COUNT(a)"); ASSERT_EQ(aggregate_columns[0].function, AggregateFunction::Count); ASSERT_EQ(*jit_read_tuples->find_input_column(aggregate_columns[0].tuple_entry), ColumnID{0}); ASSERT_EQ(aggregate_columns[1].column_name, "SUM(b)"); ASSERT_EQ(aggregate_columns[1].function, AggregateFunction::Sum); ASSERT_EQ(*jit_read_tuples->find_input_column(aggregate_columns[1].tuple_entry), ColumnID{1}); ASSERT_EQ(aggregate_columns[2].column_name, "AVG(a + b)"); ASSERT_EQ(aggregate_columns[2].function, AggregateFunction::Avg); // This aggregate function should operates on the result of the previously computed expression ASSERT_EQ(aggregate_columns[2].tuple_entry, expression->result_entry()); ASSERT_EQ(aggregate_columns[3].column_name, "MIN(a)"); ASSERT_EQ(aggregate_columns[3].function, AggregateFunction::Min); ASSERT_EQ(*jit_read_tuples->find_input_column(aggregate_columns[3].tuple_entry), ColumnID{0}); ASSERT_EQ(aggregate_columns[4].column_name, "MAX(b)"); ASSERT_EQ(aggregate_columns[4].function, AggregateFunction::Max); ASSERT_EQ(*jit_read_tuples->find_input_column(aggregate_columns[4].tuple_entry), ColumnID{1}); ASSERT_EQ(aggregate_columns[5].column_name, "COUNT(*)"); ASSERT_EQ(aggregate_columns[5].function, AggregateFunction::Count); ASSERT_EQ(aggregate_columns[5].tuple_entry.tuple_index(), 0u); } TEST_F(JitAwareLQPTranslatorTest, LimitOperator) { const auto node_table_a = StoredTableNode::make("table_a"); const auto node_table_a_col_a = node_table_a->get_column("a"); const auto value = std::make_shared<ValueExpression>(int64_t{123}); const auto table_scan = PredicateNode::make(equals_(node_table_a_col_a, value), node_table_a); const auto limit = LimitNode::make(value, table_scan); const auto jit_operator_wrapper = translate_lqp(limit); ASSERT_NE(jit_operator_wrapper, nullptr); // Check the type of jit operators in the operator pipeline const auto jit_operators = jit_operator_wrapper->jit_operators(); ASSERT_EQ(jit_operator_wrapper->jit_operators().size(), 4u); const auto jit_read_tuples = std::dynamic_pointer_cast<JitReadTuples>(jit_operators[0]); const auto jit_filter = std::dynamic_pointer_cast<JitFilter>(jit_operators[1]); const auto jit_limit = std::dynamic_pointer_cast<JitLimit>(jit_operators[2]); const auto jit_write_references = std::dynamic_pointer_cast<JitWriteReferences>(jit_operators[3]); ASSERT_NE(jit_read_tuples, nullptr); ASSERT_NE(jit_filter, nullptr); ASSERT_NE(jit_limit, nullptr); ASSERT_NE(jit_write_references, nullptr); ASSERT_EQ(jit_read_tuples->row_count_expression(), value); } } // namespace opossum
50.741319
120
0.774763
[ "shape", "vector" ]
f3b934d4fa1ba89fddc763af7de6ec9371d222f0
14,928
cc
C++
third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.h" #include <memory> #include <utility> #include "base/memory/ptr_util.h" #include "third_party/blink/renderer/core/animation/interpolable_length.h" #include "third_party/blink/renderer/core/animation/list_interpolation_functions.h" #include "third_party/blink/renderer/core/animation/side_index.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_property_names.h" #include "third_party/blink/renderer/core/css/css_quad_value.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" #include "third_party/blink/renderer/core/style/computed_style.h" namespace blink { namespace { enum class SideType { kNumber, kAuto, kLength, }; const BorderImageLengthBox& GetBorderImageLengthBox( const CSSProperty& property, const ComputedStyle& style) { switch (property.PropertyID()) { case CSSPropertyID::kBorderImageOutset: return style.BorderImageOutset(); case CSSPropertyID::kBorderImageWidth: return style.BorderImageWidth(); case CSSPropertyID::kWebkitMaskBoxImageOutset: return style.MaskBoxImageOutset(); case CSSPropertyID::kWebkitMaskBoxImageWidth: return style.MaskBoxImageWidth(); default: NOTREACHED(); return style.BorderImageOutset(); } } void SetBorderImageLengthBox(const CSSProperty& property, ComputedStyle& style, const BorderImageLengthBox& box) { switch (property.PropertyID()) { case CSSPropertyID::kBorderImageOutset: style.SetBorderImageOutset(box); break; case CSSPropertyID::kWebkitMaskBoxImageOutset: style.SetMaskBoxImageOutset(box); break; case CSSPropertyID::kBorderImageWidth: style.SetBorderImageWidth(box); break; case CSSPropertyID::kWebkitMaskBoxImageWidth: style.SetMaskBoxImageWidth(box); break; default: NOTREACHED(); break; } } } // namespace // The NonInterpolableValue for the CSSBorderImageLengthBoxInterpolationType // as a whole is a NonInterpolableList with kSideIndexCount items. Each entry // in that list is either an instance of this class, or it's the // NonInterpolableValue returned by LengthInterpolationFunctions. class CSSBorderImageLengthBoxSideNonInterpolableValue : public NonInterpolableValue { public: static scoped_refptr<CSSBorderImageLengthBoxSideNonInterpolableValue> Create( SideType side_type) { DCHECK_NE(SideType::kLength, side_type); return base::AdoptRef( new CSSBorderImageLengthBoxSideNonInterpolableValue(side_type)); } SideType GetSideType() const { return side_type_; } DECLARE_NON_INTERPOLABLE_VALUE_TYPE(); private: CSSBorderImageLengthBoxSideNonInterpolableValue(const SideType side_type) : side_type_(side_type) {} const SideType side_type_; }; DEFINE_NON_INTERPOLABLE_VALUE_TYPE( CSSBorderImageLengthBoxSideNonInterpolableValue); template <> struct DowncastTraits<CSSBorderImageLengthBoxSideNonInterpolableValue> { static bool AllowFrom(const NonInterpolableValue* value) { return value && AllowFrom(*value); } static bool AllowFrom(const NonInterpolableValue& value) { return value.GetType() == CSSBorderImageLengthBoxSideNonInterpolableValue::static_type_; } }; namespace { SideType GetSideType(const BorderImageLength& side) { if (side.IsNumber()) { return SideType::kNumber; } if (side.length().IsAuto()) { return SideType::kAuto; } DCHECK(side.length().IsSpecified()); return SideType::kLength; } SideType GetSideType(const CSSValue& side) { auto* side_primitive_value = DynamicTo<CSSPrimitiveValue>(side); if (side_primitive_value && side_primitive_value->IsNumber()) { return SideType::kNumber; } auto* side_identifier_value = DynamicTo<CSSIdentifierValue>(side); if (side_identifier_value && side_identifier_value->GetValueID() == CSSValueID::kAuto) { return SideType::kAuto; } return SideType::kLength; } SideType GetSideType(const NonInterpolableValue* side) { // We interpret nullptr as kLength, because LengthInterpolationFunctions // returns a nullptr NonInterpolableValue if there is no percent unit. // // In cases where LengthInterpolationFunctions is not used to convert the // value (kAuto, kNumber), we will always have a non-interpolable value of // type CSSBorderImageLengthBoxSideNonInterpolableValue. auto* non_interpolable = DynamicTo<CSSBorderImageLengthBoxSideNonInterpolableValue>(side); if (!side || !non_interpolable) return SideType::kLength; return non_interpolable->GetSideType(); } struct SideTypes { explicit SideTypes(const BorderImageLengthBox& box) { type[kSideTop] = GetSideType(box.Top()); type[kSideRight] = GetSideType(box.Right()); type[kSideBottom] = GetSideType(box.Bottom()); type[kSideLeft] = GetSideType(box.Left()); } explicit SideTypes(const CSSQuadValue& quad) { type[kSideTop] = GetSideType(*quad.Top()); type[kSideRight] = GetSideType(*quad.Right()); type[kSideBottom] = GetSideType(*quad.Bottom()); type[kSideLeft] = GetSideType(*quad.Left()); } explicit SideTypes(const InterpolationValue& underlying) { const auto& non_interpolable_list = To<NonInterpolableList>(*underlying.non_interpolable_value); DCHECK_EQ(kSideIndexCount, non_interpolable_list.length()); type[kSideTop] = GetSideType(non_interpolable_list.Get(0)); type[kSideRight] = GetSideType(non_interpolable_list.Get(1)); type[kSideBottom] = GetSideType(non_interpolable_list.Get(2)); type[kSideLeft] = GetSideType(non_interpolable_list.Get(3)); } bool operator==(const SideTypes& other) const { for (size_t i = 0; i < kSideIndexCount; i++) { if (type[i] != other.type[i]) return false; } return true; } bool operator!=(const SideTypes& other) const { return !(*this == other); } SideType type[kSideIndexCount]; }; class UnderlyingSideTypesChecker : public CSSInterpolationType::CSSConversionChecker { public: explicit UnderlyingSideTypesChecker(const SideTypes& underlying_side_types) : underlying_side_types_(underlying_side_types) {} private: bool IsValid(const StyleResolverState&, const InterpolationValue& underlying) const final { return underlying_side_types_ == SideTypes(underlying); } const SideTypes underlying_side_types_; }; class InheritedSideTypesChecker : public CSSInterpolationType::CSSConversionChecker { public: InheritedSideTypesChecker(const CSSProperty& property, const SideTypes& inherited_side_types) : property_(property), inherited_side_types_(inherited_side_types) {} private: bool IsValid(const StyleResolverState& state, const InterpolationValue& underlying) const final { return inherited_side_types_ == SideTypes(GetBorderImageLengthBox(property_, *state.ParentStyle())); } const CSSProperty& property_; const SideTypes inherited_side_types_; }; InterpolationValue ConvertBorderImageNumberSide(double number) { return InterpolationValue( std::make_unique<InterpolableNumber>(number), CSSBorderImageLengthBoxSideNonInterpolableValue::Create( SideType::kNumber)); } InterpolationValue ConvertBorderImageAutoSide() { return InterpolationValue( std::make_unique<InterpolableList>(0), CSSBorderImageLengthBoxSideNonInterpolableValue::Create(SideType::kAuto)); } InterpolationValue ConvertBorderImageLengthBox(const BorderImageLengthBox& box, double zoom) { auto list = std::make_unique<InterpolableList>(kSideIndexCount); Vector<scoped_refptr<const NonInterpolableValue>> non_interpolable_values( kSideIndexCount); const BorderImageLength* sides[kSideIndexCount] = {}; sides[kSideTop] = &box.Top(); sides[kSideRight] = &box.Right(); sides[kSideBottom] = &box.Bottom(); sides[kSideLeft] = &box.Left(); return ListInterpolationFunctions::CreateList( kSideIndexCount, [&sides, zoom](wtf_size_t index) { const BorderImageLength& side = *sides[index]; if (side.IsNumber()) return ConvertBorderImageNumberSide(side.Number()); if (side.length().IsAuto()) return ConvertBorderImageAutoSide(); return InterpolationValue( InterpolableLength::MaybeConvertLength(side.length(), zoom)); }); } void CompositeSide(UnderlyingValue& underlying_value, double underlying_fraction, const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value) { switch (GetSideType(non_interpolable_value)) { case SideType::kNumber: case SideType::kLength: underlying_value.MutableInterpolableValue().ScaleAndAdd( underlying_fraction, interpolable_value); break; case SideType::kAuto: break; default: NOTREACHED(); break; } } bool NonInterpolableSidesAreCompatible(const NonInterpolableValue* a, const NonInterpolableValue* b) { return GetSideType(a) == GetSideType(b); } } // namespace InterpolationValue CSSBorderImageLengthBoxInterpolationType::MaybeConvertNeutral( const InterpolationValue& underlying, ConversionCheckers& conversion_checkers) const { SideTypes underlying_side_types(underlying); conversion_checkers.push_back( std::make_unique<UnderlyingSideTypesChecker>(underlying_side_types)); return InterpolationValue(underlying.interpolable_value->CloneAndZero(), underlying.non_interpolable_value); } InterpolationValue CSSBorderImageLengthBoxInterpolationType::MaybeConvertInitial( const StyleResolverState& state, ConversionCheckers&) const { return ConvertBorderImageLengthBox( GetBorderImageLengthBox( CssProperty(), state.GetDocument().GetStyleResolver().InitialStyle()), 1); } InterpolationValue CSSBorderImageLengthBoxInterpolationType::MaybeConvertInherit( const StyleResolverState& state, ConversionCheckers& conversion_checkers) const { const BorderImageLengthBox& inherited = GetBorderImageLengthBox(CssProperty(), *state.ParentStyle()); conversion_checkers.push_back(std::make_unique<InheritedSideTypesChecker>( CssProperty(), SideTypes(inherited))); return ConvertBorderImageLengthBox(inherited, state.ParentStyle()->EffectiveZoom()); } InterpolationValue CSSBorderImageLengthBoxInterpolationType::MaybeConvertValue( const CSSValue& value, const StyleResolverState*, ConversionCheckers&) const { const auto* quad = DynamicTo<CSSQuadValue>(value); if (!quad) return nullptr; auto list = std::make_unique<InterpolableList>(kSideIndexCount); Vector<scoped_refptr<const NonInterpolableValue>> non_interpolable_values( kSideIndexCount); const CSSValue* sides[kSideIndexCount] = {}; sides[kSideTop] = quad->Top(); sides[kSideRight] = quad->Right(); sides[kSideBottom] = quad->Bottom(); sides[kSideLeft] = quad->Left(); return ListInterpolationFunctions::CreateList( kSideIndexCount, [&sides](wtf_size_t index) { const CSSValue& side = *sides[index]; auto* side_primitive_value = DynamicTo<CSSPrimitiveValue>(side); if (side_primitive_value && side_primitive_value->IsNumber()) { return ConvertBorderImageNumberSide( side_primitive_value->GetDoubleValue()); } auto* side_identifier_value = DynamicTo<CSSIdentifierValue>(side); if (side_identifier_value && side_identifier_value->GetValueID() == CSSValueID::kAuto) { return ConvertBorderImageAutoSide(); } return InterpolationValue( InterpolableLength::MaybeConvertCSSValue(side)); }); } InterpolationValue CSSBorderImageLengthBoxInterpolationType:: MaybeConvertStandardPropertyUnderlyingValue( const ComputedStyle& style) const { return ConvertBorderImageLengthBox( GetBorderImageLengthBox(CssProperty(), style), style.EffectiveZoom()); } PairwiseInterpolationValue CSSBorderImageLengthBoxInterpolationType::MaybeMergeSingles( InterpolationValue&& start, InterpolationValue&& end) const { if (SideTypes(start) != SideTypes(end)) return nullptr; return PairwiseInterpolationValue(std::move(start.interpolable_value), std::move(end.interpolable_value), std::move(start.non_interpolable_value)); } void CSSBorderImageLengthBoxInterpolationType::Composite( UnderlyingValueOwner& underlying_value_owner, double underlying_fraction, const InterpolationValue& value, double interpolation_fraction) const { ListInterpolationFunctions::Composite( underlying_value_owner, underlying_fraction, *this, value, ListInterpolationFunctions::LengthMatchingStrategy::kEqual, WTF::BindRepeating( ListInterpolationFunctions::InterpolableValuesKnownCompatible), WTF::BindRepeating(NonInterpolableSidesAreCompatible), WTF::BindRepeating(CompositeSide)); } void CSSBorderImageLengthBoxInterpolationType::ApplyStandardPropertyValue( const InterpolableValue& interpolable_value, const NonInterpolableValue* non_interpolable_value, StyleResolverState& state) const { const auto& list = To<InterpolableList>(interpolable_value); const auto& non_interpolable_list = To<NonInterpolableList>(*non_interpolable_value); const auto& convert_side = [&list, &non_interpolable_list, &state](wtf_size_t index) -> BorderImageLength { switch (GetSideType(non_interpolable_list.Get(index))) { case SideType::kNumber: return clampTo<double>(To<InterpolableNumber>(list.Get(index))->Value(), 0); case SideType::kAuto: return Length::Auto(); case SideType::kLength: return To<InterpolableLength>(*list.Get(index)) .CreateLength(state.CssToLengthConversionData(), kValueRangeNonNegative); default: NOTREACHED(); return Length::Auto(); } }; BorderImageLengthBox box(convert_side(kSideTop), convert_side(kSideRight), convert_side(kSideBottom), convert_side(kSideLeft)); SetBorderImageLengthBox(CssProperty(), *state.Style(), box); } } // namespace blink
35.971084
101
0.727827
[ "vector" ]
f3b9ef50d035d1451c7a5cfadf2e668cfcb0b6b7
4,956
hpp
C++
include/Bit/Audio/OpenAL/OpenALAudioDevice.hpp
jimmiebergmann/Bit-Engine
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
[ "Zlib" ]
null
null
null
include/Bit/Audio/OpenAL/OpenALAudioDevice.hpp
jimmiebergmann/Bit-Engine
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
[ "Zlib" ]
null
null
null
include/Bit/Audio/OpenAL/OpenALAudioDevice.hpp
jimmiebergmann/Bit-Engine
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
[ "Zlib" ]
null
null
null
// /////////////////////////////////////////////////////////////////////////// // Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com // // This software is provided 'as-is', without any express or // implied warranty. In no event will the authors be held // liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute // it freely, 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. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but // is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any // source distribution. // /////////////////////////////////////////////////////////////////////////// #ifndef BIT_AUDIO_OPENAL_AUDIO_DEVICE_HPP #define BIT_AUDIO_OPENAL_AUDIO_DEVICE_HPP #include <Bit/Build.hpp> #include <Bit/NonCopyable.hpp> #include <Bit/Audio/AudioDevice.hpp> #include <Bit/Audio/OpenAL/OpenAL.hpp> namespace Bit { //////////////////////////////////////////////////////////////// /// \ingroup Audio /// \brief OpenAL audio device class.' /// /// Stereo sounds wont work in 3D. /// Use "force mono" if you want to make sure that the sound /// will work in any 3D scene. /// //////////////////////////////////////////////////////////////// class BIT_API OpenALAudioDevice : public AudioDevice, NonCopyable { public: //////////////////////////////////////////////////////////////// /// \brief Default constructor. /// //////////////////////////////////////////////////////////////// OpenALAudioDevice( ); //////////////////////////////////////////////////////////////// /// \brief Destructor. Closing the device. /// //////////////////////////////////////////////////////////////// ~OpenALAudioDevice( ); //////////////////////////////////////////////////////////////// /// \brief Open the audio device. /// //////////////////////////////////////////////////////////////// virtual Bool Open( ); //////////////////////////////////////////////////////////////// /// \brief Close the audio device. /// //////////////////////////////////////////////////////////////// virtual void Close( ); //////////////////////////////////////////////////////////////// /// \brief Making this audio device to the current one. /// //////////////////////////////////////////////////////////////// virtual void MakeCurrent( ); //////////////////////////////////////////////////////////////// /// \brief Create a sound object. /// /// \return A pointer to the Sound /// //////////////////////////////////////////////////////////////// virtual Sound * CreateSound( ); //////////////////////////////////////////////////////////////// /// \brief Create a sound buffer object. /// /// \return A pointer to the sound buffer. /// //////////////////////////////////////////////////////////////// virtual SoundBuffer * CreateSoundBuffer( ); //////////////////////////////////////////////////////////////// /// \brief Set the global volume. Value from 0.0 to 1.0. /// //////////////////////////////////////////////////////////////// virtual void SetGlobalVolume( Float32 p_Volume ); //////////////////////////////////////////////////////////////// /// \brief Set the listener position. /// /// \param p_Position 3D position of the listener. /// //////////////////////////////////////////////////////////////// virtual void SetListenerPosition( Vector3f32 p_Position ); //////////////////////////////////////////////////////////////// /// \brief Set the listener position. /// /// \param p_Position 3D position of the target. /// Defines what direction the listener is looking. /// //////////////////////////////////////////////////////////////// virtual void SetListenerTarget( Vector3f32 p_Target ); //////////////////////////////////////////////////////////////// /// \brief Set the listener position. /// /// \param p_Position Set the velocity of the listener. /// //////////////////////////////////////////////////////////////// virtual void SetListenerVelocity( Vector3f32 p_Velocity ); //////////////////////////////////////////////////////////////// /// \brief Checks if the device is open. /// //////////////////////////////////////////////////////////////// virtual Bool IsOpen( ) const; private: // Private varaibles Bool m_Open; ///< Is the device open? ALCdevice * m_pDevice; ///< OpenAL device. ALCcontext * m_pContext; ///< OpenAl context. }; } #endif
34.416667
78
0.424334
[ "object", "3d" ]
f3ba03ff3c49a2772b68ae2848d0154a5f6289b0
21,766
cpp
C++
libcat/src/cat_gfx_drawablecanvas.cpp
shadow-paw/cat
975749c9d716687f1bd74c80d474fed6065768de
[ "MIT" ]
5
2017-11-20T09:56:48.000Z
2019-01-26T14:44:14.000Z
libcat/src/cat_gfx_drawablecanvas.cpp
shadow-paw/osal
975749c9d716687f1bd74c80d474fed6065768de
[ "MIT" ]
3
2017-12-17T11:23:29.000Z
2020-07-01T04:14:24.000Z
libcat/src/cat_gfx_drawablecanvas.cpp
shadow-paw/cat
975749c9d716687f1bd74c80d474fed6065768de
[ "MIT" ]
3
2017-11-18T18:18:19.000Z
2018-12-27T08:41:45.000Z
#include "cat_gfx_drawablecanvas.h" #include <stdlib.h> #include <string> #include "cat_util_string.h" using namespace cat; // ---------------------------------------------------------------------------- DrawableCanvas::DrawableCanvas() { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) m_width = m_height = 0; m_hdc = NULL; m_hbitmap = m_obitmap = NULL; m_bmpixel = nullptr; m_pixel = nullptr; #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) m_width = m_height = 0; m_pixel = nullptr; m_context = nullptr; m_font = nullptr; m_textcolor = nullptr; #elif defined (PLATFORM_ANDROID) m_jni.bitmap_class = nullptr; m_jni.canvas_class = nullptr; m_jni.paint_class = nullptr; m_jni.rect_class = nullptr; m_jni.glut_class = nullptr; m_jni.bitmap = nullptr; m_jni.canvas = nullptr; m_jni.paint = nullptr; m_jni.rect = nullptr; #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- DrawableCanvas::~DrawableCanvas() { release(); } // ---------------------------------------------------------------------------- bool DrawableCanvas::resize(int width, int height) { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) BITMAPINFO bmi = { 0 }; bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; // B,G,R,0 bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = 0; bmi.bmiHeader.biClrUsed = 0; bmi.bmiHeader.biClrImportant = 0; m_hdc = CreateCompatibleDC(NULL); if (m_hdc == NULL) goto fail; m_hbitmap = CreateDIBSection(NULL, &bmi, DIB_RGB_COLORS, (void**)&m_bmpixel, NULL, 0); if (m_hbitmap == NULL) goto fail; m_obitmap = (HBITMAP)SelectObject(m_hdc, m_hbitmap); if (m_pixel) _aligned_free(m_pixel); if ((m_pixel = (uint32_t*)_aligned_malloc(width * height * 4, 32)) == NULL) goto fail; memset (m_pixel, 0, width * height * 4); SetBkColor(m_hdc, 0); SetBkMode(m_hdc, TRANSPARENT); m_width = width; m_height = height; return true; fail: release(); return false; #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) uint32_t* new_pixel = (uint32_t*)realloc(m_pixel, width * height * sizeof(uint32_t)); if (!new_pixel) return false; m_width = width; m_height = height; m_pixel = new_pixel; // Create Context CGColorSpaceRef cspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); m_context = CGBitmapContextCreate(m_pixel, width, height, 8, 4 * m_width, cspace, kCGImageAlphaPremultipliedLast); CGColorSpaceRelease(cspace); // Invert transform CGContextSetTextMatrix(m_context, CGAffineTransformIdentity); CGContextTranslateCTM(m_context, 0, height); CGContextScaleCTM(m_context, 1.0, -1.0); // Clear set_textcolor(0xffffffff); clear(0); return true; #elif defined (PLATFORM_ANDROID) m_width = width; m_height = height; JNIHelper jni; // jcfg = Bitmap.Config.valueOf(ARGB_8888) jobject jcfg = jni.CallStaticObjectMethod("android/graphics/Bitmap$Config", "valueOf", "(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;", jni.NewStringUTF("ARGB_8888")); // jbitmap = Bitmap.createBitmap(width, height, jcfg); jobject jbitmap = jni.CallStaticObjectMethod("android/graphics/Bitmap", "createBitmap", "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;", width, height, jcfg); // jcanvas = new Canvas(jbitmap); jobject jcanvas = jni.NewObject("android/graphics/Canvas", "(Landroid/graphics/Bitmap;)V", jbitmap); // jpaint = new Paint(ANTI_ALIAS_FLAG); const jint ANTI_ALIAS_FLAG = 1; jobject jpaint = jni.NewObject("android/graphics/Paint", "(I)V", ANTI_ALIAS_FLAG); // jrect = new Rect(); jobject jrect = jni.NewObject("android/graphics/Rect", "()V"); // Retain our objects m_jni.bitmap = jni.NewGlobalRef(jbitmap); m_jni.canvas = jni.NewGlobalRef(jcanvas); m_jni.paint = jni.NewGlobalRef(jpaint); m_jni.rect = jni.NewGlobalRef(jrect); // Cache Method m_jni.bitmap_class = (jclass)jni.NewGlobalRef(jni.FindClass("android/graphics/Bitmap")); m_jni.bitmap_eraseColor = jni.GetMethodID(m_jni.bitmap_class, "eraseColor", "(I)V"); m_jni.canvas_class = (jclass)jni.NewGlobalRef(jni.FindClass("android/graphics/Canvas")); m_jni.canvas_drawText = jni.GetMethodID(m_jni.canvas_class, "drawText", "(Ljava/lang/String;FFLandroid/graphics/Paint;)V"); m_jni.canvas_drawRect = jni.GetMethodID(m_jni.canvas_class, "drawRect", "(FFFFLandroid/graphics/Paint;)V"); m_jni.canvas_drawLine = jni.GetMethodID(m_jni.canvas_class, "drawLine", "(FFFFLandroid/graphics/Paint;)V"); m_jni.paint_class = (jclass)jni.NewGlobalRef(jni.FindClass("android/graphics/Paint")); m_jni.paint_setTextSize = jni.GetMethodID(m_jni.paint_class, "setTextSize", "(F)V"); m_jni.paint_setARGB = jni.GetMethodID(m_jni.paint_class, "setARGB", "(IIII)V"); m_jni.paint_getTextBounds = jni.GetMethodID(m_jni.paint_class, "getTextBounds", "(Ljava/lang/String;IILandroid/graphics/Rect;)V"); m_jni.rect_class = (jclass)jni.NewGlobalRef(jni.FindClass("android/graphics/Rect")); m_jni.rect_height = jni.GetMethodID(m_jni.rect_class, "height", "()I"); m_jni.rect_width = jni.GetMethodID(m_jni.rect_class, "width", "()I"); m_jni.glut_class = (jclass)jni.NewGlobalRef(jni.FindClass("android/opengl/GLUtils")); m_jni.glut_texImage2D = jni.GetStaticMethodID(m_jni.glut_class, "texImage2D", "(IILandroid/graphics/Bitmap;I)V"); // Reset Paint color jni.CallVoidMethod(m_jni.paint, m_jni.paint_setARGB, 0, 0, 0, 0); return false; fail: release(); return false; #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- void DrawableCanvas::release() { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) m_width = m_height = 0; if (m_hdc) { if (m_ofont) SelectObject(m_hdc, m_ofont); if (m_obitmap) SelectObject(m_hdc, m_obitmap); DeleteDC(m_hdc); m_hdc = NULL; } if (m_hfont) DeleteObject(m_hfont); if (m_hbitmap) DeleteObject(m_hbitmap); m_bmpixel = nullptr; if (m_pixel) { _aligned_free(m_pixel); m_pixel = nullptr; } #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) m_width = m_height = 0; if (m_font) { CFRelease(m_font); m_font = nullptr; } if (m_textcolor) { CFRelease(m_textcolor); m_textcolor = nullptr; } if (m_context) { CGContextRelease(m_context); m_context = nullptr; } if (m_pixel) { free(m_pixel); m_pixel = nullptr; } #elif defined (PLATFORM_ANDROID) JNIHelper jni; if (m_jni.bitmap_class) { jni.DeleteGlobalRef(m_jni.bitmap_class); m_jni.bitmap_class = nullptr; } if (m_jni.canvas_class) { jni.DeleteGlobalRef(m_jni.canvas_class); m_jni.canvas_class = nullptr; } if (m_jni.rect_class) { jni.DeleteGlobalRef(m_jni.rect_class); m_jni.rect_class = nullptr; } if (m_jni.glut_class) { jni.DeleteGlobalRef(m_jni.glut_class); m_jni.glut_class = nullptr; } if (m_jni.bitmap) { jni.DeleteGlobalRef(m_jni.bitmap); m_jni.bitmap = nullptr; } if (m_jni.canvas) { jni.DeleteGlobalRef(m_jni.canvas); m_jni.canvas = nullptr; } if (m_jni.paint) { jni.DeleteGlobalRef(m_jni.paint); m_jni.paint = nullptr; } if (m_jni.rect) { jni.DeleteGlobalRef(m_jni.rect); m_jni.rect = nullptr; } #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- void DrawableCanvas::texImage2D(Texture& tex) { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) GdiFlush(); update_rgba(); tex.update(Texture::Format::RGBA, m_width, m_height, m_pixel); #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) CGContextFlush(m_context); tex.bind(0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_pixel); tex.unbind(0); #elif defined (PLATFORM_ANDROID) JNIHelper jni; tex.bind(0); // GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); jni.CallStaticVoidMethod(m_jni.glut_class, m_jni.glut_texImage2D, GL_TEXTURE_2D, 0, m_jni.bitmap, 0); tex.unbind(0); #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- void DrawableCanvas::clear(unsigned int color) { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) RECT rc = { 0, 0, m_width, m_height }; HBRUSH hBrush = CreateSolidBrush(rgba2gdicolor(color)); FillRect(m_hdc, &rc, hBrush); DeleteObject(hBrush); #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) if (color & 0xff000000) { CGFloat components[] = { ((CGFloat)(color & 0xFF)) / 255.0f, ((CGFloat)((color >> 8) & 0xFF)) / 255.0f, ((CGFloat)((color >> 16) & 0xFF)) / 255.0f, ((CGFloat)((color >> 24) & 0xFF)) / 255.0f }; CGContextSetFillColor(m_context, components); CGContextFillRect(m_context, CGRectMake(0, 0, m_width, m_height)); } else { CGContextClearRect(m_context, CGRectMake(0, 0, m_width, m_height)); } #elif defined (PLATFORM_ANDROID) JNIHelper jni; jni.CallVoidMethod(m_jni.bitmap, m_jni.bitmap_eraseColor, color); #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- void DrawableCanvas::set_textcolor(unsigned int color) { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) SetTextColor(m_hdc, rgba2gdicolor(color)); #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) CGFloat components[] = { ((CGFloat)(color & 0xFF)) / 255.0f, ((CGFloat)((color >> 8) & 0xFF)) / 255.0f, ((CGFloat)((color >> 16) & 0xFF)) / 255.0f, ((CGFloat)((color >> 24) & 0xFF)) / 255.0f }; if (m_textcolor) CGColorRelease(m_textcolor); CGColorSpaceRef cspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); m_textcolor = CGColorCreate(cspace, components); CGColorSpaceRelease(cspace); #elif defined (PLATFORM_ANDROID) JNIHelper jni; jni.CallVoidMethod(m_jni.paint, m_jni.paint_setARGB, color >> 24, 0xFF & (color >> 16), 0xFF & (color >> 8), 0xFF & color); #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- void DrawableCanvas::set_textstyle(const TextStyle& style) { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) LOGFONT lf = { 0 }; lf.lfHeight = -style.fontsize; // negative = pixel lf.lfWidth = 0; lf.lfEscapement = 0; lf.lfOrientation = 0; lf.lfWeight = (style.appearance & TextStyle::Bold) ? FW_HEAVY : FW_SEMIBOLD; lf.lfItalic = (style.appearance & TextStyle::Italic) ? TRUE : FALSE; lf.lfUnderline = (style.appearance & TextStyle::Underline) ? TRUE : FALSE; lf.lfStrikeOut = (style.appearance & TextStyle::Strike) ? TRUE : FALSE; lf.lfCharSet = DEFAULT_CHARSET; lf.lfOutPrecision = OUT_TT_ONLY_PRECIS; lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; lf.lfQuality = NONANTIALIASED_QUALITY; lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; wcsncpy_s(lf.lfFaceName, L"Verdana", sizeof(lf.lfFaceName) / sizeof(lf.lfFaceName[0])); HFONT hFont; hFont = CreateFontIndirect(&lf); if (hFont == NULL) return; if (m_hfont) { SelectObject(m_hdc, hFont); DeleteObject(m_hfont); } else { m_ofont = (HFONT)SelectObject(m_hdc, hFont); } m_hfont = hFont; #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) if (m_font) CFRelease(m_font); CFMutableDictionaryRef attr = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); // family CFStringRef family = CFStringCreateWithCString(kCFAllocatorDefault, "Helvetica", kCFStringEncodingUTF8); // Courier CFDictionaryAddValue(attr, kCTFontFamilyNameAttribute, family); CFRelease(family); // font size CFNumberRef fontsize = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &style.fontsize); CFDictionaryAddValue(attr, kCTFontSizeAttribute, fontsize); CFRelease(fontsize); // bold if (style.appearance & TextStyle::Bold) { CFStringRef bold = CFStringCreateWithCString(kCFAllocatorDefault, "Bold", kCFStringEncodingUTF8); CFDictionaryAddValue(attr, kCTFontStyleNameAttribute, bold); CFRelease(bold); } CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes(attr); m_font = CTFontCreateWithFontDescriptor(descriptor, 0.0, NULL); CFRelease(attr); CFRelease(descriptor); #elif defined (PLATFORM_ANDROID) JNIHelper jni; jni.CallVoidMethod(m_jni.paint, m_jni.paint_setTextSize, (float)style.fontsize); // TODO: Bold with Typeface.DEFAULT_BOLD #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- void DrawableCanvas::calctext(const char* utf8, int* w, int* h) { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) RECT rc = { 0 }; std::basic_string<TCHAR> text = StringUtil::make_tstring(utf8); ::DrawText(m_hdc, text.c_str(), -1, &rc, DT_NOCLIP | DT_NOPREFIX | DT_LEFT | DT_TOP | DT_SINGLELINE | DT_CALCRECT); *w = rc.right - rc.left + 2; // reserve +1 for shadow *h = rc.bottom - rc.top + 2; #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) if (utf8) { CFAttributedStringRef str = create_string(utf8); CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(str); CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints( frameSetter, /* Framesetter */ CFRangeMake(0, 0), /* String range (entire string) */ NULL, /* Frame attributes */ CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX), /* Constraints (CGFLOAT_MAX indicates unconstrained) */ NULL /* Gives the range of string that fits into the constraints, doesn't matter in your situation */ ); CFRelease(frameSetter); CFRelease(str); *w = suggestedSize.width + 1; // reserve +1 for shadow *h = suggestedSize.height + 1; } else { *w = 0; *h = 0; } #elif defined (PLATFORM_ANDROID) JNIHelper jni; jstring s = jni.NewStringUTF(utf8); jsize slen = jni.GetStringLength(s); jni.CallVoidMethod(m_jni.paint, m_jni.paint_getTextBounds, s, 0, slen, m_jni.rect); *w = jni.CallIntMethod(m_jni.rect, m_jni.rect_width) + 1; // reserve +1 for shadow *h = jni.CallIntMethod(m_jni.rect, m_jni.rect_height) + 1; #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- void DrawableCanvas::drawtext(const char* utf8, int x, int y, int w, int h) { if (!utf8) return; #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) RECT rc = { x, y, x + w, y + h }; std::basic_string<TCHAR> text = StringUtil::make_tstring(utf8); ::DrawText(m_hdc, text.c_str(), -1, &rc, DT_NOCLIP | DT_NOPREFIX | DT_LEFT | DT_TOP | DT_SINGLELINE); #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) if (utf8 == NULL) return; // CGContextSetRGBFillColor (context, 1, 0, 1, 1); // CGContextFillRect (context, CGRectMake (x, y, width, height )); CFAttributedStringRef str = create_string(utf8); CTLineRef line = CTLineCreateWithAttributedString(str); CGContextSetTextPosition(m_context, x, m_height - h - y + 2); CTLineDraw(line, m_context); CFRelease(line); CFRelease(str); #elif defined (PLATFORM_ANDROID) JNIHelper jni; jstring s = jni.NewStringUTF(utf8); jni.CallVoidMethod(m_jni.canvas, m_jni.canvas_drawText, s, (float)x, (float)(m_height - y - 2), m_jni.paint); #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- void DrawableCanvas::line(unsigned int color, int x1, int y1, int x2, int y2) { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) HPEN pen = CreatePen(PS_SOLID, 1, rgba2gdicolor(color)); HPEN o = (HPEN)SelectObject(m_hdc, pen); MoveToEx(m_hdc, x1, y1, NULL); LineTo(m_hdc, x2, y2); SelectObject(m_hdc, o); DeleteObject(pen); #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) CGFloat components[] = { ((CGFloat)(color & 0xFF)) / 255.0f, ((CGFloat)((color >> 8) & 0xFF)) / 255.0f, ((CGFloat)((color >> 16) & 0xFF)) / 255.0f, ((CGFloat)((color >> 24) & 0xFF)) / 255.0f }; CGColorSpaceRef cspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); CGColorRef cgcolor = CGColorCreate(cspace, components); CGContextSetStrokeColorWithColor(m_context, cgcolor); CGContextSetLineWidth(m_context, 1.0); CGContextMoveToPoint(m_context, x1 + 1, m_height - y1 - 1); CGContextAddLineToPoint(m_context, x2 + 1, m_height - y2 - 1); CGContextStrokePath(m_context); CGColorRelease(cgcolor); CGColorSpaceRelease(cspace); #elif defined (PLATFORM_ANDROID) JNIHelper jni; jni.CallVoidMethod(m_jni.canvas, m_jni.canvas_drawLine, (float)x1, (float)(m_height - y1), (float)x2, (float)(m_height - y2), m_jni.paint); #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- void DrawableCanvas::fill(unsigned int color, int x1, int y1, int x2, int y2) { #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) // TODO: Implement #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) CGFloat components[] = { ((CGFloat)(color & 0xFF)) / 255.0f, ((CGFloat)((color >> 8) & 0xFF)) / 255.0f, ((CGFloat)((color >> 16) & 0xFF)) / 255.0f, ((CGFloat)((color >> 24) & 0xFF)) / 255.0f }; CGColorSpaceRef cspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); CGColorRef cgcolor = CGColorCreate(cspace, components); CGRect rect = CGRectMake(x1 + 1, m_height - y2 - 1, x2 - x1 + 1, y2 - y1 + 1); CGContextSetFillColorWithColor(m_context, cgcolor); CGContextFillRect(m_context, rect); CGColorRelease(cgcolor); CGColorSpaceRelease(cspace); #elif defined (PLATFORM_ANDROID) #else #error Not Implemented! #endif } // ---------------------------------------------------------------------------- // Platform Specific: Windows // ---------------------------------------------------------------------------- #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) #include <emmintrin.h> COLORREF DrawableCanvas::rgba2gdicolor(uint32_t color) { unsigned int a = (color >> 26) & 0x3F; // 6 bit unsigned int r = (color >> 18) & 0x3F; // 6 bit unsigned int g = (color >> 10) & 0x3F; // 6 bit unsigned int b = (color >> 2) & 0x3F; // 6 bit return RGB(((a << 2) | (b >> 4)), ((b & 0x0F) << 4) | (g >> 2), ((g & 3) << 6) | r); } // ----------------------------------------------------------- // convert GDI buffer to gl texture, handle color space transform. // ----------------------------------------------------------- void DrawableCanvas::update_rgba() { const __m128i mask_a = _mm_set_epi32(0xFC000000, 0xFC000000, 0xFC000000, 0xFC000000); const __m128i mask_r = _mm_set_epi32(0x00FC0000, 0x00FC0000, 0x00FC0000, 0x00FC0000); const __m128i mask_g = _mm_set_epi32(0x0000FC00, 0x0000FC00, 0x0000FC00, 0x0000FC00); const __m128i mask_b = _mm_set_epi32(0x000000FC, 0x000000FC, 0x000000FC, 0x000000FC); const __m128i* src = (const __m128i*) m_bmpixel; __m128i* des = (__m128i*) m_pixel; for (int j = 0; j<m_width * m_height / 4; j++) { __m128i s = _mm_load_si128(src); __m128i a = _mm_slli_epi32(s, 8); __m128i r = _mm_slli_epi32(s, 6); __m128i g = _mm_slli_epi32(s, 4); __m128i b = _mm_slli_epi32(s, 2); a = _mm_and_si128(a, mask_a); r = _mm_and_si128(r, mask_r); g = _mm_and_si128(g, mask_g); b = _mm_and_si128(b, mask_b); a = _mm_or_si128(a, r); g = _mm_or_si128(g, b); a = _mm_or_si128(a, g); _mm_store_si128(des, a); src++; des++; } } // ---------------------------------------------------------------------------- // Platform Specific: PLATFORM_MACOSX, PLATFORM_IOS // ---------------------------------------------------------------------------- #elif defined(PLATFORM_MAC) || defined(PLATFORM_IOS) CFAttributedStringRef DrawableCanvas::create_string(const char* utf8) { CFStringRef strref = CFStringCreateWithCString(kCFAllocatorDefault, utf8, kCFStringEncodingUTF8); CFStringRef keys[] = { kCTFontAttributeName, kCTForegroundColorAttributeName }; CFTypeRef values[] = { m_font, m_textcolor }; CFDictionaryRef attributes = CFDictionaryCreate(kCFAllocatorDefault, (const void**)&keys, (const void**)&values, sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFAttributedStringRef str = CFAttributedStringCreate(kCFAllocatorDefault, strref, attributes); CFRelease(strref); CFRelease(attributes); return str; } // ---------------------------------------------------------------------------- #endif
43.186508
150
0.628228
[ "transform" ]
f3ba33446fbcbcda6aeb317f91631679c98c7069
26,983
cpp
C++
cpp/depends/igl/headers/igl/opengl/ViewerData.cpp
GitZHCODE/zspace_modules
2264cb837d2f05184a51b7b453c7e24288e88ee1
[ "MIT" ]
null
null
null
cpp/depends/igl/headers/igl/opengl/ViewerData.cpp
GitZHCODE/zspace_modules
2264cb837d2f05184a51b7b453c7e24288e88ee1
[ "MIT" ]
null
null
null
cpp/depends/igl/headers/igl/opengl/ViewerData.cpp
GitZHCODE/zspace_modules
2264cb837d2f05184a51b7b453c7e24288e88ee1
[ "MIT" ]
null
null
null
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "ViewerData.h" #include "ViewerCore.h" #include "../per_face_normals.h" #include "../material_colors.h" #include "../per_vertex_normals.h" // Really? Just for GL_NEAREST? #include "gl.h" #include <iostream> IGL_INLINE igl::opengl::ViewerData::ViewerData() : dirty(MeshGL::DIRTY_ALL), show_faces (~unsigned(0)), show_lines (~unsigned(0)), face_based (false), double_sided (false), invert_normals (false), show_overlay (~unsigned(0)), show_overlay_depth(~unsigned(0)), show_vertex_labels(0), show_face_labels (0), show_custom_labels(0), show_texture (false), use_matcap (false), point_size(30), line_width(0.5f), label_size(1), line_color(0,0,0,1), label_color(0,0,0.04,1), shininess(35.0f), id(-1), is_visible (~unsigned(0)) { clear(); }; IGL_INLINE void igl::opengl::ViewerData::set_face_based(bool newvalue) { if (face_based != newvalue) { face_based = newvalue; dirty = MeshGL::DIRTY_ALL; } } // Helpers that draws the most common meshes IGL_INLINE void igl::opengl::ViewerData::set_mesh( const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F) { using namespace std; Eigen::MatrixXd V_temp; // If V only has two columns, pad with a column of zeros if (_V.cols() == 2) { V_temp = Eigen::MatrixXd::Zero(_V.rows(),3); V_temp.block(0,0,_V.rows(),2) = _V; } else V_temp = _V; if (V.rows() == 0 && F.rows() == 0) { V = V_temp; F = _F; compute_normals(); uniform_colors( Eigen::Vector3d(GOLD_AMBIENT[0], GOLD_AMBIENT[1], GOLD_AMBIENT[2]), Eigen::Vector3d(GOLD_DIFFUSE[0], GOLD_DIFFUSE[1], GOLD_DIFFUSE[2]), Eigen::Vector3d(GOLD_SPECULAR[0], GOLD_SPECULAR[1], GOLD_SPECULAR[2])); // Generates a checkerboard texture grid_texture(); } else { if (_V.rows() == V.rows() && _F.rows() == F.rows()) { V = V_temp; F = _F; } else cerr << "ERROR (set_mesh): The new mesh has a different number of vertices/faces. Please clear the mesh before plotting."<<endl; } dirty |= MeshGL::DIRTY_FACE | MeshGL::DIRTY_POSITION; } IGL_INLINE void igl::opengl::ViewerData::set_vertices(const Eigen::MatrixXd& _V) { V = _V; assert(F.size() == 0 || F.maxCoeff() < V.rows()); dirty |= MeshGL::DIRTY_POSITION; } IGL_INLINE void igl::opengl::ViewerData::set_normals(const Eigen::MatrixXd& N) { using namespace std; if (N.rows() == V.rows()) { set_face_based(false); V_normals = N; } else if (N.rows() == F.rows() || N.rows() == F.rows()*3) { set_face_based(true); F_normals = N; } else cerr << "ERROR (set_normals): Please provide a normal per face, per corner or per vertex."<<endl; dirty |= MeshGL::DIRTY_NORMAL; } IGL_INLINE void igl::opengl::ViewerData::set_visible(bool value, unsigned int core_id /*= 1*/) { if (value) is_visible |= core_id; else is_visible &= ~core_id; } IGL_INLINE void igl::opengl::ViewerData::copy_options(const ViewerCore &from, const ViewerCore &to) { to.set(show_overlay , from.is_set(show_overlay) ); to.set(show_overlay_depth, from.is_set(show_overlay_depth)); to.set(show_texture , from.is_set(show_texture) ); to.set(use_matcap , from.is_set(use_matcap) ); to.set(show_faces , from.is_set(show_faces) ); to.set(show_lines , from.is_set(show_lines) ); } IGL_INLINE void igl::opengl::ViewerData::set_colors(const Eigen::MatrixXd &C) { using namespace std; using namespace Eigen; // This Gouraud coloring should be deprecated in favor of Phong coloring in // set-data if(C.rows()>0 && C.cols() == 1) { assert(false && "deprecated: call set_data directly instead"); return set_data(C); } // Ambient color should be darker color const auto ambient = [](const MatrixXd & C)->MatrixXd { MatrixXd T = 0.1*C; T.col(3) = C.col(3); return T; }; // Specular color should be a less saturated and darker color: dampened // highlights const auto specular = [](const MatrixXd & C)->MatrixXd { const double grey = 0.3; MatrixXd T = grey+0.1*(C.array()-grey); T.col(3) = C.col(3); return T; }; if (C.rows() == 1) { for (unsigned i=0;i<V_material_diffuse.rows();++i) { if (C.cols() == 3) V_material_diffuse.row(i) << C.row(0),1; else if (C.cols() == 4) V_material_diffuse.row(i) << C.row(0); } V_material_ambient = ambient(V_material_diffuse); V_material_specular = specular(V_material_diffuse); for (unsigned i=0;i<F_material_diffuse.rows();++i) { if (C.cols() == 3) F_material_diffuse.row(i) << C.row(0),1; else if (C.cols() == 4) F_material_diffuse.row(i) << C.row(0); } F_material_ambient = ambient(F_material_diffuse); F_material_specular = specular(F_material_diffuse); } else if(C.rows() == V.rows() || C.rows() == F.rows()) { // face based colors? if((C.rows()==F.rows()) && (C.rows() != V.rows() || face_based)) { set_face_based(true); for (unsigned i=0;i<F_material_diffuse.rows();++i) { if (C.cols() == 3) F_material_diffuse.row(i) << C.row(i), 1; else if (C.cols() == 4) F_material_diffuse.row(i) << C.row(i); } F_material_ambient = ambient(F_material_diffuse); F_material_specular = specular(F_material_diffuse); } else/*(C.rows() == V.rows())*/ { set_face_based(false); for (unsigned i=0;i<V_material_diffuse.rows();++i) { if (C.cols() == 3) V_material_diffuse.row(i) << C.row(i), 1; else if (C.cols() == 4) V_material_diffuse.row(i) << C.row(i); } V_material_ambient = ambient(V_material_diffuse); V_material_specular = specular(V_material_diffuse); } } else cerr << "ERROR (set_colors): Please provide a single color, or a color per face or per vertex."<<endl; dirty |= MeshGL::DIRTY_DIFFUSE | MeshGL::DIRTY_SPECULAR | MeshGL::DIRTY_AMBIENT; } IGL_INLINE void igl::opengl::ViewerData::set_uv(const Eigen::MatrixXd& UV) { using namespace std; if (UV.rows() == V.rows()) { set_face_based(false); V_uv = UV; } else cerr << "ERROR (set_UV): Please provide uv per vertex."<<endl;; dirty |= MeshGL::DIRTY_UV; } IGL_INLINE void igl::opengl::ViewerData::set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F) { set_face_based(true); V_uv = UV_V.block(0,0,UV_V.rows(),2); F_uv = UV_F; dirty |= MeshGL::DIRTY_UV; } IGL_INLINE void igl::opengl::ViewerData::set_texture( const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& R, const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& G, const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& B) { texture_R = R; texture_G = G; texture_B = B; texture_A = Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>::Constant(R.rows(),R.cols(),255); dirty |= MeshGL::DIRTY_TEXTURE; } IGL_INLINE void igl::opengl::ViewerData::set_texture( const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& R, const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& G, const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& B, const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& A) { texture_R = R; texture_G = G; texture_B = B; texture_A = A; dirty |= MeshGL::DIRTY_TEXTURE; } IGL_INLINE void igl::opengl::ViewerData::set_data( const Eigen::VectorXd & D, double caxis_min, double caxis_max, igl::ColorMapType cmap, int num_steps) { if(!show_texture) { Eigen::MatrixXd CM; igl::colormap(cmap,Eigen::VectorXd::LinSpaced(num_steps,0,1).eval(),0,1,CM); set_colormap(CM); } Eigen::MatrixXd UV = ((D.array()-caxis_min)/(caxis_max-caxis_min)).replicate(1,2); if(D.size() == V.rows()) { set_uv(UV); }else { assert(D.size() == F.rows()); Eigen::MatrixXi UV_F = Eigen::VectorXi::LinSpaced(F.rows(),0,F.rows()-1).replicate(1,3); set_uv(UV,UV_F); } } IGL_INLINE void igl::opengl::ViewerData::set_data(const Eigen::VectorXd & D, igl::ColorMapType cmap, int num_steps) { const double caxis_min = D.minCoeff(); const double caxis_max = D.maxCoeff(); return set_data(D,caxis_min,caxis_max,cmap,num_steps); } IGL_INLINE void igl::opengl::ViewerData::set_colormap(const Eigen::MatrixXd & CM) { assert(CM.cols() == 3 && "colormap CM should have 3 columns"); // Convert to R,G,B textures const Eigen::Matrix<unsigned char,Eigen::Dynamic, Eigen::Dynamic> R = (CM.col(0)*255.0).cast<unsigned char>(); const Eigen::Matrix<unsigned char,Eigen::Dynamic, Eigen::Dynamic> G = (CM.col(1)*255.0).cast<unsigned char>(); const Eigen::Matrix<unsigned char,Eigen::Dynamic, Eigen::Dynamic> B = (CM.col(2)*255.0).cast<unsigned char>(); set_colors(Eigen::RowVector3d(1,1,1)); set_texture(R,G,B); show_texture = ~unsigned(0); meshgl.tex_filter = GL_NEAREST; meshgl.tex_wrap = GL_CLAMP_TO_EDGE; } IGL_INLINE void igl::opengl::ViewerData::set_points( const Eigen::MatrixXd& P, const Eigen::MatrixXd& C) { // clear existing points points.resize(0,0); add_points(P,C); } IGL_INLINE void igl::opengl::ViewerData::add_points(const Eigen::MatrixXd& P, const Eigen::MatrixXd& C) { Eigen::MatrixXd P_temp; // If P only has two columns, pad with a column of zeros if (P.cols() == 2) { P_temp = Eigen::MatrixXd::Zero(P.rows(),3); P_temp.block(0,0,P.rows(),2) = P; } else P_temp = P; int lastid = points.rows(); points.conservativeResize(points.rows() + P_temp.rows(),6); for (unsigned i=0; i<P_temp.rows(); ++i) points.row(lastid+i) << P_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1); dirty |= MeshGL::DIRTY_OVERLAY_POINTS; } IGL_INLINE void igl::opengl::ViewerData::clear_points() { points.resize(0, 6); } IGL_INLINE void igl::opengl::ViewerData::set_edges( const Eigen::MatrixXd& P, const Eigen::MatrixXi& E, const Eigen::MatrixXd& C) { using namespace Eigen; lines.resize(E.rows(),9); assert(C.cols() == 3); for(int e = 0;e<E.rows();e++) { RowVector3d color; if(C.size() == 3) { color<<C; }else if(C.rows() == E.rows()) { color<<C.row(e); } lines.row(e)<< P.row(E(e,0)), P.row(E(e,1)), color; } dirty |= MeshGL::DIRTY_OVERLAY_LINES; } IGL_INLINE void igl::opengl::ViewerData::set_edges_from_vector_field( const Eigen::MatrixXd& P, const Eigen::MatrixXd& V, const Eigen::MatrixXd& C) { assert(P.rows() == V.rows()); Eigen::MatrixXi E(P.rows(),2); const Eigen::MatrixXd PV = (Eigen::MatrixXd(P.rows()+V.rows(),3)<<P,P+V).finished(); for(int i = 0;i<P.rows();i++) { E(i,0) = i; E(i,1) = i+P.rows(); } const Eigen::MatrixXd CC = C.replicate<2,1>(); set_edges(PV,E, C.rows() == 1?C:C.replicate<2,1>()); } IGL_INLINE void igl::opengl::ViewerData::add_edges(const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C) { Eigen::MatrixXd P1_temp,P2_temp; // If P1 only has two columns, pad with a column of zeros if (P1.cols() == 2) { P1_temp = Eigen::MatrixXd::Zero(P1.rows(),3); P1_temp.block(0,0,P1.rows(),2) = P1; P2_temp = Eigen::MatrixXd::Zero(P2.rows(),3); P2_temp.block(0,0,P2.rows(),2) = P2; } else { P1_temp = P1; P2_temp = P2; } int lastid = lines.rows(); lines.conservativeResize(lines.rows() + P1_temp.rows(),9); for (unsigned i=0; i<P1_temp.rows(); ++i) lines.row(lastid+i) << P1_temp.row(i), P2_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1); dirty |= MeshGL::DIRTY_OVERLAY_LINES; } IGL_INLINE void igl::opengl::ViewerData::clear_edges() { lines.resize(0, 9); } IGL_INLINE void igl::opengl::ViewerData::add_label(const Eigen::VectorXd& P, const std::string& str) { Eigen::RowVectorXd P_temp; // If P only has two columns, pad with a column of zeros if (P.size() == 2) { P_temp = Eigen::RowVectorXd::Zero(3); P_temp << P.transpose(), 0; } else P_temp = P; int lastid = labels_positions.rows(); labels_positions.conservativeResize(lastid+1, 3); labels_positions.row(lastid) = P_temp; labels_strings.push_back(str); dirty |= MeshGL::DIRTY_CUSTOM_LABELS; } IGL_INLINE void igl::opengl::ViewerData::set_labels(const Eigen::MatrixXd& P, const std::vector<std::string>& str) { assert(P.rows() == str.size() && "position # and label # do not match!"); assert(P.cols() == 3 && "dimension of label positions incorrect!"); labels_positions = P; labels_strings = str; dirty |= MeshGL::DIRTY_CUSTOM_LABELS; } IGL_INLINE void igl::opengl::ViewerData::clear_labels() { labels_positions.resize(0,3); labels_strings.clear(); } IGL_INLINE void igl::opengl::ViewerData::clear() { V = Eigen::MatrixXd (0,3); F = Eigen::MatrixXi (0,3); F_material_ambient = Eigen::MatrixXd (0,4); F_material_diffuse = Eigen::MatrixXd (0,4); F_material_specular = Eigen::MatrixXd (0,4); V_material_ambient = Eigen::MatrixXd (0,4); V_material_diffuse = Eigen::MatrixXd (0,4); V_material_specular = Eigen::MatrixXd (0,4); F_normals = Eigen::MatrixXd (0,3); V_normals = Eigen::MatrixXd (0,3); V_uv = Eigen::MatrixXd (0,2); F_uv = Eigen::MatrixXi (0,3); lines = Eigen::MatrixXd (0,9); points = Eigen::MatrixXd (0,6); vertex_labels_positions = Eigen::MatrixXd (0,3); face_labels_positions = Eigen::MatrixXd (0,3); labels_positions = Eigen::MatrixXd (0,3); vertex_labels_strings.clear(); face_labels_strings.clear(); labels_strings.clear(); face_based = false; double_sided = false; invert_normals = false; show_texture = false; use_matcap = false; } IGL_INLINE void igl::opengl::ViewerData::compute_normals() { if(V.cols() == 2) { F_normals = Eigen::RowVector3d(0,0,1).replicate(F.rows(),1); V_normals = Eigen::RowVector3d(0,0,1).replicate(V.rows(),1); }else { assert(V.cols() == 3); igl::per_face_normals(V, F, F_normals); igl::per_vertex_normals(V, F, F_normals, V_normals); } dirty |= MeshGL::DIRTY_NORMAL; } IGL_INLINE void igl::opengl::ViewerData::uniform_colors( const Eigen::Vector3d& ambient, const Eigen::Vector3d& diffuse, const Eigen::Vector3d& specular) { Eigen::Vector4d ambient4; Eigen::Vector4d diffuse4; Eigen::Vector4d specular4; ambient4 << ambient, 1; diffuse4 << diffuse, 1; specular4 << specular, 1; uniform_colors(ambient4,diffuse4,specular4); } IGL_INLINE void igl::opengl::ViewerData::uniform_colors( const Eigen::Vector4d& ambient, const Eigen::Vector4d& diffuse, const Eigen::Vector4d& specular) { V_material_ambient.resize(V.rows(),4); V_material_diffuse.resize(V.rows(),4); V_material_specular.resize(V.rows(),4); for (unsigned i=0; i<V.rows();++i) { V_material_ambient.row(i) = ambient; V_material_diffuse.row(i) = diffuse; V_material_specular.row(i) = specular; } F_material_ambient.resize(F.rows(),4); F_material_diffuse.resize(F.rows(),4); F_material_specular.resize(F.rows(),4); for (unsigned i=0; i<F.rows();++i) { F_material_ambient.row(i) = ambient; F_material_diffuse.row(i) = diffuse; F_material_specular.row(i) = specular; } dirty |= MeshGL::DIRTY_SPECULAR | MeshGL::DIRTY_DIFFUSE | MeshGL::DIRTY_AMBIENT; } IGL_INLINE void igl::opengl::ViewerData::normal_matcap() { const int size = 512; texture_R.resize(size, size); texture_G.resize(size, size); texture_B.resize(size, size); const Eigen::Vector3d navy(0.3,0.3,0.5); static const auto clamp = [](double t){ return std::max(std::min(t,1.0),0.0);}; for(int i = 0;i<size;i++) { const double x = (double(i)/double(size-1)*2.-1.); for(int j = 0;j<size;j++) { const double y = (double(j)/double(size-1)*2.-1.); const double z = sqrt(1.0-std::min(x*x+y*y,1.0)); Eigen::Vector3d C = Eigen::Vector3d(x*0.5+0.5,y*0.5+0.5,z); texture_R(i,j) = clamp(C(0))*255; texture_G(i,j) = clamp(C(1))*255; texture_B(i,j) = clamp(C(2))*255; } } texture_A.setConstant(texture_R.rows(),texture_R.cols(),255); dirty |= MeshGL::DIRTY_TEXTURE; } IGL_INLINE void igl::opengl::ViewerData::grid_texture() { unsigned size = 128; unsigned size2 = size/2; texture_R.resize(size, size); for (unsigned i=0; i<size; ++i) { for (unsigned j=0; j<size; ++j) { texture_R(i,j) = 0; if ((i<size2 && j<size2) || (i>=size2 && j>=size2)) texture_R(i,j) = 255; } } texture_G = texture_R; texture_B = texture_R; texture_A = Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>::Constant(texture_R.rows(),texture_R.cols(),255); dirty |= MeshGL::DIRTY_TEXTURE; } // Populate VBOs of a particular label stype (Vert, Face, Custom) IGL_INLINE void igl::opengl::ViewerData::update_labels( igl::opengl::MeshGL& meshgl, igl::opengl::MeshGL::TextGL& GL_labels, const Eigen::MatrixXd& positions, const std::vector<std::string>& strings ){ if (positions.rows()>0) { int numCharsToRender = 0; for(size_t p=0; p<positions.rows(); p++) { numCharsToRender += strings.at(p).length(); } GL_labels.label_pos_vbo.resize(numCharsToRender, 3); GL_labels.label_char_vbo.resize(numCharsToRender, 1); GL_labels.label_offset_vbo.resize(numCharsToRender, 1); GL_labels.label_indices_vbo.resize(numCharsToRender, 1); int idx=0; assert(strings.size() == positions.rows()); for(size_t s=0; s<strings.size(); s++) { const auto & label = strings.at(s); for(size_t c=0; c<label.length(); c++) { GL_labels.label_pos_vbo.row(idx) = positions.row(s).cast<float>(); GL_labels.label_char_vbo(idx) = (float)(label.at(c)); GL_labels.label_offset_vbo(idx) = c; GL_labels.label_indices_vbo(idx) = idx; idx++; } } } } IGL_INLINE void igl::opengl::ViewerData::updateGL( const igl::opengl::ViewerData& data, const bool invert_normals, igl::opengl::MeshGL& meshgl ) { if (!meshgl.is_initialized) { meshgl.init(); } bool per_corner_uv = (data.F_uv.rows() == data.F.rows()); bool per_corner_normals = (data.F_normals.rows() == 3 * data.F.rows()); meshgl.dirty |= data.dirty; // Input: // X #F by dim quantity // Output: // X_vbo #F*3 by dim scattering per corner const auto per_face = [&data]( const Eigen::MatrixXd & X, MeshGL::RowMatrixXf & X_vbo) { assert(X.cols() == 4); X_vbo.resize(data.F.rows()*3,4); for (unsigned i=0; i<data.F.rows();++i) for (unsigned j=0;j<3;++j) X_vbo.row(i*3+j) = X.row(i).cast<float>(); }; // Input: // X #V by dim quantity // Output: // X_vbo #F*3 by dim scattering per corner const auto per_corner = [&data]( const Eigen::MatrixXd & X, MeshGL::RowMatrixXf & X_vbo) { X_vbo.resize(data.F.rows()*3,X.cols()); for (unsigned i=0; i<data.F.rows();++i) for (unsigned j=0;j<3;++j) X_vbo.row(i*3+j) = X.row(data.F(i,j)).cast<float>(); }; if (!data.face_based) { if (!(per_corner_uv || per_corner_normals)) { // Vertex positions if (meshgl.dirty & MeshGL::DIRTY_POSITION) meshgl.V_vbo = data.V.cast<float>(); // Vertex normals if (meshgl.dirty & MeshGL::DIRTY_NORMAL) { meshgl.V_normals_vbo = data.V_normals.cast<float>(); if (invert_normals) meshgl.V_normals_vbo = -meshgl.V_normals_vbo; } // Per-vertex material settings if (meshgl.dirty & MeshGL::DIRTY_AMBIENT) meshgl.V_ambient_vbo = data.V_material_ambient.cast<float>(); if (meshgl.dirty & MeshGL::DIRTY_DIFFUSE) meshgl.V_diffuse_vbo = data.V_material_diffuse.cast<float>(); if (meshgl.dirty & MeshGL::DIRTY_SPECULAR) meshgl.V_specular_vbo = data.V_material_specular.cast<float>(); // Face indices if (meshgl.dirty & MeshGL::DIRTY_FACE) meshgl.F_vbo = data.F.cast<unsigned>(); // Texture coordinates if (meshgl.dirty & MeshGL::DIRTY_UV) { meshgl.V_uv_vbo = data.V_uv.cast<float>(); } } else { // Per vertex properties with per corner UVs if (meshgl.dirty & MeshGL::DIRTY_POSITION) { per_corner(data.V,meshgl.V_vbo); } if (meshgl.dirty & MeshGL::DIRTY_AMBIENT) { meshgl.V_ambient_vbo.resize(data.F.rows()*3,4); per_corner(data.V_material_ambient,meshgl.V_ambient_vbo); } if (meshgl.dirty & MeshGL::DIRTY_DIFFUSE) { meshgl.V_diffuse_vbo.resize(data.F.rows()*3,4); per_corner(data.V_material_diffuse,meshgl.V_diffuse_vbo); } if (meshgl.dirty & MeshGL::DIRTY_SPECULAR) { meshgl.V_specular_vbo.resize(data.F.rows()*3,4); per_corner(data.V_material_specular,meshgl.V_specular_vbo); } if (meshgl.dirty & MeshGL::DIRTY_NORMAL) { meshgl.V_normals_vbo.resize(data.F.rows()*3,3); per_corner(data.V_normals,meshgl.V_normals_vbo); if (invert_normals) meshgl.V_normals_vbo = -meshgl.V_normals_vbo; } if (meshgl.dirty & MeshGL::DIRTY_FACE) { meshgl.F_vbo.resize(data.F.rows(),3); for (unsigned i=0; i<data.F.rows();++i) meshgl.F_vbo.row(i) << i*3+0, i*3+1, i*3+2; } if ( (meshgl.dirty & MeshGL::DIRTY_UV) && data.V_uv.rows()>0) { meshgl.V_uv_vbo.resize(data.F.rows()*3,2); for (unsigned i=0; i<data.F.rows();++i) for (unsigned j=0;j<3;++j) meshgl.V_uv_vbo.row(i*3+j) = data.V_uv.row(per_corner_uv ? data.F_uv(i,j) : data.F(i,j)).cast<float>(); } } } else { if (meshgl.dirty & MeshGL::DIRTY_POSITION) { per_corner(data.V,meshgl.V_vbo); } if (meshgl.dirty & MeshGL::DIRTY_AMBIENT) { per_face(data.F_material_ambient,meshgl.V_ambient_vbo); } if (meshgl.dirty & MeshGL::DIRTY_DIFFUSE) { per_face(data.F_material_diffuse,meshgl.V_diffuse_vbo); } if (meshgl.dirty & MeshGL::DIRTY_SPECULAR) { per_face(data.F_material_specular,meshgl.V_specular_vbo); } if (meshgl.dirty & MeshGL::DIRTY_NORMAL) { meshgl.V_normals_vbo.resize(data.F.rows()*3,3); for (unsigned i=0; i<data.F.rows();++i) for (unsigned j=0;j<3;++j) meshgl.V_normals_vbo.row(i*3+j) = per_corner_normals ? data.F_normals.row(i*3+j).cast<float>() : data.F_normals.row(i).cast<float>(); if (invert_normals) meshgl.V_normals_vbo = -meshgl.V_normals_vbo; } if (meshgl.dirty & MeshGL::DIRTY_FACE) { meshgl.F_vbo.resize(data.F.rows(),3); for (unsigned i=0; i<data.F.rows();++i) meshgl.F_vbo.row(i) << i*3+0, i*3+1, i*3+2; } if( (meshgl.dirty & MeshGL::DIRTY_UV) && data.V_uv.rows()>0) { meshgl.V_uv_vbo.resize(data.F.rows()*3,2); for (unsigned i=0; i<data.F.rows();++i) for (unsigned j=0;j<3;++j) meshgl.V_uv_vbo.row(i*3+j) = data.V_uv.row(per_corner_uv ? data.F_uv(i,j) : data.F(i,j)).cast<float>(); } } if (meshgl.dirty & MeshGL::DIRTY_TEXTURE) { meshgl.tex_u = data.texture_R.rows(); meshgl.tex_v = data.texture_R.cols(); meshgl.tex.resize(data.texture_R.size()*4); for (unsigned i=0;i<data.texture_R.size();++i) { meshgl.tex(i*4+0) = data.texture_R(i); meshgl.tex(i*4+1) = data.texture_G(i); meshgl.tex(i*4+2) = data.texture_B(i); meshgl.tex(i*4+3) = data.texture_A(i); } } if (meshgl.dirty & MeshGL::DIRTY_OVERLAY_LINES) { meshgl.lines_V_vbo.resize(data.lines.rows()*2,3); meshgl.lines_V_colors_vbo.resize(data.lines.rows()*2,3); meshgl.lines_F_vbo.resize(data.lines.rows()*2,1); for (unsigned i=0; i<data.lines.rows();++i) { meshgl.lines_V_vbo.row(2*i+0) = data.lines.block<1, 3>(i, 0).cast<float>(); meshgl.lines_V_vbo.row(2*i+1) = data.lines.block<1, 3>(i, 3).cast<float>(); meshgl.lines_V_colors_vbo.row(2*i+0) = data.lines.block<1, 3>(i, 6).cast<float>(); meshgl.lines_V_colors_vbo.row(2*i+1) = data.lines.block<1, 3>(i, 6).cast<float>(); meshgl.lines_F_vbo(2*i+0) = 2*i+0; meshgl.lines_F_vbo(2*i+1) = 2*i+1; } } if (meshgl.dirty & MeshGL::DIRTY_OVERLAY_POINTS) { meshgl.points_V_vbo.resize(data.points.rows(),3); meshgl.points_V_colors_vbo.resize(data.points.rows(),3); meshgl.points_F_vbo.resize(data.points.rows(),1); for (unsigned i=0; i<data.points.rows();++i) { meshgl.points_V_vbo.row(i) = data.points.block<1, 3>(i, 0).cast<float>(); meshgl.points_V_colors_vbo.row(i) = data.points.block<1, 3>(i, 3).cast<float>(); meshgl.points_F_vbo(i) = i; } } if (meshgl.dirty & MeshGL::DIRTY_FACE_LABELS) { if(face_labels_positions.rows()==0) { face_labels_positions.conservativeResize(F.rows(), 3); Eigen::MatrixXd faceNormals = F_normals.normalized(); for (int f=0; f<F.rows();++f) { std::string faceName = std::to_string(f); face_labels_positions.row(f) = V.row(F.row(f)(0)); face_labels_positions.row(f) += V.row(F.row(f)(1)); face_labels_positions.row(f) += V.row(F.row(f)(2)); face_labels_positions.row(f) /= 3.; face_labels_positions.row(f) = (faceNormals*0.05).row(f) + face_labels_positions.row(f); face_labels_strings.push_back(faceName); } } update_labels( meshgl, meshgl.face_labels, face_labels_positions, face_labels_strings ); } if (meshgl.dirty & MeshGL::DIRTY_VERTEX_LABELS) { if(vertex_labels_positions.rows()==0) { vertex_labels_positions.conservativeResize(V.rows(), 3); Eigen::MatrixXd normalized = V_normals.normalized(); for (int v=0; v<V.rows();++v) { std::string vertName = std::to_string(v); vertex_labels_positions.row(v) = (normalized*0.1).row(v) + V.row(v); vertex_labels_strings.push_back(vertName); } } update_labels( meshgl, meshgl.vertex_labels, vertex_labels_positions, vertex_labels_strings ); } if (meshgl.dirty & MeshGL::DIRTY_CUSTOM_LABELS) { update_labels( meshgl, meshgl.custom_labels, labels_positions, labels_strings ); } }
29.202381
134
0.627803
[ "mesh", "geometry", "vector" ]
f3bb861d521c206804d5af94da8cb3eb58649920
15,689
cpp
C++
project/learn-opengl-2/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
project/learn-opengl-2/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
project/learn-opengl-2/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#include <cassert> #include <chrono> #include <string> #include <fstream> #include <iostream> #include <GL/glew.h> #include <SDL2/SDL.h> // #include <SDL2/SDL_image.h> #define ILUT_USE_OPENGL #include <IL/il.h> #include <IL/ilut.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace std; constexpr char VERTEX_SHADER_FILE[] = "./vertex.vsh"; constexpr char FRAGMENT_SHADER_FILE[] = "./fragment.fsh"; constexpr char AXIS_VERTEX_SHADER_FILE[] = "./axis.vsh"; constexpr char AXIS_FRAGMENT_SHADER_FILE[] = "./axis.fsh"; constexpr char TEXTURE_FILE_1[] = "./box.jpg"; /** * 从指定的文件中读取渲染器 * * 该函数分为两步,首先从文件中读取源码 * 然后将读取的源码交给OpenGL * * @param shader 指定目标渲染器 * @param path 指定渲染器源码的位置 * * @remark: * 该函数不会对渲染器进行编译,编译请使用glCompileShader * 中途有一个检查文件是否被打开的assert,可能导致程序退出 */ void ReadShaderFile(GLuint shader, const std::string &path); /** * 这是主函数,没啥好讲的 * * @return 返回程序的最终状态 */ int main() { // 载入SDL2 assert(SDL_Init(SDL_INIT_VIDEO) == 0); // 设置OpenGL属性 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // 创建窗口和OpenGL上下文 SDL_Window *wnd = nullptr; SDL_GLContext context = nullptr; wnd = SDL_CreateWindow("OpenGL 3.3", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL); context = SDL_GL_CreateContext(wnd); assert(wnd != nullptr); assert(context != nullptr); // 载入GLEW glewExperimental = GL_TRUE; assert(glewInit() == GLEW_OK); glGetError(); // GLEW一开始会设置一个没用的设置,忽略即可 GLint status; // 加载顶点渲染器 GLuint boxVertexShader; boxVertexShader = glCreateShader(GL_VERTEX_SHADER); ReadShaderFile(boxVertexShader, VERTEX_SHADER_FILE); glCompileShader(boxVertexShader); glGetShaderiv(boxVertexShader, GL_COMPILE_STATUS, &status); assert(status == true); // 加载片段渲染器 GLuint boxFragmentShader; boxFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); ReadShaderFile(boxFragmentShader, FRAGMENT_SHADER_FILE); glCompileShader(boxFragmentShader); glGetShaderiv(boxFragmentShader, GL_COMPILE_STATUS, &status); assert(status == true); // 加载坐标轴的渲染器 GLuint axisVertexShader, axisFragmentShader; axisVertexShader = glCreateShader(GL_VERTEX_SHADER); axisFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); ReadShaderFile(axisVertexShader, AXIS_VERTEX_SHADER_FILE); ReadShaderFile(axisFragmentShader, AXIS_FRAGMENT_SHADER_FILE); glCompileShader(axisVertexShader); glCompileShader(axisFragmentShader); glGetShaderiv(axisVertexShader, GL_COMPILE_STATUS, &status); assert(status == true); glGetShaderiv(axisFragmentShader, GL_COMPILE_STATUS, &status); assert(status == true); // 制作渲染程序 GLuint boxShaderProgram; boxShaderProgram = glCreateProgram(); glAttachShader(boxShaderProgram, boxVertexShader); glAttachShader(boxShaderProgram, boxFragmentShader); glLinkProgram(boxShaderProgram); glGetProgramiv(boxShaderProgram, GL_LINK_STATUS, &status); assert(status == true); // 制作坐标轴渲染程序 GLuint axisShaderProgram; axisShaderProgram = glCreateProgram(); glAttachShader(axisShaderProgram, axisVertexShader); glAttachShader(axisShaderProgram, axisFragmentShader); glLinkProgram(axisShaderProgram); glGetProgramiv(axisShaderProgram, GL_LINK_STATUS, &status); assert(status == true); // 删除渲染器 // 连接后不再需要 glDeleteShader(boxVertexShader); glDeleteShader(boxFragmentShader); glDeleteShader(axisVertexShader); glDeleteShader(axisFragmentShader); // 加载材质 ilInit(); ILuint textureDate; textureDate = ilGenImage(); ilBindImage(textureDate); ilLoadImage(TEXTURE_FILE_1); ILint width = ilGetInteger(IL_IMAGE_WIDTH); ILint height = ilGetInteger(IL_IMAGE_HEIGHT); ILubyte *texturePtr = ilGetData(); ilBindImage(0); GLuint textures[1]; glGenTextures(1, textures); glBindTexture(GL_TEXTURE_2D, textures[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, texturePtr); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); assert(textures[0] != 0); ilDeleteImage(textureDate); // 设置顶点数据 GLfloat axisVertices[] = { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // x start 1000.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // x end 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, // y start 0.0f, 1000.0f, 0.0f, 0.0f, 1.0f, 0.0f, // y end 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, // z start 0.0f, 0.0f, 1000.0f, 0.0f, 0.0f, 1.0f // z end }; GLfloat vertices[] = { // x y r g b s t -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // 0 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // 1 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // 3 -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // 4 -0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // 5 0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // 6 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // 7 -0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // 8 -0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // 9 -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // 10 -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // 11 -0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // 12 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // 13 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // 14 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // 15 0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // 16 -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // 17 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // 18 0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // 19 -0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // 20 -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // 21 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // 22 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // 23 -0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // 24 }; // 设置索引数组 GLuint indices[] = { 0, 1, 2, 2, 3, 0, // face 1 4, 5, 6, 6, 7, 4, // face 2 8, 9, 10, 10, 11, 8, // face 3 12, 13, 14, 14, 15, 12, // face 4 16, 17, 18, 18, 19, 16, // face 5 20, 21, 22, 22, 23, 20 // face 6 }; glm::mat4 projection; glm::mat4 view; glm::mat4 model; // projection = glm::perspective(45.0f, 800.0f / 600.0f, 1.0f, 100.0f); projection = glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f); // view = glm::lookAt(glm::vec3(2.0f, 2.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), // glm::vec3(0.0f, 1.0f, 0.0f)); view = glm::mat4(); model = glm::mat4(); constexpr GLuint AXIS_INDEX = 0; constexpr GLuint BOX_INDEX = 1; // 生成VAO GLuint VAO[2]; glGenVertexArrays(2, VAO); assert(VAO[0] != 0); assert(VAO[1] != 0); // 生成VBO GLuint VBO[2]; glGenBuffers(2, VBO); assert(VBO[0] != 0); assert(VBO[1] != 0); // 生成EBO GLuint EBO; glGenBuffers(1, &EBO); assert(EBO != 0); // 绑定box的相关设置 glBindVertexArray(VAO[BOX_INDEX]); glBindBuffer(GL_ARRAY_BUFFER, VBO[BOX_INDEX]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_READ); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glUseProgram(boxShaderProgram); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8, nullptr); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8, reinterpret_cast<GLvoid *>(3 * sizeof(GLfloat))); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8, reinterpret_cast<GLvoid *>(6 * sizeof(GLfloat))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); // 设置box的uniform GLint uniBoxProjection = glGetUniformLocation(boxShaderProgram, "projection"); GLint uniBoxView = glGetUniformLocation(boxShaderProgram, "view"); GLint uniBoxModel = glGetUniformLocation(boxShaderProgram, "model"); assert(uniBoxProjection != -1); assert(uniBoxView != -1); assert(uniBoxModel != -1); glUniformMatrix4fv(uniBoxProjection, 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(uniBoxView, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(uniBoxModel, 1, GL_FALSE, glm::value_ptr(model)); assert(glGetError() == GL_NO_ERROR); // 绑定坐标轴的相关设置 glBindVertexArray(VAO[AXIS_INDEX]); glBindBuffer(GL_ARRAY_BUFFER, VBO[AXIS_INDEX]); glBufferData(GL_ARRAY_BUFFER, sizeof(axisVertices), axisVertices, GL_STATIC_DRAW); glUseProgram(axisShaderProgram); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, nullptr); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<GLvoid *>(3 * sizeof(GLfloat))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); // 设置坐标轴的uniform GLint uniAxisProjection = glGetUniformLocation(axisShaderProgram, "projection"); GLint uniAxisView = glGetUniformLocation(axisShaderProgram, "view"); GLint uniAxisModel = glGetUniformLocation(axisShaderProgram, "model"); assert(uniAxisProjection != -1); assert(uniAxisView != -1); assert(uniAxisModel != -1); glUniformMatrix4fv(uniAxisProjection, 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(uniAxisView, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(uniAxisModel, 1, GL_FALSE, glm::value_ptr(model)); assert(glGetError() == GL_NO_ERROR); // OpenGL的其他设置 glEnable(GL_DEPTH_TEST); assert(glGetError() == GL_NO_ERROR); auto start = chrono::high_resolution_clock::now(); bool flag = true; // 指示运行状态 SDL_Event e; // SDL2的事件 GLfloat rotateX = 0.0f; GLfloat rotateY = 0.0f; GLfloat rotateZ = 0.0f; // TODO GLfloat angleX = 0.0f; GLfixed angleY = 0.0f; GLfloat angleZ = 0.0f; chrono::high_resolution_clock::time_point startX; chrono::high_resolution_clock::time_point startY; chrono::high_resolution_clock::time_point startZ; startX = startY = startZ = chrono::high_resolution_clock::now(); string text; string finalText; Sint32 textStart; Sint32 selLen; // 主循环 while (flag) { // 事件处理 if (SDL_PollEvent(&e)) { switch (e.type) { case SDL_QUIT: flag = false; continue; case SDL_KEYDOWN: cout << e.key.keysym.sym << endl; switch (e.key.keysym.sym) { case SDLK_q: rotateX = -1.0f; break; case SDLK_w: rotateX = 1.0f; break; case SDLK_a: rotateY = -1.0f; break; case SDLK_s: rotateY = 1.0f; break; case SDLK_z: rotateZ = -1.0f; break; case SDLK_x: rotateZ = 1.0f; break; case SDLK_p: { cout << "Saving screenshot..." << endl; unsigned char *data = new unsigned char[800 * 600 * 4]; glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0, 0, 800, 600, GL_RGB, GL_UNSIGNED_BYTE, data); ILuint image = ilGenImage(); ilBindImage(image); ilutGLScreen(); ilEnable(IL_FILE_OVERWRITE); ilSaveImage("screenshot.png"); ilBindImage(0); delete[] data; ilDeleteImage(image); } break; case SDLK_ESCAPE: flag = false; continue; } // switch to e.key.keysym.sym break; case SDL_KEYUP: switch (e.key.keysym.sym) { case SDLK_q: case SDLK_w: rotateX = 0.0f; break; case SDLK_a: case SDLK_s: rotateY = 0.0f; break; case SDLK_z: case SDLK_x: rotateZ = 0.0f; break; case SDLK_F1: SDL_StopTextInput(); break; case SDLK_F2: SDL_StartTextInput(); SDL_Rect inputRect = { 0, 0, 800, 600 }; SDL_SetTextInputRect(&inputRect); break; } // switch to e.key.keysym.sym break; } // switch to e.type } // 渲染区 glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); auto end = chrono::high_resolution_clock::now(); auto passedTime = chrono::duration_cast<chrono::duration<float>>(end - start).count(); model = glm::mat4(); if (!(rotateX == 0.0f && rotateY == 0.0f && rotateZ == 0.0f)) { model = glm::rotate(model, passedTime * 20.0f, glm::vec3(rotateX, rotateY, rotateZ)); } // glBindBuffer(GL_ARRAY_BUFFER, VBO[BOX_INDEX]); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glUseProgram(boxShaderProgram); glBindVertexArray(VAO[BOX_INDEX]); glUniformMatrix4fv(uniBoxModel, 1, GL_FALSE, glm::value_ptr(model)); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); // glBindBuffer(GL_ARRAY_BUFFER, VBO[AXIS_INDEX]); glUseProgram(axisShaderProgram); glBindVertexArray(VAO[AXIS_INDEX]); glUniformMatrix4fv(uniAxisModel, 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_LINES, 0, 6); // 提交 glFlush(); SDL_GL_SwapWindow(wnd); } // while // 删除渲染程序 glDeleteProgram(boxShaderProgram); glDeleteProgram(axisShaderProgram); // 删除EBO glDeleteBuffers(1, &EBO); // 删除VBO glDeleteBuffers(2, VBO); // 删除VAO glDeleteVertexArrays(2, VAO); // 销毁窗口和OpenGL上下文 SDL_GL_DeleteContext(context); SDL_DestroyWindow(wnd); // 退出SDL2 SDL_Quit(); return 0; } // function main void ReadShaderFile(GLuint shader, const std::string &path) { std::ifstream fileReader(path); assert(fileReader.is_open()); std::string lineBuffer, fileBuffer; while (std::getline(fileReader, lineBuffer)) { fileBuffer += lineBuffer; fileBuffer += '\n'; } // while const GLchar *source = fileBuffer.data(); glShaderSource(shader, 1, &source, nullptr); }
33.523504
83
0.581809
[ "model" ]
f3bd221bc3c940de970935e177560a3adb3f6839
2,663
cpp
C++
graphs/hlpp.cpp
prince776/CodeBook
874fc7f94011ad1d25a55bcd91fecd2a11eb5a9b
[ "CC0-1.0" ]
17
2021-01-25T12:07:17.000Z
2022-02-26T17:20:31.000Z
graphs/hlpp.cpp
NavneelSinghal/CodeBook
ff60ace9107dd19ef8ba81e175003f567d2a9070
[ "CC0-1.0" ]
null
null
null
graphs/hlpp.cpp
NavneelSinghal/CodeBook
ff60ace9107dd19ef8ba81e175003f567d2a9070
[ "CC0-1.0" ]
4
2021-02-28T11:13:44.000Z
2021-11-20T12:56:20.000Z
template <int MAXN, class T = int> struct HLPP { const T INF = numeric_limits<T>::max(); struct edge { int to, rev; T f; }; int s = MAXN - 1, t = MAXN - 2; vector<edge> adj[MAXN]; vector<int> lst[MAXN], gap[MAXN]; T excess[MAXN]; int highest, height[MAXN], cnt[MAXN], work; void addEdge(int from, int to, int f, bool isDirected = true) { adj[from].push_back({to, adj[to].size(), f}); adj[to].push_back({from, adj[from].size() - 1, isDirected ? 0 : f}); } void updHeight(int v, int nh) { work++; if (height[v] != MAXN) cnt[height[v]]--; height[v] = nh; if (nh == MAXN) return; cnt[nh]++, highest = nh; gap[nh].push_back(v); if (excess[v] > 0) lst[nh].push_back(v); } void globalRelabel() { work = 0; fill(all(height), MAXN); fill(all(cnt), 0); for (int i = 0; i < highest; i++) lst[i].clear(), gap[i].clear(); height[t] = 0; queue<int> q({t}); while (!q.empty()) { int v = q.front(); q.pop(); for (auto& e : adj[v]) if (height[e.to] == MAXN && adj[e.to][e.rev].f > 0) q.push(e.to), updHeight(e.to, height[v] + 1); highest = height[v]; } } void push(int v, edge& e) { if (excess[e.to] == 0) lst[height[e.to]].push_back(e.to); T df = min(excess[v], e.f); e.f -= df, adj[e.to][e.rev].f += df; excess[v] -= df, excess[e.to] += df; } void discharge(int v) { int nh = MAXN; for (auto& e : adj[v]) { if (e.f > 0) { if (height[v] == height[e.to] + 1) { push(v, e); if (excess[v] <= 0) return; } else nh = min(nh, height[e.to] + 1); } } if (cnt[height[v]] > 1) updHeight(v, nh); else { for (int i = height[v]; i <= highest; i++) { for (auto j : gap[i]) updHeight(j, MAXN); gap[i].clear(); } } } T calc(int heur_n = MAXN) { fill(all(excess), 0); excess[s] = INF, excess[t] = -INF; globalRelabel(); for (auto& e : adj[s]) push(s, e); for (; highest >= 0; highest--) { while (!lst[highest].empty()) { int v = lst[highest].back(); lst[highest].pop_back(); discharge(v); if (work > 4 * heur_n) globalRelabel(); } } return excess[t] + INF; } };
28.329787
76
0.425836
[ "vector" ]
f3beeb76b92c526bdbccba727a464291aaa09c26
513
cpp
C++
08. Hashing/15 More than N-K Occurrences/15a More Than N k Occurences.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
190
2021-02-10T17:01:01.000Z
2022-03-20T00:21:43.000Z
08. Hashing/15 More than N-K Occurrences/15a More Than N k Occurences.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
null
null
null
08. Hashing/15 More than N-K Occurrences/15a More Than N k Occurences.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
27
2021-03-26T11:35:15.000Z
2022-03-06T07:34:54.000Z
#include<bits/stdc++.h> using namespace std; /* print elements occuring more than (n/k) times in array */ void nkOcc(vector<int> v, int k)//time comp. O(n*logn) ; space comp. O(1) { int n = v.size(); sort(v.begin(), v.end()); int i = 1, cnt = 1; while (i < n) { while (i < n and v[i] == v[i - 1]) { cnt++; i++; } if (cnt > (n / k)) { cout << v[i - 1] << " "; } cnt = 1; i++; } } int main() { vector<int> v = {10, 10, 20, 30, 20, 10, 10}; int k = 2; nkOcc(v, k); return 0; }
13.5
73
0.489279
[ "vector" ]
f3c58e1afdd80d428619b0a61be9a363ee6466d3
43,782
cpp
C++
net/config/netcfg/tcpipcfg/dlgaddr.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/config/netcfg/tcpipcfg/dlgaddr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/config/netcfg/tcpipcfg/dlgaddr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//----------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1997. // // File: D L G A D D R . C P P // // Contents: CTcpAddrPage implementation // // Notes: CTcpAddrPage is the IP Address page // // Author: tongl 5 Nov, 1997 //----------------------------------------------------------------------- #include "pch.h" #pragma hdrstop #include "tcpipobj.h" #include "dlgaddr.h" #include "resource.h" #include "tcpconst.h" #include "tcperror.h" #include "tcphelp.h" #include "tcputil.h" #include "ncatlui.h" #include "ncstl.h" #include "ncui.h" #include "ncsvc.h" #include "ncperms.h" #include "dlgaddrm.h" #include "dlgdns.h" #include "dlgwins.h" #include "dlgatm.h" #include "dlgopt.h" #include "dlgras.h" CTcpAddrPage::CTcpAddrPage(CTcpipcfg * ptcpip, const DWORD * adwHelpIDs) : m_pageBackup(ptcpip, g_aHelpIDS_IDD_BACK_UP), m_hBackupPage(NULL) { Assert(ptcpip); m_ptcpip = ptcpip; m_adwHelpIDs = adwHelpIDs; m_pAdapterInfo = ptcpip->GetConnectionAdapterInfo(); m_fModified = FALSE; m_fWarnedDisjointGw = FALSE; m_fWarnedMismatchIPandGw = FALSE; m_fPropShtOk = FALSE; m_fPropShtModified = FALSE; m_fLmhostsFileReset = FALSE; //IPSec is removed from connection UI // m_fIpsecPolicySet = FALSE; m_ConnType = m_ptcpip->GetConnectionType(); Assert(m_ConnType != CONNECTION_UNSET); m_fRasNotAdmin = m_ptcpip->IsRasNotAdmin(); m_pIpSettingsPage = NULL; m_pTcpDnsPage = NULL; m_pTcpWinsPage = NULL; m_pAtmArpcPage = NULL; m_pTcpOptionsPage = NULL; m_pTcpRasPage = NULL; } CTcpAddrPage::~CTcpAddrPage() { FreeCollectionAndItem(m_vstrWarnedDupIpList); } LRESULT CTcpAddrPage::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled) { // limit the field ranges for the address fields m_ipAddress.Create(m_hWnd, IDC_IPADDR_IP); m_ipAddress.SetFieldRange(0, c_iIPADDR_FIELD_1_LOW, c_iIPADDR_FIELD_1_HIGH); m_ipDnsPrimary.Create(m_hWnd, IDC_DNS_PRIMARY); m_ipDnsPrimary.SetFieldRange(0, c_iIPADDR_FIELD_1_LOW, c_iIPADDR_FIELD_1_HIGH); m_ipDnsSecondary.Create(m_hWnd, IDC_DNS_SECONDARY); m_ipDnsSecondary.SetFieldRange(0, c_iIPADDR_FIELD_1_LOW, c_iIPADDR_FIELD_1_HIGH); if (m_ConnType == CONNECTION_LAN) { // these are for Lan connections only m_ipSubnetMask.Create(m_hWnd, IDC_IPADDR_SUB); m_ipDefGateway.Create(m_hWnd, IDC_IPADDR_GATE); m_ipDefGateway.SetFieldRange(0, c_iIPADDR_FIELD_1_LOW, c_iIPADDR_FIELD_1_HIGH); } if (!FHasPermission(NCPERM_AllowAdvancedTCPIPConfig)) { ::EnableWindow(GetDlgItem(IDC_IPADDR_ADVANCED), FALSE); } return 0; } LRESULT CTcpAddrPage::OnContextMenu(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled) { ShowContextHelp(m_hWnd, HELP_CONTEXTMENU, m_adwHelpIDs); return 0; } LRESULT CTcpAddrPage::OnHelp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled) { LPHELPINFO lphi = reinterpret_cast<LPHELPINFO>(lParam); Assert(lphi); if (HELPINFO_WINDOW == lphi->iContextType) { ShowContextHelp(static_cast<HWND>(lphi->hItemHandle), HELP_WM_HELP, m_adwHelpIDs); } return 0; } LRESULT CTcpAddrPage::OnActive(int idCtrl, LPNMHDR pnmh, BOOL& fHandled) { m_fSetInitialValue = TRUE; SetInfo(); m_fSetInitialValue = FALSE; ::SetWindowLongPtr(m_hWnd, DWLP_MSGRESULT, 0); return 0; } LRESULT CTcpAddrPage::OnKillActive(int idCtrl, LPNMHDR pnmh, BOOL& fHandled) { // All error values are loaded and then checked here // while all non-error values are checked in OnApply BOOL fError = FALSE; // Allow page to lose active status HWND hWndFocus = 0; // If the ip address and subnet mask on this page mismatch, // just raise error and do not update the UI if (m_ConnType == CONNECTION_LAN) { if (m_ipAddress.IsBlank() && !m_ipSubnetMask.IsBlank()) { NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_NO_IP, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipAddress; fError = TRUE; } else if (!m_ipAddress.IsBlank() && m_ipSubnetMask.IsBlank()) { NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_NOSUBNET, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipSubnetMask; fError = TRUE; } } if (!m_ipDnsPrimary.IsBlank() && !m_ipDnsSecondary.IsBlank()) { tstring strPrimaryDns; tstring strSecondDns; m_ipDnsPrimary.GetAddress(&strPrimaryDns); m_ipDnsSecondary.GetAddress(&strSecondDns); if (strPrimaryDns == strSecondDns) { NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_DUP_SECOND_DNS, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipDnsSecondary; fError = TRUE; } } // Now, update in memory structure if (!fError) { UpdateInfo(); if (m_ConnType != CONNECTION_LAN) { if (!m_pAdapterInfo->m_fEnableDhcp) { // simply make sure ip address is not empty for RAS connections if (!m_pAdapterInfo->m_vstrIpAddresses.size()) { NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_NO_IP, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipAddress; fError = TRUE; } else { DWORD ardwIp[4]; GetNodeNum(m_pAdapterInfo->m_vstrIpAddresses[0]->c_str(), ardwIp); if (ardwIp[0] > c_iIPADDR_FIELD_1_HIGH || ardwIp[0] < c_iIPADDR_FIELD_1_LOW) { IPAlertPrintf(m_hWnd, IDS_INCORRECT_IP_FIELD_1, ardwIp[0], c_iIPADDR_FIELD_1_LOW, c_iIPADDR_FIELD_1_HIGH); hWndFocus = (HWND) m_ipAddress; fError = TRUE; } } } } else // for Lan connections { // Check validate IP address and duplication on each card before // allowing the page to lose focus IP_VALIDATION_ERR err; // Validate IP Address for adapter used in this connection if ((err = ValidateIp(m_pAdapterInfo)) != ERR_NONE) { switch(err) { case ERR_HOST_ALL0: NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_HOST_ALL_0, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipAddress; break; case ERR_HOST_ALL1: NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_HOST_ALL_1, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipAddress; break; case ERR_SUBNET_ALL0: NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_SUBNET_ALL_0, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipSubnetMask; break; case ERR_NO_IP: NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_NO_IP, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipAddress; break; case ERR_NO_SUBNET: NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_NOSUBNET, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipSubnetMask; break; case ERR_UNCONTIGUOUS_SUBNET: NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_ERROR_UNCONTIGUOUS_SUBNET, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipSubnetMask; break; default: NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INCORRECT_IPADDRESS, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); hWndFocus = (HWND) m_ipAddress; break; } fError = TRUE; } if ((!fError) && (!m_pAdapterInfo->m_fEnableDhcp)) { // Check ip address duplicates between this adapter and any other // enabled LAN adapters in our first memory list // same adapter if (FHasDuplicateIp(m_pAdapterInfo)) { // duplicate IP address on same adapter is an error NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_DUPLICATE_IP_ERROR, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); fError = TRUE; } // check the IP address and the static gateway are in the same subnet // Multip IP and multiple gateways will show up on both general page // and the advanced page. // To avoid confusing error messages, we only do this validation when // there is only one IP address and one gateway. if (!fError && !m_fWarnedMismatchIPandGw && 1 == m_pAdapterInfo->m_vstrIpAddresses.size() && 1 == m_pAdapterInfo->m_vstrDefaultGateway.size() && 1 == m_pAdapterInfo->m_vstrSubnetMask.size()) { if (!FIpAndGatewayInSameSubNet(m_pAdapterInfo->m_vstrIpAddresses[0]->c_str(), m_pAdapterInfo->m_vstrSubnetMask[0]->c_str(), m_pAdapterInfo->m_vstrDefaultGateway[0]->c_str())) { // duplicate IP address on same adapter is an error if (NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_ERROR_IP_GW_MISMATH, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_YESNO | MB_DEFBUTTON2) == IDNO) { fError = TRUE; } else { m_fWarnedMismatchIPandGw = TRUE; } } } // The pvcard is a readonly version of the first memory state const VCARD * pvcard = m_ptcpip->GetConstAdapterInfoVector(); // different adapter if (!fError) { int iDupCard; VSTR_ITER iterIpBegin = m_pAdapterInfo->m_vstrIpAddresses.begin(); VSTR_ITER iterIpEnd = m_pAdapterInfo->m_vstrIpAddresses.end(); VSTR_ITER iterIp = iterIpBegin; for( ; iterIp != iterIpEnd ; ++iterIp) { if ((iDupCard=CheckForDuplicates(pvcard, m_pAdapterInfo, **iterIp)) >=0) { Assert((*pvcard)[iDupCard]->m_guidInstanceId != m_pAdapterInfo->m_guidInstanceId); // duplicate IP address between different adapters is not necessarily an error // we raise a warning(requested by bug# 158578) if (!FAlreadyWarned(**iterIp)) { UINT uIdMsg = IDS_DUPLICATE_IP_WARNING; if (FIsCardNotPresentOrMalFunctioning(&((*pvcard)[iDupCard]->m_guidInstanceId))) { // bug 286379, if the dup card is malfunctioning or not physically present, // we should give a more specific error uIdMsg = IDS_DUP_MALFUNCTION_IP_WARNING; } //here is the normal case: both cards are functioning if (NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, uIdMsg, MB_APPLMODAL | MB_ICONINFORMATION | MB_YESNO, (*iterIp)->c_str(), (*pvcard)[iDupCard]->m_strDescription.c_str()) == IDYES) { fError = TRUE; // NOT ok to leave the UI } else { // user said the dup is ok, don't warn them again m_vstrWarnedDupIpList.push_back(new tstring((*iterIp)->c_str())); } } } if (fError) break; } } //if we have static gateway, check whether other cards also have //static gateway. If yes, then the computer may not work properly //as a router or edge box. Warn user about this configuration if (!fError && !m_fWarnedDisjointGw && 0 < m_pAdapterInfo->m_vstrDefaultGateway.size()) { for(UINT i = 0; i < pvcard->size(); ++i) { if (0 < (*pvcard)[i]->m_vstrDefaultGateway.size() && (*pvcard)[i]->m_guidInstanceId != m_pAdapterInfo->m_guidInstanceId && !FIsCardNotPresentOrMalFunctioning(&((*pvcard)[i]->m_guidInstanceId))) { if (NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_WRN_DISJOINT_NET, MB_APPLMODAL | MB_ICONINFORMATION | MB_YESNO | MB_DEFBUTTON2) == IDNO) { fError = TRUE; } else { //if the user want to have gateways on multiple nics on purpose, //don't warn the user any more m_fWarnedDisjointGw = TRUE; } //In either case of accepting or not-accepting, there is //no need for additional check for this break; } } } } } if (fError) // page not going away, we should update the Ui with what's in memory SetInfo(); } //we need to change focus to the control that contains invalidate data if (fError && hWndFocus) ::SetFocus(hWndFocus); ::SetWindowLongPtr(m_hWnd, DWLP_MSGRESULT, fError); return fError; } LRESULT CTcpAddrPage::OnApply(int idCtrl, LPNMHDR pnmh, BOOL& fHandled) { BOOL nResult = PSNRET_NOERROR; if(m_fLmhostsFileReset) // if lmhosts has been reset { m_ptcpip->SetSecondMemoryLmhostsFileReset(); } //IPSec is removed from connection UI /* if (m_fIpsecPolicySet) { m_ptcpip->SetSecondMemoryIpsecPolicySet(); } */ //Bug 232011, warning the user that the local IP address will be set as the primary DNS // server address if DHCP is disabled and DNS server list is empty, if DNS server service // is installed. if((!m_pAdapterInfo->m_fEnableDhcp) && (m_pAdapterInfo->m_vstrDnsServerList.size() == 0)) { CServiceManager scm; CService svc; HRESULT hr = scm.HrOpenService (&svc, c_szSvcDnsServer, NO_LOCK, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS); if(SUCCEEDED(hr)) { NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_TCPIP_DNS_EMPTY, MB_OK | MB_APPLMODAL | MB_ICONEXCLAMATION); } } if (!IsModified()) { ::SetWindowLongPtr(m_hWnd, DWLP_MSGRESULT, nResult); return nResult; } m_ptcpip->SetSecondMemoryModified(); SetModifiedTo(FALSE); // this page is no longer modified ::SetWindowLongPtr(m_hWnd, DWLP_MSGRESULT, nResult); return nResult; } LRESULT CTcpAddrPage::OnCancel(int idCtrl, LPNMHDR pnmh, BOOL& fHandled) { return 0; } LRESULT CTcpAddrPage::OnDhcpButton(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch(wNotifyCode) { case BN_CLICKED: case BN_DOUBLECLICKED: if (!m_pAdapterInfo->m_fEnableDhcp) // if Dhcp was disabled { // turn on DHCP button and disable the ip and subnet controls m_pAdapterInfo->m_fEnableDhcp = TRUE; EnableGroup(m_pAdapterInfo->m_fEnableDhcp); PageModified(); FreeCollectionAndItem(m_pAdapterInfo->m_vstrIpAddresses); m_ipAddress.ClearAddress(); if (m_ConnType == CONNECTION_LAN) { FreeCollectionAndItem(m_pAdapterInfo->m_vstrSubnetMask); FreeCollectionAndItem(m_pAdapterInfo->m_vstrDefaultGateway); FreeCollectionAndItem(m_pAdapterInfo->m_vstrDefaultGatewayMetric); m_ipSubnetMask.ClearAddress(); m_ipDefGateway.ClearAddress(); } } // if !m_pAdapterInfo->m_fEnableDhcp break; } // switch return 0; } LRESULT CTcpAddrPage::OnFixedButton(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch(wNotifyCode) { case BN_CLICKED: case BN_DOUBLECLICKED: if (m_pAdapterInfo->m_fEnableDhcp) { PageModified(); // turn off DHCP button and enable the ip and subnet controls m_pAdapterInfo->m_fEnableDhcp = FALSE; EnableGroup(m_pAdapterInfo->m_fEnableDhcp); } break; } // switch return 0; } LRESULT CTcpAddrPage::OnDnsDhcp(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch(wNotifyCode) { case BN_CLICKED: case BN_DOUBLECLICKED: PageModified(); FreeCollectionAndItem(m_pAdapterInfo->m_vstrDnsServerList); m_ipDnsPrimary.ClearAddress(); m_ipDnsSecondary.ClearAddress(); EnableStaticDns(FALSE); break; } // switch return 0; } LRESULT CTcpAddrPage::OnDnsFixed(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch(wNotifyCode) { case BN_CLICKED: case BN_DOUBLECLICKED: PageModified(); EnableStaticDns(TRUE); ::SetFocus(GetDlgItem(IDC_DNS_PRIMARY)); break; } // switch return 0; } LRESULT CTcpAddrPage::OnAdvancedButton(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch (wNotifyCode) { case BN_CLICKED: case BN_DOUBLECLICKED: BOOL fErr = FALSE; if (m_ConnType == CONNECTION_LAN) { // check inconsistency between ip address & subnet mask if (m_ipAddress.IsBlank() && !m_ipSubnetMask.IsBlank()) { NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_NO_IP, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); ::SetFocus(m_ipAddress); fErr = TRUE; } else if (!m_ipAddress.IsBlank() && m_ipSubnetMask.IsBlank()) { NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_INVALID_NOSUBNET, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); ::SetFocus(m_ipSubnetMask); fErr = TRUE; } } if (!m_ipDnsPrimary.IsBlank() && !m_ipDnsSecondary.IsBlank()) { tstring strPrimaryDns; tstring strSecondDns; m_ipDnsPrimary.GetAddress(&strPrimaryDns); m_ipDnsSecondary.GetAddress(&strSecondDns); if (strPrimaryDns == strSecondDns) { NcMsgBox(m_hWnd, IDS_MSFT_TCP_TEXT, IDS_DUP_SECOND_DNS, MB_APPLMODAL | MB_ICONEXCLAMATION | MB_OK); ::SetFocus(m_ipDnsSecondary); fErr = TRUE; } } if (!fErr) { // update our in memory structure with what's in the controls UpdateInfo(); // Bring up the advanced pages ADAPTER_INFO adapterInfo; adapterInfo = *m_pAdapterInfo; GLOBAL_INFO glbInfo; glbInfo = *(m_ptcpip->GetGlobalInfo()); INT_PTR iRet = DoPropertySheet(&adapterInfo, &glbInfo); if (iRet != -1) { if (m_fPropShtOk && m_fPropShtModified) { // Something changed, so mark the page as modified PageModified(); // Reset values m_fPropShtOk = FALSE; m_fPropShtModified = FALSE; // Update second memory info structure *m_pAdapterInfo = adapterInfo; GLOBAL_INFO * pGlbInfo = m_ptcpip->GetGlobalInfo(); *pGlbInfo = glbInfo; } } // Update the controls with new data SetInfo(); } break; } return 0; } //Show or Hide the backup configuration page depend on the //current settings of dhcp vs static void CTcpAddrPage::ShowOrHideBackupPage() { if (IsDlgButtonChecked(IDC_IP_DHCP) || IsDlgButtonChecked(IDC_DNS_DHCP)) { //show the backup configuration page if (NULL == m_hBackupPage) { m_hBackupPage = m_pageBackup.CreatePage(IDD_BACK_UP, 0); Assert(m_hBackupPage); if (m_hBackupPage) { ::SendMessage(GetParent(), PSM_ADDPAGE, 0, (LPARAM) m_hBackupPage); } } } else { //hide the backup configuration page if (NULL != m_hBackupPage) { ::SendMessage(GetParent(), PSM_REMOVEPAGE, 1, (LPARAM) m_hBackupPage); m_hBackupPage = NULL; } } } INT_PTR CTcpAddrPage::DoPropertySheet(ADAPTER_INFO * pAdapterDlg, GLOBAL_INFO * pGlbDlg) { Assert(pAdapterDlg); Assert(pGlbDlg); HRESULT hr = S_OK; INT_PTR iRet = -1; HPROPSHEETPAGE *ahpsp = NULL; int cPages = 0; // Create property pages // ahpsp is allocated memory by CoTaskMemAlloc hr = HrSetupPropPages(pAdapterDlg, pGlbDlg, &ahpsp, &cPages); if (SUCCEEDED(hr)) { // Show the property sheet PROPSHEETHEADER psh = {0}; psh.dwSize = sizeof(PROPSHEETHEADER); psh.dwFlags = PSH_NOAPPLYNOW; psh.hwndParent = ::GetActiveWindow(); psh.hInstance = _Module.GetModuleInstance(); psh.pszIcon = NULL; psh.pszCaption = (PWSTR)SzLoadIds(IDS_TCP_ADV_HEADER); psh.nPages = cPages; psh.phpage = ahpsp; iRet = PropertySheet(&psh); if (-1 == iRet) { DWORD dwError = GetLastError(); TraceError("CTcpAddrPage::DoPropertySheet", HRESULT_FROM_WIN32(dwError)); } } if (m_pIpSettingsPage) { delete m_pIpSettingsPage; m_pIpSettingsPage = NULL; } if (m_pTcpDnsPage) { delete m_pTcpDnsPage; m_pTcpDnsPage = NULL; } if (m_pTcpWinsPage) { delete m_pTcpWinsPage; m_pTcpWinsPage = NULL; } if (m_pAtmArpcPage) { delete m_pAtmArpcPage; m_pAtmArpcPage = NULL; } if (m_pTcpOptionsPage) { delete m_pTcpOptionsPage; m_pTcpOptionsPage = NULL; } if (m_pTcpRasPage) { delete m_pTcpRasPage; m_pTcpRasPage = NULL; } if (ahpsp) CoTaskMemFree(ahpsp); return iRet; } HRESULT CTcpAddrPage::HrSetupPropPages( ADAPTER_INFO * pAdapterDlg, GLOBAL_INFO * pGlbDlg, HPROPSHEETPAGE ** pahpsp, INT * pcPages) { HRESULT hr = S_OK; // initialize output parameters int cPages = 0; HPROPSHEETPAGE *ahpsp = NULL; // Set up the property pages cPages = 4; if (m_ConnType == CONNECTION_LAN) { m_pIpSettingsPage = new CIpSettingsPage(this, pAdapterDlg, g_aHelpIDs_IDD_IPADDR_ADV); if (m_pIpSettingsPage == NULL) { CORg(E_OUTOFMEMORY); } } else { m_pTcpRasPage = new CTcpRasPage(this, pAdapterDlg, g_aHelpIDs_IDD_OPT_RAS); if (m_pTcpRasPage == NULL) { CORg(E_OUTOFMEMORY); } } m_pTcpDnsPage = new CTcpDnsPage(this, pAdapterDlg, pGlbDlg, g_aHelpIDs_IDD_TCP_DNS); m_pTcpWinsPage = new CTcpWinsPage(m_ptcpip, this, pAdapterDlg, pGlbDlg, g_aHelpIDs_IDD_TCP_WINS); if ((m_pTcpDnsPage == NULL) || (m_pTcpWinsPage == NULL)) { CORg(E_OUTOFMEMORY); } if (pAdapterDlg->m_fIsAtmAdapter) { m_pAtmArpcPage = new CAtmArpcPage(this, pAdapterDlg, g_aHelpIDs_IDD_ATM_ARPC); if (m_pAtmArpcPage == NULL) { CORg(E_OUTOFMEMORY); } cPages++; } //After removing the IPSec connection UI, there are no options to //put in the option tab. So we just go ahead remove it. if (!pAdapterDlg->m_fIsRasFakeAdapter) { m_pTcpOptionsPage = new CTcpOptionsPage(this, pAdapterDlg, pGlbDlg, g_aHelpIDs_IDD_TCP_OPTIONS); if (m_pTcpOptionsPage == NULL) { CORg(E_OUTOFMEMORY); } } else { //we remove the option tab for the ras connections cPages--; } // Allocate a buffer large enough to hold the handles to all of our // property pages. ahpsp = (HPROPSHEETPAGE *)CoTaskMemAlloc(sizeof(HPROPSHEETPAGE) * cPages); if (!ahpsp) { CORg(E_OUTOFMEMORY); } cPages =0; if (m_ConnType == CONNECTION_LAN) { ahpsp[cPages++] = m_pIpSettingsPage->CreatePage(IDD_IPADDR_ADV, 0); } else { ahpsp[cPages++] = m_pTcpRasPage->CreatePage(IDD_OPT_RAS, 0); } ahpsp[cPages++] = m_pTcpDnsPage->CreatePage(IDD_TCP_DNS, 0); ahpsp[cPages++] = m_pTcpWinsPage->CreatePage(IDD_TCP_WINS, 0); if (pAdapterDlg->m_fIsAtmAdapter) { ahpsp[cPages++] = m_pAtmArpcPage->CreatePage(IDD_ATM_ARPC, 0); } if (!pAdapterDlg->m_fIsRasFakeAdapter && m_pTcpOptionsPage) { ahpsp[cPages++] = m_pTcpOptionsPage->CreatePage(IDD_TCP_OPTIONS, 0); } *pahpsp = ahpsp; *pcPages = cPages; Error: if (FAILED(hr)) { if (m_pIpSettingsPage) { delete m_pIpSettingsPage; m_pIpSettingsPage = NULL; } if (m_pTcpDnsPage) { delete m_pTcpDnsPage; m_pTcpDnsPage = NULL; } if (m_pTcpWinsPage) { delete m_pTcpWinsPage; m_pTcpWinsPage = NULL; } if (m_pAtmArpcPage) { delete m_pAtmArpcPage; m_pAtmArpcPage = NULL; } if (m_pTcpOptionsPage) { delete m_pTcpOptionsPage; m_pTcpOptionsPage = NULL; } if (m_pTcpRasPage) { delete m_pTcpRasPage; m_pTcpRasPage = NULL; } } return hr; } LRESULT CTcpAddrPage::OnIpAddrIp(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch (wNotifyCode) { case EN_CHANGE: PageModified(); break; } return 0; } LRESULT CTcpAddrPage::OnIpAddrSub(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch (wNotifyCode) { case EN_CHANGE: PageModified(); break; case EN_SETFOCUS: // if the subnet mask is blank, create a mask and insert it into // the control if (!m_ipAddress.IsBlank() && m_ipSubnetMask.IsBlank()) { tstring strSubnetMask; tstring strIpAddress; m_ipAddress.GetAddress(&strIpAddress); // generate the mask and update the control, and internal structure GenerateSubnetMask(m_ipAddress, &strSubnetMask); m_ipSubnetMask.SetAddress(strSubnetMask.c_str()); ReplaceFirstAddress(&(m_pAdapterInfo->m_vstrSubnetMask), strSubnetMask.c_str()); } break; } return 0; } LRESULT CTcpAddrPage::OnIpAddrGateway(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch (wNotifyCode) { case EN_CHANGE: PageModified(); break; } return 0; } LRESULT CTcpAddrPage::OnDnsPrimary(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch (wNotifyCode) { case EN_CHANGE: PageModified(); break; } return 0; } LRESULT CTcpAddrPage::OnDnsSecondary(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled) { switch (wNotifyCode) { case EN_CHANGE: PageModified(); break; } return 0; } LRESULT CTcpAddrPage::OnIpFieldChange(int idCtrl, LPNMHDR pnmh, BOOL& fHandled) { LPNMIPADDRESS lpnmipa; int iLow = c_iIpLow; int iHigh = c_iIpHigh; switch(idCtrl) { case IDC_IPADDR_IP: case IDC_IPADDR_GATE: case IDC_DNS_PRIMARY: case IDC_DNS_SECONDARY: lpnmipa = (LPNMIPADDRESS) pnmh; if (0==lpnmipa->iField) { iLow = c_iIPADDR_FIELD_1_LOW; iHigh = c_iIPADDR_FIELD_1_HIGH; }; IpCheckRange(lpnmipa, m_hWnd, iLow, iHigh, (IDC_IPADDR_IP == idCtrl || IDC_IPADDR_GATE == idCtrl)); break; case IDC_IPADDR_SUB: lpnmipa = (LPNMIPADDRESS) pnmh; IpCheckRange(lpnmipa, m_hWnd, iLow, iHigh); break; default: break; } return 0; } void CTcpAddrPage::EnableGroup(BOOL fEnableDhcp) { BOOL fStaticIp = !fEnableDhcp; CheckDlgButton(IDC_IP_DHCP, fEnableDhcp); CheckDlgButton(IDC_IP_FIXED, fStaticIp); ::EnableWindow(GetDlgItem(IDC_IPADDR_IPTEXT), fStaticIp); ::EnableWindow(GetDlgItem(IDC_IPADDR_IP), fStaticIp); if (m_ConnType == CONNECTION_LAN) { ::EnableWindow(GetDlgItem(IDC_IPADDR_SUBTEXT), fStaticIp); ::EnableWindow(GetDlgItem(IDC_IPADDR_SUB), fStaticIp); ::EnableWindow(GetDlgItem(IDC_IPADDR_GATE), fStaticIp); ::EnableWindow(GetDlgItem(IDC_IPADDR_GATETEXT), fStaticIp); } if (!fEnableDhcp) // enforce DNS address option { CheckDlgButton(IDC_DNS_DHCP, FALSE); CheckDlgButton(IDC_DNS_FIXED, TRUE); ::EnableWindow(GetDlgItem(IDC_DNS_DHCP), FALSE); EnableStaticDns(TRUE); } else { ::EnableWindow(GetDlgItem(IDC_DNS_DHCP), TRUE); } if (CONNECTION_LAN == m_ConnType) { ShowOrHideBackupPage(); } } void CTcpAddrPage::EnableStaticDns(BOOL fUseStaticDns) { ::EnableWindow(GetDlgItem(IDC_DNS_PRIMARY), fUseStaticDns); ::EnableWindow(GetDlgItem(IDC_DNS_PRIMARY_TEXT), fUseStaticDns); ::EnableWindow(GetDlgItem(IDC_DNS_SECONDARY), fUseStaticDns); ::EnableWindow(GetDlgItem(IDC_DNS_SECONDARY_TEXT), fUseStaticDns); } // Set info to controls using the data in m_pAdapterInfo void CTcpAddrPage::SetInfo() { Assert(m_pAdapterInfo); // Dhcp Ip address is not allowed when Dhcp server is installed or // it is a SLIP connection // const GLOBAL_INFO * pglb = m_ptcpip->GetConstGlobalInfo(); // if ((pglb->m_fDhcpServerInstalled) || (m_ConnType == CONNECTION_RAS_SLIP)) if (m_ConnType == CONNECTION_RAS_SLIP) { ::EnableWindow(GetDlgItem(IDC_IP_DHCP), FALSE); m_pAdapterInfo->m_fEnableDhcp = 0; } EnableGroup(m_pAdapterInfo->m_fEnableDhcp); // Set Ip address if(m_pAdapterInfo->m_fEnableDhcp == 0) //Dhcp disabled, static IP { tstring strTmp; if (fQueryFirstAddress(m_pAdapterInfo->m_vstrIpAddresses, &strTmp)) m_ipAddress.SetAddress(strTmp.c_str()); else m_ipAddress.ClearAddress(); } else //Dhcp enabled { m_ipAddress.ClearAddress(); FreeCollectionAndItem(m_pAdapterInfo->m_vstrIpAddresses); } // Set Subnet mask and default gateway if Lan connection if (m_ConnType == CONNECTION_LAN) { if(m_pAdapterInfo->m_fEnableDhcp == 0) //Dhcp disabled, static IP { tstring strTmp; if (fQueryFirstAddress(m_pAdapterInfo->m_vstrSubnetMask, &strTmp)) m_ipSubnetMask.SetAddress(strTmp.c_str()); else m_ipSubnetMask.ClearAddress(); if (fQueryFirstAddress(m_pAdapterInfo->m_vstrDefaultGateway, &strTmp)) m_ipDefGateway.SetAddress(strTmp.c_str()); else m_ipDefGateway.ClearAddress(); } else //Dhcp enabled { m_ipSubnetMask.ClearAddress(); FreeCollectionAndItem(m_pAdapterInfo->m_vstrSubnetMask); tstring strGateway; if (fQueryFirstAddress(m_pAdapterInfo->m_vstrDefaultGateway, &strGateway)) m_ipDefGateway.SetAddress(strGateway.c_str()); else m_ipDefGateway.ClearAddress(); } } // Set Dns addresses BOOL fUseStaticDns = ((!m_pAdapterInfo->m_fEnableDhcp) || (m_pAdapterInfo->m_vstrDnsServerList.size() >0)); CheckDlgButton(IDC_DNS_DHCP, !fUseStaticDns); CheckDlgButton(IDC_DNS_FIXED, fUseStaticDns); EnableStaticDns(fUseStaticDns); if (fUseStaticDns) { tstring strTmp; if (fQueryFirstAddress(m_pAdapterInfo->m_vstrDnsServerList, &strTmp)) m_ipDnsPrimary.SetAddress(strTmp.c_str()); else m_ipDnsPrimary.ClearAddress(); if (fQuerySecondAddress(m_pAdapterInfo->m_vstrDnsServerList, &strTmp)) m_ipDnsSecondary.SetAddress(strTmp.c_str()); else m_ipDnsSecondary.ClearAddress(); } else { m_ipDnsPrimary.ClearAddress(); m_ipDnsSecondary.ClearAddress(); } } // Update info in m_pAdapterInfo with what's in the controls void CTcpAddrPage::UpdateInfo() { Assert(m_pAdapterInfo); if (!m_pAdapterInfo->m_fEnableDhcp) // If DHCP disabled { tstring strNewAddress; // ip address & subnet mask if (!m_ipAddress.IsBlank()) { m_ipAddress.GetAddress(&strNewAddress); ReplaceFirstAddress(&(m_pAdapterInfo->m_vstrIpAddresses), strNewAddress.c_str()); if (m_ConnType == CONNECTION_LAN) { if (m_ipSubnetMask.IsBlank()) { SendDlgItemMessage(IDC_IPADDR_SUB, WM_SETFOCUS, 0, 0); } else { m_ipSubnetMask.GetAddress(&strNewAddress); ReplaceFirstAddress(&(m_pAdapterInfo->m_vstrSubnetMask), strNewAddress.c_str()); } } } else // no ip address { if (m_ConnType == CONNECTION_LAN) { if (m_ipSubnetMask.IsBlank()) { // delete the first ip address and subnet mask if (m_pAdapterInfo->m_vstrIpAddresses.size()) { FreeVectorItem(m_pAdapterInfo->m_vstrIpAddresses, 0); if (!m_pAdapterInfo->m_vstrIpAddresses.empty()) m_ipAddress.SetAddress(m_pAdapterInfo->m_vstrIpAddresses[0]->c_str()); if (m_pAdapterInfo->m_vstrSubnetMask.size()) { FreeVectorItem(m_pAdapterInfo->m_vstrSubnetMask, 0); if (!m_pAdapterInfo->m_vstrSubnetMask.empty()) m_ipSubnetMask.SetAddress(m_pAdapterInfo->m_vstrSubnetMask[0]->c_str()); } } } else { AssertSz(FALSE, "No ip address."); } } else // RAS connection, simply delete IP address { if (m_pAdapterInfo->m_vstrIpAddresses.size()) { FreeVectorItem(m_pAdapterInfo->m_vstrIpAddresses, 0); } } } // default gateway if (m_ConnType == CONNECTION_LAN) { if (!m_ipDefGateway.IsBlank()) { m_ipDefGateway.GetAddress(&strNewAddress); ReplaceFirstAddress(&(m_pAdapterInfo->m_vstrDefaultGateway), strNewAddress.c_str()); int iSize = m_pAdapterInfo->m_vstrDefaultGatewayMetric.size(); if (m_pAdapterInfo->m_vstrDefaultGatewayMetric.size() == 0) { WCHAR buf[IP_LIMIT]; //if there is no default gateway before (that's the reason metric list is //empty), we add the default metric for it _ltot(c_dwDefaultMetricOfGateway, buf, 10); m_pAdapterInfo->m_vstrDefaultGatewayMetric.push_back(new tstring(buf)); } } else { if (m_pAdapterInfo->m_vstrDefaultGateway.size() >0) { FreeVectorItem(m_pAdapterInfo->m_vstrDefaultGateway, 0); if (!m_pAdapterInfo->m_vstrDefaultGateway.empty()) m_ipDefGateway.SetAddress(m_pAdapterInfo->m_vstrDefaultGateway[0]->c_str()); if (m_pAdapterInfo->m_vstrDefaultGatewayMetric.size() >0) FreeVectorItem(m_pAdapterInfo->m_vstrDefaultGatewayMetric, 0); } } } } // DNS addresses UpdateAddressList(&(m_pAdapterInfo->m_vstrDnsServerList), m_ipDnsPrimary, m_ipDnsSecondary); } // Update a vector of strings with values from two IP address // controls void CTcpAddrPage::UpdateAddressList(VSTR * pvstrList, IpControl& ipPrimary, IpControl& ipSecondary) { tstring str; if (pvstrList->size()<=2) // if the list did not have more than two addresses { // Free the list FreeCollectionAndItem(*pvstrList); // Insert new addresses if any if (!ipPrimary.IsBlank()) { ipPrimary.GetAddress(&str); pvstrList->push_back(new tstring(str.c_str())); } if (!ipSecondary.IsBlank()) { ipSecondary.GetAddress(&str); pvstrList->push_back(new tstring(str.c_str())); } } else { // Replace addresses if they exists if (!ipSecondary.IsBlank()) { ipSecondary.GetAddress(&str); ReplaceSecondAddress(pvstrList, str.c_str()); } else { FreeVectorItem(*pvstrList, 1); } if (!ipPrimary.IsBlank()) { ipPrimary.GetAddress(&str); ReplaceFirstAddress(pvstrList, str.c_str()); } else { FreeVectorItem(*pvstrList, 0); } //fix Bug 425112: Update the UI if either of the IP control //is blank because sometimes UpdateInfo get called twice (which // will make us delete the address twice if we dont update the UI) if (ipPrimary.IsBlank() || ipSecondary.IsBlank()) { if (!pvstrList->empty()) { ipPrimary.SetAddress((*pvstrList)[0]->c_str()); } if (pvstrList->size() >= 2) { ipSecondary.SetAddress((*pvstrList)[1]->c_str()); } } } } BOOL CTcpAddrPage::FIsCardNotPresentOrMalFunctioning(GUID * pguidCard) { Assert(pguidCard); BOOL fRet = FALSE; FARPROC pfnHrGetPnpDeviceStatus = NULL; HMODULE hNetman = NULL; HRESULT hrTmp = S_OK; NETCON_STATUS ncStatus = NCS_CONNECTED; hrTmp = HrLoadLibAndGetProc(L"netman.dll", "HrGetPnpDeviceStatus", &hNetman, &pfnHrGetPnpDeviceStatus); if (SUCCEEDED(hrTmp)) { hrTmp = (*(PHRGETPNPDEVICESTATUS)pfnHrGetPnpDeviceStatus)( pguidCard, &ncStatus); FreeLibrary(hNetman); } if (SUCCEEDED(hrTmp) && (NCS_HARDWARE_MALFUNCTION == ncStatus || NCS_HARDWARE_NOT_PRESENT == ncStatus)) { fRet = TRUE; } return fRet; }
30.985138
113
0.525399
[ "vector" ]
f3c669265ded77b88c08c3d102987a4f9d881d4c
7,641
hpp
C++
cppcache/src/statistics/StatArchiveWriter.hpp
rhoughton-pivot/geode-native
ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd
[ "Apache-2.0" ]
48
2017-02-08T22:24:07.000Z
2022-02-06T02:47:56.000Z
cppcache/src/statistics/StatArchiveWriter.hpp
rhoughton-pivot/geode-native
ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd
[ "Apache-2.0" ]
388
2017-02-13T17:09:45.000Z
2022-03-29T22:18:39.000Z
cppcache/src/statistics/StatArchiveWriter.hpp
rhoughton-pivot/geode-native
ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd
[ "Apache-2.0" ]
68
2017-02-09T18:43:15.000Z
2022-03-14T22:59:13.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef GEODE_STATISTICS_STATARCHIVEWRITER_H_ #define GEODE_STATISTICS_STATARCHIVEWRITER_H_ #include <chrono> #include <list> #include <map> #include <vector> #include <geode/Cache.hpp> #include <geode/DataOutput.hpp> #include <geode/ExceptionTypes.hpp> #include <geode/internal/geode_globals.hpp> #include "../SerializationRegistry.hpp" #include "../util/Log.hpp" #include "HostStatSampler.hpp" #include "StatisticDescriptor.hpp" #include "StatisticDescriptorImpl.hpp" #include "Statistics.hpp" #include "StatisticsType.hpp" #include "StatsDef.hpp" constexpr int8_t ARCHIVE_VERSION = 4; constexpr int8_t SAMPLE_TOKEN = 0; constexpr int8_t RESOURCE_TYPE_TOKEN = 1; constexpr int8_t RESOURCE_INSTANCE_CREATE_TOKEN = 2; constexpr int8_t RESOURCE_INSTANCE_DELETE_TOKEN = 3; constexpr int8_t RESOURCE_INSTANCE_INITIALIZE_TOKEN = 4; constexpr int8_t HEADER_TOKEN = 77; constexpr int8_t ILLEGAL_RESOURCE_INST_ID = -1; constexpr int16_t MAX_BYTE_RESOURCE_INST_ID = 252; constexpr int16_t SHORT_RESOURCE_INST_ID_TOKEN = 253; constexpr int32_t INT_RESOURCE_INST_ID_TOKEN = 254; constexpr int16_t ILLEGAL_RESOURCE_INST_ID_TOKEN = -1; constexpr int32_t MAX_SHORT_RESOURCE_INST_ID = 65535; constexpr int32_t MAX_SHORT_TIMESTAMP = 65534; constexpr int32_t INT_TIMESTAMP_TOKEN = 65535; namespace apache { namespace geode { namespace statistics { class HostStatSampler; using apache::geode::client::CacheImpl; using apache::geode::client::DataOutput; using std::chrono::steady_clock; using std::chrono::system_clock; /** * Some of the classes which are used by the StatArchiveWriter Class * 1. StatDataOutput // Just a wrapper around DataOutput so that the number of * // bytes written is incremented automatically. * 2. ResourceType // The ResourceType and the ResourceInst class is used * 3. ResourceInst // by the StatArchiveWriter class for keeping track of * // of the Statistics object and the value of the * // descriptors in the previous sample run. */ class StatDataOutput { public: explicit StatDataOutput(CacheImpl *cache); StatDataOutput(std::string, CacheImpl *cache); ~StatDataOutput(); /** * Returns the number of bytes written into the buffer so far. * This does not takes the compression into account. */ int64_t getBytesWritten(); /** * Writes the buffer into the outfile. */ void flush(); /** * Writes the buffer into the outfile and sets bytesWritten to zero. */ void resetBuffer(); /** * Writes 8 bit integer value in the buffer. */ void writeByte(int8_t v); /** * Writes boolean value in the buffer. * Nothing but an int8. */ void writeBoolean(int8_t v); /** * Writes 16 bit integer value in the buffer. */ void writeShort(int16_t v); /** * Writes Long value 32 bit in the buffer. */ void writeInt(int32_t v); /** * Writes Double value 64 bit in the buffer. */ void writeLong(int64_t v); /** * Writes string value in the buffer. */ void writeUTF(std::string v); /** * This method is for the unit tests only for this class. */ const uint8_t *getBuffer(); void close(); void openFile(std::string, int64_t); private: int64_t bytesWritten; std::unique_ptr<DataOutput> dataBuffer; std::string outFile; FILE *m_fp; bool closed; friend class StatArchiveWriter; }; class ResourceType { public: ResourceType(int32_t id, const StatisticsType *type); ResourceType(const ResourceType &) = delete; ResourceType &operator=(const ResourceType &) = delete; int32_t getId() const; const std::vector<std::shared_ptr<StatisticDescriptor>> &getStats() const; size_t getNumOfDescriptors() const; private: int32_t id; const StatisticsType *type; }; class ResourceInst { public: ResourceInst(int32_t id, Statistics *, const ResourceType *, StatDataOutput *); ResourceInst(const ResourceInst &) = delete; ResourceInst &operator=(const ResourceInst &) = delete; ~ResourceInst(); int32_t getId(); Statistics *getResource(); const ResourceType *getType() const; int64_t getStatValue(std::shared_ptr<StatisticDescriptor> f); void writeSample(); void writeStatValue(std::shared_ptr<StatisticDescriptor> s, int64_t v); void writeCompactValue(int64_t v); void writeResourceInst(StatDataOutput *, int32_t); private: int32_t id; Statistics *resource; const ResourceType *type; /* This will contain the previous values of the descriptors */ int64_t *archivedStatValues; StatDataOutput *dataOut; /* To know whether the instance has come for the first time */ bool firstTime = true; }; class HostStatSampler; class StatArchiveWriter { HostStatSampler *sampler_; StatDataOutput *dataBuffer_; CacheImpl *cache_; steady_clock::time_point previousTimeStamp_; int32_t resourceTypeId_; int32_t resourceInstId_; size_t bytesWrittenToFile_; size_t sampleSize_; std::string archiveFile_; std::map<Statistics *, std::shared_ptr<ResourceInst>> resourceInstMap_; std::map<const StatisticsType *, const ResourceType *> resourceTypeMap_; void allocateResourceInst(Statistics *r); void sampleResources(); void resampleResources(); void writeResourceInst(StatDataOutput *, int32_t); void writeTimeStamp(const steady_clock::time_point &timeStamp); void writeStatValue(std::shared_ptr<StatisticDescriptor> f, int64_t v, DataOutput dataOut); const ResourceType *getResourceType(const Statistics *); bool resourceInstMapHas(Statistics *sp); public: StatArchiveWriter(std::string archiveName, HostStatSampler *sampler, CacheImpl *cache); ~StatArchiveWriter(); /** * Returns the number of bytes written so far to this archive. * This does not take compression into account. */ size_t bytesWritten(); /** * Archives a sample snapshot at the given timeStamp. * @param timeStamp a value obtained using NanoTimer::now. */ void sample(const steady_clock::time_point &timeStamp); /** * Archives a sample snapshot at the current time. */ void sample(); /** * Closes the statArchiver by flushing its data to disk and closing its * output stream. */ void close(); /** * Closes the statArchiver by closing its output stream. */ void closeFile(); /** * Opens the statArchiver by opening the file provided as a parameter. * @param filename string representation of the file name */ void openFile(std::string filename); /** * Returns the size of number of bytes written so far to this archive. */ size_t getSampleSize(); /** * Flushes the contents of the dataBuffer to the archiveFile */ void flush(); }; } // namespace statistics } // namespace geode } // namespace apache #endif // GEODE_STATISTICS_STATARCHIVEWRITER_H_
30.082677
78
0.729747
[ "object", "vector" ]
f3c712e2365fac72997700b38de29ee96580b163
2,708
cpp
C++
Agreste-Game-Engine/Agreste-Game-Engine/Cubemap.cpp
Joimar/Agreste-Game-Engine
a8b1f1d0e4e7d3fd7c7e57081158ca7505d8e6c0
[ "MIT" ]
null
null
null
Agreste-Game-Engine/Agreste-Game-Engine/Cubemap.cpp
Joimar/Agreste-Game-Engine
a8b1f1d0e4e7d3fd7c7e57081158ca7505d8e6c0
[ "MIT" ]
null
null
null
Agreste-Game-Engine/Agreste-Game-Engine/Cubemap.cpp
Joimar/Agreste-Game-Engine
a8b1f1d0e4e7d3fd7c7e57081158ca7505d8e6c0
[ "MIT" ]
null
null
null
#include "Cubemap.h" Cubemap::Cubemap(std::string path): textureID(0), shader("skybox.vs", "skybox.fs") { std::vector<std::string> faces = getFacePaths(path); loadCubeMap(faces); // skybox VAO glGenVertexArrays(1, &skyboxVAO); glGenBuffers(1, &skyboxVBO); glBindVertexArray(skyboxVAO); glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(this->skyBoxVertices), &skyBoxVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); } void Cubemap::draw(glm::mat4 View, glm::mat4 Projection) { // draw skybox as last glDepthFunc(GL_LEQUAL); // change depth function so depth test passes when values are equal to depth buffer's content this->shader.Use(); shader.setMat4("view", View); shader.setMat4("projection", Projection); // skybox cube glBindVertexArray(skyboxVAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glDepthFunc(GL_LESS); // set depth function back to default } std::vector<std::string> Cubemap::getFacePaths(std::string path) { std::vector<std::string> aux; for (const auto & entry : fs::directory_iterator(path)) { aux.push_back(entry.path().string()); } return aux; } unsigned int Cubemap::getTextureID() { return textureID; } unsigned int Cubemap::getSkyboxVAO() { return skyboxVAO; } unsigned int Cubemap::getSkyboxVBO() { return skyboxVBO; } void Cubemap::setTextureID(unsigned int texId) { textureID = texId; } void Cubemap::setSkyboxVAO(unsigned int vaoId) { skyboxVAO = vaoId; } void Cubemap::setSkyboxVBO(unsigned int vboId) { skyboxVBO = vboId; } void Cubemap::loadCubeMap(std::vector<std::string> faces) { glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); int width, height, nrComponents; for (unsigned int i = 0; i < faces.size(); i++) { unsigned char *data = SOIL_load_image(faces[i].c_str(), &width, &height, &nrComponents, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); SOIL_free_image_data(data); } else { std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl; SOIL_free_image_data(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); }
26.038462
119
0.747046
[ "vector" ]
f3cdc003b211e3a11b07caa2c395bf983510e76c
7,707
cpp
C++
hphp/runtime/vm/jit/call-target-profile.cpp
ritikagrawat/hhvm
4f18db152aeea6c380c877f38fc99778a5511008
[ "PHP-3.01", "Zend-2.0" ]
1
2019-11-01T13:46:07.000Z
2019-11-01T13:46:07.000Z
hphp/runtime/vm/jit/call-target-profile.cpp
ritikagrawat/hhvm
4f18db152aeea6c380c877f38fc99778a5511008
[ "PHP-3.01", "Zend-2.0" ]
2
2020-10-11T22:54:12.000Z
2021-07-20T22:12:10.000Z
hphp/runtime/vm/jit/call-target-profile.cpp
ritikagrawat/hhvm
4f18db152aeea6c380c877f38fc99778a5511008
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/jit/call-target-profile.h" #include "hphp/runtime/base/runtime-option.h" #include "hphp/runtime/vm/func.h" #include "hphp/runtime/vm/jit/prof-data-serialize.h" #include "hphp/util/trace.h" #include <cstring> #include <sstream> namespace HPHP { namespace jit { TRACE_SET_MOD(irlower); /////////////////////////////////////////////////////////////////////////////// const size_t CallTargetProfile::kMaxEntries; void CallTargetProfile::init() { if (m_init) return; m_init = true; for (size_t i = 0; i < kMaxEntries; i++) { m_entries[i] = Entry{}; } } void CallTargetProfile::report(const Func* func) { assertx(func); auto const funcId = func->getFuncId(); FTRACE(5, "CallTargetProfile::report: funcId {} ({})\n", funcId, func->fullName()); init(); size_t i = 0; for (; i < kMaxEntries; i++) { auto& entry = m_entries[i]; if (entry.funcId == InvalidFuncId) { entry.funcId = funcId; entry.count = 1; return; } if (entry.funcId == funcId) { entry.count++; return; } } m_untracked++; } void CallTargetProfile::reduce(CallTargetProfile& profile, const CallTargetProfile& other) { Entry allEntries[kMaxEntries * 2]; size_t nEntries = 0; if (profile.m_init) { // Copy into `allEntries' all the valid entries from `profile'. for (size_t i = 0; i < kMaxEntries; i++) { auto const& entry = profile.m_entries[i]; if (entry.funcId == InvalidFuncId) break; allEntries[nEntries++] = entry; } } if (other.m_init) { // Handle the entries from `other', either by adding to matching entries // from `profile' or by adding new entries to `allEntries'. for (size_t o = 0; o < kMaxEntries; o++) { auto const& otherEntry = other.m_entries[o]; if (otherEntry.funcId == InvalidFuncId) break; size_t p = 0; for (; p < kMaxEntries; p++) { auto& entry = allEntries[p]; if (entry.funcId == otherEntry.funcId) { entry.count += otherEntry.count; break; } } if (p == kMaxEntries) { // Didn't find `otherEntry' among the entries from `profile', so add a // new entry. allEntries[nEntries++] = otherEntry; } } } profile.m_init |= other.m_init; if (!profile.m_init) return; // Sort the entries in `allEntries' and select the top kMaxEntries. The rest // is put in m_untracked. std::sort(allEntries, allEntries + nEntries, [&] (const Entry& a, const Entry& b) { // Sort in decreasing order of `count' while keeping invalid // entries at the end. if (b.funcId == InvalidFuncId) return a.funcId != InvalidFuncId; if (a.funcId == InvalidFuncId) return false; return a.count > b.count; }); auto const nEntriesToCopy = std::min(kMaxEntries, nEntries); memcpy(profile.m_entries, allEntries, nEntriesToCopy * sizeof(Entry)); // Update `profile's untracked count. profile.m_untracked += other.m_untracked; for (size_t i = kMaxEntries; i < nEntries; i++) { auto const& entry = allEntries[i]; if (entry.funcId == InvalidFuncId) break; profile.m_untracked += entry.count; } } const Func* CallTargetProfile::choose(double& probability) const { if (!m_init) { probability = 0; return nullptr; } assertx(m_entries[0].funcId != InvalidFuncId); FTRACE(3, "CallTargetProfile::choose(): {}\n", *this); size_t bestIdx = 0; uint64_t total = m_untracked + m_entries[0].count; for (size_t i = 1; i < kMaxEntries ; i++) { auto const& entry = m_entries[i]; if (entry.funcId == InvalidFuncId) break; total += entry.count; if (entry.count > m_entries[bestIdx].count) { bestIdx = i; } } auto const& best = m_entries[bestIdx]; auto bestFunc = Func::fromFuncId(best.funcId); probability = (double)best.count / total; FTRACE(2, "CallTargetProfile::choose(): best funcId {} ({}), " "probability = {:.2}\n", best.funcId, bestFunc->fullName(), probability); return bestFunc; } std::string CallTargetProfile::toString() const { if (!m_init) return std::string("uninitialized"); std::ostringstream out; uint64_t total = m_untracked; for (auto const& entry : m_entries) { if (entry.funcId != InvalidFuncId) { total += entry.count; } } for (auto const& entry : m_entries) { if (entry.funcId != InvalidFuncId) { out << folly::format("FuncId {}: {} ({:.1f}%), ", entry.funcId, entry.count, total == 0 ? 0 : 100.0 * entry.count / total); } } out << folly::format("Untracked: {} ({:.1f}%)", m_untracked, total == 0 ? 0 : 100.0 * m_untracked / total); return out.str(); } folly::dynamic CallTargetProfile::toDynamic() const { using folly::dynamic; if (!m_init) return dynamic(); uint64_t total = m_untracked; for (auto const& entry : m_entries) { if (entry.funcId != InvalidFuncId) { total += entry.count; } } dynamic entries = dynamic::array; for (auto const& entry : m_entries) { if (entry.funcId != InvalidFuncId) { auto percent = total == 0 ? 0 : 100.0 * entry.count / total; entries.push_back(dynamic::object("funcId", entry.funcId) ("count", entry.count) ("percent", percent)); } } auto percent = total == 0 ? 0 : 100.0 * m_untracked / total; dynamic untracked = dynamic::object("count", m_untracked) ("percent", percent); return dynamic::object("entries", entries) ("untracked", untracked) ("total", total) ("profileType", "CallTargetProfile"); } void CallTargetProfile::serialize(ProfDataSerializer& ser) const { for (size_t i = 0; i < kMaxEntries; i++) { auto const funcId = m_entries[i].funcId; const Func* func = funcId == kInvalidId ? nullptr : Func::fromFuncId(funcId); write_func(ser, func); write_raw(ser, m_entries[i].count); } write_raw(ser, m_untracked); write_raw(ser, m_init); } void CallTargetProfile::deserialize(ProfDataDeserializer& ser) { for (size_t i = 0; i < kMaxEntries; i++) { auto const func = read_func(ser); m_entries[i].funcId = func != nullptr ? func->getFuncId() : kInvalidId; read_raw(ser, m_entries[i].count); } read_raw(ser, m_untracked); read_raw(ser, m_init); } /////////////////////////////////////////////////////////////////////////////// }}
32.518987
79
0.557675
[ "object" ]
f3cefbf239a18d7b282bc455b41d4af77008bc2e
1,415
hpp
C++
src/libpanacea/attribute_manipulators/reducer.hpp
lanl/PANACEA
9779bdb6dcc3be41ea7b286ae55a21bb269e0339
[ "BSD-3-Clause" ]
null
null
null
src/libpanacea/attribute_manipulators/reducer.hpp
lanl/PANACEA
9779bdb6dcc3be41ea7b286ae55a21bb269e0339
[ "BSD-3-Clause" ]
null
null
null
src/libpanacea/attribute_manipulators/reducer.hpp
lanl/PANACEA
9779bdb6dcc3be41ea7b286ae55a21bb269e0339
[ "BSD-3-Clause" ]
null
null
null
#ifndef PANACEA_PRIVATE_REDUCER_H #define PANACEA_PRIVATE_REDUCER_H #pragma once // Local private PANACEA includes #include "attributes/covariance.hpp" #include "attributes/dimensions.hpp" #include "attributes/reduced_covariance.hpp" // Standard includes #include <vector> namespace panacea { class Reducer { private: /* * The starting theshold is used to determine when linear dependence is * occuring. The lower this value is the less likely that linear dependence * will be detected, initially. However, the threshold is iteratively * increased until the determinant is > 0. */ double starting_threshold_ = 1E-9; public: Reducer() = default; explicit Reducer(double threshold) : starting_threshold_(threshold){}; /** * @brief Designed to reduce/rearrange the covariance matrix * * Sometimes it is impossible to create the inverse of a covariance * matrix, e.g. if the matrix has linearly dependent terms. * * The purpose of the Reducer class is to eliminate dimensions that lead * to linear dependence while prioritizing the dimensions as they are * passed in with the preferred_dimensions argument. * * @param cov * @param preferred_dimensions * * @return */ ReducedCovariance reduce(const Covariance &cov, Dimensions preferred_dimensions) const; }; } // namespace panacea #endif // PANACEA_PRIVATE_REDUCER_H
28.877551
77
0.732862
[ "vector" ]
f3d1debd80dc51497309a08ed2b840f7112f2f32
1,948
hpp
C++
src/realm/object-store/util/generic/scheduler.hpp
aleyooop/realm-core
9874d5164927ea39273b241a5af14b596a3233e9
[ "Apache-2.0" ]
null
null
null
src/realm/object-store/util/generic/scheduler.hpp
aleyooop/realm-core
9874d5164927ea39273b241a5af14b596a3233e9
[ "Apache-2.0" ]
null
null
null
src/realm/object-store/util/generic/scheduler.hpp
aleyooop/realm-core
9874d5164927ea39273b241a5af14b596a3233e9
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include <thread> #include <realm/object-store/util/scheduler.hpp> namespace realm::util { class GenericScheduler : public realm::util::Scheduler { public: GenericScheduler() = default; bool is_on_thread() const noexcept override { return m_id == std::this_thread::get_id(); } bool is_same_as(const Scheduler* other) const noexcept override { auto o = dynamic_cast<const GenericScheduler*>(other); return (o && (o->m_id == m_id)); } bool can_deliver_notifications() const noexcept override { return false; } void set_notify_callback(std::function<void()>) override {} void notify() override {} void schedule_writes() override {} void schedule_completions() override {} bool can_schedule_writes() const noexcept override { return false; } bool can_schedule_completions() const noexcept override { return false; } void set_schedule_writes_callback(util::UniqueFunction<void()>) override {} void set_schedule_completions_callback(util::UniqueFunction<void()>) override {} private: std::thread::id m_id = std::this_thread::get_id(); }; } // namespace realm::util
31.934426
84
0.64117
[ "object" ]
f3e080dd79ffc7d340ccfe79429d9fbdb9e538d9
54,089
cpp
C++
Source/V2World/V2World.cpp
Zemurin/EU3ToVic2
7df6de2039986ed46683d792ec0c72bbdf6a2f18
[ "MIT" ]
2
2020-03-29T02:03:42.000Z
2020-03-29T08:53:57.000Z
Source/V2World/V2World.cpp
klorpa/EU3ToVic2
7df6de2039986ed46683d792ec0c72bbdf6a2f18
[ "MIT" ]
null
null
null
Source/V2World/V2World.cpp
klorpa/EU3ToVic2
7df6de2039986ed46683d792ec0c72bbdf6a2f18
[ "MIT" ]
3
2020-03-28T21:17:58.000Z
2022-01-11T00:04:25.000Z
/*Copyright (c) 2014 The Paradox Game Converters Project 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.*/ #define WIN32_LEAN_AND_MEAN #include "V2World.h" #include <Windows.h> #include <fstream> #include <algorithm> #include <io.h> #include <list> #include <queue> #include <cmath> #include <cfloat> #include <sys/stat.h> #include "../Parsers/Parser.h" #include "../Log.h" #include "../Mapper.h" #include "../Configuration.h" #include "../WinUtils.h" #include "../EU3World/EU3World.h" #include "../EU3World/EU3Relations.h" #include "../EU3World/EU3Loan.h" #include "../EU3World/EU3Leader.h" #include "../EU3World/EU3Province.h" #include "../EU3World/EU3Diplomacy.h" #include "V2Province.h" #include "V2State.h" #include "V2Relations.h" #include "V2Army.h" #include "V2Leader.h" #include "V2Pop.h" #include "V2Country.h" #include "V2Reforms.h" #include "V2Flags.h" #include "V2LeaderTraits.h" typedef struct fileWithCreateTime { string filename; time_t createTime; bool operator < (const fileWithCreateTime &rhs) const { return createTime < rhs.createTime; }; } fileWithCreateTime; V2World::V2World(vector<pair<string, string>> minorities) { struct _finddata_t provinceFileData; intptr_t fileListing = NULL; list<string> directories; directories.push_back(""); struct _stat st; while (directories.size() > 0) { if ((fileListing = _findfirst((Configuration::getV2Path() + "\\history\\provinces" + directories.front() + "\\*.*").c_str(), &provinceFileData)) == -1L) { LOG(LogLevel::Error) << "Could not open directory " << Configuration::getV2Path() << "\\history\\provinces" << directories.front() << "\\*.*"; exit(-1); } do { if (strcmp(provinceFileData.name, ".") == 0 || strcmp(provinceFileData.name, "..") == 0) { continue; } if (provinceFileData.attrib & _A_SUBDIR) { string newDirectory = directories.front() + "\\" + provinceFileData.name; directories.push_back(newDirectory); } else { V2Province* newProvince = new V2Province(directories.front() + "\\" + provinceFileData.name); provinces.insert(make_pair(newProvince->getNum(), newProvince)); } } while (_findnext(fileListing, &provinceFileData) == 0); _findclose(fileListing); directories.pop_front(); } // Get province names if (_stat(".\\blankMod\\output\\localisation\\text.csv", &st) == 0) { getProvinceLocalizations(".\\blankMod\\output\\localisation\\text.csv"); } else { getProvinceLocalizations((Configuration::getV2Path() + "\\localisation\\text.csv")); } // set V2 basic population levels LOG(LogLevel::Info) << "Importing historical pops."; //map< string, map<string, long int> > countryPops; // country, poptype, num totalWorldPopulation = 0; set<string> fileNames; WinUtils::GetAllFilesInFolder(".\\blankMod\\output\\history\\pops\\1836.1.1\\", fileNames); for (set<string>::iterator itr = fileNames.begin(); itr != fileNames.end(); itr++) { list<int>* popProvinces = new list<int>; Object* obj2 = doParseFile((".\\blankMod\\output\\history\\pops\\1836.1.1\\" + *itr).c_str()); // generic object vector<Object*> leaves = obj2->getLeaves(); for (unsigned int j = 0; j < leaves.size(); j++) { int provNum = atoi(leaves[j]->getKey().c_str()); map<int, V2Province*>::iterator k = provinces.find(provNum); if (k == provinces.end()) { LOG(LogLevel::Warning) << "Could not find province " << provNum << " for original pops."; continue; } else { /*auto countryPopItr = countryPops.find(k->second->getOwner()); if (countryPopItr == countryPops.end()) { map<string, long int> newCountryPop; pair<map< string, map<string, long int> >::iterator, bool> newIterator = countryPops.insert(make_pair(k->second->getOwner(), newCountryPop)); countryPopItr = newIterator.first; }*/ int provincePopulation = 0; int provinceSlavePopulation = 0; popProvinces->push_back(provNum); vector<Object*> pops = leaves[j]->getLeaves(); for(unsigned int l = 0; l < pops.size(); l++) { string popType = pops[l]->getKey(); int popSize = atoi(pops[l]->getLeaf("size").c_str()); string popCulture = pops[l]->getLeaf("culture"); string popReligion = pops[l]->getLeaf("religion"); /*auto popItr = countryPopItr->second.find(pops[l]->getKey()); if (popItr == countryPopItr->second.end()) { long int newPopSize = 0; pair<map<string, long int>::iterator, bool> newIterator = countryPopItr->second.insert(make_pair(popType, newPopSize)); popItr = newIterator.first; } popItr->second += popSize;*/ totalWorldPopulation += popSize; V2Pop* newPop = new V2Pop(popType, popSize, popCulture, popReligion); k->second->addOldPop(newPop); for (auto minorityItr : minorities) { if ((popCulture == minorityItr.first) && (popReligion == minorityItr.second)) { k->second->addMinorityPop(newPop); break; } else if ((minorityItr.first == "") && (popReligion == minorityItr.second)) { newPop->setCulture(""); k->second->addMinorityPop(newPop); break; } else if ((popCulture == minorityItr.first) && (minorityItr.second == "")) { newPop->setReligion(""); k->second->addMinorityPop(newPop); break; } } if ((popType == "slaves") || (popCulture.substr(0, 4) == "afro")) { provinceSlavePopulation += popSize; } provincePopulation += popSize; } auto province = provinces.find(provNum); if (province != provinces.end()) { province->second->setSlaveProportion( 1.0 * provinceSlavePopulation / provincePopulation); } } popRegions.insert( make_pair(*itr, popProvinces) ); } } WinUtils::GetAllFilesInFolder(Configuration::getV2Path() + "\\history\\pops\\1836.1.1\\", fileNames); for (set<string>::iterator itr = fileNames.begin(); itr != fileNames.end(); itr++) { auto duplicateCheck = popRegions.find(*itr); if (duplicateCheck != popRegions.end()) { continue; } list<int>* popProvinces = new list<int>; Object* obj2 = doParseFile((Configuration::getV2Path() + "\\history\\pops\\1836.1.1\\" + *itr).c_str()); // generic object vector<Object*> leaves = obj2->getLeaves(); for (unsigned int j = 0; j < leaves.size(); j++) { int provNum = atoi(leaves[j]->getKey().c_str()); map<int, V2Province*>::iterator k = provinces.find(provNum); if (k == provinces.end()) { LOG(LogLevel::Warning) << "Could not find province " << provNum << " for original pops."; continue; } else { /*auto countryPopItr = countryPops.find(k->second->getOwner()); if (countryPopItr == countryPops.end()) { map<string, long int> newCountryPop; pair<map< string, map<string, long int> >::iterator, bool> newIterator = countryPops.insert(make_pair(k->second->getOwner(), newCountryPop)); countryPopItr = newIterator.first; }*/ int provincePopulation = 0; int provinceSlavePopulation = 0; popProvinces->push_back(provNum); vector<Object*> pops = leaves[j]->getLeaves(); for(unsigned int l = 0; l < pops.size(); l++) { string popType = pops[l]->getKey(); int popSize = atoi(pops[l]->getLeaf("size").c_str()); string popCulture = pops[l]->getLeaf("culture"); string popReligion = pops[l]->getLeaf("religion"); /*auto popItr = countryPopItr->second.find(pops[l]->getKey()); if (popItr == countryPopItr->second.end()) { long int newPopSize = 0; pair<map<string, long int>::iterator, bool> newIterator = countryPopItr->second.insert(make_pair(popType, newPopSize)); popItr = newIterator.first; } popItr->second += popSize;*/ totalWorldPopulation += popSize; V2Pop* newPop = new V2Pop(popType, popSize, popCulture, popReligion); k->second->addOldPop(newPop); for (auto minorityItr : minorities) { if ((popCulture == minorityItr.first) && (popReligion == minorityItr.second)) { k->second->addMinorityPop(newPop); break; } else if ((minorityItr.first == "") && (popReligion == minorityItr.second)) { newPop->setCulture(""); k->second->addMinorityPop(newPop); break; } else if ((popCulture == minorityItr.first) && (minorityItr.second == "")) { newPop->setReligion(""); k->second->addMinorityPop(newPop); break; } } if ((popType == "slaves") || (popCulture.substr(0, 4) == "afro")) { provinceSlavePopulation += popSize; } provincePopulation += popSize; } auto province = provinces.find(provNum); if (province != provinces.end()) { province->second->setSlaveProportion( 1.0 * provinceSlavePopulation / provincePopulation); } } popRegions.insert( make_pair(*itr, popProvinces) ); } } /*for (auto countryItr = countryPops.begin(); countryItr != countryPops.end(); countryItr++) { long int total = 0; for (auto popsItr = countryItr->second.begin(); popsItr != countryItr->second.end(); popsItr++) { total += popsItr->second; } for (auto popsItr = countryItr->second.begin(); popsItr != countryItr->second.end(); popsItr++) { LOG(LogLevel::Info) << "," << countryItr->first << "," << popsItr->first << "," << popsItr->second << "," << (double)popsItr->second / total; } LOG(LogLevel::Info) << "," << countryItr->first << "," << "Total," << total << "," << (double)total/total; }*/ // determine whether a province is coastal or not by checking if it has a naval base // if it's not coastal, we won't try to put any navies in it (otherwise Vicky crashes) LOG(LogLevel::Info) << "Finding coastal provinces."; Object* obj2 = doParseFile((Configuration::getV2Path() + "\\map\\positions.txt").c_str()); if (obj2 == NULL) { LOG(LogLevel::Error) << "Could not parse file " << Configuration::getV2Path() << "\\map\\positions.txt"; exit(-1); } vector<Object*> objProv = obj2->getLeaves(); if (objProv.size() == 0) { LOG(LogLevel::Error) << "map\\positions.txt failed to parse."; exit(1); } for (vector<Object*>::iterator itr = objProv.begin(); itr != objProv.end(); ++itr) { int provinceNum = atoi((*itr)->getKey().c_str()); vector<Object*> objPos = (*itr)->getValue("building_position"); if (objPos.size() == 0) { continue; } vector<Object*> objNavalBase = objPos[0]->getValue("naval_base"); if (objNavalBase.size() != 0) { // this province is coastal for (map<int, V2Province*>::iterator pitr = provinces.begin(); pitr != provinces.end(); ++pitr) { if ( pitr->first == provinceNum) { pitr->second->setCoastal(true); break; } } } } countries.clear(); LOG(LogLevel::Info) << "Getting potential countries"; potentialCountries.clear(); dynamicCountries.clear(); const date FirstStartDate = date("1836.1.1"); ifstream V2CountriesInput; if (_stat(".\\blankMod\\output\\common\\countries.txt", &st) == 0) { V2CountriesInput.open(".\\blankMod\\output\\common\\countries.txt"); } else { V2CountriesInput.open((Configuration::getV2Path() + "\\common\\countries.txt").c_str()); } if (!V2CountriesInput.is_open()) { LOG(LogLevel::Error) << "Could not open countries.txt"; exit(1); } bool staticSection = true; while (!V2CountriesInput.eof()) { string line; getline(V2CountriesInput, line); if ( (line[0] == '#') || (line.size() < 3) ) { continue; } else if (line.substr(0,12) == "dynamic_tags") { staticSection = false; continue; } string tag; tag = line.substr(0, 3); string countryFileName; int start = line.find_first_of('/'); int size = line.find_last_of('\"') - start; countryFileName = line.substr(start, size); Object* countryData; if (_stat((string(".\\blankMod\\output\\common\\countries\\") + countryFileName).c_str(), &st) == 0) { countryData = doParseFile((string(".\\blankMod\\output\\common\\countries\\") + countryFileName).c_str()); if (countryData == NULL) { LOG(LogLevel::Warning) << "Could not parse file .\\blankMod\\output\\common\\countries\\" << countryFileName; } } else if (_stat((Configuration::getV2Path() + "\\common\\countries\\" + countryFileName).c_str(), &st) == 0) { countryData = doParseFile((Configuration::getV2Path() + "\\common\\countries\\" + countryFileName).c_str()); if (countryData == NULL) { LOG(LogLevel::Warning) << "Could not parse file " << Configuration::getV2Path() << "\\common\\countries\\" << countryFileName; } } else { LOG(LogLevel::Debug) << "Could not find file common\\countries\\" << countryFileName << " - skipping"; continue; } vector<Object*> partyData = countryData->getValue("party"); vector<V2Party*> localParties; for (vector<Object*>::iterator itr = partyData.begin(); itr != partyData.end(); ++itr) { V2Party* newParty = new V2Party(*itr); localParties.push_back(newParty); } V2Country* newCountry = new V2Country(tag, countryFileName, localParties, this, false, !staticSection); if (staticSection) { potentialCountries.push_back(newCountry); } else { potentialCountries.push_back(newCountry); dynamicCountries.insert( make_pair(tag, newCountry) ); } } V2CountriesInput.close(); colonies.clear(); } void V2World::output() const { // Create common\countries path. string countriesPath = "Output\\" + Configuration::getOutputName() + "\\common\\countries"; if (!WinUtils::TryCreateFolder(countriesPath)) { return; } // Output common\countries.txt LOG(LogLevel::Debug) << "Writing countries file"; FILE* allCountriesFile; if (fopen_s(&allCountriesFile, ("Output\\" + Configuration::getOutputName() + "\\common\\countries.txt").c_str(), "w") != 0) { LOG(LogLevel::Error) << "Could not create countries file"; exit(-1); } for (map<string, V2Country*>::const_iterator i = countries.begin(); i != countries.end(); i++) { const V2Country& country = *i->second; map<string, V2Country*>::const_iterator j = dynamicCountries.find(country.getTag()); if (j == dynamicCountries.end()) { country.outputToCommonCountriesFile(allCountriesFile); } } fprintf(allCountriesFile, "\n"); if ((Configuration::getV2Gametype() == "HOD") || (Configuration::getV2Gametype() == "HoD_NNM")) { fprintf(allCountriesFile, "##HoD Dominions\n"); fprintf(allCountriesFile, "dynamic_tags = yes # any tags after this is considered dynamic dominions\n"); for (map<string, V2Country*>::const_iterator i = dynamicCountries.begin(); i != dynamicCountries.end(); i++) { i->second->outputToCommonCountriesFile(allCountriesFile); } } fclose(allCountriesFile); // Create flags for all new countries. V2Flags flags; flags.SetV2Tags(countries); flags.Output(); // Create localisations for all new countries. We don't actually know the names yet so we just use the tags as the names. LOG(LogLevel::Debug) << "Writing localisation text"; string localisationPath = "Output\\" + Configuration::getOutputName() + "\\localisation"; if (!WinUtils::TryCreateFolder(localisationPath)) { return; } string source = Configuration::getV2Path() + "\\localisation\\text.csv"; string dest = localisationPath + "\\text.csv"; WinUtils::TryCopyFile(source, dest); FILE* localisationFile; if (fopen_s(&localisationFile, dest.c_str(), "a") != 0) { LOG(LogLevel::Error) << "Could not update localisation text file"; exit(-1); } for (map<string, V2Country*>::const_iterator i = countries.begin(); i != countries.end(); i++) { const V2Country& country = *i->second; if (country.isNewCountry()) { country.outputLocalisation(localisationFile); } } fclose(localisationFile); LOG(LogLevel::Debug) << "Writing provinces"; for (map<int, V2Province*>::const_iterator i = provinces.begin(); i != provinces.end(); i++) { i->second->output(); } LOG(LogLevel::Debug) << "Writing countries"; for (auto itr = countries.begin(); itr != countries.end(); itr++) { itr->second->output(); } diplomacy.output(); outputPops(); // verify countries got written ifstream V2CountriesInput; V2CountriesInput.open(("Output\\" + Configuration::getOutputName() + "\\common\\countries.txt").c_str()); if (!V2CountriesInput.is_open()) { LOG(LogLevel::Error) << "Could not open countries.txt"; exit(1); } bool staticSection = true; while (!V2CountriesInput.eof()) { string line; getline(V2CountriesInput, line); if ((line[0] == '#') || (line.size() < 3)) { continue; } else if (line.substr(0, 12) == "dynamic_tags") { continue; } string countryFileName; int start = line.find_first_of('/'); int size = line.find_last_of('\"') - start - 1; countryFileName = line.substr(start + 1, size); struct _stat st; if (_stat(("Output\\" + Configuration::getOutputName() + "\\common\\countries\\" + countryFileName).c_str(), &st) == 0) { } else if (_stat((Configuration::getV2Path() + "\\common\\countries\\" + countryFileName).c_str(), &st) == 0) { } else { LOG(LogLevel::Warning) << "common\\countries\\" << countryFileName << " does not exists. This will likely crash Victoria 2."; continue; } } V2CountriesInput.close(); } void V2World::outputPops() const { LOG(LogLevel::Debug) << "Writing pops"; for (map<string, list<int>* >::const_iterator itr = popRegions.begin(); itr != popRegions.end(); itr++) { FILE* popsFile; if (fopen_s(&popsFile, ("Output\\" + Configuration::getOutputName() + "\\history\\pops\\1836.1.1\\" + itr->first).c_str(), "w") != 0) { LOG(LogLevel::Error) << "Could not create pops file Output\\" << Configuration::getOutputName() << "\\history\\pops\\1836.1.1\\" << itr->first; exit(-1); } for (list<int>::const_iterator provNumItr = itr->second->begin(); provNumItr != itr->second->end(); provNumItr++) { map<int, V2Province*>::const_iterator provItr = provinces.find(*provNumItr); if (provItr != provinces.end()) { provItr->second->outputPops(popsFile); } else { LOG(LogLevel::Error) << "Could not find province " << *provNumItr << " while outputing pops!"; } } delete itr->second; } } bool scoresSorter(pair<V2Country*, int> first, pair<V2Country*, int> second) { return (first.second > second.second); } void V2World::convertCountries(const EU3World& sourceWorld, const CountryMapping& countryMap, const cultureMapping& cultureMap, const unionCulturesMap& unionCultures, const religionMapping& religionMap, const governmentMapping& governmentMap, const inverseProvinceMapping& inverseProvinceMap, const vector<techSchool>& techSchools, map<int, int>& leaderMap, const V2LeaderTraits& lt, const EU3RegionsMapping& regionsMap) { vector<string> outputOrder; outputOrder.clear(); for (unsigned int i = 0; i < potentialCountries.size(); i++) { outputOrder.push_back(potentialCountries[i]->getTag()); } map<string, EU3Country*> sourceCountries = sourceWorld.getCountries(); for (map<string, EU3Country*>::iterator i = sourceCountries.begin(); i != sourceCountries.end(); i++) { EU3Country* sourceCountry = i->second; std::string EU3Tag = sourceCountry->getTag(); V2Country* destCountry = NULL; const std::string& V2Tag = countryMap[EU3Tag]; if (!V2Tag.empty()) { for (vector<V2Country*>::iterator j = potentialCountries.begin(); j != potentialCountries.end() && !destCountry; j++) { V2Country* candidateDestCountry = *j; if (candidateDestCountry->getTag() == V2Tag) { destCountry = candidateDestCountry; } } if (!destCountry) { // No such V2 country exists yet for this tag so we make a new one. std::string countryFileName = '/' + sourceCountry->getName() + ".txt"; destCountry = new V2Country(V2Tag, countryFileName, std::vector<V2Party*>(), this, true, false); } destCountry->initFromEU3Country(sourceCountry, outputOrder, countryMap, cultureMap, religionMap, unionCultures, governmentMap, inverseProvinceMap, techSchools, leaderMap, lt, regionsMap); countries.insert(make_pair(V2Tag, destCountry)); } else { LOG(LogLevel::Warning) << "Could not convert EU3 tag " << i->second->getTag() << " to V2"; } } // set national values list< pair<V2Country*, int> > libertyScores; list< pair<V2Country*, int> > equalityScores; set<V2Country*> valuesUnset; for (map<string, V2Country*>::iterator countryItr = countries.begin(); countryItr != countries.end(); countryItr++) { int libertyScore = 1; int equalityScore = 1; int orderScore = 1; countryItr->second->getNationalValueScores(libertyScore, equalityScore, orderScore); if (libertyScore > orderScore) { libertyScores.push_back(make_pair(countryItr->second, libertyScore)); } if ((equalityScore > orderScore) && (equalityScore > libertyScore)) { equalityScores.push_back(make_pair(countryItr->second, equalityScore)); } valuesUnset.insert(countryItr->second); LOG(LogLevel::Debug) << "Value scores for " << countryItr->first << ": order = " << orderScore << ", liberty = " << libertyScore << ", equality = " << equalityScore; } equalityScores.sort(scoresSorter); int equalityLeft = 5; for (list< pair<V2Country*, int> >::iterator equalItr = equalityScores.begin(); equalItr != equalityScores.end(); equalItr++) { if (equalityLeft < 1) { break; } set<V2Country*>::iterator unsetItr = valuesUnset.find(equalItr->first); if (unsetItr != valuesUnset.end()) { valuesUnset.erase(unsetItr); equalItr->first->setNationalValue("nv_equality"); equalityLeft--; LOG(LogLevel::Debug) << equalItr->first->getTag() << " got national value equality"; } } libertyScores.sort(scoresSorter); int libertyLeft = 20; for (list< pair<V2Country*, int> >::iterator libItr = libertyScores.begin(); libItr != libertyScores.end(); libItr++) { if (libertyLeft < 1) { break; } set<V2Country*>::iterator unsetItr = valuesUnset.find(libItr->first); if (unsetItr != valuesUnset.end()) { valuesUnset.erase(unsetItr); libItr->first->setNationalValue("nv_liberty"); libertyLeft--; LOG(LogLevel::Debug) << libItr->first->getTag() << " got national value liberty"; } } for (set<V2Country*>::iterator unsetItr = valuesUnset.begin(); unsetItr != valuesUnset.end(); unsetItr++) { (*unsetItr)->setNationalValue("nv_order"); LOG(LogLevel::Debug) << (*unsetItr)->getTag() << " got national value order"; } // ALL potential countries should be output to the file, otherwise some things don't get initialized right for (vector<V2Country*>::iterator itr = potentialCountries.begin(); itr != potentialCountries.end(); ++itr) { map<string, V2Country*>::iterator citr = countries.find((*itr)->getTag()); if (citr == countries.end()) { (*itr)->initFromHistory(); countries.insert(make_pair((*itr)->getTag(), *itr)); } } // put countries in the same order as potentialCountries was (this is the same order V2 will save them in) /*vector<V2Country*> sortedCountries; for (vector<string>::const_iterator oitr = outputOrder.begin(); oitr != outputOrder.end(); ++oitr) { map<string, V2Country*>::iterator itr = countries.find((*itr)->getTag()); { if ( (*itr)->getTag() == (*oitr) ) { sortedCountries.push_back(*itr); break; } } } countries.swap(sortedCountries);*/ } void V2World::scalePrestige() { double highestPrestige = 0.0; for (auto countryItr: countries) { double prestige = countryItr.second->getPrestige(); if (prestige > highestPrestige) { highestPrestige = prestige; } } double scale = 100.0 / highestPrestige; for (auto countryItr: countries) { countryItr.second->scalePrestige(scale); } } void V2World::convertDiplomacy(const EU3World& sourceWorld, const CountryMapping& countryMap) { vector<EU3Agreement> agreements = sourceWorld.getDiplomacy()->getAgreements(); for (vector<EU3Agreement>::iterator itr = agreements.begin(); itr != agreements.end(); ++itr) { const std::string& EU3Tag1 = itr->country1; const std::string& V2Tag1 = countryMap[EU3Tag1]; if (V2Tag1.empty()) { LOG(LogLevel::Warning) << "EU3 Country " << EU3Tag1 << " used in diplomatic agreement doesn't exist"; continue; } const std::string& EU3Tag2 = itr->country2; const std::string& V2Tag2 = countryMap[EU3Tag2]; if (V2Tag2.empty()) { LOG(LogLevel::Warning) << "EU3 Country " << EU3Tag2 << " used in diplomatic agreement doesn't exist"; continue; } map<string, V2Country*>::iterator country1 = countries.find(V2Tag1); map<string, V2Country*>::iterator country2 = countries.find(V2Tag2); if (country1 == countries.end()) { LOG(LogLevel::Warning) << "Vic2 country " << V2Tag1 << " used in diplomatic agreement doesn't exist"; continue; } if (country2 == countries.end()) { LOG(LogLevel::Warning) << "Vic2 country " << V2Tag2 << " used in diplomatic agreement doesn't exist"; continue; } V2Relations* r1 = country1->second->getRelations(V2Tag2); if (!r1) { r1 = new V2Relations(V2Tag2); country1->second->addRelation(r1); } V2Relations* r2 = country2->second->getRelations(V2Tag1); if (!r2) { r2 = new V2Relations(V2Tag1); country2->second->addRelation(r2); } if ((itr->type == "royal_marriage") || (itr->type == "guarantee")) { // influence level +1, but never exceed 4 if (r1->getLevel() < 4) r1->setLevel(r1->getLevel() + 1); } if (itr->type == "royal_marriage") { // royal marriage is bidirectional; influence level +1, but never exceed 4 if (r2->getLevel() < 4) r2->setLevel(r2->getLevel() + 1); } if ((itr->type == "sphere") || (itr->type == "vassal") || (itr->type == "union")) { // influence level = 5 r1->setLevel(5); /* FIXME: is this desirable? // if relations are too poor, country2 will immediately eject country1's ambassadors at the start of the game // so, for stability's sake, give their relations a boost if (r1->getRelations() < 1) r1->setRelations(1); if (r2->getRelations() < 1) r2->setRelations(1); */ } if ((itr->type == "alliance") || (itr->type == "vassal") || (itr->type == "union") || (itr->type == "guarantee")) { // copy agreement V2Agreement v2a; v2a.country1 = V2Tag1; v2a.country2 = V2Tag2; v2a.start_date = itr->startDate; v2a.type = itr->type; diplomacy.addAgreement(v2a); } } } struct MTo1ProvinceComp { vector<EU3Province*> provinces; }; void V2World::convertProvinces(const EU3World& sourceWorld, const provinceMapping& provinceMap, const resettableMap& resettableProvinces, const CountryMapping& countryMap, const cultureMapping& cultureMap, const cultureMapping& slaveCultureMap, const religionMapping& religionMap, const stateIndexMapping& stateIndexMap, const EU3RegionsMapping& regionsMap) { for (map<int, V2Province*>::iterator i = provinces.begin(); i != provinces.end(); i++) { int destNum = i->first; provinceMapping::const_iterator provinceLink = provinceMap.find(destNum); if ( (provinceLink == provinceMap.end()) || (provinceLink->second.size() == 0) ) { LOG(LogLevel::Warning) << "No source for " << i->second->getName() << " (province " << destNum << ')'; continue; } else if (provinceLink->second[0] == 0) { continue; } else if ((Configuration::getResetProvinces() == "yes") && (resettableProvinces.count(destNum) > 0)) { i->second->setResettable(true); continue; } i->second->clearCores(); EU3Province* oldProvince = NULL; EU3Country* oldOwner = NULL; // determine ownership by province count, or total base tax (if province count is tied) map<string, MTo1ProvinceComp> provinceBins; double newProvinceTotalBaseTax = 0; for (vector<int>::const_iterator itr = provinceLink->second.begin(); itr != provinceLink->second.end(); ++itr) { EU3Province* province = sourceWorld.getProvince(*itr); if (!province) { LOG(LogLevel::Warning) << "Old province " << provinceLink->second[0] << " does not exist (bad mapping?)"; continue; } EU3Country* owner = province->getOwner(); string tag; if (owner != NULL) { tag = owner->getTag(); } else { tag = ""; } if (provinceBins.find(tag) == provinceBins.end()) { provinceBins[tag] = MTo1ProvinceComp(); } if (((Configuration::getV2Gametype() == "HOD") || (Configuration::getV2Gametype() == "HoD-NNM")) && (province->getPopulation() < 1000) && (owner != NULL)) { stateIndexMapping::const_iterator stateIndexMapping = stateIndexMap.find(i->first); if (stateIndexMapping == stateIndexMap.end()) { LOG(LogLevel::Warning) << "Could not find state index for province " << i->first; continue; } else { map< int, set<string> >::iterator colony = colonies.find(stateIndexMapping->second); if (colony == colonies.end()) { set<string> countries; countries.insert(owner->getTag()); colonies.insert( make_pair(stateIndexMapping->second, countries) ); } else { colony->second.insert(owner->getTag()); } } } else { provinceBins[tag].provinces.push_back(province); newProvinceTotalBaseTax += province->getBaseTax(); // I am the new owner if there is no current owner, or I have more provinces than the current owner, // or I have the same number of provinces, but more population, than the current owner if ( (oldOwner == NULL) || (provinceBins[tag].provinces.size() > provinceBins[oldOwner->getTag()].provinces.size()) || (provinceBins[tag].provinces.size() == provinceBins[oldOwner->getTag()].provinces.size()) ) { oldOwner = owner; oldProvince = province; } } } if (oldOwner == NULL) { i->second->setOwner(""); continue; } const std::string& V2Tag = countryMap[oldOwner->getTag()]; if (V2Tag.empty()) { LOG(LogLevel::Warning) << "Could not map provinces owned by " << oldOwner->getTag(); } else { i->second->setOwner(V2Tag); map<string, V2Country*>::iterator ownerItr = countries.find(V2Tag); if (ownerItr != countries.end()) { ownerItr->second->addProvince(i->second); } i->second->convertFromOldProvince(oldProvince); for (map<string, MTo1ProvinceComp>::iterator mitr = provinceBins.begin(); mitr != provinceBins.end(); ++mitr) { for (vector<EU3Province*>::iterator vitr = mitr->second.provinces.begin(); vitr != mitr->second.provinces.end(); ++vitr) { // assign cores vector<EU3Country*> oldCores = (*vitr)->getCores(sourceWorld.getCountries()); for(vector<EU3Country*>::iterator j = oldCores.begin(); j != oldCores.end(); j++) { std::string coreEU3Tag = (*j)->getTag(); // skip this core if the country is the owner of the EU3 province but not the V2 province // (i.e. "avoid boundary conflicts that didn't exist in EU3"). // this country may still get core via a province that DID belong to the current V2 owner if (( coreEU3Tag == mitr->first) && ( coreEU3Tag != oldOwner->getTag())) { continue; } const std::string& coreV2Tag = countryMap[coreEU3Tag]; if (!coreV2Tag.empty()) { i->second->addCore(coreV2Tag); } } // determine demographics double provPopRatio = (*vitr)->getBaseTax() / newProvinceTotalBaseTax; vector<EU3PopRatio> popRatios = (*vitr)->getPopRatios(); for (vector<EU3PopRatio>::iterator prItr = popRatios.begin(); prItr != popRatios.end(); ++prItr) { bool matched = false; string culture = ""; for (cultureMapping::const_iterator cultureItr = cultureMap.begin(); (cultureItr != cultureMap.end()) && (!matched); cultureItr++) { if (cultureItr->srcCulture == prItr->culture) { bool match = true; for (vector<distinguisher>::const_iterator distinguisherItr = cultureItr->distinguishers.begin(); distinguisherItr != cultureItr->distinguishers.end(); distinguisherItr++) { if (distinguisherItr->first == DTOwner) { if ((*vitr)->getOwner()->getTag() != distinguisherItr->second) { match = false; } } else if (distinguisherItr->first == DTReligion) { if (prItr->religion != distinguisherItr->second) { match = false; } } else if (distinguisherItr->first == DTRegion) { auto regions = regionsMap.find(i->second->getSrcProvince()->getNum()); if ((regions == regionsMap.end()) || (regions->second.find(distinguisherItr->second) == regions->second.end())) { match = false; } else { match = true; } } else { LOG(LogLevel::Warning) << "Unhandled distinguisher type in culture rules"; } } if (match) { culture = cultureItr->dstCulture; matched = true; } } } if (!matched) { LOG(LogLevel::Warning) << "Could not set culture for pops in province " << destNum; } string religion = ""; religionMapping::const_iterator religionItr = religionMap.find(prItr->religion); if (religionItr != religionMap.end()) { religion = religionItr->second; } else { LOG(LogLevel::Warning) << "Could not set religion for pops in province " << destNum; } matched = false; string slaveCulture = ""; for (cultureMapping::const_iterator slaveCultureItr = slaveCultureMap.begin(); (slaveCultureItr != slaveCultureMap.end()) && (!matched); slaveCultureItr++) { if (slaveCultureItr->srcCulture == prItr->culture) { bool match = true; for (vector<distinguisher>::const_iterator distinguisherItr = slaveCultureItr->distinguishers.begin(); distinguisherItr != slaveCultureItr->distinguishers.end(); distinguisherItr++) { if (distinguisherItr->first == DTOwner) { if ((*vitr)->getOwner()->getTag() != distinguisherItr->second) { match = false; } } else if (distinguisherItr->first == DTReligion) { if (prItr->religion != distinguisherItr->second) { match = false; } } else if (distinguisherItr->first == DTRegion) { auto regions = regionsMap.find(i->second->getSrcProvince()->getNum()); if ((regions == regionsMap.end()) || (regions->second.find(distinguisherItr->second) == regions->second.end())) { match = false; } } else { LOG(LogLevel::Warning) << "Unhandled distinguisher type in culture rules"; } } if (match) { slaveCulture = slaveCultureItr->dstCulture; matched = true; } } } if (!matched) { //LOG(LogLevel::Warning) << "Could not set slave culture for pops in province " << destNum; slaveCulture = "african_minor"; } V2Demographic demographic; demographic.culture = culture; demographic.slaveCulture = slaveCulture; demographic.religion = religion; demographic.ratio = prItr->popRatio * provPopRatio; demographic.oldCountry = oldOwner; demographic.oldProvince = *vitr; //LOG(LogLevel::Info) << "EU4 Province " << (*vitr)->getNum() << ", Vic2 Province " << i->second->getNum() << ", Culture: " << culture << ", Religion: " << religion << ", popRatio: " << prItr->popRatio << ", provPopRatio: " << provPopRatio << ", ratio: " << demographic.ratio; i->second->addPopDemographic(demographic); } // set forts and naval bases if ((*vitr)->hasBuilding("fort4") || (*vitr)->hasBuilding("fort5") || (*vitr)->hasBuilding("fort6")) { i->second->setFortLevel(1); } } } } } } void V2World::setupColonies(const adjacencyMapping& adjacencyMap, const continentMapping& continentMap) { for (map<string, V2Country*>::iterator countryItr = countries.begin(); countryItr != countries.end(); countryItr++) { // find all land connections to capitals map<int, V2Province*> openProvinces = provinces; queue<int> goodProvinces; map<int, V2Province*>::iterator openItr = openProvinces.find(countryItr->second->getCapital()); if (openItr == openProvinces.end()) { continue; } if (openItr->second->getOwner() != countryItr->first) // if the capital is not owned, don't bother running { continue; } openItr->second->setLandConnection(true); goodProvinces.push(openItr->first); openProvinces.erase(openItr); do { int currentProvince = goodProvinces.front(); goodProvinces.pop(); if (currentProvince > static_cast<int>(adjacencyMap.size())) { LOG(LogLevel::Warning) << "No adjacency mapping for province " << currentProvince; continue; } vector<int> adjacencies = adjacencyMap[currentProvince]; for (unsigned int i = 0; i < adjacencies.size(); i++) { map<int, V2Province*>::iterator openItr = openProvinces.find(adjacencies[i]); if (openItr == openProvinces.end()) { continue; } if (openItr->second->getOwner() != countryItr->first) { continue; } openItr->second->setLandConnection(true); goodProvinces.push(openItr->first); openProvinces.erase(openItr); } } while (goodProvinces.size() > 0); // find all provinces on the same continent as the owner's capital string capitalContinent = ""; map<int, V2Province*>::iterator capital = provinces.find(countryItr->second->getCapital()); if (capital != provinces.end()) { continentMapping::const_iterator itr = continentMap.find(capital->first); if (itr != continentMap.end()) { capitalContinent = itr->second; } else { continue; } } else { continue; } auto ownedProvinces = countryItr->second->getProvinces(); for (auto provItr = ownedProvinces.begin(); provItr != ownedProvinces.end(); provItr++) { continentMapping::const_iterator itr = continentMap.find(provItr->first); if ((itr != continentMap.end()) && (itr->second == capitalContinent)) { provItr->second->setSameContinent(true); } } } for (map<int, V2Province*>::iterator provItr = provinces.begin(); provItr != provinces.end(); provItr++) { provItr->second->determineColonial(); } } static int stateId = 0; void V2World::setupStates(const stateMapping& stateMap) { list<V2Province*> unassignedProvs; for (map<int, V2Province*>::iterator itr = provinces.begin(); itr != provinces.end(); ++itr) { unassignedProvs.push_back(itr->second); } list<V2Province*>::iterator iter; while(unassignedProvs.size() > 0) { iter = unassignedProvs.begin(); int provId = (*iter)->getNum(); string owner = (*iter)->getOwner(); if (owner == "") { unassignedProvs.erase(iter); continue; } V2State* newState = new V2State(stateId, *iter); stateId++; stateMapping::const_iterator stateItr = stateMap.find(provId); vector<int> neighbors; if (stateItr != stateMap.end()) { neighbors = stateItr->second; } bool colonised = (*iter)->isColonial(); newState->setColonial(colonised); iter = unassignedProvs.erase(iter); for (vector<int>::iterator i = neighbors.begin(); i != neighbors.end(); i++) { for(iter = unassignedProvs.begin(); iter != unassignedProvs.end(); iter++) { if ((*iter)->getNum() == *i) { if ((*iter)->getOwner() == owner) { if ((*iter)->isColonial() == colonised) { newState->addProvince(*iter); iter = unassignedProvs.erase(iter); } } } } } map<string, V2Country*>::iterator iter2 = countries.find(owner); if (iter2 != countries.end()) { iter2->second->addState(newState); } } } void V2World::convertUncivReforms() { for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); ++itr) { itr->second->convertUncivReforms(); } } void V2World::setupPops(EU3World& sourceWorld) { long my_totalWorldPopulation = static_cast<long>(0.55 * totalWorldPopulation); double popWeightRatio = my_totalWorldPopulation / sourceWorld.getWorldWeightSum(); for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); ++itr) { itr->second->setupPops(sourceWorld, popWeightRatio); } if (Configuration::getConvertPopTotals()) { LOG(LogLevel::Info) << "Total world population: " << my_totalWorldPopulation; } else { LOG(LogLevel::Info) << "Total world population: " << totalWorldPopulation; } LOG(LogLevel::Info) << "Total world weight sum: " << sourceWorld.getWorldWeightSum(); LOG(LogLevel::Info) << my_totalWorldPopulation << " / " << sourceWorld.getWorldWeightSum(); LOG(LogLevel::Info) << "Population per weight point is: " << popWeightRatio; long newTotalPopulation = 0; for (auto itr = provinces.begin(); itr != provinces.end(); itr++) { newTotalPopulation += itr->second->getTotalPopulation(); } LOG(LogLevel::Info) << "New total world population: " << newTotalPopulation; } void V2World::addUnions(const unionMapping& unionMap) { for (map<int, V2Province*>::iterator provItr = provinces.begin(); provItr != provinces.end(); provItr++) { for (unionMapping::const_iterator unionItr = unionMap.begin(); unionItr != unionMap.end(); unionItr++) { if (provItr->second->hasCulture(unionItr->first, 0.5) && !provItr->second->wasInfidelConquest() && !provItr->second->wasColony()) { provItr->second->addCore(unionItr->second); } } } } //#define TEST_V2_PROVINCES void V2World::convertArmies(const EU3World& sourceWorld, const inverseProvinceMapping& inverseProvinceMap, const map<int,int>& leaderIDMap, adjacencyMapping adjacencyMap) { // hack for naval bases. not ALL naval bases are in port provinces, and if you spawn a navy at a naval base in // a non-port province, Vicky crashes.... vector<int> port_whitelist; { int temp = 0; ifstream s("port_whitelist.txt"); while (s.good() && !s.eof()) { s >> temp; port_whitelist.push_back(temp); } s.close(); } // get cost per regiment values double cost_per_regiment[num_reg_categories] = { 0.0 }; Object* obj2 = doParseFile("regiment_costs.txt"); if (obj2 == NULL) { LOG(LogLevel::Error) << "Could not parse file regiment_costs.txt"; exit(-1); } vector<Object*> objTop = obj2->getLeaves(); if (objTop.size() == 0 || objTop[0]->getLeaves().size() == 0) { LOG(LogLevel::Error) << "regment_costs.txt failed to parse"; exit(1); } for (int i = 0; i < num_reg_categories; ++i) { string regiment_cost = objTop[0]->getLeaf(RegimentCategoryNames[i]); cost_per_regiment[i] = atoi(regiment_cost.c_str()); } // convert armies for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); ++itr) { itr->second->convertArmies(leaderIDMap, cost_per_regiment, inverseProvinceMap, provinces, port_whitelist, adjacencyMap); } } void V2World::convertTechs(const EU3World& sourceWorld) { map<string, EU3Country*> sourceCountries = sourceWorld.getCountries(); double oldLandMean; double landMean; double highestLand; double oldNavalMean; double navalMean; double highestNaval; double oldTradeMean; double tradeMean; double highestTrade; double oldProductionMean; double productionMean; double highestProduction; double oldGovernmentMean; double governmentMean; double highestGovernment; int num = 2; map<string, EU3Country*>::iterator i = sourceCountries.begin(); if (sourceCountries.size() == 0) { return; } while (i->second->getProvinces().size() == 0) { i++; } highestLand = oldLandMean = landMean = i->second->getLandTech(); highestNaval = oldNavalMean = navalMean = i->second->getNavalTech(); highestTrade = oldTradeMean = tradeMean = i->second->getTradeTech(); highestProduction = oldProductionMean = productionMean = i->second->getProductionTech(); highestGovernment = oldGovernmentMean = governmentMean = i->second->getGovernmentTech(); for (i++; i != sourceCountries.end(); i++) { if (i->second->getProvinces().size() == 0) { continue; } double newTech = i->second->getLandTech(); landMean = oldLandMean + ((newTech - oldLandMean) / num); oldLandMean = landMean; if (newTech > highestLand) { highestLand = newTech; } newTech = i->second->getNavalTech(); navalMean = oldNavalMean + ((newTech - oldNavalMean) / num); oldNavalMean = navalMean; if (newTech > highestNaval) { highestNaval = newTech; } newTech = i->second->getTradeTech(); tradeMean = oldTradeMean + ((newTech - oldTradeMean) / num); oldTradeMean = tradeMean; if (newTech > highestTrade) { highestTrade = newTech; } newTech = i->second->getProductionTech(); productionMean = oldProductionMean + ((newTech - oldProductionMean) / num); oldProductionMean = productionMean; if (newTech > highestProduction) { highestProduction = newTech; } newTech = i->second->getGovernmentTech(); governmentMean = oldGovernmentMean + ((newTech - oldGovernmentMean) / num); oldGovernmentMean = governmentMean; if (newTech > highestGovernment) { highestGovernment = newTech; } num++; } for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); itr++) { if ((Configuration::getV2Gametype() == "vanilla") || itr->second->isCivilized()) { itr->second->setArmyTech(landMean, highestLand); itr->second->setNavyTech(navalMean, highestNaval); itr->second->setCommerceTech(tradeMean, highestTrade); itr->second->setIndustryTech(productionMean, highestProduction); itr->second->setCultureTech(governmentMean, highestGovernment); } } } void V2World::allocateFactories(const EU3World& sourceWorld, const V2FactoryFactory& factoryBuilder) { // determine average production tech map<string, EU3Country*> sourceCountries = sourceWorld.getCountries(); double productionMean = 0.0f; int num = 1; for (map<string, EU3Country*>::iterator itr = sourceCountries.begin(); itr != sourceCountries.end(); ++itr) { if ( (itr)->second->getProvinces().size() == 0) { continue; } if (( (itr)->second->getTechGroup() != "western" ) && ( (itr)->second->getTechGroup() != "latin" )) { continue; } double prodTech = (itr)->second->getProductionTech(); productionMean += ((prodTech - productionMean) / num); ++num; } // give all extant civilized nations an industrial score deque<pair<double, V2Country*>> weightedCountries; for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); ++itr) { if ( !itr->second->isCivilized() ) { continue; } const EU3Country* sourceCountry = itr->second->getSourceCountry(); if (sourceCountry == NULL) { continue; } if (sourceCountry->getProvinces().size() == 0) { continue; } // modified manufactory weight follows diminishing returns curve y = x^(3/4)+log((x^2)/5+1) int manuCount = sourceCountry->getManufactoryCount(); double manuWeight = pow(manuCount, 0.75) + log((manuCount * manuCount) / 5.0 + 1.0); double industryWeight = (sourceCountry->getProductionTech() - productionMean) + manuWeight; // having one manufactory and average tech is not enough; you must have more than one, or above-average tech if (industryWeight > 1.0) { weightedCountries.push_back(pair<double, V2Country*>(industryWeight, itr->second)); } } if (weightedCountries.size() < 1) { LOG(LogLevel::Warning) << "No countries are able to accept factories"; return; } sort(weightedCountries.begin(), weightedCountries.end()); // allow a maximum of 10 (plus any tied at tenth place) countries to recieve factories deque<pair<double, V2Country*>> restrictCountries; double threshold = 1.0; double totalIndWeight = 0.0; for (deque<pair<double, V2Country*>>::reverse_iterator itr = weightedCountries.rbegin(); itr != weightedCountries.rend(); ++itr) { if ((restrictCountries.size() > 10) && (itr->first < (threshold - FLT_EPSILON))) { break; } restrictCountries.push_front(*itr); // preserve sort totalIndWeight += itr->first; threshold = itr->first; } weightedCountries.swap(restrictCountries); // remove nations that won't have enough industiral score for even one factory deque<V2Factory*> factoryList = factoryBuilder.buildFactories(); while (((weightedCountries.begin()->first / totalIndWeight) * factoryList.size() + 0.5 /*round*/) < 1.0) { weightedCountries.pop_front(); } // determine how many factories each eligible nation gets vector<pair<int, V2Country*>> factoryCounts; for (deque<pair<double, V2Country*>>::iterator itr = weightedCountries.begin(); itr != weightedCountries.end(); ++itr) { int factories = int(((itr->first / totalIndWeight) * factoryList.size()) + 0.5 /*round*/); LOG(LogLevel::Debug) << itr->second->getTag() << " has industrial weight " << itr->first << " granting max " << factories << " factories"; factoryCounts.push_back(pair<int, V2Country*>(factories, itr->second)); } // allocate the factories vector<pair<int, V2Country*>>::iterator lastReceptiveCountry = factoryCounts.begin(); vector<pair<int, V2Country*>>::iterator citr = factoryCounts.begin(); while (factoryList.size() > 0) { bool accepted = false; if (citr->first > 0) // can take more factories { for (deque<V2Factory*>::iterator qitr = factoryList.begin(); qitr != factoryList.end(); ++qitr) { if ( citr->second->addFactory(*qitr) ) { --(citr->first); lastReceptiveCountry = citr; accepted = true; factoryList.erase(qitr); break; } } } if (!accepted && citr == lastReceptiveCountry) { Log logOutput(LogLevel::Debug); logOutput << "No countries will accept any of the remaining factories:\n"; for (deque<V2Factory*>::iterator qitr = factoryList.begin(); qitr != factoryList.end(); ++qitr) { logOutput << "\t " << (*qitr)->getTypeName() << '\n'; } break; } if (++citr == factoryCounts.end()) { citr = factoryCounts.begin(); // loop around to beginning } } } map<string, V2Country*> V2World::getPotentialCountries() const { map<string, V2Country*> retVal; for (vector<V2Country*>::const_iterator i = potentialCountries.begin(); i != potentialCountries.end(); i++) { retVal[ (*i)->getTag() ] = *i; } return retVal; } map<string, V2Country*> V2World::getDynamicCountries() const { map<string, V2Country*> retVal = dynamicCountries; return retVal; } void V2World::getProvinceLocalizations(string file) { ifstream read; string line; read.open( file.c_str() ); while (read.good() && !read.eof()) { getline(read, line); if (line.substr(0,4) == "PROV" && isdigit(line.c_str()[4])) { int position = line.find_first_of(';'); int num = atoi( line.substr(4, position - 4).c_str() ); string name = line.substr(position + 1, line.find_first_of(';', position + 1) - position - 1); for (auto i: provinces) { if (i.first == num) { i.second->setName(name); break; } } } } read.close(); } V2Country* V2World::getCountry(string tag) { map<string, V2Country*>::iterator itr = countries.find(tag); if (itr != countries.end()) { return itr->second; } else { return NULL; } }
32.544525
421
0.634528
[ "object", "vector" ]
f3e5adeadae3dbe259c7cccc034a495ee19cf581
1,003
cpp
C++
C++ Version/plane.cpp
hpatel0392/Ray-Tracer
3c306810130ba7831bb14a89c9755025e3dcafb3
[ "MIT" ]
null
null
null
C++ Version/plane.cpp
hpatel0392/Ray-Tracer
3c306810130ba7831bb14a89c9755025e3dcafb3
[ "MIT" ]
null
null
null
C++ Version/plane.cpp
hpatel0392/Ray-Tracer
3c306810130ba7831bb14a89c9755025e3dcafb3
[ "MIT" ]
null
null
null
/* * plane.cpp * Author: Harsh Patel * Date: 11-15-2015 * Plane's method definitions */ #include "plane.h" #include "rt.h" #include "vector.h" // checkered plane constructor Plane::Plane(Vector norm, double dist, bool check, COLOR_T clr1, COLOR_T clr2, double rf) : normal( norm ), distance( dist ), Object( check, rf, clr1, clr2 ) { this->normal.normalize(); } /* * intersection * Checks to see if the ray intersects the plane * if intersection is found, t is set and inter and norm are computed and set * returns false if no intersection occurs, or true if intersection occurs */ bool Plane::intersection(RAY_T ray, double &t, Vector &inter, Vector &norm) { double dot_dir = normal * ray.dir; double dot_org = normal * ray.org; // if dot_dir == 0 , stop if( dot_dir == 0 ) return false; t = -(dot_org + distance ) / dot_dir; // stop if t < 0 if ( t < 0 ) return false; inter = ray.org + ray.dir * (t); norm = normal; return true; }
21.804348
91
0.644068
[ "object", "vector" ]
f3edc43c50435a99b13b31a5aa4648309381dcfd
34,308
cpp
C++
libvast/src/system/node.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
null
null
null
libvast/src/system/node.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
null
null
null
libvast/src/system/node.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
null
null
null
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2016 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #include "vast/system/node.hpp" #include "vast/fwd.hpp" #include "vast/atoms.hpp" #include "vast/concept/convertible/to.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/endpoint.hpp" #include "vast/concept/printable/stream.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/concept/printable/vast/expression.hpp" #include "vast/concept/printable/vast/json.hpp" #include "vast/config.hpp" #include "vast/data.hpp" #include "vast/defaults.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/process.hpp" #include "vast/detail/settings.hpp" #include "vast/format/csv.hpp" #include "vast/format/json.hpp" #include "vast/format/json/default_selector.hpp" #include "vast/format/json/suricata_selector.hpp" #include "vast/format/json/zeek_selector.hpp" #include "vast/format/syslog.hpp" #include "vast/format/test.hpp" #include "vast/format/zeek.hpp" #include "vast/logger.hpp" #include "vast/plugin.hpp" #include "vast/system/accountant.hpp" #include "vast/system/accountant_config.hpp" #include "vast/system/configuration.hpp" #include "vast/system/node.hpp" #include "vast/system/posix_filesystem.hpp" #include "vast/system/shutdown.hpp" #include "vast/system/spawn_archive.hpp" #include "vast/system/spawn_arguments.hpp" #include "vast/system/spawn_catalog.hpp" #include "vast/system/spawn_counter.hpp" #include "vast/system/spawn_disk_monitor.hpp" #include "vast/system/spawn_eraser.hpp" #include "vast/system/spawn_explorer.hpp" #include "vast/system/spawn_exporter.hpp" #include "vast/system/spawn_importer.hpp" #include "vast/system/spawn_index.hpp" #include "vast/system/spawn_node.hpp" #include "vast/system/spawn_or_connect_to_node.hpp" #include "vast/system/spawn_pivoter.hpp" #include "vast/system/spawn_sink.hpp" #include "vast/system/spawn_source.hpp" #include "vast/system/spawn_type_registry.hpp" #include "vast/system/status.hpp" #include "vast/system/terminate.hpp" #include "vast/system/version_command.hpp" #include "vast/table_slice.hpp" #include "vast/taxonomies.hpp" #include <caf/function_view.hpp> #include <caf/io/middleman.hpp> #include <caf/settings.hpp> #include <chrono> #include <csignal> #include <fstream> #include <sstream> namespace vast::system { namespace { // This is a side-channel to communicate the self pointer into the spawn- and // send-command functions, whose interfaces are constrained by the command // factory. thread_local node_actor::stateful_pointer<node_state> this_node = nullptr; // Convenience function for wrapping an error into a CAF message. auto make_error_msg(ec code, std::string msg) { return caf::make_message(caf::make_error(code, std::move(msg))); } /// A list of components that are essential for importing and exporting data /// from the node. std::set<const char*> core_components = {"archive", "filesystem", "importer", "catalog", "index"}; bool is_core_component(std::string_view type) { auto pred = [&](const char* x) { return x == type; }; return std::any_of(std::begin(core_components), std::end(core_components), pred); } /// Helper function to determine whether a component can be spawned at most /// once. bool is_singleton(std::string_view type) { // TODO: All of these actor interfaces are strongly typed. The value of `type` // is received via the actor interface of the NODE sometimes, which means that // we cannot just pass arbitrary actors to it. Atoms aren't really an option // either, because `caf::atom_value` was removed with CAF 0.18. We can, // however, abuse the fact that every typed actor has a type ID assigned, and // change the node to work with type IDs over actor names everywhere. This // refactoring will be much easier once the NODE itself is a typed actor, so // let's hold off until then. const char* singletons[] = {"accountant", "archive", "disk-monitor", "eraser", "filesystem", "importer", "index", "catalog", "type-registry"}; auto pred = [&](const char* x) { return x == type; }; return std::any_of(std::begin(singletons), std::end(singletons), pred); } // Sends an atom to a registered actor. Blocks until the actor responds. caf::message send_command(const invocation& inv, caf::actor_system&) { auto first = inv.arguments.begin(); auto last = inv.arguments.end(); // Expect exactly two arguments. if (std::distance(first, last) != 2) return make_error_msg(ec::syntax_error, "expected two arguments: receiver " "and message atom"); // Get destination actor from the registry. auto dst = this_node->state.registry.find_by_label(*first); if (dst == nullptr) return make_error_msg(ec::syntax_error, "registry contains no actor named " + *first); // Dispatch to destination. auto f = caf::make_function_view(caf::actor_cast<caf::actor>(dst)); auto send = [&](auto atom_value) { if (auto res = f(atom_value)) return std::move(*res); else return caf::make_message(std::move(res.error())); }; if (*(first + 1) == "run") return send(atom::run_v); return make_error_msg(ec::unimplemented, "trying to send unsupported atom: " + *(first + 1)); } void collect_component_status(node_actor::stateful_pointer<node_state> self, status_verbosity v) { struct extra_state { size_t memory_usage = 0; static void deliver(caf::typed_response_promise<std::string>&& promise, record&& content) { // We strip and sort the output for a cleaner presentation of the data. if (auto json = to_json(sort(strip(content)))) promise.deliver(std::move(*json)); } // In-place sort each level of the tree. static record& sort(record&& r) { std::sort(r.begin(), r.end()); for (auto& [_, value] : r) if (auto* nested = caf::get_if<record>(&value)) sort(std::move(*nested)); return r; }; }; auto rs = make_status_request_state<extra_state, std::string>(self); // Pre-fill the version information. auto version = retrieve_versions(); rs->content["version"] = version; // Pre-fill our result with system stats. auto system = record{}; if (v >= status_verbosity::info) { system["in-memory-table-slices"] = count{table_slice::instances()}; system["database-path"] = self->state.dir.string(); merge(detail::get_status(), system, policy::merge_lists::no); } if (v >= status_verbosity::detailed) { auto config_files = list{}; std::transform(system::loaded_config_files().begin(), system::loaded_config_files().end(), std::back_inserter(config_files), [](const std::filesystem::path& x) { return x.string(); }); std::transform(plugins::loaded_config_files().begin(), plugins::loaded_config_files().end(), std::back_inserter(config_files), [](const std::filesystem::path& x) { return x.string(); }); system["config-files"] = std::move(config_files); } if (v >= status_verbosity::debug) { auto& sys = self->system(); system["running-actors"] = count{sys.registry().running()}; system["detached-actors"] = count{sys.detached_actors()}; system["worker-threads"] = count{sys.scheduler().num_workers()}; } rs->content["system"] = std::move(system); const auto timeout = defaults::system::initial_request_timeout; // Send out requests and collects answers. for (const auto& [label, component] : self->state.registry.components()) { // Requests to busy remote sources and sinks can easily delay the combined // response because the status requests don't get scheduled soon enough. // NOTE: We must use `caf::actor::node` rather than // `caf::actor_system::node`, because the actor system for remote actors is // proxied, so using `component.actor.home_system().node()` will result in // a different `node_id` from the one we actually want to compare. if (component.actor.node() != self->node()) continue; collect_status(rs, timeout, v, component.actor, rs->content, label); } } /// Registers (and monitors) a component through the node. caf::error register_component(node_actor::stateful_pointer<node_state> self, const caf::actor& component, const std::string& type, const std::string& label = {}) { if (!self->state.registry.add(component, type, label)) { auto msg // separate variable for clang-format only = fmt::format("{} failed to add component to registry: {}", *self, label.empty() ? type : label); return caf::make_error(ec::unspecified, std::move(msg)); } self->monitor(component); return caf::none; } /// Deregisters (and demonitors) a component through the node. caf::expected<caf::actor> deregister_component(node_actor::stateful_pointer<node_state> self, const std::string& label) { auto component = self->state.registry.remove(label); if (!component) { auto msg // separate variable for clang-format only = fmt::format("{} failed to deregister non-existant component: {}", *self, label); return caf::make_error(ec::unspecified, std::move(msg)); } self->demonitor(component->actor); return component->actor; } } // namespace caf::message dump_command(const invocation& inv, caf::actor_system&) { auto as_yaml = caf::get_or(inv.options, "vast.dump.yaml", false); auto self = this_node; auto [type_registry] = self->state.registry.find<type_registry_actor>(); if (!type_registry) return caf::make_message(caf::make_error(ec::missing_component, // "type-registry")); caf::error request_error = caf::none; auto rp = self->make_response_promise(); // The overload for 'request(...)' taking a 'std::chrono::duration' does not // respect the specified message priority, so we convert to 'caf::duration' // by hand. const auto timeout = caf::duration{defaults::system::initial_request_timeout}; self ->request<caf::message_priority::high>(type_registry, timeout, atom::get_v, atom::taxonomies_v) .then( [=](struct taxonomies taxonomies) mutable { auto result = list{}; result.reserve(taxonomies.concepts.size()); if (inv.full_name == "dump" || inv.full_name == "dump concepts") { for (auto& [name, concept_] : taxonomies.concepts) { auto fields = list{}; fields.reserve(concept_.fields.size()); for (auto& field : concept_.fields) fields.push_back(std::move(field)); auto concepts = list{}; concepts.reserve(concept_.concepts.size()); for (auto& concept_ : concept_.concepts) concepts.push_back(std::move(concept_)); auto entry = record{ {"concept", record{ {"name", std::move(name)}, {"description", std::move(concept_.description)}, {"fields", std::move(fields)}, {"concepts", std::move(concepts)}, }}, }; result.push_back(std::move(entry)); } } if (inv.full_name == "dump" || inv.full_name == "dump models") { for (auto& [name, model] : taxonomies.models) { auto definition = list{}; definition.reserve(model.definition.size()); for (auto& definition_entry : model.definition) definition.push_back(std::move(definition_entry)); auto entry = record{ {"model", record{ {"name", std::move(name)}, {"description", std::move(model.description)}, {"definition", std::move(definition)}, }}, }; result.push_back(std::move(entry)); } } if (as_yaml) { if (auto yaml = to_yaml(data{std::move(result)})) rp.deliver(to_string(std::move(*yaml))); else request_error = std::move(yaml.error()); } else { if (auto json = to_json(data{std::move(result)})) rp.deliver(std::move(*json)); else request_error = std::move(json.error()); } }, [=](caf::error& err) mutable { request_error = std::move(err); }); if (request_error) return caf::make_message(std::move(request_error)); return caf::none; } caf::message status_command(const invocation& inv, caf::actor_system&) { auto self = this_node; auto verbosity = status_verbosity::info; if (caf::get_or(inv.options, "vast.status.detailed", false)) verbosity = status_verbosity::detailed; if (caf::get_or(inv.options, "vast.status.debug", false)) verbosity = status_verbosity::debug; collect_component_status(self, verbosity); return caf::none; } caf::expected<caf::actor> spawn_accountant(node_actor::stateful_pointer<node_state> self, spawn_arguments& args) { const auto& options = args.inv.options; auto metrics_opts = caf::get_or(options, "vast.metrics", caf::settings{}); auto cfg = to_accountant_config(metrics_opts); if (!cfg) return cfg.error(); return caf::actor_cast<caf::actor>( self->spawn(accountant, std::move(*cfg), self->state.dir)); } caf::expected<caf::actor> spawn_component(node_actor::stateful_pointer<node_state> self, const invocation& inv, spawn_arguments& args) { VAST_TRACE_SCOPE("{} {}", VAST_ARG(inv), VAST_ARG(args)); using caf::atom_uint; auto i = node_state::component_factory.find(inv.full_name); if (i == node_state::component_factory.end()) return caf::make_error(ec::unspecified, "invalid spawn component"); return i->second(self, args); } caf::message kill_command(const invocation& inv, caf::actor_system&) { auto self = this_node; auto first = inv.arguments.begin(); auto last = inv.arguments.end(); if (std::distance(first, last) != 1) return make_error_msg(ec::syntax_error, "expected exactly one component " "argument"); auto rp = self->make_response_promise(); auto& label = *first; auto component = deregister_component(self, label); if (!component) { rp.deliver(caf::make_error(ec::unspecified, fmt::format("no such component: {}", label))); } else { terminate<policy::parallel>(self, std::move(*component)) .then( [=](atom::done) mutable { VAST_DEBUG("{} terminated component {}", *self, label); rp.deliver(atom::ok_v); }, [=](const caf::error& err) mutable { VAST_WARN("{} failed to terminate component {}: {}", *self, label, err); rp.deliver(err); }); } return caf::none; } /// Lifts a factory function that accepts `local_actor*` as first argument /// to a function accpeting `node_actor::stateful_pointer<node_state>` instead. template <caf::expected<caf::actor> (*Fun)(caf::local_actor*, spawn_arguments&)> node_state::component_factory_fun lift_component_factory() { return [](node_actor::stateful_pointer<node_state> self, spawn_arguments& args) { // Delegate to lifted function. return Fun(self, args); }; } template <caf::expected<caf::actor> (*Fun)( node_actor::stateful_pointer<node_state>, spawn_arguments&)> node_state::component_factory_fun lift_component_factory() { return Fun; } auto make_component_factory() { auto result = node_state::named_component_factory{ {"spawn accountant", lift_component_factory<spawn_accountant>()}, {"spawn archive", lift_component_factory<spawn_archive>()}, {"spawn counter", lift_component_factory<spawn_counter>()}, {"spawn disk-monitor", lift_component_factory<spawn_disk_monitor>()}, {"spawn eraser", lift_component_factory<spawn_eraser>()}, {"spawn exporter", lift_component_factory<spawn_exporter>()}, {"spawn explorer", lift_component_factory<spawn_explorer>()}, {"spawn importer", lift_component_factory<spawn_importer>()}, {"spawn catalog", lift_component_factory<spawn_catalog>()}, {"spawn type-registry", lift_component_factory<spawn_type_registry>()}, {"spawn index", lift_component_factory<spawn_index>()}, {"spawn pivoter", lift_component_factory<spawn_pivoter>()}, {"spawn source", lift_component_factory<spawn_source>()}, {"spawn source csv", lift_component_factory<spawn_source>()}, {"spawn source json", lift_component_factory<spawn_source>()}, {"spawn source suricata", lift_component_factory<spawn_source>()}, {"spawn source syslog", lift_component_factory<spawn_source>()}, {"spawn source test", lift_component_factory<spawn_source>()}, {"spawn source zeek", lift_component_factory<spawn_source>()}, {"spawn source zeek-json", lift_component_factory<spawn_source>()}, {"spawn sink zeek", lift_component_factory<spawn_sink>()}, {"spawn sink csv", lift_component_factory<spawn_sink>()}, {"spawn sink ascii", lift_component_factory<spawn_sink>()}, {"spawn sink json", lift_component_factory<spawn_sink>()}, }; for (const auto& plugin : plugins::get()) { if (const auto* reader = plugin.as<reader_plugin>()) { auto command = fmt::format("spawn source {}", reader->reader_format()); result.emplace(command, lift_component_factory<spawn_source>()); } if (const auto* writer = plugin.as<writer_plugin>()) { auto command = fmt::format("spawn sink {}", writer->writer_format()); result.emplace(command, lift_component_factory<spawn_sink>()); } } return result; } auto make_command_factory() { // When updating this list, remember to update its counterpart in // application.cpp as well iff necessary auto result = command::factory{ {"dump", dump_command}, {"dump concepts", dump_command}, {"dump models", dump_command}, {"kill", kill_command}, {"send", send_command}, {"spawn accountant", node_state::spawn_command}, {"spawn archive", node_state::spawn_command}, {"spawn counter", node_state::spawn_command}, {"spawn disk-monitor", node_state::spawn_command}, {"spawn eraser", node_state::spawn_command}, {"spawn explorer", node_state::spawn_command}, {"spawn exporter", node_state::spawn_command}, {"spawn importer", node_state::spawn_command}, {"spawn catalog", node_state::spawn_command}, {"spawn type-registry", node_state::spawn_command}, {"spawn index", node_state::spawn_command}, {"spawn pivoter", node_state::spawn_command}, {"spawn sink ascii", node_state::spawn_command}, {"spawn sink csv", node_state::spawn_command}, {"spawn sink json", node_state::spawn_command}, {"spawn sink zeek", node_state::spawn_command}, {"spawn source csv", node_state::spawn_command}, {"spawn source json", node_state::spawn_command}, {"spawn source suricata", node_state::spawn_command}, {"spawn source syslog", node_state::spawn_command}, {"spawn source test", node_state::spawn_command}, {"spawn source zeek", node_state::spawn_command}, {"spawn source zeek-json", node_state::spawn_command}, {"status", status_command}, }; for (const auto& plugin : plugins::get()) { if (const auto* reader = plugin.as<reader_plugin>()) { auto command = fmt::format("spawn source {}", reader->reader_format()); result.emplace(command, node_state::spawn_command); } if (const auto* writer = plugin.as<writer_plugin>()) { auto command = fmt::format("spawn sink {}", writer->writer_format()); result.emplace(command, node_state::spawn_command); } } return result; } std::string generate_label(node_actor::stateful_pointer<node_state> self, std::string_view component) { // C++20: remove the indirection through std::string. auto n = self->state.label_counters[std::string{component}]++; return std::string{component} + '-' + std::to_string(n); } caf::message node_state::spawn_command(const invocation& inv, [[maybe_unused]] caf::actor_system& sys) { VAST_TRACE_SCOPE("{}", inv); using std::begin; using std::end; auto* self = this_node; if (self->state.tearing_down) return caf::make_message(caf::make_error( // ec::no_error, "can't spawn a component while tearing down")); auto rp = self->make_response_promise(); // We configured the command to have the name of the component. auto inv_name_split = detail::split(inv.full_name, " "); VAST_ASSERT(inv_name_split.size() > 1); std::string comp_type{inv_name_split[1]}; // Auto-generate label if none given. std::string label; if (auto label_ptr = caf::get_if<std::string>(&inv.options, "vast.spawn." "label")) { label = *label_ptr; if (label.empty()) { auto err = caf::make_error(ec::unspecified, "empty component label"); rp.deliver(err); return caf::make_message(std::move(err)); } if (self->state.registry.find_by_label(label)) { auto err = caf::make_error(ec::unspecified, "duplicate component label"); rp.deliver(err); return caf::make_message(std::move(err)); } } else { label = comp_type; if (!is_singleton(comp_type)) { label = generate_label(self, comp_type); VAST_DEBUG("{} auto-generated new label: {}", *self, label); } } VAST_DEBUG("{} spawns a {} with the label {}", *self, comp_type, label); auto spawn_inv = inv; if (comp_type == "source") { auto spawn_opt = caf::get_or(spawn_inv.options, "vast.spawn", caf::settings{}); auto source_opt = caf::get_or(spawn_opt, "source", caf::settings{}); auto import_opt = caf::get_or(spawn_inv.options, "vast.import", caf::settings{}); detail::merge_settings(source_opt, import_opt, policy::merge_lists::no); spawn_inv.options["import"] = import_opt; caf::put(spawn_inv.options, "vast.import", import_opt); } auto spawn_actually = [=](spawn_arguments& args) mutable { // Spawn our new VAST component. auto component = spawn_component(self, args.inv, args); if (!component) { if (component.error()) VAST_WARN("{} failed to spawn component: {}", __func__, render(component.error())); rp.deliver(component.error()); return caf::make_message(std::move(component.error())); } if (auto err = register_component(self, *component, comp_type, label)) { rp.deliver(err); return caf::make_message(std::move(err)); } VAST_DEBUG("{} registered {} as {}", *self, comp_type, label); rp.deliver(*component); return caf::make_message(*component); }; auto handle_taxonomies = [=](expression e) mutable { VAST_DEBUG("{} received the substituted expression {}", *self, to_string(e)); spawn_arguments args{spawn_inv, self->state.dir, label, std::move(e)}; spawn_actually(args); }; // Retrieve taxonomies and delay spawning until the response arrives if we're // dealing with a query... auto query_handlers = std::set<std::string>{"counter", "exporter"}; if (query_handlers.count(comp_type) > 0u && !caf::get_or(spawn_inv.options, "vast." + comp_type + ".disable-taxonomies", false)) { if (auto [type_registry] = self->state.registry.find<type_registry_actor>(); type_registry) { auto expr = normalized_and_validated(spawn_inv.arguments); if (!expr) { rp.deliver(expr.error()); return make_message(expr.error()); } self ->request(type_registry, defaults::system::initial_request_timeout, atom::resolve_v, std::move(*expr)) .then(handle_taxonomies, [=](caf::error err) mutable { rp.deliver(err); return make_message(err); }); return caf::none; } } // ... or spawn the component right away if not. spawn_arguments args{spawn_inv, self->state.dir, label, std::nullopt}; return spawn_actually(args); } node_actor::behavior_type node(node_actor::stateful_pointer<node_state> self, std::string name, std::filesystem::path dir, std::chrono::milliseconds shutdown_grace_period) { self->state.name = std::move(name); self->state.dir = std::move(dir); // Initialize component and command factories. node_state::component_factory = make_component_factory(); node_state::command_factory = make_command_factory(); // Initialize the file system with the node directory as root. auto fs = self->spawn<caf::detached>(posix_filesystem, self->state.dir); auto err = register_component(self, caf::actor_cast<caf::actor>(fs), "filesystem"); VAST_ASSERT(err == caf::none); // Registration cannot fail; empty registry. // Remove monitored components. self->set_down_handler([=](const caf::down_msg& msg) { VAST_DEBUG("{} got DOWN from {}", *self, msg.source); if (!self->state.tearing_down) { auto actor = caf::actor_cast<caf::actor>(msg.source); auto component = self->state.registry.remove(actor); VAST_ASSERT(component); // Terminate if a singleton dies. if (is_core_component(component->type)) { VAST_ERROR("{} terminates after DOWN from {}", *self, component->type); self->send_exit(self, caf::exit_reason::user_shutdown); } } }); // Terminate deterministically on shutdown. self->set_exit_handler([=](const caf::exit_msg& msg) { VAST_DEBUG("{} got EXIT from {}", *self, msg.source); self->state.tearing_down = true; // Ignore duplicate EXIT messages except for hard kills. self->set_exit_handler([=](const caf::exit_msg& msg) { if (msg.reason == caf::exit_reason::kill) { VAST_WARN("{} received hard kill and terminates immediately", *self); self->quit(msg.reason); } else { VAST_DEBUG("{} ignores duplicate EXIT message from {}", *self, msg.source); } }); auto& registry = self->state.registry; // Core components are terminated in a second stage, we remove them from the // registry upfront and deal with them later. std::vector<caf::actor> core_shutdown_handles; caf::actor filesystem_handle; // The components listed here need to be terminated in sequential order. // The importer needs to shut down first because it might still have // buffered data. The index uses the archive for querying. The filesystem // is needed by all others for the persisting logic. auto shutdown_sequence = std::initializer_list<const char*>{ "importer", "index", "archive", "catalog", "filesystem"}; // Make sure that these remain in sync. VAST_ASSERT(std::set<const char*>{shutdown_sequence} == core_components); for (const char* name : shutdown_sequence) { if (auto comp = registry.remove(name)) { if (comp->type == "filesystem") filesystem_handle = comp->actor; else core_shutdown_handles.push_back(comp->actor); } } std::vector<caf::actor> aux_components; for (const auto& [_, comp] : registry.components()) { self->demonitor(comp.actor); // Ignore remote actors. if (comp.actor->node() != self->node()) continue; aux_components.push_back(comp.actor); } // Drop everything. registry.clear(); auto shutdown_kill_timeout = shutdown_grace_period / 5; auto core_shutdown_sequence = [=, core_shutdown_handles = std::move(core_shutdown_handles), filesystem_handle = std::move(filesystem_handle)]() mutable { for (const auto& comp : core_shutdown_handles) self->demonitor(comp); shutdown<policy::sequential>(self, std::move(core_shutdown_handles), shutdown_grace_period, shutdown_kill_timeout); // We deliberately do not send an exit message to the filesystem // actor, as that would mean that actors not tracked by the component // registry which hold a strong handle to the filesystem actor cannot // use it for persistence on shutdown. self->demonitor(filesystem_handle); filesystem_handle = {}; }; terminate<policy::parallel>(self, std::move(aux_components), shutdown_grace_period, shutdown_kill_timeout) .then( [self, core_shutdown_sequence](atom::done) mutable { VAST_DEBUG("{} terminated auxiliary actors, commencing core shutdown " "sequence...", *self); core_shutdown_sequence(); }, [self, core_shutdown_sequence](const caf::error& err) mutable { VAST_ERROR("{} failed to cleanly terminate auxiliary actors {}, " "shutting down core components", *self, err); core_shutdown_sequence(); }); }); // Define the node behavior. return { [self](atom::run, const invocation& inv) -> caf::result<caf::message> { VAST_DEBUG("{} got command {} with options {} and arguments {}", *self, inv.full_name, inv.options, inv.arguments); // Run the command. this_node = self; return run(inv, self->system(), node_state::command_factory); }, [self](atom::internal, atom::spawn, atom::plugin) -> caf::result<void> { // Add all plugins to the component registry. for (const auto& plugin : plugins::get()) { if (const auto* component = plugin.as<component_plugin>()) { if (auto handle = component->make_component(self); !handle) return caf::make_error( // ec::unspecified, fmt::format("{} failed to spawn component " "plugin {}", *self, component->name())); else if (auto err = register_component( self, caf::actor_cast<caf::actor>(handle), component->name()); err && err != caf::no_error) return caf::make_error( // ec::unspecified, fmt::format("{} failed to register component " "plugin {} in component registry: " "{}", *self, component->name(), err)); } } return {}; }, [self](atom::spawn, const invocation& inv) { VAST_DEBUG("{} got spawn command {} with options {} and arguments {}", *self, inv.full_name, inv.options, inv.arguments); // Run the command. this_node = self; auto msg = run(inv, self->system(), node_state::command_factory); auto result = caf::expected<caf::actor>{caf::no_error}; if (!msg) { result = std::move(msg.error()); } else if (msg->empty()) { VAST_VERBOSE("{} encountered empty invocation response", *self); } else { msg->apply({ [&](caf::error& x) { result = std::move(x); }, [&](caf::actor& x) { result = std::move(x); }, [&](caf::message& x) { VAST_ERROR("{} encountered invalid invocation response: {}", *self, deep_to_string(x)); result = caf::make_error(ec::invalid_result, "invalid spawn invocation response", std::move(x)); }, }); } return result; }, [self](atom::put, const caf::actor& component, const std::string& type) -> caf::result<atom::ok> { VAST_DEBUG("{} got new {}", *self, type); if (type.empty()) return caf::make_error(ec::unspecified, "empty component type"); // Check if the new component is a singleton. auto& registry = self->state.registry; if (is_singleton(type) && registry.find_by_label(type)) return caf::make_error(ec::unspecified, "component already exists"); // Generate label auto label = generate_label(self, type); VAST_DEBUG("{} generated new component label {}", *self, label); if (auto err = register_component(self, component, type, label)) return err; return atom::ok_v; }, [self](atom::get, atom::type, const std::string& type) { VAST_DEBUG("{} got a request for a component of type {}", *self, type); auto result = self->state.registry.find_by_type(type); VAST_DEBUG("{} responds to the request for {} with {}", *self, type, result); return result; }, [self](atom::get, atom::label, const std::string& label) { VAST_DEBUG("{} got a request for the component {}", *self, label); auto result = self->state.registry.find_by_label(label); VAST_DEBUG("{} responds to the request for {} with {}", *self, label, result); return result; }, [self](atom::get, atom::label, const std::vector<std::string>& labels) { VAST_DEBUG("{} got a request for the components {}", *self, labels); std::vector<caf::actor> result; result.reserve(labels.size()); for (const auto& label : labels) result.push_back(self->state.registry.find_by_label(label)); VAST_DEBUG("{} responds to the request for {} with {}", *self, labels, result); return result; }, [](atom::get, atom::version) { // return retrieve_versions(); }, [self](atom::signal, int signal) { VAST_WARN("{} got signal {}", *self, ::strsignal(signal)); }, }; } } // namespace vast::system
41.94132
80
0.632739
[ "render", "vector", "model", "transform" ]
f3f3ccd25f5ad08a644d9be36c7aafaf9f79fdf9
4,388
cpp
C++
luogu/4841/me.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
luogu/4841/me.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
luogu/4841/me.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=132000; const int MOD=1004535809; inline int read(){ int x=0,f=0; char ch=getchar(); while(ch<'0'||ch>'9') f|=(ch=='-'),ch=getchar(); while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); return f==0 ? x : -x; } inline void write(int x){ if(x<0) {x=~(x-1); putchar('-');} if(x>9) write(x/10); putchar(x%10+'0'); } typedef vector<int> Poly; void read_Poly(Poly &A,int n){ A.resize(n); for(register int i=0;i<n;++i) A[i]=read(); } void write_Poly(Poly A){ for(register int i=0;i<(int)A.size();++i) write(A[i]),printf(" "); puts(""); } int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;} int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;} #define mul(a,b) (ll)(a)*(b)%MOD void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;} void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;} void Mul(int &x,int y){x=1ll*x*y%MOD;} int qpow(int x,ll y){int ret=1; while(y) {if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;} int Inv(int x){return qpow(x,MOD-2);} int inv[N]; namespace FFT{ int rev[N<<1],G[N<<1],IG[N<<1]; int init(int n){ int len=1; while(len<n) len<<=1; rev[0]=0; rev[len-1]=len-1; for(register int i=1;i<len-1;++i) rev[i]=(rev[i>>1]>>1)+(i&1 ? len>>1 : 0); for(register int i=1;i<=len;i<<=1){ G[i]=qpow(3,(MOD-1)/i); IG[i]=qpow(G[i],MOD-2); } return len; } void ntt(int *a,int len,int flag){ for(register int i=0;i<len;++i) if(i<rev[i]) swap(a[i],a[rev[i]]); for(register int h=1;h<len;h<<=1){ int wn=(flag==1 ? G[h<<1] : IG[h<<1]); for(register int i=0;i<len;i+=(h<<1)){ int W=1,tmp1,tmp2; for(register int j=i;j<i+h;++j){ tmp1=a[j], tmp2=mul(a[j+h],W); a[j]=add(tmp1,tmp2); a[j+h]=sub(tmp1,tmp2); W=mul(W,wn); } } } if(flag==-1){ int invlen=qpow(len,MOD-2); for(register int i=0;i<len;++i) a[i]=mul(a[i],invlen); } } void multi(int *a,int *b,int len) { ntt(a,len,1); ntt(b,len,1); for(register int i=0;i<len;++i) a[i]=mul(a[i],b[i]); ntt(a,len,-1); } } Poly operator + (Poly A,Poly B){ int len=max((int)A.size(),(int)B.size()); A.resize(len); B.resize(len); for(register int i=0;i<len;++i) Add(A[i],B[i]); return A; } Poly operator - (Poly A,Poly B){ int len=max((int)A.size(),(int)B.size()); A.resize(len); B.resize(len); for(register int i=0;i<len;++i) Sub(A[i],B[i]); return A; } Poly operator * (Poly A,Poly B){ static int a[N<<1],b[N<<1]; int M=(int)A.size()+(int)B.size()-1; int len=FFT::init(M); A.resize(len); B.resize(len); for(register int i=0;i<len;++i) a[i]=A[i],b[i]=B[i]; FFT::multi(a,b,len); A.resize(M); for(register int i=0;i<M;++i) A[i]=a[i]; return A; } void reverse(Poly &A){ for(register int i=0;i<(int)A.size()/2;++i){ swap(A[i],A[(int)A.size()-1-i]); } } void Inverse(Poly A,Poly &B,int n){ static int a[N<<1],b[N<<1]; if(n==1){ B[0]=Inv(A[0]); return; } int mid=(n+1)/2; Inverse(A,B,mid); int len=FFT::init(n<<1); for(register int i=0;i<len;++i) a[i]=b[i]=0; for(register int i=0;i<n;++i) a[i]=A[i]; for(register int i=0;i<mid;++i) b[i]=B[i]; FFT::ntt(a,len,1); FFT::ntt(b,len,1); for(register int i=0;i<len;++i){ b[i]=mul(b[i],sub(2,mul(a[i],b[i]))); } FFT::ntt(b,len,-1); for(register int i=0;i<n;++i) B[i]=b[i]; } Poly Polynomial_Inverse(Poly A){ Poly B; B.resize(A.size()); Inverse(A,B,(int)A.size()); return B; } int ifac[N],fac[N]; signed main(){ inv[0]=1; inv[1]=1; for(register int i=2;i<N;++i) inv[i]=mul(MOD-MOD/i,inv[MOD%i]); int n=read(); ifac[0]=1; for(int i=1;i<=n;i++) ifac[i]=mul(ifac[i-1],inv[i]); fac[0]=1; for(int i=1;i<=n;i++) fac[i]=mul(fac[i-1],i); Poly H,G,F; H.resize(n+1); G.resize(n+1); for(int i=1;i<=n;i++) H[i]=qpow(2,1ll*i*(i-1)/2); for(int i=1;i<=n;i++) G[i]=mul(H[i],ifac[i-1]),H[i]=mul(H[i],ifac[i]); H[0]=1; F=G*Polynomial_Inverse(H); for(int i=1;i<=n;i++) F[i]=mul(F[i],fac[i-1]); cout<<F[n]<<endl; return 0; }
29.85034
98
0.5
[ "vector" ]
f3f463bda08dc96673cc93d4e3bfad14f1114a1e
6,681
cc
C++
deviceOnline/src/device_alive.cc
houbin/alarm
3c0c150ac85a0f1092d26de55ee3af6beac4fc15
[ "Apache-2.0" ]
null
null
null
deviceOnline/src/device_alive.cc
houbin/alarm
3c0c150ac85a0f1092d26de55ee3af6beac4fc15
[ "Apache-2.0" ]
null
null
null
deviceOnline/src/device_alive.cc
houbin/alarm
3c0c150ac85a0f1092d26de55ee3af6beac4fc15
[ "Apache-2.0" ]
null
null
null
//============================================================================ // Name : deviceOnline.cpp // Author : yaocoder // Version : // Copyright : Your copyright notice // Description : Hello World in C, Ansi-style //============================================================================ #include <signal.h> #include "defines.h" #include "init_configure.h" #include "master_thread.h" #include "redis_conn_pool.h" #include "global_settings.h" #include "../../public/utils.h" #include "../../public/config_file.h" #include "redis_opt.h" #include "device_alive.h" #include "test.h" #include "local_transport.h" #include "logic_opt.h" static void InitConfigure(); static void SettingsAndPrint(); static void InitRedis(); static void Run(); static void SigUsr(int signo); PushMsgQueue *g_push_msg_queue = NULL; HttpClient *g_http_client = NULL; TestThread *g_test_thread = NULL; int main(int argc, char **argv) { /* process arguments */ int c; std::string version = std::string("1.0.387"); while (-1 != (c = getopt(argc, argv, "v" /* 获取程序版本号,配合svn */ ))) { switch (c) { case 'v': printf("The version is %s\n", version.c_str()); return EXIT_SUCCESS; default: break; } } InitConfigure(); SettingsAndPrint(); if(signal(SIGUSR1, SigUsr) == SIG_ERR) { LOG4CXX_FATAL(g_logger, "Configure signal failed."); exit(EXIT_FAILURE); } InitRedis(); if (daemon(1, 0) == -1) { LOG4CXX_FATAL(g_logger, "daemon failed."); } // clear redis data ClearDeviceCache(); // start http client int ret = 0; ret = StartHttpClient(); if (ret != 0) { LOG4CXX_ERROR(g_logger, "start http client error, ret " << ret); return -1; } // start local_transport CLocalTransport *local_transport = CLocalTransport::GetInstance(); local_transport->SetupLocalTransport(); Run(); return EXIT_SUCCESS; } void ClearDeviceCache() { bool bRet; long long cursor = 0; long long next_cursor = 0; long long keys_sum_count = 0; redisContext* redis_con = CRedisConnPool::GetInstance()->GetRedisContext(); CRedisOpt redis_opt; redis_opt.SetRedisContext(redis_con); redis_opt.SelectDB(REDIS_DEVICE_INFO); while (true) { vector<string> vec_keys; bRet = redis_opt.Scan(cursor, vec_keys, next_cursor); if (!bRet) { LOG4CXX_ERROR(g_logger, "redis_opt hscan error, cursor " << cursor << ", next_cursor " << next_cursor); break; } vector<string>::iterator iter = vec_keys.begin(); for (; iter != vec_keys.end(); iter++) { LOG4CXX_ERROR(g_logger, "redis_opt clear " << *iter); redis_opt.Del(*iter); } cursor = next_cursor; keys_sum_count += vec_keys.size(); if (cursor == 0) { LOG4CXX_INFO(g_logger, "redis_opt scan over, sum of keys " << keys_sum_count); break; } } CRedisConnPool::GetInstance()->ReleaseRedisContext(redis_con); return; } int StartHttpClient() { int ret = 0; g_http_client = new HttpClient(); if (g_http_client == NULL) { return -1; } ret = g_http_client->Init(); if (ret != 0) { LOG4CXX_FATAL(g_logger, "http client init failed."); return ret; } g_http_client->Start(); return 0; } void Run() { // start push message queue g_push_msg_queue = new PushMsgQueue(); g_push_msg_queue->Start(); CMasterThread masterThread; if(!masterThread.InitMasterThread()) { LOG4CXX_FATAL(g_logger, "InitMasterThread failed."); exit(EXIT_FAILURE); } masterThread.Run(); } void SigUsr(int signo) { if(signo == SIGUSR1) { /* 重新加载应用配置文件(仅仅是连接超时时间),log4cxx日志配置文件*/ InitConfigure(); SettingsAndPrint(); LOG4CXX_INFO(g_logger, "reload configure."); return; } } void InitConfigure() { CInitConfig initConfObj; initConfObj.SetConfigFilePath(std::string("/etc/jovision/alarm/conf/")); std::string project_name = "deviceOnline"; initConfObj.InitLog4cxx(project_name); if (!initConfObj.LoadConfiguration(project_name)) { LOG4CXX_FATAL(g_logger, "LoadConfiguration failed."); exit(EXIT_FAILURE); } } void InitRedis() { RedisConnInfo redisConnInfo; redisConnInfo.max_conn_num = 4; redisConnInfo.ip = utils::G<ConfigFile>().read<std::string> ("redis.ip", "127.0.0.1"); redisConnInfo.port = utils::G<ConfigFile>().read<int> ("redis.port", 6379); if (!CRedisConnPool::GetInstance()->Init(redisConnInfo)) { LOG4CXX_FATAL(g_logger, "Init redisConnPool failed."); exit(EXIT_FAILURE); } } void SettingsAndPrint() { utils::G<CGlobalSettings>().public_addr_ = utils::G<ConfigFile>().read<string> ("public.addr", "127.0.0.1"); utils::G<CGlobalSettings>().private_addr_ = utils::G<ConfigFile>().read<string> ("private.addr", "127.0.0.1"); utils::G<CGlobalSettings>().remote_listen_port_ = utils::G<ConfigFile>().read<int> ("remote.listen.port", 15030); utils::G<CGlobalSettings>().thread_num_= utils::G<ConfigFile>().read<int> ("worker.thread.num", 4); utils::G<CGlobalSettings>().client_heartbeat_timeout_ = utils::G<ConfigFile>().read<int>("client.heartbeat.timeout", 11); utils::G<CGlobalSettings>().local_listen_port_ = utils::G<ConfigFile>().read<int>("local.listen.port", 15031); utils::G<CGlobalSettings>().local_conn_timeout_ = utils::G<ConfigFile>().read<int>("local.conn.timeout", 5); utils::G<CGlobalSettings>().httpserver_url_ = utils::G<ConfigFile>().read<string>("httpserver.url", "http://172.16.27.219:8081/netalarm-rs/rsapi/userauth/login"); LOG4CXX_INFO(g_logger, "******deviceOnline.public.addr = " << utils::G<CGlobalSettings>().public_addr_ << "******"); LOG4CXX_INFO(g_logger, "******deviceOnline.private.addr = " << utils::G<CGlobalSettings>().private_addr_ << "******"); LOG4CXX_INFO(g_logger, "******deviceOnline.remote.listen.port = " << utils::G<CGlobalSettings>().remote_listen_port_ << "******"); LOG4CXX_INFO(g_logger, "******deviceOnline.worker.thread.num = " << utils::G<CGlobalSettings>().thread_num_ << "******"); LOG4CXX_INFO(g_logger, "******deviceOnline.client.timeout.s = " << utils::G<CGlobalSettings>().client_heartbeat_timeout_ << "******"); LOG4CXX_INFO(g_logger, "******deviceOnline.httpserver.url = " << utils::G<CGlobalSettings>().httpserver_url_ << "******"); }
29.174672
166
0.612184
[ "vector" ]
f3f6fb54c707bbe0b71d98d9dc752f9e1cc31fa4
2,226
cpp
C++
mlir/lib/IR/TypeRange.cpp
rarutyun/llvm
76fa6b3bcade074bdedef740001c4528e1aa08a8
[ "Apache-2.0" ]
305
2019-09-14T17:16:05.000Z
2022-03-31T15:05:20.000Z
mlir/lib/IR/TypeRange.cpp
rarutyun/llvm
76fa6b3bcade074bdedef740001c4528e1aa08a8
[ "Apache-2.0" ]
11
2019-10-17T21:11:52.000Z
2022-02-17T20:10:00.000Z
mlir/lib/IR/TypeRange.cpp
rarutyun/llvm
76fa6b3bcade074bdedef740001c4528e1aa08a8
[ "Apache-2.0" ]
24
2019-10-03T11:22:11.000Z
2022-01-25T09:59:30.000Z
//===- TypeRange.cpp ------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "mlir/IR/TypeRange.h" #include "mlir/IR/Operation.h" using namespace mlir; //===----------------------------------------------------------------------===// // TypeRange TypeRange::TypeRange(ArrayRef<Type> types) : TypeRange(types.data(), types.size()) {} TypeRange::TypeRange(OperandRange values) : TypeRange(values.begin().getBase(), values.size()) {} TypeRange::TypeRange(ResultRange values) : TypeRange(values.getBase()->getResultTypes().slice(values.getStartIndex(), values.size())) {} TypeRange::TypeRange(ArrayRef<Value> values) : TypeRange(values.data(), values.size()) {} TypeRange::TypeRange(ValueRange values) : TypeRange(OwnerT(), values.size()) { detail::ValueRangeOwner owner = values.begin().getBase(); if (auto *op = reinterpret_cast<Operation *>(owner.ptr.dyn_cast<void *>())) this->base = op->getResultTypes().drop_front(owner.startIndex).data(); else if (auto *operand = owner.ptr.dyn_cast<OpOperand *>()) this->base = operand; else this->base = owner.ptr.get<const Value *>(); } /// See `llvm::detail::indexed_accessor_range_base` for details. TypeRange::OwnerT TypeRange::offset_base(OwnerT object, ptrdiff_t index) { if (const auto *value = object.dyn_cast<const Value *>()) return {value + index}; if (auto *operand = object.dyn_cast<OpOperand *>()) return {operand + index}; return {object.dyn_cast<const Type *>() + index}; } /// See `llvm::detail::indexed_accessor_range_base` for details. Type TypeRange::dereference_iterator(OwnerT object, ptrdiff_t index) { if (const auto *value = object.dyn_cast<const Value *>()) return (value + index)->getType(); if (auto *operand = object.dyn_cast<OpOperand *>()) return (operand + index)->get().getType(); return object.dyn_cast<const Type *>()[index]; }
43.647059
80
0.615004
[ "object" ]
f3fcafbe15127cdbd9a116ab62b78b8ebe8659ae
29,335
cpp
C++
solid/frame/mprpc/test/test_clientfrontback_download.cpp
solidoss/solidframe
92fa8ce5737b9e88f3df3f549a38e9df79b7bf96
[ "BSL-1.0" ]
4
2020-12-05T23:33:32.000Z
2021-10-04T02:59:41.000Z
solid/frame/mprpc/test/test_clientfrontback_download.cpp
solidoss/solidframe
92fa8ce5737b9e88f3df3f549a38e9df79b7bf96
[ "BSL-1.0" ]
1
2020-03-22T20:38:05.000Z
2020-03-22T20:38:05.000Z
solid/frame/mprpc/test/test_clientfrontback_download.cpp
solidoss/solidframe
92fa8ce5737b9e88f3df3f549a38e9df79b7bf96
[ "BSL-1.0" ]
2
2021-01-30T09:08:52.000Z
2021-02-20T03:33:33.000Z
#include "solid/frame/mprpc/mprpcsocketstub_openssl.hpp" #include "solid/frame/mprpc/mprpccompression_snappy.hpp" #include "solid/frame/mprpc/mprpcconfiguration.hpp" #include "solid/frame/mprpc/mprpcprotocol_serialization_v3.hpp" #include "solid/frame/mprpc/mprpcservice.hpp" #include "solid/frame/manager.hpp" #include "solid/frame/scheduler.hpp" #include "solid/frame/service.hpp" #include "solid/frame/aio/aioactor.hpp" #include "solid/frame/aio/aiolistener.hpp" #include "solid/frame/aio/aioreactor.hpp" #include "solid/frame/aio/aioresolver.hpp" #include "solid/frame/aio/aiotimer.hpp" #include "solid/utility/string.hpp" #include "solid/system/directory.hpp" #include "solid/system/exception.hpp" #include "solid/system/log.hpp" #include <fstream> #include <future> #include <iomanip> #include <iostream> #include <sstream> using namespace std; using namespace solid; using AioSchedulerT = frame::Scheduler<frame::aio::Reactor>; using SecureContextT = frame::aio::openssl::Context; namespace { LoggerT logger("test"); frame::mprpc::ServiceT* pmprpc_back_client = nullptr; frame::mprpc::ServiceT* pmprpc_front_server = nullptr; atomic<size_t> expect_count(0); promise<void> prom; namespace back { struct Request; } //namespace back namespace front { struct Response; struct Request : frame::mprpc::Message { string name_; ofstream ofs_; bool send_request_; Request() { } Request(Response& _res); Request(const string& _name) : name_(_name) , send_request_(true) { } ~Request() override { } SOLID_REFLECT_V1(_s, _rthis, _rctx) { _s.add(_rthis.name_, _rctx, 1, "name"); } }; struct Response : frame::mprpc::Message { uint32_t error_; ostringstream oss_; mutable istringstream iss_; std::shared_ptr<back::Request> req_ptr_; frame::mprpc::RecipientId recipient_id_; Response() : error_(0) { } Response(Request& _req) : frame::mprpc::Message(_req) , error_(0) { } ~Response() override { } SOLID_REFLECT_V1(_rr, _rthis, _rctx) { _rr.add(_rthis.error_, _rctx, 1, "error"); if constexpr (!Reflector::is_const_reflector) { auto progress_lambda = [](Context& _rctx, std::ostream& _ris, uint64_t _len, const bool _done, const size_t _index, const char* _name) { //NOTE: here you can use context.any()for actual implementation if (_done) { solid_log(logger, Verbose, "Progress(" << _name << "): " << _len << " done = " << _done); } }; _rr.add(_rthis.oss_, _rctx, 2, "stream", [&progress_lambda](auto& _rmeta) { _rmeta.progressFunction(progress_lambda); }); } else { auto progress_lambda = [](Context& _rctx, std::istream& _ris, uint64_t _len, const bool _done, const size_t _index, const char* _name) { //NOTE: here you can use context.any()for actual implementation if (_done) { solid_log(logger, Verbose, "Progress(" << _name << "): " << _len << " done = " << _done); } }; _rr.add(_rthis.iss_, _rctx, 2, "stream", [&progress_lambda](auto& _rmeta) { _rmeta.progressFunction(progress_lambda); }); } } }; Request::Request(Response& _res) : frame::mprpc::Message(_res) { } void on_server_receive_first_request( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<front::Request>& _rsent_msg_ptr, std::shared_ptr<front::Request>& _rrecv_msg_ptr, ErrorConditionT const& _rerror); void on_server_response( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Response>& _rsent_msg_ptr, std::shared_ptr<Response>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_log(logger, Verbose, "front: on message: " << _rsent_msg_ptr.get()); } void on_client_request( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Request>& _rsent_msg_ptr, std::shared_ptr<Request>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_log(logger, Verbose, "front: on message"); } void on_client_response( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Response>& _rsent_msg_ptr, std::shared_ptr<Response>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_log(logger, Verbose, "front: on message"); } void on_client_receive_response( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Request>& _rsent_msg_ptr, std::shared_ptr<Response>& _rrecv_msg_ptr, ErrorConditionT const& _rerror); } //namespace front namespace back { struct Response; struct Request : frame::mprpc::Message { string name_; std::shared_ptr<front::Response> res_ptr_; frame::mprpc::RecipientId recipient_id_; bool await_response_; Request() { } Request(Response& _res); ~Request() override { } SOLID_REFLECT_V1(_rr, _rthis, _rctx) { _rr.add(_rthis.name_, _rctx, 1, "name"); } }; struct Response : frame::mprpc::Message { uint32_t error_; ostringstream oss_; mutable ifstream ifs_; Response() : error_(0) { } Response(Request& _req) : frame::mprpc::Message(_req) , error_(0) { } ~Response() override { } SOLID_REFLECT_V1(_rr, _rthis, _rctx) { _rr.add(_rthis.error_, _rctx, 1, "error"); if constexpr (!Reflector::is_const_reflector) { auto progress_lambda = [](Context& _rctx, std::ostream& _ris, uint64_t _len, const bool _done, const size_t _index, const char* _name) { //NOTE: here you can use context.any()for actual implementation if (_done) { solid_log(logger, Verbose, "Progress(" << _name << "): " << _len << " done = " << _done); } }; _rr.add(_rthis.oss_, _rctx, 2, "stream", [&progress_lambda](auto& _rmeta) { _rmeta.progressFunction(progress_lambda); }); } else { auto progress_lambda = [](Context& _rctx, std::istream& _ris, uint64_t _len, const bool _done, const size_t _index, const char* _name) { //NOTE: here you can use context.any()for actual implementation if (_done) { solid_log(logger, Verbose, "Progress(" << _name << "): " << _len << " done = " << _done); } }; _rr.add(_rthis.ifs_, _rctx, 2, "stream", [&progress_lambda](auto& _rmeta) { _rmeta.progressFunction(progress_lambda).size(100 * 1024); }); } } }; Request::Request(Response& _res) : frame::mprpc::Message(_res) { } void on_server_receive_first_request( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Request>& _rsent_msg_ptr, std::shared_ptr<Request>& _rrecv_msg_ptr, ErrorConditionT const& _rerror); void on_server_response( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Response>& _rsent_msg_ptr, std::shared_ptr<Response>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_log(logger, Verbose, "back: on message"); } void on_client_request( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Request>& _rsent_msg_ptr, std::shared_ptr<Request>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_log(logger, Verbose, "back: on message"); } void on_client_response( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Response>& _rsent_msg_ptr, std::shared_ptr<Response>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_log(logger, Verbose, "back: on message"); } } //namespace back void create_files(vector<string>& _file_vec, const char* _path_prefix, uint64_t _count, uint64_t _start_size, uint64_t _increment_size); void check_files(const vector<string>& _file_vec, const char* _path_prefix_client, const char* _path_prefix_server); } //namespace int test_clientfrontback_download(int argc, char* argv[]) { solid::log_start(std::cerr, {".*:EWX", "test:IEW"}); size_t max_per_pool_connection_count = 1; bool secure = false; bool compress = false; uint64_t count = 4; uint64_t start_size = make_number("30M"); uint64_t increment_size = make_number("10M"); if (argc > 1) { max_per_pool_connection_count = atoi(argv[1]); if (max_per_pool_connection_count == 0) { max_per_pool_connection_count = 1; } if (max_per_pool_connection_count > 100) { max_per_pool_connection_count = 100; } } if (argc > 2) { if (*argv[2] == 's' || *argv[2] == 'S') { secure = true; } if (*argv[2] == 'c' || *argv[2] == 'C') { compress = true; } if (*argv[2] == 'b' || *argv[2] == 'B') { secure = true; compress = true; } } if (argc > 3) { count = atoi(argv[1]); } if (argc > 4) { start_size = make_number(argv[2]); } if (argc > 5) { increment_size = make_number(argv[3]); } system("rm -rf client_storage"); system("rm -rf server_storage"); Directory::create("client_storage"); Directory::create("server_storage"); vector<string> file_vec; create_files(file_vec, "server_storage", count, start_size, increment_size); solid_log(logger, Info, "Done creating files"); { AioSchedulerT sch_client; AioSchedulerT sch_front; AioSchedulerT sch_back; frame::Manager m; frame::mprpc::ServiceT mprpc_front_client(m); frame::mprpc::ServiceT mprpc_front_server(m); frame::mprpc::ServiceT mprpc_back_client(m); frame::mprpc::ServiceT mprpc_back_server(m); ErrorConditionT err; CallPool<void()> cwp{WorkPoolConfiguration(), 1}; frame::aio::Resolver resolver(cwp); sch_client.start(1); sch_front.start(1); sch_back.start(1); std::string back_port; std::string front_port; { //mprpc back_server initialization auto proto = frame::mprpc::serialization_v3::create_protocol<reflection::v1::metadata::Variant, uint8_t>( reflection::v1::metadata::factory, [&](auto& _rmap) { _rmap.template registerMessage<back::Request>(1, "Request", back::on_server_receive_first_request); _rmap.template registerMessage<back::Response>(2, "Response", back::on_server_response); }); frame::mprpc::Configuration cfg(sch_back, proto); //cfg.recv_buffer_capacity = 1024; //cfg.send_buffer_capacity = 1024; cfg.server.listener_address_str = "0.0.0.0:0"; cfg.server.connection_start_state = frame::mprpc::ConnectionState::Active; if (secure) { solid_dbg(logger, Info, "Configure SSL server -------------------------------------"); frame::mprpc::openssl::setup_server( cfg, [](frame::aio::openssl::Context& _rctx) -> ErrorCodeT { _rctx.loadVerifyFile("echo-ca-cert.pem" /*"/etc/pki/tls/certs/ca-bundle.crt"*/); _rctx.loadCertificateFile("echo-server-cert.pem"); _rctx.loadPrivateKeyFile("echo-server-key.pem"); return ErrorCodeT(); }, frame::mprpc::openssl::NameCheckSecureStart{"echo-client"}); } if (compress) { frame::mprpc::snappy::setup(cfg); } mprpc_back_server.start(std::move(cfg)); { std::ostringstream oss; oss << mprpc_back_server.configuration().server.listenerPort(); back_port = oss.str(); solid_dbg(logger, Verbose, "back listens on port: " << back_port); } } { //mprpc back_client initialization auto proto = frame::mprpc::serialization_v3::create_protocol<reflection::v1::metadata::Variant, uint8_t>( reflection::v1::metadata::factory, [&](auto& _rmap) { _rmap.template registerMessage<back::Request>(1, "Request", back::on_client_request); _rmap.template registerMessage<back::Response>(2, "Response", back::on_client_response); }); frame::mprpc::Configuration cfg(sch_front, proto); cfg.pool_max_active_connection_count = max_per_pool_connection_count; cfg.client.name_resolve_fnc = frame::mprpc::InternetResolverF(resolver, back_port.c_str() /*, SocketInfo::Inet4*/); cfg.client.connection_start_state = frame::mprpc::ConnectionState::Active; if (secure) { solid_dbg(logger, Info, "Configure SSL client ------------------------------------"); frame::mprpc::openssl::setup_client( cfg, [](frame::aio::openssl::Context& _rctx) -> ErrorCodeT { _rctx.loadVerifyFile("echo-ca-cert.pem" /*"/etc/pki/tls/certs/ca-bundle.crt"*/); _rctx.loadCertificateFile("echo-client-cert.pem"); _rctx.loadPrivateKeyFile("echo-client-key.pem"); return ErrorCodeT(); }, frame::mprpc::openssl::NameCheckSecureStart{"echo-server"}); } if (compress) { frame::mprpc::snappy::setup(cfg); } mprpc_back_client.start(std::move(cfg)); pmprpc_back_client = &mprpc_back_client; } { //mprpc front_server initialization auto proto = frame::mprpc::serialization_v3::create_protocol<reflection::v1::metadata::Variant, uint8_t>( reflection::v1::metadata::factory, [&](auto& _rmap) { _rmap.template registerMessage<front::Request>(1, "Request", front::on_server_receive_first_request); _rmap.template registerMessage<front::Response>(2, "Response", front::on_server_response); }); frame::mprpc::Configuration cfg(sch_front, proto); //cfg.recv_buffer_capacity = 1024; //cfg.send_buffer_capacity = 1024; cfg.server.listener_address_str = "0.0.0.0:0"; cfg.server.connection_start_state = frame::mprpc::ConnectionState::Active; if (secure) { solid_dbg(logger, Info, "Configure SSL server -------------------------------------"); frame::mprpc::openssl::setup_server( cfg, [](frame::aio::openssl::Context& _rctx) -> ErrorCodeT { _rctx.loadVerifyFile("echo-ca-cert.pem" /*"/etc/pki/tls/certs/ca-bundle.crt"*/); _rctx.loadCertificateFile("echo-server-cert.pem"); _rctx.loadPrivateKeyFile("echo-server-key.pem"); return ErrorCodeT(); }, frame::mprpc::openssl::NameCheckSecureStart{"echo-client"}); } if (compress) { frame::mprpc::snappy::setup(cfg); } mprpc_front_server.start(std::move(cfg)); { std::ostringstream oss; oss << mprpc_front_server.configuration().server.listenerPort(); front_port = oss.str(); solid_dbg(logger, Verbose, "front listens on port: " << front_port); } pmprpc_front_server = &mprpc_front_server; } { //mprpc front_client initialization auto proto = frame::mprpc::serialization_v3::create_protocol<reflection::v1::metadata::Variant, uint8_t>( reflection::v1::metadata::factory, [&](auto& _rmap) { _rmap.template registerMessage<front::Request>(1, "Request", front::on_client_request); _rmap.template registerMessage<front::Response>(2, "Response", front::on_client_response); }); frame::mprpc::Configuration cfg(sch_client, proto); cfg.pool_max_active_connection_count = max_per_pool_connection_count; cfg.client.name_resolve_fnc = frame::mprpc::InternetResolverF(resolver, front_port.c_str() /*, SocketInfo::Inet4*/); cfg.client.connection_start_state = frame::mprpc::ConnectionState::Active; if (secure) { solid_dbg(logger, Info, "Configure SSL client ------------------------------------"); frame::mprpc::openssl::setup_client( cfg, [](frame::aio::openssl::Context& _rctx) -> ErrorCodeT { _rctx.loadVerifyFile("echo-ca-cert.pem" /*"/etc/pki/tls/certs/ca-bundle.crt"*/); _rctx.loadCertificateFile("echo-client-cert.pem"); _rctx.loadPrivateKeyFile("echo-client-key.pem"); return ErrorCodeT(); }, frame::mprpc::openssl::NameCheckSecureStart{"echo-server"}); } if (compress) { frame::mprpc::snappy::setup(cfg); } mprpc_front_client.start(std::move(cfg)); } expect_count = file_vec.size(); for (const auto& f : file_vec) { auto msg_ptr = make_shared<front::Request>(f); msg_ptr->ofs_.open(string("client_storage/") + f); mprpc_front_client.sendRequest("localhost", msg_ptr, front::on_client_receive_response); } auto fut = prom.get_future(); solid_check(fut.wait_for(chrono::seconds(150)) == future_status::ready, "Taking too long - waited 150 secs"); fut.get(); solid_log(logger, Info, "Done upload"); check_files(file_vec, "client_storage", "server_storage"); solid_log(logger, Info, "Done file checking - exiting"); } return 0; } namespace { size_t real_size(size_t _sz) { //offset + (align - (offset mod align)) mod align return _sz + ((sizeof(uint64_t) - (_sz % sizeof(uint64_t))) % sizeof(uint64_t)); } void create_files(vector<string>& _file_vec, const char* _path_prefix, uint64_t _count, uint64_t _start_size, uint64_t _increment_size) { string pattern; for (int j = 0; j < 1; ++j) { for (int i = 0; i < 127; ++i) { int c = (i + j) % 127; if (isprint(c) != 0 && isblank(c) == 0) { pattern += static_cast<char>(c); } } } size_t sz = real_size(pattern.size()); if (sz > pattern.size()) { pattern.resize(sz - sizeof(uint64_t)); } else if (sz < pattern.size()) { pattern.resize(sz); } string fname; uint64_t crtsz = _start_size; for (size_t i = 0; i < _count; ++i) { { ostringstream oss; oss << "test_file_" << i << "_" << crtsz << ".txt"; _file_vec.emplace_back(oss.str()); } fname = string(_path_prefix) + '/' + _file_vec.back(); ofstream ofs(fname); solid_check(ofs, "failed open file: " << fname); int64_t sz = crtsz; int64_t line = 0; do { ofs << hex << setw(8) << setfill('0') << line << ' '; ofs.write(pattern.data(), pattern.size()); ofs << "\r\n"; sz -= pattern.size(); sz -= 11; ++line; } while (sz > 0); crtsz += _increment_size; } } void compare_streams(istream& _is1, istream& _is2) { constexpr size_t bufsz = 4 * 1024; char buf1[bufsz]; char buf2[bufsz]; uint64_t off = 0; do { _is1.read(buf1, bufsz); _is2.read(buf2, bufsz); size_t r1 = _is1.gcount(); size_t r2 = _is2.gcount(); solid_check(r1 == r2, "failed read at offset: " << off); solid_check(memcmp(buf1, buf2, r1) == 0, "failed chec at offset: " << off); off += r1; } while (!_is1.eof() || !_is2.eof()); solid_check(_is1.eof() && _is2.eof(), "not both streams eof"); } void check_files(const vector<string>& _file_vec, const char* _path_prefix_client, const char* _path_prefix_server) { for (auto& f : _file_vec) { string clientpath = string(_path_prefix_client) + '/' + f; string serverpath = string(_path_prefix_server) + '/' + f; ifstream ifsc(clientpath); ifstream ifss(serverpath); solid_check(ifsc, "Failed open: " << clientpath); solid_check(ifss, "Failed open: " << serverpath); compare_streams(ifsc, ifss); } } namespace back { void on_client_receive_response( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<back::Request>& _rsent_msg_ptr, std::shared_ptr<back::Response>& _rrecv_msg_ptr, ErrorConditionT const& _rerror); } //namespace back namespace front { //----------------------------------------------------------------------------- // client //----------------------------------------------------------------------------- void on_client_receive_response( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Request>& _rsent_msg_ptr, std::shared_ptr<Response>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_check(_rrecv_msg_ptr); solid_check(_rrecv_msg_ptr->error_ == 0); string s = _rrecv_msg_ptr->oss_.str(); _rsent_msg_ptr->ofs_.write(s.data(), s.size()); solid_log(logger, Verbose, "received response data of size: " << s.size()); frame::mprpc::MessageFlagsT flags; if (!_rrecv_msg_ptr->isResponseLast()) { if (_rsent_msg_ptr->send_request_) { _rsent_msg_ptr->send_request_ = false; auto res_ptr = make_shared<Request>(*_rrecv_msg_ptr); auto err = _rctx.service().sendMessage(_rctx.recipientId(), res_ptr, {frame::mprpc::MessageFlagsE::Response}); solid_log(logger, Verbose, "send response to: " << _rctx.recipientId() << " err: " << err.message()); } else { _rsent_msg_ptr->send_request_ = true; } } else { _rsent_msg_ptr->ofs_.flush(); if (expect_count.fetch_sub(1) == 1) { prom.set_value(); } } } //----------------------------------------------------------------------------- // front server side //----------------------------------------------------------------------------- void on_server_receive_request( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<front::Response>& _rsent_msg_ptr, std::shared_ptr<front::Request>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_check(_rrecv_msg_ptr); solid_check(_rrecv_msg_ptr->name_.empty()); solid_log(logger, Verbose, "front: received request"); auto req_ptr = std::move(_rsent_msg_ptr->req_ptr_); pmprpc_back_client->sendMessage(_rsent_msg_ptr->recipient_id_, req_ptr, {frame::mprpc::MessageFlagsE::Response}); } void on_server_receive_first_request( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<front::Request>& _rsent_msg_ptr, std::shared_ptr<front::Request>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_check(_rrecv_msg_ptr); solid_log(logger, Verbose, "front: received first request for file: " << _rrecv_msg_ptr->name_); auto req_ptr = make_shared<back::Request>(); frame::mprpc::MessageFlagsT flags; req_ptr->name_ = std::move(_rrecv_msg_ptr->name_); req_ptr->recipient_id_ = _rctx.recipientId(); req_ptr->res_ptr_ = make_shared<front::Response>(*_rrecv_msg_ptr); req_ptr->await_response_ = true; pmprpc_back_client->sendRequest("localhost", req_ptr, back::on_client_receive_response, flags); } } //namespace front namespace back { void on_client_receive_response( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<back::Request>& _rsent_msg_ptr, std::shared_ptr<back::Response>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_log(logger, Verbose, "back: received response for: " << _rsent_msg_ptr->name_); std::shared_ptr<front::Response> res_ptr = make_shared<front::Response>(); res_ptr->error_ = _rrecv_msg_ptr->error_; res_ptr->iss_.str(_rrecv_msg_ptr->oss_.str()); res_ptr->header(_rsent_msg_ptr->res_ptr_->header()); if (_rrecv_msg_ptr->isResponseLast()) { frame::mprpc::MessageFlagsT flags{frame::mprpc::MessageFlagsE::AwaitResponse, frame::mprpc::MessageFlagsE::ResponseLast}; solid_log(logger, Verbose, "back: sent last response to front: " << res_ptr.get()); pmprpc_front_server->sendMessage(_rsent_msg_ptr->recipient_id_, res_ptr, flags); } else { if (_rsent_msg_ptr->await_response_) { frame::mprpc::MessageFlagsT flags{frame::mprpc::MessageFlagsE::AwaitResponse, frame::mprpc::MessageFlagsE::ResponsePart}; _rsent_msg_ptr->await_response_ = false; res_ptr->recipient_id_ = _rctx.recipientId(); res_ptr->req_ptr_ = make_shared<back::Request>(*_rrecv_msg_ptr); solid_log(logger, Verbose, "back: sent response part to front with wait: " << res_ptr.get()); pmprpc_front_server->sendMessage(_rsent_msg_ptr->recipient_id_, res_ptr, front::on_server_receive_request, flags); } else { frame::mprpc::MessageFlagsT flags{frame::mprpc::MessageFlagsE::ResponsePart}; _rsent_msg_ptr->await_response_ = true; solid_log(logger, Verbose, "back: sent response part to front without wait: " << res_ptr.get()); pmprpc_front_server->sendMessage(_rsent_msg_ptr->recipient_id_, res_ptr, flags); } } } //----------------------------------------------------------------------------- // server //----------------------------------------------------------------------------- void on_server_receive_request( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Response>& _rsent_msg_ptr, std::shared_ptr<Request>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { solid_check(_rrecv_msg_ptr); if (!_rsent_msg_ptr->ifs_.eof()) { solid_log(logger, Verbose, "Sending " << _rrecv_msg_ptr->name_ << " to " << _rctx.recipientId()); frame::mprpc::MessageFlagsT flags{frame::mprpc::MessageFlagsE::ResponsePart, frame::mprpc::MessageFlagsE::AwaitResponse}; _rctx.service().sendMessage(_rctx.recipientId(), _rsent_msg_ptr, on_server_receive_request, flags); flags.reset(frame::mprpc::MessageFlagsE::AwaitResponse); _rctx.service().sendMessage(_rctx.recipientId(), _rsent_msg_ptr, flags); } else { solid_log(logger, Verbose, "Sending to " << _rctx.recipientId() << " last"); frame::mprpc::MessageFlagsT flags{frame::mprpc::MessageFlagsE::ResponseLast}; _rctx.service().sendMessage(_rctx.recipientId(), _rsent_msg_ptr, flags); } } void on_server_receive_first_request( frame::mprpc::ConnectionContext& _rctx, std::shared_ptr<Request>& _rsent_msg_ptr, std::shared_ptr<Request>& _rrecv_msg_ptr, ErrorConditionT const& _rerror) { string path = string("server_storage") + '/' + _rrecv_msg_ptr->name_; auto res_ptr = make_shared<Response>(*_rrecv_msg_ptr); res_ptr->ifs_.open(path); solid_check(res_ptr->ifs_, "failed open file: " << path); if (!res_ptr->ifs_.eof()) { solid_log(logger, Verbose, "Sending " << _rrecv_msg_ptr->name_ << " to " << _rctx.recipientId()); frame::mprpc::MessageFlagsT flags{frame::mprpc::MessageFlagsE::ResponsePart, frame::mprpc::MessageFlagsE::AwaitResponse}; auto error = _rctx.service().sendMessage(_rctx.recipientId(), res_ptr, on_server_receive_request, flags); solid_check(!error, "failed send message: " << error.message()); flags.reset(frame::mprpc::MessageFlagsE::AwaitResponse); error = _rctx.service().sendMessage(_rctx.recipientId(), res_ptr, flags); solid_check(!error, "failed send message: " << error.message()); } else { solid_log(logger, Verbose, "Sending " << _rsent_msg_ptr->name_ << " to " << _rctx.recipientId() << " last"); frame::mprpc::MessageFlagsT flags{frame::mprpc::MessageFlagsE::ResponseLast}; _rctx.service().sendMessage(_rctx.recipientId(), res_ptr, flags); } } } //namespace back } //namespace
36.082411
150
0.587183
[ "vector", "solid" ]
f3fcd754c7e9034cb59006e9f9bf149820ed7132
5,288
cc
C++
content/browser/media/media_devices_permission_checker.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/media/media_devices_permission_checker.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/media/media_devices_permission_checker.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/media/media_devices_permission_checker.h" #include <utility> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/task/post_task.h" #include "content/browser/frame_host/render_frame_host_delegate.h" #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "third_party/blink/public/common/mediastream/media_devices.h" #include "url/gurl.h" #include "url/origin.h" namespace content { namespace { MediaDevicesManager::BoolDeviceTypes DoCheckPermissionsOnUIThread( MediaDevicesManager::BoolDeviceTypes requested_device_types, int render_process_id, int render_frame_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderFrameHostImpl* frame_host = RenderFrameHostImpl::FromID(render_process_id, render_frame_id); // If there is no |frame_host|, return false for all permissions. if (!frame_host) return MediaDevicesManager::BoolDeviceTypes(); RenderFrameHostDelegate* delegate = frame_host->delegate(); url::Origin origin = frame_host->GetLastCommittedOrigin(); bool audio_permission = delegate->CheckMediaAccessPermission( frame_host, origin, blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE); bool mic_feature_policy = true; bool camera_feature_policy = true; mic_feature_policy = frame_host->IsFeatureEnabled( blink::mojom::FeaturePolicyFeature::kMicrophone); camera_feature_policy = frame_host->IsFeatureEnabled(blink::mojom::FeaturePolicyFeature::kCamera); MediaDevicesManager::BoolDeviceTypes result; // Speakers. // TODO(guidou): use specific permission for audio output when it becomes // available. See http://crbug.com/556542. result[blink::MEDIA_DEVICE_TYPE_AUDIO_OUTPUT] = requested_device_types[blink::MEDIA_DEVICE_TYPE_AUDIO_OUTPUT] && audio_permission; // Mic. result[blink::MEDIA_DEVICE_TYPE_AUDIO_INPUT] = requested_device_types[blink::MEDIA_DEVICE_TYPE_AUDIO_INPUT] && audio_permission && mic_feature_policy; // Camera. result[blink::MEDIA_DEVICE_TYPE_VIDEO_INPUT] = requested_device_types[blink::MEDIA_DEVICE_TYPE_VIDEO_INPUT] && delegate->CheckMediaAccessPermission( frame_host, origin, blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE) && camera_feature_policy; return result; } bool CheckSinglePermissionOnUIThread(blink::MediaDeviceType device_type, int render_process_id, int render_frame_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); MediaDevicesManager::BoolDeviceTypes requested; requested[device_type] = true; MediaDevicesManager::BoolDeviceTypes result = DoCheckPermissionsOnUIThread( requested, render_process_id, render_frame_id); return result[device_type]; } } // namespace MediaDevicesPermissionChecker::MediaDevicesPermissionChecker() : use_override_(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseFakeUIForMediaStream)), override_value_( base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kUseFakeUIForMediaStream) != "deny") {} MediaDevicesPermissionChecker::MediaDevicesPermissionChecker( bool override_value) : use_override_(true), override_value_(override_value) {} bool MediaDevicesPermissionChecker::CheckPermissionOnUIThread( blink::MediaDeviceType device_type, int render_process_id, int render_frame_id) const { if (use_override_) return override_value_; return CheckSinglePermissionOnUIThread(device_type, render_process_id, render_frame_id); } void MediaDevicesPermissionChecker::CheckPermission( blink::MediaDeviceType device_type, int render_process_id, int render_frame_id, base::OnceCallback<void(bool)> callback) const { if (use_override_) { std::move(callback).Run(override_value_); return; } base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&CheckSinglePermissionOnUIThread, device_type, render_process_id, render_frame_id), std::move(callback)); } void MediaDevicesPermissionChecker::CheckPermissions( MediaDevicesManager::BoolDeviceTypes requested, int render_process_id, int render_frame_id, base::OnceCallback<void(const MediaDevicesManager::BoolDeviceTypes&)> callback) const { if (use_override_) { MediaDevicesManager::BoolDeviceTypes result; result.fill(override_value_); std::move(callback).Run(result); return; } base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DoCheckPermissionsOnUIThread, requested, render_process_id, render_frame_id), std::move(callback)); } } // namespace content
35.72973
80
0.74792
[ "vector" ]
f3ff34e8767c6b0a502d4d9c6bc31a7596ff7cda
3,672
cpp
C++
gamegio-library/src/gamegio/HasNode.cpp
tril0byte/HGamer3D
7979c67d9b4672a5b2d1a50320a6d47b1a97ff05
[ "Apache-2.0" ]
27
2015-06-08T16:45:47.000Z
2022-02-22T14:40:52.000Z
gamegio-library/src/gamegio/HasNode.cpp
tril0byte/HGamer3D
7979c67d9b4672a5b2d1a50320a6d47b1a97ff05
[ "Apache-2.0" ]
18
2015-04-20T20:42:02.000Z
2020-12-11T03:46:17.000Z
gamegio-library/src/gamegio/HasNode.cpp
tril0byte/HGamer3D
7979c67d9b4672a5b2d1a50320a6d47b1a97ff05
[ "Apache-2.0" ]
4
2017-06-20T13:24:18.000Z
2021-10-07T19:18:03.000Z
// C++ part of bindings for graphics // HGamer3D Library (A project to enable 3D game development in Haskell) // Copyright 2015 - 2017 Peter Althainz // // Distributed under the Apache License, Version 2.0 // (See attached file LICENSE or copy at // http://www.apache.org/licenses/LICENSE-2.0) // // file: gamegio-library/src/HasNode/graphics3d.cpp #include <sstream> #include <iostream> #include <fstream> #include <string> #include <cmath> #include "HasNode.hpp" #include "Graphics3DSystem.hpp" #include "Urho3D/Math/Quaternion.h" #include "Vec3Cbor.hpp" #include "UnitQuaternionCbor.hpp" #include "EntityIdCbor.hpp" #include "ParentCbor.hpp" #include "VisibleCbor.hpp" using namespace std; using namespace cbd; GIO_METHOD_FUNC(HasNode, Pos) GIO_METHOD_FUNC(HasNode, Scale) GIO_METHOD_FUNC(HasNode, Ori) GIO_METHOD_FUNC(HasNode, Visible) GIO_METHOD_FUNC(HasNode, EntityId) GIO_METHOD_FUNC(HasNode, Parent) // Factory Implementation GCO_FACTORY_IMP(HasNode) GCO_FACTORY_METHOD(HasNode, ctPosition, Pos) GCO_FACTORY_METHOD(HasNode, ctScale, Scale) GCO_FACTORY_METHOD(HasNode, ctOrientation, Ori) GCO_FACTORY_METHOD(HasNode, ctEntityId, EntityId) GCO_FACTORY_METHOD(HasNode, ctParent, Parent) GCO_FACTORY_METHOD(HasNode, ctVisible, Visible) GCO_FACTORY_IMP_END // Orientation, Position, Scale FrItem HasNode::msgCreate(FrMsg m, FrMsgLength l) { HasNode *hn = new HasNode(); // hn->node->CreateComponent<StaticModel>(); return (FrItem)hn; } // HasNode::HasNode(Graphics3DSystem *g) HasNode::HasNode() { Graphics3DSystem *g3ds = Graphics3DSystem::getG3DS(); node = g3ds->scene->CreateChild(); } HasNode::~HasNode() { node->Remove(); } void HasNode::msgDestroy() { delete this; } void HasNode::msgOri(FrMsg m, FrMsgLength l) { CborParser parser; CborValue it; cbor_parser_init(m, l, 0, &parser, &it); cbd::UnitQuaternion uq; readUnitQuaternion(&it, &uq); node->SetRotation(Quaternion(uq.w, uq.x, uq.y, uq.z)); }; void HasNode::msgPos(FrMsg m, FrMsgLength l) { CborParser parser; CborValue it; cbor_parser_init(m, l, 0, &parser, &it); Vec3 vec; readVec3(&it, &vec); node->SetPosition(Vector3(vec.x, vec.y, vec.z)); }; void HasNode::msgScale(FrMsg m, FrMsgLength l) { CborParser parser; CborValue it; cbor_parser_init(m, l, 0, &parser, &it); Vec3 vec; readVec3(&it, &vec); node->SetScale(Vector3(vec.x, vec.y, vec.z)); }; void printEID(EntityId eid) { for(int j = 0; j < 16; j++) printf("%02X", eid[j]); cout << "\n"; } void HasNode::msgParent(FrMsg m, FrMsgLength l) { CborParser parser; CborValue it; cbor_parser_init(m, l, 0, &parser, &it); cbd::EntityId eid; readEntityId(&it, &eid); // set new parent Graphics3DSystem* g3ds = Graphics3DSystem::getG3DS(); // std::cout << "HasNode - msgParent: "; // printEID(eid); std::map<EntityId, Node*>::iterator newParent = g3ds->node_map.find(eid); if (newParent != g3ds->node_map.end()) { Node* oldParent = node->GetParent(); if (oldParent) { oldParent->RemoveChild(node); } newParent->second->AddChild(node); } else { // std::cout << "HasNode-msgParent: parent id not found"; } } void HasNode::msgEntityId(FrMsg m, FrMsgLength l) { CborParser parser; CborValue it; cbor_parser_init(m, l, 0, &parser, &it); EntityId eid; readEntityId(&it, &eid); // std::cout << "HasNode - set id: "; // printEID(eid); Graphics3DSystem::getG3DS()->node_map[eid] = node; } void HasNode::msgVisible(FrMsg m, FrMsgLength l) { CborParser parser; CborValue it; cbor_parser_init(m, l, 0, &parser, &it); bool visible; cbd::readVisible(&it, &visible); node->SetEnabled(visible); }
23.538462
75
0.699074
[ "3d" ]
6d0652ad2c98608613323b13663277979f608bc4
4,831
hpp
C++
remote_core/remote_core/include/TrainingSession.hpp
DaveAMoore/remote_core
a46280a7cee5d52ca08d11ea2de518a7d5e12ca5
[ "MIT" ]
null
null
null
remote_core/remote_core/include/TrainingSession.hpp
DaveAMoore/remote_core
a46280a7cee5d52ca08d11ea2de518a7d5e12ca5
[ "MIT" ]
null
null
null
remote_core/remote_core/include/TrainingSession.hpp
DaveAMoore/remote_core
a46280a7cee5d52ca08d11ea2de518a7d5e12ca5
[ "MIT" ]
null
null
null
// // TrainingSession.hpp // remote_core // // Created by David Moore on 11/5/18. // Copyright © 2018 David Moore. All rights reserved. // #ifndef TrainingSession_hpp #define TrainingSession_hpp #include <iostream> #include <memory> #include "Remote.hpp" #include "Error.hpp" #define START_TRAINING_SESSION_DIRECTIVE "startTrainingSession" #define SUSPEND_TRAINING_SESSION_DIRECTIVE "suspendTrainingSession" #define CREATE_COMMAND_DIRECTIVE "createCommandWithLocalizedTitle" #define LEARN_COMMAND_DIRECTIVE "learnCommand" #define TRAINING_SESSION_DID_BEGIN_DIRECTIVE "trainingSessionDidBegin" #define TRAINING_SESSION_DID_FAIL_WITH_ERROR_DIRECTIVE "trainingSessionDidFailWithError" #define TRAINING_SESSION_WILL_LEARN_COMMAND_DIRECTIVE "trainingSessionWillLearnCommand" #define TRAINING_SESSION_DID_LEARN_COMMAND_DIRECTIVE "trainingSessionDidLearnCommand" #define TRAINING_SESSION_DID_REQUEST_INCLUSIVE_ARBITRARY_INPUT_DIRECTIVE "trainingSessionDidRequestInclusiveArbitraryInput" #define TRAINING_SESSION_DID_REQUEST_INPUT_FOR_COMMAND_DIRECTIVE "trainingSessionDidRequestInputForCommand" #define TRAINING_SESSION_DID_REQUEST_EXCLUSIVE_ARBITRARY_INPUT_DIRECTIVE "trainingSessionDidRequestExclusiveArbitraryInput" namespace RemoteCore { class HardwareController; class TrainingSessionDelegate; class TrainingSession { private: std::string sessionID; Remote associatedRemote; std::weak_ptr<TrainingSessionDelegate> delegate; Command currentCommand; std::vector<std::string> availableCommandIDs; public: TrainingSession(Remote associatedRemote); std::string getSessionID(void) const { return sessionID; } Remote getAssociatedRemote(void) const { return associatedRemote; } std::weak_ptr<TrainingSessionDelegate> getDelegate(void) { return delegate; } void setDelegate(std::weak_ptr<TrainingSessionDelegate> delegate) { this->delegate = delegate; } /** Adds the config content of new remote to default config * @param remote */ void addNewRemoteConfigToDefaultConfig(Remote remote); /** Initializes the training session. This will require user input (e.g., inclusive arbitrary input). */ void start(void); /** Suspends the training session almost immediately. */ void suspend(void); /** Creates the representation of a new command with the given localized title. The localized title provided may be an empty string. */ Command createCommandWithLocalizedTitle(std::string localizedTitle); /** Starts the training process for a specific command. Note that the receiver does not determine if the command is a repeat or not. (Asynchronous) @param command The command that will be learnt. The localized title is persisted when reporting the status of this call, but it will not be modified. */ void learnCommand(Command command); /** * Trains remote through initiating irrecord in command line. * * @param remote Setup for naming of config file using remoteID */ void trainRemote(Remote remote); }; class TrainingSessionDelegate : public std::enable_shared_from_this<TrainingSessionDelegate> { public: // The training session is beginning. virtual void trainingSessionDidBegin(TrainingSession *session) {}; // A fatal error occurred cuasing the training session to fail entirely. virtual void trainingSessionDidFailWithError(TrainingSession *session, Error error) {}; // The training session is going to begin learning the command. virtual void trainingSessionWillLearnCommand(TrainingSession *session, Command command) {}; virtual void trainingSessionDidLearnCommand(TrainingSession *session, Command command) {}; // Inclusive arbitrary input indicates all buttons should be pressed – in no specific order (i.e., arbitrary). virtual void trainingSessionDidRequestInclusiveArbitraryInput(TrainingSession *session) {}; // Input should be provided for a single command, that is the one that is passed as a parameter. virtual void trainingSessionDidRequestInputForCommand(TrainingSession *session, Command command) {}; // Exclusive arbitrary input indicates that a single arbitrary command (i.e., button) should be pressed virtual void trainingSessionDidRequestExclusiveArbitraryInput(TrainingSession *session) {}; }; } #endif /* TrainingSession_hpp */
39.598361
158
0.711033
[ "vector" ]
6d0667ce6fcdd07b8b24afbd050aaae7138e85a4
20,517
hpp
C++
source/apps/encoder/enc_utils.hpp
malaterre/OpenHTJ2K
fbc6f3bc3c902f80d40aa5c3683a136a3194c926
[ "BSD-3-Clause" ]
null
null
null
source/apps/encoder/enc_utils.hpp
malaterre/OpenHTJ2K
fbc6f3bc3c902f80d40aa5c3683a136a3194c926
[ "BSD-3-Clause" ]
null
null
null
source/apps/encoder/enc_utils.hpp
malaterre/OpenHTJ2K
fbc6f3bc3c902f80d40aa5c3683a136a3194c926
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019 - 2021, Osamu Watanabe // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <algorithm> #include <iterator> #include <string> #define NO_QFACTOR 0xFF void print_help(char *cmd) { printf("JPEG 2000 Part 15 encoder\n"); printf("USAGE: %s -i inputimage(PNM format) -o output-codestream [options...]\n\n", cmd); printf("-i: Input file\n PGM and PPM are supported.\n"); printf("-o: Output codestream\n `.jhc` or `.j2c` are recommended as the extension.\n\n"); printf("OPTIONS:\n"); printf( "Stiles=Size:\n Size of tile. `Size` should be in the format " "{height, width}" ". Default is equal to the image size.\n"); printf("Sorigin=Size:\n Offset from the origin of the reference grid to the image area. Default is \n"); printf("Stile_origin=Size\n Offset from the origin of the reference grid to the first tile.\n"); printf( "Clevels=Int:\n Number of DWT decomposition.\n Valid range for number of DWT levels is from 0 to " "32 (Default is 5.)\n"); printf("Creversible=Bool:\n yes for lossless mode, no for lossy mode.\n"); printf("Cblk=Size:\n Code-block size.\n"); printf("Cprecincts=Size:\n Precinct size. Shall be power of two.\n"); printf("Cycc=Bool:\n yes to use RGB->YCbCr color space conversion.\n"); printf("Corder:\n Progression order. Valid entry is one of LRCP, RLCP, RPCL, PCRL, CPRL.\n"); printf("Cuse_sop=Bool:\n yes to use SOP (Start Of Packet) marker segment.\n"); printf("Cuse_eph=Bool:\n yes to use EPH (End of Packet Header) marker.\n"); printf("Qstep=Float:\n Base step size for quantization.\n 0.0 < base step size <= 2.0.\n"); printf("Qguard=Int:\n Number of guard bits. Valid range is from 0 to 8 (Default is 1.)\n"); printf("Qfactor=Int:\n Quality factor. Valid range is from 0 to 100 (100 is for the best quality)\n"); printf(" Note: If this option is present, Qstep is ignored and Cycc is set to `yes`.\n"); } class element_siz_local { public: uint32_t x; uint32_t y; element_siz_local() : x(0), y(0) {} element_siz_local(uint32_t x0, uint32_t y0) { x = x0; y = y0; } }; size_t popcount_local(uintmax_t num) { size_t precision = 0; while (num != 0) { if (1 == (num & 1)) { precision++; } num >>= 1; } return precision; } int32_t log2i32(int32_t x) { if (x <= 0) { printf("ERROR: cannot compute log2 of negative value.\n"); exit(EXIT_FAILURE); } int32_t y = 0; while (x > 1) { y++; x >>= 1; } return y; } class j2k_argset { private: std::vector<std::string> args; element_siz_local origin; element_siz_local tile_origin; uint8_t transformation; uint8_t use_ycc; uint8_t dwt_levels; element_siz_local cblksize; bool max_precincts; std::vector<element_siz_local> prctsize; element_siz_local tilesize; uint8_t Porder; bool use_sop; bool use_eph; double base_step_size; uint8_t num_guard; bool qderived; uint8_t qfactor; public: j2k_argset(int argc, char *argv[]) : origin(0, 0), tile_origin(0, 0), transformation(0), use_ycc(1), dwt_levels(5), cblksize(4, 4), max_precincts(true), tilesize(0, 0), Porder(0), use_sop(false), use_eph(false), base_step_size(0.0), num_guard(1), qderived(false), qfactor(NO_QFACTOR) { args.reserve(argc); // skip command itself for (int i = 1; i < argc; ++i) { args.emplace_back(argv[i]); } get_help(argc, argv); for (auto &arg : args) { char &c = arg.front(); int pos0, pos1; std::string param, val; std::string subparam; element_siz_local tmpsiz; switch (c) { case 'S': pos0 = arg.find_first_of('='); param = arg.substr(1, pos0 - 1); if (param == "tiles") { pos0 = arg.find_first_of('='); if (args[pos0] != "{") { } pos0++; pos1 = arg.find_first_of('}'); subparam = arg.substr(pos0 + 1, pos1 - pos0 - 1); pos0 = subparam.find_first_of(','); tilesize.y = std::stoi(subparam.substr(0, pos0)); tilesize.x = std::stoi(subparam.substr(pos0 + 1, 4)); break; } if (param == "origin") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Sorigin needs a coordinate for the origin {y,x}\n"); exit(EXIT_FAILURE); } pos0 = arg.find_first_of('{'); if (pos0 == std::string::npos) { printf("ERROR: Sorigin needs a coordinate for the origin {y,x}\n"); exit(EXIT_FAILURE); } pos1 = arg.find_first_of('}'); if (pos1 == std::string::npos) { printf("ERROR: Sorigin needs a coordinate for the origin {y,x}\n"); exit(EXIT_FAILURE); } subparam = arg.substr(pos0 + 1, pos1 - pos0 - 1); pos0 = subparam.find_first_of(','); origin.y = std::stoi(subparam.substr(0, pos0)); origin.x = std::stoi(subparam.substr(pos0 + 1, subparam.length())); break; } if (param == "tile_origin") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Stile_origin needs a coordinate for the origin {y,x}\n"); exit(EXIT_FAILURE); } pos0 = arg.find_first_of('{'); if (pos0 == std::string::npos) { printf("ERROR: Stile_origin needs a coordinate for the origin {y,x}\n"); exit(EXIT_FAILURE); } pos1 = arg.find_first_of('}'); if (pos1 == std::string::npos) { printf("ERROR: Stile_origin needs a coordinate for the origin {y,x}\n"); exit(EXIT_FAILURE); } subparam = arg.substr(pos0 + 1, pos1 - pos0 - 1); pos0 = subparam.find_first_of(','); tile_origin.y = std::stoi(subparam.substr(0, pos0)); tile_origin.x = std::stoi(subparam.substr(pos0 + 1, subparam.length())); break; } printf("ERROR: unknown parameter S%s\n", param.c_str()); exit(EXIT_FAILURE); break; case 'C': pos0 = arg.find_first_of('='); param = arg.substr(1, pos0 - 1); if (param == "reversible") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Creversible needs =yes or =no\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 3); if (val == "yes") { transformation = 1; } break; } if (param == "ycc") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Cycc needs =yes or =no\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 3); if (val == "yes") { use_ycc = 1; } else { use_ycc = 0; } break; } if (param == "levels") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Clevels needs =dwt_levels (0 - 32)\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 3); int tmp = std::stoi(val); if (tmp < 0 || tmp > 32) { printf("ERROR: number of DWT levels shall be in the range of [0, 32]\n"); exit(EXIT_FAILURE); } dwt_levels = static_cast<uint8_t>(tmp); break; } if (param == "blk") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Cblk needs a size of codeblock {height,width}\n"); exit(EXIT_FAILURE); } pos0 = arg.find_first_of('{'); if (pos0 == std::string::npos) { printf("ERROR: Cblk needs a size of codeblock {height,width}\n"); exit(EXIT_FAILURE); } pos1 = arg.find_first_of('}'); if (pos1 == std::string::npos) { printf("ERROR: Cblk needs a size of codeblock {height,width}\n"); exit(EXIT_FAILURE); } subparam = arg.substr(pos0 + 1, pos1 - pos0 - 1); pos0 = subparam.find_first_of(','); tmpsiz.y = std::stoi(subparam.substr(0, pos0)); tmpsiz.x = std::stoi(subparam.substr(pos0 + 1, 4)); if ((popcount_local(tmpsiz.y) > 1) || (popcount_local(tmpsiz.x) > 1)) { printf("ERROR: code block size must be power of two.\n"); exit(EXIT_FAILURE); } if (tmpsiz.x < 4 || tmpsiz.y < 4) { printf("ERROR: code block size must be greater than four\n"); exit(EXIT_FAILURE); } if (tmpsiz.x * tmpsiz.y > 4096) { printf("ERROR: code block area must be less than or equal to 4096.\n"); exit(EXIT_FAILURE); } cblksize.x = log2i32(tmpsiz.x) - 2; cblksize.y = log2i32(tmpsiz.y) - 2; break; } if (param == "precincts") { max_precincts = false; pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Cprecincts needs at least one precinct size {height,width}\n"); exit(EXIT_FAILURE); } pos0 = arg.find_first_of('{'); if (pos0 == std::string::npos) { printf("ERROR: Cprecincts needs at least one precinct size {height,width}\n"); exit(EXIT_FAILURE); } while (pos0 != std::string::npos) { pos1 = arg.find(std::string("}"), pos0); if (pos1 == std::string::npos) { printf("ERROR: Cprecincts needs at least one precinct size {height,width}\n"); exit(EXIT_FAILURE); } subparam = arg.substr(pos0 + 1, pos1 - pos0 - 1); pos0 = subparam.find_first_of(','); tmpsiz.y = std::stoi(subparam.substr(0, pos0)); tmpsiz.x = std::stoi(subparam.substr(pos0 + 1, 5)); if ((popcount_local(tmpsiz.y) > 1) || (popcount_local(tmpsiz.x) > 1)) { printf("ERROR: precinct size must be power of two.\n"); exit(EXIT_FAILURE); } prctsize.emplace_back(log2i32(tmpsiz.x), log2i32(tmpsiz.y)); pos0 = arg.find(std::string("{"), pos1); } break; } if (param == "order") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Corder needs progression order =(LRCP, RLCP, RPCL, PCRL, CPRL)\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 4); if (val == "LRCP") { Porder = 0; } else if (val == "RLCP") { Porder = 1; } else if (val == "RPCL") { Porder = 2; } else if (val == "PCRL") { Porder = 3; } else if (val == "CPRL") { Porder = 4; } else { printf("ERROR: unknown progression order %s\n", val.c_str()); exit(EXIT_FAILURE); } break; } if (param == "use_sop") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Cuse_sop needs =yes or =no\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 3); if (val == "yes") { use_sop = true; } break; } if (param == "use_eph") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Cuse_eph needs =yes or =no\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 3); if (val == "yes") { use_eph = true; } break; } printf("ERROR: unknown parameter C%s\n", param.c_str()); exit(EXIT_FAILURE); break; case 'Q': pos0 = arg.find_first_of('='); param = arg.substr(1, pos0 - 1); if (param == "step") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Qstep needs base step size in float (0.0 < step <= 2.0)\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 50); base_step_size = std::stod(val); if (base_step_size <= 0.0 || base_step_size > 2.0) { printf("ERROR: base step size shall be in the range of (0.0, 2.0]\n"); exit(EXIT_FAILURE); } break; } if (param == "guard") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Qguard needs number of guard bits (0-7)\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 2); int tmp = std::stoi(val); if (tmp < 0 || tmp > 7) { printf("ERROR: number of guard bits shall be in the range of [0, 7]\n"); exit(EXIT_FAILURE); } num_guard = static_cast<uint8_t>(tmp); break; } if (param == "derived") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Qderived needs =yes or =no\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 3); if (val == "yes") { qderived = true; } break; } if (param == "factor") { pos0 = arg.find_first_of('='); if (pos0 == std::string::npos) { printf("ERROR: Qfactor needs value of quality (0-100)\n"); exit(EXIT_FAILURE); } val = arg.substr(pos0 + 1, 3); int tmp = std::stoi(val); if (tmp < 0 || tmp > 100) { printf("ERROR: value of Qfactor shall be in the range of [0, 100]\n"); exit(EXIT_FAILURE); } qfactor = static_cast<uint8_t>(tmp); break; } printf("ERROR: unknown parameter Q%s\n", param.c_str()); exit(EXIT_FAILURE); break; default: break; } } } std::vector<std::string> get_infile() { auto p = std::find(args.begin(), args.end(), "-i"); if (p == args.end()) { printf("ERROR: input file (\"-i\") is missing!\n"); exit(EXIT_FAILURE); } auto idx = std::distance(args.begin(), p); if (idx + 1 > args.size() - 1) { printf("ERROR: file name for input is missing!\n"); exit(EXIT_FAILURE); } const std::string buf = args[idx + 1]; const std::string comma(","); std::string::size_type pos = 0; std::string::size_type newpos; std::vector<std::string> fnames; std::string::size_type aa = buf.length(); while (true) { newpos = buf.find(comma, pos + comma.length()); fnames.push_back(buf.substr(pos, newpos - pos)); pos = newpos; if (pos != std::string::npos) { pos += 1; } else { break; } } return fnames; // return args[idx + 1].c_str(); } std::string get_outfile() { auto p = std::find(args.begin(), args.end(), "-o"); if (p == args.end()) { printf("ERROR: output file (\"-o\") is missing!\n"); exit(EXIT_FAILURE); } auto idx = std::distance(args.begin(), p); if (idx + 1 > args.size() - 1) { printf("ERROR: file name for output is missing!\n"); exit(EXIT_FAILURE); } return args[idx + 1]; } int32_t get_num_iteration() { int32_t num_iteration = 1; auto p = std::find(args.begin(), args.end(), "-iter"); if (p == args.end()) { return num_iteration; } auto idx = std::distance(args.begin(), p); if (idx + 1 > args.size() - 1) { printf("ERROR: -iter requires number of iteration\n"); exit(EXIT_FAILURE); } return std::stoi(args[idx + 1]); } uint32_t get_num_threads() { // zero implies all threads uint32_t num_threads = 0; auto p = std::find(args.begin(), args.end(), "-num_threads"); if (p == args.end()) { return num_threads; } auto idx = std::distance(args.begin(), p); if (idx + 1 > args.size() - 1) { printf("ERROR: -iter requires number of iteration\n"); exit(EXIT_FAILURE); } return (uint32_t)std::stoul(args[idx + 1]); } uint8_t get_jph_color_space() { uint8_t val = 0; auto p = std::find(args.begin(), args.end(), "-jph_color_space"); if (p == args.end()) { return val; } auto idx = std::distance(args.begin(), p); if (idx + 1 > args.size() - 1) { printf("ERROR: -jph_color_space requires name of color-space\n"); exit(EXIT_FAILURE); } if (args[idx + 1].compare("YCC") && args[idx + 1].compare("RGB")) { printf("ERROR: invalid name for color-space\n"); exit(EXIT_FAILURE); } else if (args[idx + 1].compare("YCC") == 0) { val = 1; } return val; } void get_help(int argc, char *argv[]) { auto p = std::find(args.begin(), args.end(), "-h"); if (p == args.end() && argc > 1) { return; } print_help(argv[0]); exit(EXIT_SUCCESS); } element_siz_local get_origin() const { return origin; } element_siz_local get_tile_origin() const { return tile_origin; } uint8_t get_transformation() const { return transformation; } uint8_t get_ycc() const { return use_ycc; } uint8_t get_dwt_levels() const { return dwt_levels; } element_siz_local get_cblk_size() { return cblksize; } bool is_max_precincts() const { return max_precincts; } std::vector<element_siz_local> get_prct_size() { return prctsize; } element_siz_local get_tile_size() { return tilesize; } uint8_t get_progression() const { return Porder; } bool is_use_sop() const { return use_sop; } bool is_use_eph() const { return use_eph; } double get_basestep_size() const { return base_step_size; } uint8_t get_num_guard() const { return num_guard; } bool is_derived() const { return qderived; } uint8_t get_qfactor() const { return qfactor; } };
36.6375
107
0.530097
[ "vector" ]
6d0696d8c708d0413fb5f3105bdcbcbb2b9b3f10
4,626
cpp
C++
dart/collision/ode/detail/OdeMesh.cpp
malasiot/dart-vsim-octomap
d7afcacdcdcf7da688fb61caf1761b1309888ffe
[ "BSD-2-Clause" ]
null
null
null
dart/collision/ode/detail/OdeMesh.cpp
malasiot/dart-vsim-octomap
d7afcacdcdcf7da688fb61caf1761b1309888ffe
[ "BSD-2-Clause" ]
null
null
null
dart/collision/ode/detail/OdeMesh.cpp
malasiot/dart-vsim-octomap
d7afcacdcdcf7da688fb61caf1761b1309888ffe
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2011-2017, The DART development contributors * All rights reserved. * * The list of contributors can be found at: * https://github.com/dartsim/dart/blob/master/LICENSE * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "dart/collision/ode/detail/OdeMesh.hpp" #include "dart/dynamics/MeshShape.hpp" namespace dart { namespace collision { namespace detail { //============================================================================== OdeMesh::OdeMesh( const OdeCollisionObject* parent, const aiScene* scene, const Eigen::Vector3d& scale) : OdeGeom(parent), mOdeTriMeshDataId(nullptr) { // Fill vertices, normals, and indices in the ODE friendly data structures. fillArrays(scene, scale); /// This will hold the vertex data of the triangle mesh if (!mOdeTriMeshDataId) mOdeTriMeshDataId = dGeomTriMeshDataCreate(); // Build the ODE triangle mesh dGeomTriMeshDataBuildDouble1( mOdeTriMeshDataId, mVertices.data(), 3*sizeof(double), static_cast<int>(mVertices.size()), mIndices.data(), static_cast<int>(mIndices.size()), 3*sizeof(int), mNormals.data()); mGeomId = dCreateTriMesh(0, mOdeTriMeshDataId, nullptr, nullptr, nullptr); } //============================================================================== OdeMesh::~OdeMesh() { dGeomDestroy(mGeomId); if (mOdeTriMeshDataId) dGeomTriMeshDataDestroy(mOdeTriMeshDataId); } //============================================================================== void OdeMesh::updateEngineData() { // Do nothing } //============================================================================== void OdeMesh::fillArrays(const aiScene* scene, const Eigen::Vector3d& scale) { mVertices.clear(); mNormals.clear(); mIndices.clear(); // Cound the total numbers of vertices and indices. auto mNumVertices = 0u; auto mNumIndices = 0u; for (auto i = 0u; i < scene->mNumMeshes; ++i) { const auto mesh = scene->mMeshes[i]; mNumVertices += mesh->mNumVertices; mNumIndices += mesh->mNumFaces; } mNumVertices *= 3u; mNumIndices *= 3u; // The number of indices of each face is always 3 because we use the assimp // option `aiProcess_Triangulate` when loading meshes. mVertices.resize(mNumVertices); mNormals.resize(mNumVertices); mIndices.resize(mNumIndices); auto vertexIndex = 0u; auto indexIndex = 0u; for (auto i = 0u; i < scene->mNumMeshes; ++i) { const auto mesh = scene->mMeshes[i]; for (auto j = 0u; j < mesh->mNumVertices; ++j) { mVertices[vertexIndex] = mesh->mVertices[j].x * scale.x(); mNormals[vertexIndex++] = mesh->mNormals[j].x; mVertices[vertexIndex] = mesh->mVertices[j].y * scale.y(); mNormals[vertexIndex++] = mesh->mNormals[j].y; mVertices[vertexIndex] = mesh->mVertices[j].z * scale.z(); mNormals[vertexIndex++] = mesh->mNormals[j].z; } for (auto j = 0u; j < mesh->mNumFaces; ++j) { mIndices[indexIndex++] = mesh->mFaces[j].mIndices[0]; mIndices[indexIndex++] = mesh->mFaces[j].mIndices[1]; mIndices[indexIndex++] = mesh->mFaces[j].mIndices[2]; } } } } // namespace detail } // namespace collision } // namespace dart
32.808511
80
0.646995
[ "mesh" ]
6d07ce67e8241b0bae75655325cb7f610797c60d
29,185
cpp
C++
src/Generating/Noise3DGenerator.cpp
fairinternal/cuberite
a8c63a757c73279b854e5ef9622287d1c7d68b85
[ "Apache-2.0" ]
null
null
null
src/Generating/Noise3DGenerator.cpp
fairinternal/cuberite
a8c63a757c73279b854e5ef9622287d1c7d68b85
[ "Apache-2.0" ]
null
null
null
src/Generating/Noise3DGenerator.cpp
fairinternal/cuberite
a8c63a757c73279b854e5ef9622287d1c7d68b85
[ "Apache-2.0" ]
null
null
null
// Nosie3DGenerator.cpp // Generates terrain using 3D noise, rather than composing. Is a test. #include "Globals.h" #include "Noise3DGenerator.h" #include "../IniFile.h" #include "../LinearInterpolation.h" #include "../LinearUpscale.h" /* // Perform an automatic test of upscaling upon program start (use breakpoints to debug): class Test { public: Test(void) { DoTest1(); DoTest2(); } void DoTest1(void) { float In[3 * 3 * 3]; for (size_t i = 0; i < ARRAYCOUNT(In); i++) { In[i] = (float)(i % 5); } Debug3DNoise(In, 3, 3, 3, "Upscale3D in"); float Out[17 * 33 * 35]; LinearUpscale3DArray(In, 3, 3, 3, Out, 8, 16, 17); Debug3DNoise(Out, 17, 33, 35, "Upscale3D test"); } void DoTest2(void) { float In[3 * 3]; for (size_t i = 0; i < ARRAYCOUNT(In); i++) { In[i] = (float)(i % 5); } Debug2DNoise(In, 3, 3, "Upscale2D in"); float Out[17 * 33]; LinearUpscale2DArray(In, 3, 3, Out, 8, 16); Debug2DNoise(Out, 17, 33, "Upscale2D test"); } } gTest; //*/ #if 0 // Perform speed test of the cInterpolNoise class static class cInterpolNoiseSpeedTest { public: cInterpolNoiseSpeedTest(void) { TestSpeed2D(); TestSpeed3D(); printf("InterpolNoise speed comparison finished.\n"); } /** Compare the speed of the 3D InterpolNoise vs 3D CubicNoise. */ void TestSpeed3D(void) { printf("Evaluating 3D noise performance...\n"); static const int SIZE_X = 128; static const int SIZE_Y = 128; static const int SIZE_Z = 128; static const NOISE_DATATYPE MUL = 80; std::unique_ptr<NOISE_DATATYPE[]> arr(new NOISE_DATATYPE[SIZE_X * SIZE_Y * SIZE_Z]); cTimer timer; // Test the cInterpolNoise: cInterpolNoise<Interp5Deg> interpNoise(1); long long start = timer.GetNowTime(); for (int i = 0; i < 30; i++) { interpNoise.Generate3D(arr.get(), SIZE_X, SIZE_Y, SIZE_Z, MUL * i, MUL * i + MUL, 0, MUL, 0, MUL); } long long end = timer.GetNowTime(); printf("InterpolNoise took %.02f sec\n", static_cast<float>(end - start) / 1000); // Test the cCubicNoise: cCubicNoise cubicNoise(1); start = timer.GetNowTime(); for (int i = 0; i < 30; i++) { cubicNoise.Generate3D(arr.get(), SIZE_X, SIZE_Y, SIZE_Z, MUL * i, MUL * i + MUL, 0, MUL, 0, MUL); } end = timer.GetNowTime(); printf("CubicNoise took %.02f sec\n", static_cast<float>(end - start) / 1000); printf("3D noise performance comparison finished.\n"); } /** Compare the speed of the 2D InterpolNoise vs 2D CubicNoise. */ void TestSpeed2D(void) { printf("Evaluating 2D noise performance...\n"); static const int SIZE_X = 128; static const int SIZE_Y = 128; static const NOISE_DATATYPE MUL = 80; std::unique_ptr<NOISE_DATATYPE[]> arr(new NOISE_DATATYPE[SIZE_X * SIZE_Y]); cTimer timer; // Test the cInterpolNoise: cInterpolNoise<Interp5Deg> interpNoise(1); long long start = timer.GetNowTime(); for (int i = 0; i < 500; i++) { interpNoise.Generate2D(arr.get(), SIZE_X, SIZE_Y, MUL * i, MUL * i + MUL, 0, MUL); } long long end = timer.GetNowTime(); printf("InterpolNoise took %.02f sec\n", static_cast<float>(end - start) / 1000); // Test the cCubicNoise: cCubicNoise cubicNoise(1); start = timer.GetNowTime(); for (int i = 0; i < 500; i++) { cubicNoise.Generate2D(arr.get(), SIZE_X, SIZE_Y, MUL * i, MUL * i + MUL, 0, MUL); } end = timer.GetNowTime(); printf("CubicNoise took %.02f sec\n", static_cast<float>(end - start) / 1000); printf("2D noise performance comparison finished.\n"); } } g_InterpolNoiseSpeedTest; #endif //////////////////////////////////////////////////////////////////////////////// // cNoise3DGenerator: cNoise3DGenerator::cNoise3DGenerator(cChunkGenerator & a_ChunkGenerator) : super(a_ChunkGenerator), m_Perlin(1000), m_Cubic(1000) { m_Perlin.AddOctave(1, 1); m_Perlin.AddOctave(2, 0.5); m_Perlin.AddOctave(4, 0.25); m_Perlin.AddOctave(8, 0.125); m_Perlin.AddOctave(16, 0.0625); m_Cubic.AddOctave(1, 1); m_Cubic.AddOctave(2, 0.5); m_Cubic.AddOctave(4, 0.25); m_Cubic.AddOctave(8, 0.125); m_Cubic.AddOctave(16, 0.0625); } cNoise3DGenerator::~cNoise3DGenerator() { // Nothing needed yet } void cNoise3DGenerator::Initialize(cIniFile & a_IniFile) { // Params: m_SeaLevel = a_IniFile.GetValueSetI("Generator", "SeaLevel", 62); m_HeightAmplification = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DHeightAmplification", 0.1)); m_MidPoint = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DMidPoint", 68)); m_FrequencyX = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyX", 8)); m_FrequencyY = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyY", 8)); m_FrequencyZ = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyZ", 8)); m_AirThreshold = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DAirThreshold", 0.5)); } void cNoise3DGenerator::GenerateBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) { for (size_t i = 0; i < ARRAYCOUNT(a_BiomeMap); i++) { a_BiomeMap[i] = biExtremeHills; } } void cNoise3DGenerator::DoGenerate(int a_ChunkX, int a_ChunkZ, cChunkDesc & a_ChunkDesc) { NOISE_DATATYPE Noise[17 * 257 * 17]; GenerateNoiseArray(a_ChunkX, a_ChunkZ, Noise); // Output noise into chunk: for (int z = 0; z < cChunkDef::Width; z++) { for (int y = 0; y < cChunkDef::Height; y++) { int idx = z * 17 * 257 + y * 17; for (int x = 0; x < cChunkDef::Width; x++) { NOISE_DATATYPE n = Noise[idx++]; BLOCKTYPE BlockType; if (n > m_AirThreshold) { BlockType = (y > m_SeaLevel) ? E_BLOCK_AIR : E_BLOCK_STATIONARY_WATER; } else { BlockType = E_BLOCK_STONE; } a_ChunkDesc.SetBlockType(x, y, z, BlockType); } } } a_ChunkDesc.UpdateHeightmap(); ComposeTerrain (a_ChunkDesc); } void cNoise3DGenerator::GenerateNoiseArray(int a_ChunkX, int a_ChunkZ, NOISE_DATATYPE * a_OutNoise) { NOISE_DATATYPE NoiseO[DIM_X * DIM_Y * DIM_Z]; // Output for the Perlin noise NOISE_DATATYPE NoiseW[DIM_X * DIM_Y * DIM_Z]; // Workspace that the noise calculation can use and trash // Our noise array has different layout, XZY, instead of regular chunk's XYZ, that's why the coords are "renamed" NOISE_DATATYPE StartX = static_cast<NOISE_DATATYPE>(a_ChunkX * cChunkDef::Width) / m_FrequencyX; NOISE_DATATYPE EndX = static_cast<NOISE_DATATYPE>((a_ChunkX + 1) * cChunkDef::Width) / m_FrequencyX; NOISE_DATATYPE StartZ = static_cast<NOISE_DATATYPE>(a_ChunkZ * cChunkDef::Width) / m_FrequencyZ; NOISE_DATATYPE EndZ = static_cast<NOISE_DATATYPE>((a_ChunkZ + 1) * cChunkDef::Width) / m_FrequencyZ; NOISE_DATATYPE StartY = 0; NOISE_DATATYPE EndY = static_cast<NOISE_DATATYPE>(256) / m_FrequencyY; m_Perlin.Generate3D(NoiseO, DIM_X, DIM_Y, DIM_Z, StartX, EndX, StartY, EndY, StartZ, EndZ, NoiseW); // DEBUG: Debug3DNoise(NoiseO, DIM_X, DIM_Y, DIM_Z, Printf("Chunk_%d_%d_orig", a_ChunkX, a_ChunkZ)); // Precalculate a "height" array: NOISE_DATATYPE Height[DIM_X * DIM_Z]; // Output for the cubic noise heightmap ("source") m_Cubic.Generate2D(Height, DIM_X, DIM_Z, StartX / 5, EndX / 5, StartZ / 5, EndZ / 5); for (size_t i = 0; i < ARRAYCOUNT(Height); i++) { Height[i] = Height[i] * m_HeightAmplification; } // Modify the noise by height data: for (int y = 0; y < DIM_Y; y++) { NOISE_DATATYPE AddHeight = (y * UPSCALE_Y - m_MidPoint) / 30; // AddHeight *= AddHeight * AddHeight; for (int z = 0; z < DIM_Z; z++) { NOISE_DATATYPE * CurRow = &(NoiseO[y * DIM_X + z * DIM_X * DIM_Y]); for (int x = 0; x < DIM_X; x++) { CurRow[x] += AddHeight + Height[x + DIM_X * z]; } } } // DEBUG: Debug3DNoise(NoiseO, DIM_X, DIM_Y, DIM_Z, Printf("Chunk_%d_%d_hei", a_ChunkX, a_ChunkZ)); // Upscale the Perlin noise into full-blown chunk dimensions: LinearUpscale3DArray( NoiseO, DIM_X, DIM_Y, DIM_Z, a_OutNoise, UPSCALE_X, UPSCALE_Y, UPSCALE_Z ); // DEBUG: Debug3DNoise(a_OutNoise, 17, 257, 17, Printf("Chunk_%d_%d_lerp", a_ChunkX, a_ChunkZ)); } void cNoise3DGenerator::ComposeTerrain(cChunkDesc & a_ChunkDesc) { // Make basic terrain composition: for (int z = 0; z < cChunkDef::Width; z++) { for (int x = 0; x < cChunkDef::Width; x++) { int LastAir = a_ChunkDesc.GetHeight(x, z) + 1; bool HasHadWater = false; for (int y = LastAir - 1; y > 0; y--) { switch (a_ChunkDesc.GetBlockType(x, y, z)) { case E_BLOCK_AIR: { LastAir = y; break; } case E_BLOCK_STONE: { if (LastAir - y > 3) { break; } if (HasHadWater) { a_ChunkDesc.SetBlockType(x, y, z, E_BLOCK_SAND); } else { a_ChunkDesc.SetBlockType(x, y, z, (LastAir == y + 1) ? E_BLOCK_GRASS : E_BLOCK_DIRT); } break; } case E_BLOCK_STATIONARY_WATER: { LastAir = y; HasHadWater = true; break; } } // switch (GetBlockType()) } // for y a_ChunkDesc.SetBlockType(x, 0, z, E_BLOCK_BEDROCK); } // for x } // for z } //////////////////////////////////////////////////////////////////////////////// // cNoise3DComposable: cNoise3DComposable::cNoise3DComposable(int a_Seed) : m_ChoiceNoise(a_Seed), m_DensityNoiseA(a_Seed + 1), m_DensityNoiseB(a_Seed + 2), m_BaseNoise(a_Seed + 3), m_HeightAmplification(0.0), m_MidPoint(0.0), m_FrequencyX(0.0), m_FrequencyY(0.0), m_FrequencyZ(0.0), m_BaseFrequencyX(0.0), m_BaseFrequencyZ(0.0), m_ChoiceFrequencyX(0.0), m_ChoiceFrequencyY(0.0), m_ChoiceFrequencyZ(0.0), m_AirThreshold(0.0), m_LastChunkX(0x7fffffff), // Use dummy coords that won't ever be used by real chunks m_LastChunkZ(0x7fffffff) { } void cNoise3DComposable::Initialize(cIniFile & a_IniFile) { // Params: // The defaults generate extreme hills terrain m_HeightAmplification = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DHeightAmplification", 0.045)); m_MidPoint = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DMidPoint", 75)); m_FrequencyX = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyX", 40)); m_FrequencyY = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyY", 40)); m_FrequencyZ = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyZ", 40)); m_BaseFrequencyX = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DBaseFrequencyX", 40)); m_BaseFrequencyZ = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DBaseFrequencyZ", 40)); m_ChoiceFrequencyX = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DChoiceFrequencyX", 40)); m_ChoiceFrequencyY = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DChoiceFrequencyY", 80)); m_ChoiceFrequencyZ = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DChoiceFrequencyZ", 40)); m_AirThreshold = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DAirThreshold", 0)); int NumChoiceOctaves = a_IniFile.GetValueSetI("Generator", "Noise3DNumChoiceOctaves", 4); int NumDensityOctaves = a_IniFile.GetValueSetI("Generator", "Noise3DNumDensityOctaves", 6); int NumBaseOctaves = a_IniFile.GetValueSetI("Generator", "Noise3DNumBaseOctaves", 6); NOISE_DATATYPE BaseNoiseAmplitude = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "Noise3DBaseAmplitude", 1)); // Add octaves for the choice noise: NOISE_DATATYPE wavlen = 1, ampl = 0.5; for (int i = 0; i < NumChoiceOctaves; i++) { m_ChoiceNoise.AddOctave(wavlen, ampl); wavlen = wavlen * 2; ampl = ampl / 2; } // Add octaves for the density noises: wavlen = 1; ampl = 1; for (int i = 0; i < NumDensityOctaves; i++) { m_DensityNoiseA.AddOctave(wavlen, ampl); m_DensityNoiseB.AddOctave(wavlen, ampl); wavlen = wavlen * 2; ampl = ampl / 2; } // Add octaves for the base noise: wavlen = 1; ampl = BaseNoiseAmplitude; for (int i = 0; i < NumBaseOctaves; i++) { m_BaseNoise.AddOctave(wavlen, ampl); wavlen = wavlen * 2; ampl = ampl / 2; } } void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ) { if ((a_ChunkX == m_LastChunkX) && (a_ChunkZ == m_LastChunkZ)) { // The noise for this chunk is already generated in m_NoiseArray return; } m_LastChunkX = a_ChunkX; m_LastChunkZ = a_ChunkZ; // Generate all the noises: NOISE_DATATYPE ChoiceNoise[5 * 5 * 33]; NOISE_DATATYPE Workspace[5 * 5 * 33]; NOISE_DATATYPE DensityNoiseA[5 * 5 * 33]; NOISE_DATATYPE DensityNoiseB[5 * 5 * 33]; NOISE_DATATYPE BaseNoise[5 * 5]; NOISE_DATATYPE BlockX = static_cast<NOISE_DATATYPE>(a_ChunkX * cChunkDef::Width); NOISE_DATATYPE BlockZ = static_cast<NOISE_DATATYPE>(a_ChunkZ * cChunkDef::Width); // Note that we have to swap the X and Y coords, because noise generator uses [x + SizeX * y + SizeX * SizeY * z] ordering and we want "BlockY" to be "x": m_ChoiceNoise.Generate3D (ChoiceNoise, 33, 5, 5, 0, 257 / m_ChoiceFrequencyY, BlockX / m_ChoiceFrequencyX, (BlockX + 17) / m_ChoiceFrequencyX, BlockZ / m_ChoiceFrequencyZ, (BlockZ + 17) / m_ChoiceFrequencyZ, Workspace); m_DensityNoiseA.Generate3D(DensityNoiseA, 33, 5, 5, 0, 257 / m_FrequencyY, BlockX / m_FrequencyX, (BlockX + 17) / m_FrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, Workspace); m_DensityNoiseB.Generate3D(DensityNoiseB, 33, 5, 5, 0, 257 / m_FrequencyY, BlockX / m_FrequencyX, (BlockX + 17) / m_FrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, Workspace); m_BaseNoise.Generate2D (BaseNoise, 5, 5, BlockX / m_BaseFrequencyX, (BlockX + 17) / m_BaseFrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, Workspace); // Calculate the final noise based on the partial noises: for (int z = 0; z < 5; z++) { for (int x = 0; x < 5; x++) { NOISE_DATATYPE curBaseNoise = BaseNoise[x + 5 * z]; for (int y = 0; y < 33; y++) { NOISE_DATATYPE AddHeight = (static_cast<NOISE_DATATYPE>(y * 8) - m_MidPoint) * m_HeightAmplification; // If "underground", make the terrain smoother by forcing the vertical linear gradient into steeper slope: if (AddHeight < 0) { AddHeight *= 4; } // If too high, cut off any terrain: if (y > 28) { AddHeight = AddHeight + static_cast<NOISE_DATATYPE>(y - 28) / 4; } // Decide between the two density noises: int idx = 33 * x + 33 * 5 * z + y; Workspace[idx] = ClampedLerp(DensityNoiseA[idx], DensityNoiseB[idx], 8 * (ChoiceNoise[idx] + 0.5f)) + AddHeight + curBaseNoise; } } } LinearUpscale3DArray<NOISE_DATATYPE>(Workspace, 33, 5, 5, m_NoiseArray, 8, 4, 4); } void cNoise3DComposable::GenShape(int a_ChunkX, int a_ChunkZ, cChunkDesc::Shape & a_Shape) { GenerateNoiseArrayIfNeeded(a_ChunkX, a_ChunkZ); // Translate the noise array into Shape: for (int z = 0; z < cChunkDef::Width; z++) { for (int x = 0; x < cChunkDef::Width; x++) { for (int y = 0; y < cChunkDef::Height; y++) { a_Shape[y + x * 256 + z * 256 * 16] = (m_NoiseArray[y + 257 * x + 257 * 17 * z] > m_AirThreshold) ? 0 : 1; } } // for x } // for z } //////////////////////////////////////////////////////////////////////////////// // cBiomalNoise3DComposable: cBiomalNoise3DComposable::cBiomalNoise3DComposable(int a_Seed, cBiomeGenPtr a_BiomeGen) : m_ChoiceNoise(a_Seed), m_DensityNoiseA(a_Seed + 1), m_DensityNoiseB(a_Seed + 2), m_BaseNoise(a_Seed + 3), m_BiomeGen(a_BiomeGen), m_LastChunkX(0x7fffffff), // Set impossible coords for the chunk so that it's always considered stale m_LastChunkZ(0x7fffffff) { // Generate the weight distribution for summing up neighboring biomes: m_WeightSum = 0; for (int z = 0; z <= AVERAGING_SIZE * 2; z++) { for (int x = 0; x <= AVERAGING_SIZE * 2; x++) { m_Weight[z][x] = static_cast<NOISE_DATATYPE>((AVERAGING_SIZE - std::abs(AVERAGING_SIZE - x)) + (AVERAGING_SIZE - std::abs(AVERAGING_SIZE - z))); m_WeightSum += m_Weight[z][x]; } } } void cBiomalNoise3DComposable::Initialize(cIniFile & a_IniFile) { // Params: // The defaults generate extreme hills terrain m_SeaLevel = a_IniFile.GetValueSetI("Generator", "SeaLevel", 62); m_FrequencyX = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DFrequencyX", 40)); m_FrequencyY = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DFrequencyY", 40)); m_FrequencyZ = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DFrequencyZ", 40)); m_BaseFrequencyX = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DBaseFrequencyX", 40)); m_BaseFrequencyZ = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DBaseFrequencyZ", 40)); m_ChoiceFrequencyX = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DChoiceFrequencyX", 40)); m_ChoiceFrequencyY = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DChoiceFrequencyY", 80)); m_ChoiceFrequencyZ = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DChoiceFrequencyZ", 40)); m_AirThreshold = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DAirThreshold", 0)); int NumChoiceOctaves = a_IniFile.GetValueSetI("Generator", "BiomalNoise3DNumChoiceOctaves", 4); int NumDensityOctaves = a_IniFile.GetValueSetI("Generator", "BiomalNoise3DNumDensityOctaves", 6); int NumBaseOctaves = a_IniFile.GetValueSetI("Generator", "BiomalNoise3DNumBaseOctaves", 6); NOISE_DATATYPE BaseNoiseAmplitude = static_cast<NOISE_DATATYPE>(a_IniFile.GetValueSetF("Generator", "BiomalNoise3DBaseAmplitude", 1)); // Add octaves for the choice noise: NOISE_DATATYPE wavlen = 1, ampl = 0.5; for (int i = 0; i < NumChoiceOctaves; i++) { m_ChoiceNoise.AddOctave(wavlen, ampl); wavlen = wavlen * 2; ampl = ampl / 2; } // Add octaves for the density noises: wavlen = 1; ampl = 1; for (int i = 0; i < NumDensityOctaves; i++) { m_DensityNoiseA.AddOctave(wavlen, ampl); m_DensityNoiseB.AddOctave(wavlen, ampl); wavlen = wavlen * 2; ampl = ampl / 2; } // Add octaves for the base noise: wavlen = 1; ampl = BaseNoiseAmplitude; for (int i = 0; i < NumBaseOctaves; i++) { m_BaseNoise.AddOctave(wavlen, ampl); wavlen = wavlen * 2; ampl = ampl / 2; } } void cBiomalNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ) { if ((a_ChunkX == m_LastChunkX) && (a_ChunkZ == m_LastChunkZ)) { // The noise for this chunk is already generated in m_NoiseArray return; } m_LastChunkX = a_ChunkX; m_LastChunkZ = a_ChunkZ; // Calculate the parameters for the biomes: ChunkParam MidPoint; ChunkParam HeightAmp; CalcBiomeParamArrays(a_ChunkX, a_ChunkZ, HeightAmp, MidPoint); // Generate all the noises: NOISE_DATATYPE ChoiceNoise[5 * 5 * 33]; NOISE_DATATYPE Workspace[5 * 5 * 33]; NOISE_DATATYPE DensityNoiseA[5 * 5 * 33]; NOISE_DATATYPE DensityNoiseB[5 * 5 * 33]; NOISE_DATATYPE BaseNoise[5 * 5]; NOISE_DATATYPE BlockX = static_cast<NOISE_DATATYPE>(a_ChunkX * cChunkDef::Width); NOISE_DATATYPE BlockZ = static_cast<NOISE_DATATYPE>(a_ChunkZ * cChunkDef::Width); // Note that we have to swap the X and Y coords, because noise generator uses [x + SizeX * y + SizeX * SizeY * z] ordering and we want "BlockY" to be "x": m_ChoiceNoise.Generate3D (ChoiceNoise, 33, 5, 5, 0, 257 / m_ChoiceFrequencyY, BlockX / m_ChoiceFrequencyX, (BlockX + 17) / m_ChoiceFrequencyX, BlockZ / m_ChoiceFrequencyZ, (BlockZ + 17) / m_ChoiceFrequencyZ, Workspace); m_DensityNoiseA.Generate3D(DensityNoiseA, 33, 5, 5, 0, 257 / m_FrequencyY, BlockX / m_FrequencyX, (BlockX + 17) / m_FrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, Workspace); m_DensityNoiseB.Generate3D(DensityNoiseB, 33, 5, 5, 0, 257 / m_FrequencyY, BlockX / m_FrequencyX, (BlockX + 17) / m_FrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, Workspace); m_BaseNoise.Generate2D (BaseNoise, 5, 5, BlockX / m_BaseFrequencyX, (BlockX + 17) / m_BaseFrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, Workspace); // Calculate the final noise based on the partial noises: for (int z = 0; z < 5; z++) { for (int x = 0; x < 5; x++) { NOISE_DATATYPE curMidPoint = MidPoint[x + 5 * z]; NOISE_DATATYPE curHeightAmp = HeightAmp[x + 5 * z]; NOISE_DATATYPE curBaseNoise = BaseNoise[x + 5 * z]; for (int y = 0; y < 33; y++) { NOISE_DATATYPE AddHeight = (static_cast<NOISE_DATATYPE>(y * 8) - curMidPoint) * curHeightAmp; // If "underground", make the terrain smoother by forcing the vertical linear gradient into steeper slope: if (AddHeight < 0) { AddHeight *= 4; } // If too high, cut off any terrain: if (y > 28) { AddHeight = AddHeight + static_cast<NOISE_DATATYPE>(y - 28) / 4; } // Decide between the two density noises: int idx = 33 * x + y + 33 * 5 * z; Workspace[idx] = ClampedLerp(DensityNoiseA[idx], DensityNoiseB[idx], 8 * (ChoiceNoise[idx] + 0.5f)) + AddHeight + curBaseNoise; } } } LinearUpscale3DArray<NOISE_DATATYPE>(Workspace, 33, 5, 5, m_NoiseArray, 8, 4, 4); } void cBiomalNoise3DComposable::CalcBiomeParamArrays(int a_ChunkX, int a_ChunkZ, ChunkParam & a_HeightAmp, ChunkParam & a_MidPoint) { // Generate the 3 * 3 chunks of biomes around this chunk: cChunkDef::BiomeMap neighborBiomes[3 * 3]; for (int z = 0; z < 3; z++) { for (int x = 0; x < 3; x++) { m_BiomeGen->GenBiomes(a_ChunkX + x - 1, a_ChunkZ + z - 1, neighborBiomes[x + 3 * z]); } } // Sum up the biome values: for (int z = 0; z < 5; z++) { for (int x = 0; x < 5; x++) { NOISE_DATATYPE totalHeightAmp = 0; NOISE_DATATYPE totalMidPoint = 0; // Add up the biomes around this point: for (int relz = 0; relz <= AVERAGING_SIZE * 2; ++relz) { int colz = 16 + z * 4 + relz - AVERAGING_SIZE; // Biome Z coord relative to the neighborBiomes start int neicellz = colz / 16; // Chunk Z coord relative to the neighborBiomes start int neirelz = colz % 16; // Biome Z coord relative to cz in neighborBiomes for (int relx = 0; relx <= AVERAGING_SIZE * 2; ++relx) { int colx = 16 + x * 4 + relx - AVERAGING_SIZE; // Biome X coord relative to the neighborBiomes start int neicellx = colx / 16; // Chunk X coord relative to the neighborBiomes start int neirelx = colx % 16; // Biome X coord relative to cz in neighborBiomes EMCSBiome biome = cChunkDef::GetBiome(neighborBiomes[neicellx + neicellz * 3], neirelx, neirelz); NOISE_DATATYPE heightAmp, midPoint; GetBiomeParams(biome, heightAmp, midPoint); totalHeightAmp += heightAmp * m_Weight[relz][relx]; totalMidPoint += midPoint * m_Weight[relz][relx]; } // for relx } // for relz a_HeightAmp[x + 5 * z] = totalHeightAmp / m_WeightSum; a_MidPoint[x + 5 * z] = totalMidPoint / m_WeightSum; } // for x } // for z } void cBiomalNoise3DComposable::GetBiomeParams(EMCSBiome a_Biome, NOISE_DATATYPE & a_HeightAmp, NOISE_DATATYPE & a_MidPoint) { switch (a_Biome) { case biBeach: a_HeightAmp = 0.2f; a_MidPoint = 60; break; case biBirchForest: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biBirchForestHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biBirchForestHillsM: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biBirchForestM: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biColdBeach: a_HeightAmp = 0.3f; a_MidPoint = 62; break; case biColdTaiga: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biColdTaigaM: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biColdTaigaHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biDesertHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biDeepOcean: a_HeightAmp = 0.17f; a_MidPoint = 35; break; case biDesert: a_HeightAmp = 0.29f; a_MidPoint = 62; break; case biDesertM: a_HeightAmp = 0.29f; a_MidPoint = 62; break; case biEnd: a_HeightAmp = 0.15f; a_MidPoint = 64; break; case biExtremeHills: a_HeightAmp = 0.045f; a_MidPoint = 75; break; case biExtremeHillsEdge: a_HeightAmp = 0.1f; a_MidPoint = 70; break; case biExtremeHillsM: a_HeightAmp = 0.045f; a_MidPoint = 75; break; case biExtremeHillsPlus: a_HeightAmp = 0.04f; a_MidPoint = 80; break; case biExtremeHillsPlusM: a_HeightAmp = 0.04f; a_MidPoint = 80; break; case biFlowerForest: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biForest: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biForestHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biFrozenRiver: a_HeightAmp = 0.4f; a_MidPoint = 54; break; case biFrozenOcean: a_HeightAmp = 0.12f; a_MidPoint = 45; break; case biIceMountains: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biIcePlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; case biIcePlainsSpikes: a_HeightAmp = 0.3f; a_MidPoint = 62; break; case biJungle: a_HeightAmp = 0.1f; a_MidPoint = 63; break; case biJungleEdge: a_HeightAmp = 0.15f; a_MidPoint = 62; break; case biJungleEdgeM: a_HeightAmp = 0.15f; a_MidPoint = 62; break; case biJungleHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biJungleM: a_HeightAmp = 0.1f; a_MidPoint = 63; break; case biMegaSpruceTaiga: a_HeightAmp = 0.09f; a_MidPoint = 64; break; case biMegaSpruceTaigaHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biMegaTaiga: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biMegaTaigaHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biMesa: a_HeightAmp = 0.09f; a_MidPoint = 61; break; case biMesaBryce: a_HeightAmp = 0.15f; a_MidPoint = 61; break; case biMesaPlateau: a_HeightAmp = 0.25f; a_MidPoint = 86; break; case biMesaPlateauF: a_HeightAmp = 0.25f; a_MidPoint = 96; break; case biMesaPlateauFM: a_HeightAmp = 0.25f; a_MidPoint = 96; break; case biMesaPlateauM: a_HeightAmp = 0.25f; a_MidPoint = 86; break; case biMushroomShore: a_HeightAmp = 0.075f; a_MidPoint = 60; break; case biMushroomIsland: a_HeightAmp = 0.06f; a_MidPoint = 80; break; case biNether: a_HeightAmp = 0.01f; a_MidPoint = 64; break; case biOcean: a_HeightAmp = 0.12f; a_MidPoint = 45; break; case biPlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; case biRiver: a_HeightAmp = 0.4f; a_MidPoint = 54; break; case biRoofedForest: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biRoofedForestM: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biSavanna: a_HeightAmp = 0.3f; a_MidPoint = 62; break; case biSavannaM: a_HeightAmp = 0.3f; a_MidPoint = 62; break; case biSavannaPlateau: a_HeightAmp = 0.3f; a_MidPoint = 85; break; case biSavannaPlateauM: a_HeightAmp = 0.012f; a_MidPoint = 105; break; case biStoneBeach: a_HeightAmp = 0.075f; a_MidPoint = 60; break; case biSunflowerPlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; case biSwampland: a_HeightAmp = 0.25f; a_MidPoint = 59; break; case biSwamplandM: a_HeightAmp = 0.11f; a_MidPoint = 59; break; case biTaiga: a_HeightAmp = 0.1f; a_MidPoint = 64; break; case biTaigaM: a_HeightAmp = 0.1f; a_MidPoint = 70; break; case biTaigaHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; case biInvalidBiome: case biNumBiomes: case biVariant: case biNumVariantBiomes: { // Make a crazy terrain so that it stands out a_HeightAmp = 0.001f; a_MidPoint = 90; break; } } } void cBiomalNoise3DComposable::GenShape(int a_ChunkX, int a_ChunkZ, cChunkDesc::Shape & a_Shape) { GenerateNoiseArrayIfNeeded(a_ChunkX, a_ChunkZ); // Translate the noise array into Shape: for (int z = 0; z < cChunkDef::Width; z++) { for (int x = 0; x < cChunkDef::Width; x++) { for (int y = 0; y < cChunkDef::Height; y++) { a_Shape[y + x * 256 + z * 256 * 16] = (m_NoiseArray[y + 257 * x + 257 * 17 * z] > m_AirThreshold) ? 0 : 1; } } // for x } // for z }
36.164808
223
0.663492
[ "shape", "3d" ]
6d0b3b0a54908d373cb6ab819058870361ce7b20
14,822
cpp
C++
src/OLS.cpp
S-telescope2/URT
1acf0c11ba96a8dc0ac12823c5571f8256617641
[ "MIT" ]
79
2017-01-06T21:57:06.000Z
2022-03-16T16:08:36.000Z
src/OLS.cpp
S-telescope2/URT
1acf0c11ba96a8dc0ac12823c5571f8256617641
[ "MIT" ]
9
2016-12-16T09:45:01.000Z
2022-02-11T06:53:49.000Z
src/OLS.cpp
S-telescope2/URT
1acf0c11ba96a8dc0ac12823c5571f8256617641
[ "MIT" ]
20
2017-02-02T12:23:24.000Z
2022-02-09T17:02:57.000Z
//================================================================================================= // Copyright (C) 2016 Olivier Mallet - All Rights Reserved //================================================================================================= #include "../include/URT.hpp" namespace urt { //================================================================================================= // parameter constructor template <class T> OLS<T>::OLS(const Vector<T>& y, const Matrix<T>& x, bool stats) { // controlling x and y dimensions #ifdef USE_ARMA if (y.n_elem != x.n_rows) { #elif defined(USE_BLAZE) || defined(USE_EIGEN) if (y.size() != x.rows()) { #endif throw std::invalid_argument("\n Error: in OLS::OLS(), dependent and independent variables in OLS regression must have same number of rows.\n\n"); } #ifdef USE_ARMA else if (!y.n_elem || !x.n_rows) { #elif defined(USE_BLAZE) || defined(USE_EIGEN) else if (!y.size() || !x.rows()) { #endif throw std::invalid_argument("\n Error: in OLS::OLS(), y vector and x matrix must not be empty.\n\n"); } #ifdef USE_ARMA // number of observations this->nobs = x.n_rows; // number of regressors this->nreg = x.n_cols; #elif defined(USE_BLAZE) || defined(USE_EIGEN) // number of observations this->nobs = x.rows(); // number of regressors #ifdef USE_BLAZE this->nreg = x.columns(); #elif USE_EIGEN this->nreg = x.cols(); #endif #endif // error number of degrees of freedom this->ndf = nobs - nreg; try { #ifdef USE_ARMA // inverting matrix x square Matrix<T> ix2 = (x.t() * x).i(); // computing vector b solution of y = x * b this->param = ix2 * (x.t() * y); #elif USE_BLAZE // inverting matrix x square Matrix<T> ix2 = blaze::inv(blaze::trans(x) * x); // computing vector b solution of y = x * b this->param = ix2 * (blaze::trans(x) * y); #elif USE_EIGEN // inverting matrix x square Matrix<T> tmp = Matrix<T>::Zero(nreg, nreg); tmp.template selfadjointView<Eigen::Lower>().rankUpdate(x.transpose()); tmp.template triangularView<Eigen::Upper>() = tmp.transpose().template triangularView<Eigen::Lower>(); Matrix<T> ix2 = tmp.inverse(); // computing vector b solution of y = x * b this->param = ix2 * (x.transpose() * y); #endif // computing residuals this->resid = y - x * param; // computing sum of squared residuals #ifdef USE_ARMA this->SSR = arma::as_scalar(resid.t() * resid); #elif USE_BLAZE this->SSR = blaze::trans(resid) * resid; #elif USE_EIGEN this->SSR = resid.dot(resid); #endif // computing error variance (mean squares error or mse) this->MSE = SSR / ndf; #ifdef USE_ARMA // computing regressors variances this->var = diagvec(ix2) * MSE; // computing regressors t-statistics this->t_stat = param / sqrt(var); #elif USE_BLAZE // computing regressors variances this->var.resize(nreg); for (int i = 0; i < nreg; ++i) { this->var[i] = ix2(i, i) * MSE; } // computing regressors t-statistics this->t_stat = param * invsqrt(var); #elif USE_EIGEN // computing regressors variances this->var = ix2.diagonal() * MSE; // computing regressors t-statistics this->t_stat = param.cwiseProduct(var.cwiseSqrt().cwiseInverse()); #endif } // catching any exception caused by arma::inv() catch (std::exception& e) { std::cout << e.what() << "\n"; throw std::invalid_argument("\n Error: in OLS::OLS(), matrix inversion failed in OLS regression, please check x matrix.\n\n"); } this->stats = stats; // computing regression statistics if (stats) { this->get_stats(y, x); } } //************************************************************************************************* // compute OLS statistics (R2, adj_R2, F and DW stats) template <typename T> void OLS<T>::get_stats(const Vector<T>& y, const Matrix<T>& x) { // number of variables this->nvar = nreg; // testing if x contains an intercept (some stats are computed differently wether the regression contains an intercept or not) for (int i = 0; i < nreg; ++i) { // testing if the sum of elements if the ith column is equal to the number of rows #ifdef USE_ARMA if (arma::sum(x.col(i)) == nobs) { #elif USE_BLAZE if (x(0, i) == 1 && blaze::isUniform(column(x, i))) { #elif USE_EIGEN if ((x.col(i)).sum() == nobs) { #endif // setting OLS intercept to true this->intercept = true; // recording intercept column index this->j0 = i; // adjusting number of variables this->nvar -= 1; break; } } T SST; // computing x * b Vector<T> z = y - resid; if (intercept) { #ifdef USE_ARMA T my = mean(y); Vector<T> diff = y - my; SST = as_scalar(diff.t() * diff); z -= my; #elif USE_BLAZE T my = std::accumulate(&y[0], &y[y.size()], 0.0) / y.size(); Vector<T> diff = forEach(y, [&my](const T& val){ return val - my; }); SST = blaze::trans(diff) * diff; z = forEach(z, [&my](const T& val){ return val - my; }); #elif USE_EIGEN T my = y.mean(); Vector<T> diff = y - Vector<T>::Constant(y.size(), 1, my);; SST = diff.dot(diff); z -= Vector<T>::Constant(z.size(), 1, my); #endif } else { #ifdef USE_ARMA SST = arma::as_scalar(y.t() * y); #elif USE_BLAZE SST = blaze::trans(y) * y; #elif USE_EIGEN SST = y.dot(y); #endif } // computing R-squared this->R2 = 1 - SSR / SST; // computing adjusted R-squared this->adj_R2 = R2 - (1.0 - R2) * nvar / ndf; // computing mean of squares for model #ifdef USE_ARMA T MSM = arma::as_scalar(z.t() * z) / nvar; #elif USE_BLAZE T MSM = (blaze::trans(z) * z) / nvar; #elif USE_EIGEN T MSM = z.dot(z) / nvar; #endif // computing F-statistic this->F_stat = MSM / MSE; // computing Durbin-Watson statistic #ifdef USE_ARMA Vector<T> temp = Vector<T>(resid.memptr() + 1, resid.n_elem - 1, false) - Vector<T>(resid.memptr(), resid.n_elem - 1, false); this->DW_stat = arma::as_scalar(temp.t() * temp) / SSR; #elif USE_BLAZE Vector<T> temp = subvector(resid, 1, resid.size() - 1) - subvector(resid, 0, resid.size() - 1); this->DW_stat = (blaze::trans(temp) * temp) / SSR; #elif USE_EIGEN Vector<T> temp = resid.segment(1, resid.size() - 1) - resid.segment(0, resid.size() - 1); this->DW_stat = temp.dot(temp) / SSR; #endif this->stats = true; } //************************************************************************************************* // print results template <class T> void OLS<T>::show() { Vector<T> pval(nreg); // declaring Student's distribution boost::math::students_t tdistrib(ndf); // declaring function computing t-statistic p-value std::function<T(T)> P = [&tdistrib](const T& z){ return 2 * (1 - boost::math::cdf(tdistrib, fabs(z))); }; for (int j = 0; j < nreg; ++j) { if (!std::isnan(t_stat[j])) { pval[j] = P(t_stat[j]); } else { pval[j] = -std::nan(""); } } int gap = 2; (intercept) ? gap += 9 : gap += 1 + std::to_string(nreg).length(); std::string line1(" "); for (int i = 0; i < gap + 39; ++i) { line1 += "-"; } std::string line2(" "); for (int i = 0; i < 40; ++i) { line2 += "-"; } // outputting OLS results std::cout << "\n"; std::cout << " OLS Regression Results\n"; std::cout << " ======================\n"; std::cout << "\n"; std::cout << " Coefficients\n"; std::cout << line1 << "\n"; // outputting table column names std::cout << std::setw(gap + 42) << "Estimate Std Error t value P(>|t|)\n"; // constructing vector of column indexes std::vector<int> idx(nreg); // initializing idx with intercept column index int i, n, k = 0; (intercept) ? idx[k++] = j0, i = 0 : i = 1; for (int j = 0; j < nreg; ++j) { if (!intercept || (intercept && j != j0)) { idx[k++] = j; } } for (const auto& j : idx) { if (intercept && !i) { std::cout << std::setw(gap) << "Intercept"; ++i; } else { std::cout << std::setw(gap) << "x" + std::to_string(i++); } // outputting parameter estimates n = std::to_string(int(fabs(param[j]))).length(); if (fabs(param[j]) >= 1e6 || fabs(param[j]) < 1e-5) { std::cout << std::scientific; std::cout << std::setprecision(1); } else { std::cout << std::fixed; std::cout << std::setprecision(6 - n); } std::cout << std::setw(11) << param[j]; std::cout.unsetf(std::ios_base::scientific); std::cout.unsetf(std::ios_base::fixed); // outputting parameter standard errors n = std::to_string(int(sqrt(var[j]))).length(); if (sqrt(var[j]) >= 1e6 || sqrt(var[j]) < 1e-4) { std::cout << std::scientific; std::cout << std::setprecision(1); } else { std::cout << std::fixed; std::cout << std::setprecision(std::max(5 - n, 0)); } std::cout << std::setw(11) << sqrt(var[j]); std::cout.unsetf(std::ios_base::scientific); std::cout.unsetf(std::ios_base::fixed); // outputting parameter t-statistics n = std::to_string(int(fabs(t_stat[j]))).length(); if (fabs(t_stat[j]) >= 1e6 || fabs(t_stat[j]) < 1e-3) { std::cout << std::scientific; std::cout << std::setprecision(1); } else { std::cout << std::fixed; std::cout << std::setprecision(std::max(4 - n, 0)); } std::cout << std::setw(10) << t_stat[j]; std::cout.unsetf(std::ios_base::scientific); std::cout.unsetf(std::ios_base::fixed); // outputting parameter p-values std::cout << std::fixed << std::setprecision(3) << std::setw(9) << pval[j]; std::cout << "\n"; } std::cout << "\n"; std::cout << " Residuals\n"; std::cout << line2 << "\n"; // outputting residuals results #ifdef USE_ARMA int nres = resid.n_elem; #elif defined(USE_BLAZE) || defined(USE_EIGEN) int nres = resid.size(); #endif std::cout << std::setw(10) << "Min" << std::setw(8) << "1Q" << std::setw(8) << "Median" << std::setw(8) << "3Q" << std::setw(8) << "Max"; std::cout << "\n"; #if defined(USE_ARMA) || defined(USE_BLAZE) n = std::to_string(int(max(abs(resid)))).length(); if (max(abs(resid)) >= 1e3 || max(abs(resid)) < 1e-3) { #elif USE_EIGEN n = std::to_string(int(resid.cwiseAbs().maxCoeff())).length(); if (resid.cwiseAbs().maxCoeff() >= 1e3 || resid.cwiseAbs().maxCoeff() < 1e-3) { #endif std::cout << std::scientific; std::cout << std::setprecision(1); } else { std::cout << std::fixed; std::cout << std::setprecision(std::max(4 - n, 0)); } // sorting residuals Vector<T> sorted_resid(resid); std::sort(&sorted_resid[0], &sorted_resid[nres]); std::cout << std::setw(10) << sorted_resid[0]; std::cout << std::setw(8) << sorted_resid[round(0.25 * nres) - 1]; std::cout << std::setw(8) << sorted_resid[round(0.50 * nres) - 1]; std::cout << std::setw(8) << sorted_resid[round(0.75 * nres) - 1]; std::cout << std::setw(8) << sorted_resid[nres - 1]; std::cout << "\n\n"; std::cout << " Dimensions\n"; std::cout << line2 << "\n"; std::cout << " Number of observations " << std::setw(10) << nobs << "\n"; std::cout << " Number of degrees of freedom " << std::setw(10) << ndf << "\n"; if (stats) { std::cout << " Number of variables " << std::setw(10) << nvar << "\n"; } std::cout << "\n"; std::cout << " Analysis\n"; std::cout << line2 << "\n"; // computing residual mean #ifdef USE_ARMA T mu = mean(resid); #elif USE_BLAZE T mu = std::accumulate(&resid[0], &resid[resid.size()], 0.0) / resid.size(); #elif USE_EIGEN T mu = resid.mean(); #endif // outputting residual mean n = std::to_string(int(fabs(mu))).length(); if (fabs(mu) >= 1e3 || fabs(mu) < 1e-3) { std::cout << std::scientific; std::cout << std::setprecision(1); } else { std::cout << std::fixed; std::cout << std::setprecision(std::max(4 - n, 0)); } std::cout << " Residual mean " << std::setw(10) << mu << "\n"; // outputting residual standard error n = std::to_string(int(sqrt(MSE))).length(); if (sqrt(MSE) >= 1e3 || sqrt(MSE) < 1e-3) { std::cout << std::scientific; std::cout << std::setprecision(1); } else { std::cout << std::fixed; std::cout << std::setprecision(std::max(4 - n, 0)); } std::cout << " Residual standard error " << std::setw(10) << sqrt(MSE) << "\n"; // if OLS regression statistics have been computed previously if (stats) { std::cout << std::fixed; // outputting multiple R-squared and adjusted R-squared std::cout << " Multiple R-squared " << std::setw(10) << std::setprecision(5) << R2 << "\n"; std::cout << " Adjusted R-squared " << std::setw(10) << std::setprecision(5) << adj_R2 << "\n"; // outputting F-statistic n = std::to_string(int(F_stat)).length(); if (sqrt(MSE) >= 1e4 || sqrt(MSE) < 1e-3) { std::cout << std::scientific; std::cout << std::setprecision(1); } else { std::cout << std::fixed; std::cout << std::setprecision(std::max(4 - n, 0)); } std::cout << " F-statistic (p-value) " << std::setw(10) << std::setprecision(2) << F_stat << " "; std::cout << "(" << 1 - boost::math::ibeta(nvar/2, ndf/2, F_stat*nvar/(F_stat*nvar + ndf)) << ")\n"; // outputting Durbin-Watson statistic std::cout << std::fixed; std::cout << " Durbin-Watson statistic " << std::setw(10) << std::setprecision(3) << DW_stat << "\n"; } std::cout << "\n"; } //************************************************************************************************* // cout overload for printing results from a multi-linear regression template <class T> std::ostream& operator<<(std::ostream& out, urt::OLS<T>& result) { result.show(); return out; } //================================================================================================= }
31.806867
152
0.520712
[ "vector", "model" ]
6d1107c8581240ddadeb5c2b6c970b2aa97f6cd7
2,395
cpp
C++
llvm/3.4.2/llvm-3.4.2.src/tools/yaml2obj/yaml2obj.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
36
2015-01-13T19:34:04.000Z
2022-03-07T22:22:15.000Z
llvm/3.4.2/llvm-3.4.2.src/tools/yaml2obj/yaml2obj.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
7
2015-10-20T19:05:01.000Z
2021-11-13T14:55:47.000Z
llvm/3.4.2/llvm-3.4.2.src/tools/yaml2obj/yaml2obj.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
18
2015-04-23T20:59:52.000Z
2021-11-18T20:06:39.000Z
//===- yaml2obj - Convert YAML to a binary object file --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program takes a YAML description of an object file and outputs the // binary equivalent. // // This is used for writing tests that require binary files. // //===----------------------------------------------------------------------===// #include "yaml2obj.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/system_error.h" using namespace llvm; static cl::opt<std::string> Input(cl::Positional, cl::desc("<input>"), cl::init("-")); // TODO: The "right" way to tell what kind of object file a given YAML file // corresponds to is to look at YAML "tags" (e.g. `!Foo`). Then, different // tags (`!ELF`, `!COFF`, etc.) would be used to discriminate between them. // Interpreting the tags is needed eventually for when writing test cases, // so that we can e.g. have `!Archive` contain a sequence of `!ELF`, and // just Do The Right Thing. However, interpreting these tags and acting on // them appropriately requires some work in the YAML parser and the YAMLIO // library. enum YAMLObjectFormat { YOF_COFF, YOF_ELF }; cl::opt<YAMLObjectFormat> Format( "format", cl::desc("Interpret input as this type of object file"), cl::values( clEnumValN(YOF_COFF, "coff", "COFF object file format"), clEnumValN(YOF_ELF, "elf", "ELF object file format"), clEnumValEnd)); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. OwningPtr<MemoryBuffer> Buf; if (MemoryBuffer::getFileOrSTDIN(Input, Buf)) return 1; if (Format == YOF_COFF) { return yaml2coff(outs(), Buf.get()); } else if (Format == YOF_ELF) { return yaml2elf(outs(), Buf.get()); } else { errs() << "Not yet implemented\n"; return 1; } }
33.263889
80
0.645511
[ "object" ]
6d126a68ed5abd6e5ad5fac6d401e2bd689cf7f7
2,746
cpp
C++
exercises/6.0/src/myworkcell_core/src/myworkcell_node.cpp
JonathanPlasse/industrial_training
2de2ecbc8d1f7d2b4b724cc6badd003ca2d653d7
[ "Apache-2.0" ]
324
2015-01-31T07:35:37.000Z
2022-03-27T09:30:14.000Z
exercises/6.0/src/myworkcell_core/src/myworkcell_node.cpp
AhmedMounir/industrial_training
e6761c7bee65d3802fee6cf7c99e3113d3dc1af2
[ "Apache-2.0" ]
226
2015-01-20T17:15:56.000Z
2022-01-19T04:55:23.000Z
exercises/6.0/src/myworkcell_core/src/myworkcell_node.cpp
AhmedMounir/industrial_training
e6761c7bee65d3802fee6cf7c99e3113d3dc1af2
[ "Apache-2.0" ]
219
2015-03-29T03:05:11.000Z
2022-03-23T11:12:43.000Z
#include <ros/ros.h> #include <myworkcell_core/LocalizePart.h> #include <tf/tf.h> #include <moveit/move_group_interface/move_group_interface.h> /** * @brief The ScanNPlan class is a client of the vision and path plan servers. The ScanNPLan class takes * these services, computes transforms and published commands to the robot. */ class ScanNPlan { public: ScanNPlan(ros::NodeHandle& nh) { vision_client_ = nh.serviceClient<myworkcell_core::LocalizePart>("localize_part"); } /** * @brief start performs the motion planning and execution functions of the ScanNPlan of * the node. The start method makes a service request for a transform that * localizes the part. The start method moves the "manipulator" * move group to the localization target. The start method requests * a cartesian path based on the localization target. The start method * sends the cartesian path to the actionlib client for execution, bypassig * MoveIt! * @param base_frame is a string that specifies the reference frame * coordinate system. */ void start(const std::string& base_frame) { ROS_INFO("Attempting to localize part"); // Localize the part myworkcell_core::LocalizePart srv; srv.request.base_frame = base_frame; ROS_INFO_STREAM("Requesting pose in base frame: " << base_frame); if (!vision_client_.call(srv)) { ROS_ERROR("Could not localize part"); return; } ROS_INFO_STREAM("part localized: " << srv.response); geometry_msgs::Pose move_target = srv.response.pose; moveit::planning_interface::MoveGroupInterface move_group("manipulator"); // Plan for robot to move to part move_group.setPoseReferenceFrame(base_frame); move_group.setPoseTarget(move_target); move_group.move(); } private: // Planning components ros::ServiceClient vision_client_; }; /** * @brief main is the ros interface for the ScanNPlan Class * @param argc ROS uses this to parse remapping arguments from the command line. * @param argv ROS uses this to parse remapping arguments from the command line. * @return ROS provides typical return codes, 0 or -1, depending on the * execution. */ int main(int argc, char **argv) { ros::init(argc, argv, "myworkcell_node"); ros::NodeHandle nh; ros::NodeHandle private_node_handle("~"); ros::AsyncSpinner async_spinner(1); async_spinner.start(); ROS_INFO("ScanNPlan node has been initialized"); std::string base_frame; private_node_handle.param<std::string>("base_frame", base_frame, "world"); // parameter name, string object reference, default value ScanNPlan app(nh); ros::Duration(.5).sleep(); // wait for the class to initialize app.start(base_frame); ros::waitForShutdown(); }
32.305882
134
0.726147
[ "object", "transform" ]
6d15b2c6999ef9565e98ae3fcb81ecf78e84e0dc
7,964
cpp
C++
sqsgenerator/core/src/main.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
14
2019-11-16T10:34:04.000Z
2022-03-28T09:32:42.000Z
sqsgenerator/core/src/main.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
5
2019-11-21T05:54:07.000Z
2022-03-29T07:56:34.000Z
sqsgenerator/core/src/main.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
4
2020-09-28T14:28:23.000Z
2021-03-05T14:11:44.000Z
// // Created by dominik on 21.05.21. #include "sqs.hpp" #include <iostream> #include <thread> #include <vector> #include <chrono> #include "types.hpp" #include <boost/multi_array.hpp> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup.hpp> namespace logging = boost::log; using namespace sqsgenerator; using namespace sqsgenerator::utils; using namespace boost::numeric::ublas; static bool log_initialized = false; void init_logging() { if (! log_initialized) { static const std::string COMMON_FMT("[%TimeStamp%][%Severity%]: %Message%"); boost::log::register_simple_formatter_factory<boost::log::trivial::severity_level, char>("Severity"); boost::log::add_console_log( std::clog, boost::log::keywords::format = COMMON_FMT, boost::log::keywords::auto_flush = true ); boost::log::add_common_attributes(); logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::trace); log_initialized = true; } } void print_conf(configuration_t conf, bool endl = true) { std::cout << "{"; for (size_t i = 0; i < conf.size()-1; ++i) { std::cout << static_cast<int>(conf[i]) << ", "; } std::cout << static_cast<int>(conf.back()) << "}"; if (endl) std::cout << std::endl; } int main(int argc, char *argv[]) { init_logging(); (void) argc, (void) argv; using namespace sqsgenerator; size_t nspecies{2}; array_2d_t lattice = boost::make_multi_array<double, 3, 3>({ 0.0, 8.1 ,8.1, 8.1, 0.0, 8.1, 8.1, 8.1 ,0.0 }); array_2d_t frac_coords = boost::make_multi_array<double, 64, 3>({ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 2.50000000e-01, 0.00000000e+00, 0.00000000e+00, 5.00000000e-01, 0.00000000e+00, 0.00000000e+00, 7.50000000e-01, 0.00000000e+00, 2.50000000e-01, 0.00000000e+00, 0.00000000e+00, 2.50000000e-01, 2.50000000e-01, 0.00000000e+00, 2.50000000e-01, 5.00000000e-01, 0.00000000e+00, 2.50000000e-01, 7.50000000e-01, 0.00000000e+00, 5.00000000e-01, 0.00000000e+00, 5.48258284e-17, 5.00000000e-01, 2.50000000e-01, 0.00000000e+00, 5.00000000e-01, 5.00000000e-01, 0.00000000e+00, 5.00000000e-01, 7.50000000e-01, 0.00000000e+00, 7.50000000e-01, 0.00000000e+00, 0.00000000e+00, 7.50000000e-01, 2.50000000e-01, 1.00000000e+00, 7.50000000e-01, 5.00000000e-01, 0.00000000e+00, 7.50000000e-01, 7.50000000e-01, 2.50000000e-01, 0.00000000e+00, 0.00000000e+00, 2.50000000e-01, 0.00000000e+00, 2.50000000e-01, 2.50000000e-01, 1.09651657e-16, 5.00000000e-01, 2.50000000e-01, 0.00000000e+00, 7.50000000e-01, 2.50000000e-01, 2.50000000e-01, 0.00000000e+00, 2.50000000e-01, 2.50000000e-01, 2.50000000e-01, 2.50000000e-01, 2.50000000e-01, 5.00000000e-01, 2.50000000e-01, 2.50000000e-01, 7.50000000e-01, 2.50000000e-01, 5.00000000e-01, 5.48258284e-17, 2.50000000e-01, 5.00000000e-01, 2.50000000e-01, 2.50000000e-01, 5.00000000e-01, 5.00000000e-01, 2.50000000e-01, 5.00000000e-01, 7.50000000e-01, 2.50000000e-01, 7.50000000e-01, 0.00000000e+00, 2.50000000e-01, 7.50000000e-01, 2.50000000e-01, 2.50000000e-01, 7.50000000e-01, 5.00000000e-01, 2.50000000e-01, 7.50000000e-01, 7.50000000e-01, 5.00000000e-01, 0.00000000e+00, 0.00000000e+00, 5.00000000e-01, 5.48258284e-17, 2.50000000e-01, 5.00000000e-01, 0.00000000e+00, 5.00000000e-01, 5.00000000e-01, 0.00000000e+00, 7.50000000e-01, 5.00000000e-01, 2.50000000e-01, 2.74129142e-17, 5.00000000e-01, 2.50000000e-01, 2.50000000e-01, 5.00000000e-01, 2.50000000e-01, 5.00000000e-01, 5.00000000e-01, 2.50000000e-01, 7.50000000e-01, 5.00000000e-01, 5.00000000e-01, 0.00000000e+00, 5.00000000e-01, 5.00000000e-01, 2.50000000e-01, 5.00000000e-01, 5.00000000e-01, 5.00000000e-01, 5.00000000e-01, 5.00000000e-01, 7.50000000e-01, 5.00000000e-01, 7.50000000e-01, 0.00000000e+00, 5.00000000e-01, 7.50000000e-01, 2.50000000e-01, 5.00000000e-01, 7.50000000e-01, 5.00000000e-01, 5.00000000e-01, 7.50000000e-01, 7.50000000e-01, 7.50000000e-01, 0.00000000e+00, 0.00000000e+00, 7.50000000e-01, 0.00000000e+00, 2.50000000e-01, 7.50000000e-01, 1.00000000e+00, 5.00000000e-01, 7.50000000e-01, 0.00000000e+00, 7.50000000e-01, 7.50000000e-01, 2.50000000e-01, 0.00000000e+00, 7.50000000e-01, 2.50000000e-01, 2.50000000e-01, 7.50000000e-01, 2.50000000e-01, 5.00000000e-01, 7.50000000e-01, 2.50000000e-01, 7.50000000e-01, 7.50000000e-01, 5.00000000e-01, 0.00000000e+00, 7.50000000e-01, 5.00000000e-01, 2.50000000e-01, 7.50000000e-01, 5.00000000e-01, 5.00000000e-01, 7.50000000e-01, 5.00000000e-01, 7.50000000e-01, 7.50000000e-01, 7.50000000e-01, 0.00000000e+00, 7.50000000e-01, 7.50000000e-01, 2.50000000e-01, 7.50000000e-01, 7.50000000e-01, 5.00000000e-01, 7.50000000e-01, 7.50000000e-01, 7.50000000e-01 }); std::vector<std::string> species { "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Al", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni", "Ni" }; /*std::vector<std::string> species { "Cs", "Cl", "Cs", "Cl", "Cs", "Cl", "Cs", "Cl", "Ne", "Ne", "Ne", "Ne", "Ne", "Ne", "Ne", "Ne" };*/ std::array<bool, 3> pbc {true, true, true}; Structure structure(lattice, frac_coords, species, pbc); pair_shell_weights_t shell_weights { {4, 0.25}, {5, 0.2}, {1, 1.0}, {3, 0.33}, {2, 0.5}, {6, 1.0/6.0}, {7, 1.0/7.0} }; array_2d_t pair_weights = boost::make_multi_array<double, 2, 2>({ 1.0, 2.0, 5.0, 2.0 }); /* array_2d_t pair_weights = boost::make_multi_array<double, 4, 4>({ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 });*/ auto conf (structure.configuration()); array_3d_t target_objective(boost::extents[shell_weights.size()][nspecies][nspecies]); // std::fill(target_objective.begin(), target_objective.end(), 0.0); auto niteration {500000}; // omp_set_num_threads(1); IterationSettings settings(structure, target_objective, pair_weights, shell_weights, niteration, 10, {2, 2, 2}); // settings.shell_matrix(); auto initial_rank = rank_permutation(settings.packed_configuraton(), settings.num_species()); std::chrono::high_resolution_clock::time_point begin = std::chrono::high_resolution_clock::now(); // int mpi_threading_support_level; // MPI_Init_thread(nullptr, nullptr, MPI_THREAD_SERIALIZED, &mpi_threading_support_level); do_pair_iterations(settings); // MPI_Finalize(); std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now(); std::cout << "Time difference = " << static_cast<double>(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count())/niteration << " [µs]" << std::endl; auto f = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(); std::cout << f << std::endl; }
44.99435
424
0.594676
[ "vector" ]
6d165650b06b87fcedba8ec68b034196f27146c4
7,037
cpp
C++
01_Develop/libXMFFmpeg/Source/libavcodec/acelp_vectors.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
01_Develop/libXMFFmpeg/Source/libavcodec/acelp_vectors.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
01_Develop/libXMFFmpeg/Source/libavcodec/acelp_vectors.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* * adaptive and fixed codebook vector operations for ACELP-based codecs * * Copyright (c) 2008 Vladimir Voroshilov * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "internal.h" #include "acelp_vectors.h" #include "celp_math.h" const uint8_t ff_fc_2pulses_9bits_track1[16] = { 1, 3, 6, 8, 11, 13, 16, 18, 21, 23, 26, 28, 31, 33, 36, 38 }; const uint8_t ff_fc_2pulses_9bits_track1_gray[16] = { 1, 3, 8, 6, 18, 16, 11, 13, 38, 36, 31, 33, 21, 23, 28, 26, }; const uint8_t ff_fc_2pulses_9bits_track2_gray[32] = { 0, 2, 5, 4, 12, 10, 7, 9, 25, 24, 20, 22, 14, 15, 19, 17, 36, 31, 21, 26, 1, 6, 16, 11, 27, 29, 32, 30, 39, 37, 34, 35, }; const uint8_t ff_fc_4pulses_8bits_tracks_13[16] = { 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, }; const uint8_t ff_fc_4pulses_8bits_track_4[32] = { 3, 4, 8, 9, 13, 14, 18, 19, 23, 24, 28, 29, 33, 34, 38, 39, 43, 44, 48, 49, 53, 54, 58, 59, 63, 64, 68, 69, 73, 74, 78, 79, }; const float ff_pow_0_7[10] = { 0.700000f, 0.490000f, 0.343000f, 0.240100f, 0.168070f, 0.117649f, 0.082354f, 0.057648f, 0.040354f, 0.028248f }; const float ff_pow_0_75[10] = { 0.750000f, 0.562500f, 0.421875f, 0.316406f, 0.237305f, 0.177979f, 0.133484f, 0.100113f, 0.075085f, 0.056314f }; const float ff_pow_0_55[10] = { 0.550000f, 0.302500f, 0.166375f, 0.091506f, 0.050328f, 0.027681f, 0.015224f, 0.008373f, 0.004605f, 0.002533f }; const float ff_b60_sinc[61] = { 0.898529f , 0.865051f , 0.769257f , 0.624054f , 0.448639f , 0.265289f , 0.0959167f , -0.0412598f , -0.134338f , -0.178986f , -0.178528f , -0.142609f , -0.0849304f , -0.0205078f , 0.0369568f , 0.0773926f , 0.0955200f , 0.0912781f , 0.0689392f , 0.0357056f , 0.0f , -0.0305481f , -0.0504150f , -0.0570068f , -0.0508423f , -0.0350037f , -0.0141602f , 0.00665283f, 0.0230713f , 0.0323486f , 0.0335388f , 0.0275879f , 0.0167847f , 0.00411987f, -0.00747681f, -0.0156860f , -0.0193481f , -0.0183716f , -0.0137634f , -0.00704956f, 0.0f , 0.00582886f , 0.00939941f, 0.0103760f , 0.00903320f, 0.00604248f, 0.00238037f, -0.00109863f , -0.00366211f, -0.00497437f, -0.00503540f, -0.00402832f, -0.00241089f, -0.000579834f, 0.00103760f, 0.00222778f, 0.00277710f, 0.00271606f, 0.00213623f, 0.00115967f , 0. }; void ff_acelp_fc_pulse_per_track( int16_t* fc_v, const uint8_t *tab1, const uint8_t *tab2, int pulse_indexes, int pulse_signs, int pulse_count, int bits) { int mask = (1 << bits) - 1; int i; for(i=0; i<pulse_count; i++) { fc_v[i + tab1[pulse_indexes & mask]] += (pulse_signs & 1) ? 8191 : -8192; // +/-1 in (2.13) pulse_indexes >>= bits; pulse_signs >>= 1; } fc_v[tab2[pulse_indexes]] += (pulse_signs & 1) ? 8191 : -8192; } void ff_decode_10_pulses_35bits(const int16_t *fixed_index, AMRFixed *fixed_sparse, const uint8_t *gray_decode, int half_pulse_count, int bits) { int i; int mask = (1 << bits) - 1; fixed_sparse->no_repeat_mask = 0; fixed_sparse->n = 2 * half_pulse_count; for (i = 0; i < half_pulse_count; i++) { const int pos1 = gray_decode[fixed_index[2*i+1] & mask] + i; const int pos2 = gray_decode[fixed_index[2*i ] & mask] + i; const float sign = (fixed_index[2*i+1] & (1 << bits)) ? -1.0 : 1.0; fixed_sparse->x[2*i+1] = pos1; fixed_sparse->x[2*i ] = pos2; fixed_sparse->y[2*i+1] = sign; fixed_sparse->y[2*i ] = pos2 < pos1 ? -sign : sign; } } void ff_acelp_weighted_vector_sum( int16_t* out, const int16_t *in_a, const int16_t *in_b, int16_t weight_coeff_a, int16_t weight_coeff_b, int16_t rounder, int shift, int length) { int i; // Clipping required here; breaks OVERFLOW test. for(i=0; i<length; i++) out[i] = av_clip_int16(( in_a[i] * weight_coeff_a + in_b[i] * weight_coeff_b + rounder) >> shift); } void ff_weighted_vector_sumf(float *out, const float *in_a, const float *in_b, float weight_coeff_a, float weight_coeff_b, int length) { int i; for(i=0; i<length; i++) out[i] = weight_coeff_a * in_a[i] + weight_coeff_b * in_b[i]; } void ff_adaptive_gain_control(float *out, const float *in, float speech_energ, int size, float alpha, float *gain_mem) { int i; float postfilter_energ = ff_dot_productf(in, in, size); float gain_scale_factor = 1.0; float mem = *gain_mem; if (postfilter_energ) gain_scale_factor = sqrt(speech_energ / postfilter_energ); gain_scale_factor *= 1.0 - alpha; for (i = 0; i < size; i++) { mem = alpha * mem + gain_scale_factor; out[i] = in[i] * mem; } *gain_mem = mem; } void ff_scale_vector_to_given_sum_of_squares(float *out, const float *in, float sum_of_squares, const int n) { int i; float scalefactor = ff_dot_productf(in, in, n); if (scalefactor) scalefactor = sqrt(sum_of_squares / scalefactor); for (i = 0; i < n; i++) out[i] = in[i] * scalefactor; } void ff_set_fixed_vector(float *out, const AMRFixed *in, float scale, int size) { int i; for (i=0; i < in->n; i++) { int x = in->x[i], repeats = !((in->no_repeat_mask >> i) & 1); float y = in->y[i] * scale; if (in->pitch_lag > 0) do { out[x] += y; y *= in->pitch_fac; x += in->pitch_lag; } while (x < size && repeats); } } void ff_clear_fixed_vector(float *out, const AMRFixed *in, int size) { int i; for (i=0; i < in->n; i++) { int x = in->x[i], repeats = !((in->no_repeat_mask >> i) & 1); if (in->pitch_lag > 0) do { out[x] = 0.0; x += in->pitch_lag; } while (x < size && repeats); } }
26.858779
84
0.57354
[ "vector" ]
6d243f0f3e279423ef1a07869c313f64c6d8f91f
70,007
cc
C++
src/runtime.cc
lanhin/TripletRun
06f73a6911fae2f9874bed8f9d68bf0d3fd5e973
[ "MIT" ]
15
2019-03-22T16:07:53.000Z
2021-07-31T03:22:34.000Z
src/runtime.cc
lanhin/TripletRun
06f73a6911fae2f9874bed8f9d68bf0d3fd5e973
[ "MIT" ]
null
null
null
src/runtime.cc
lanhin/TripletRun
06f73a6911fae2f9874bed8f9d68bf0d3fd5e973
[ "MIT" ]
2
2018-05-23T08:30:39.000Z
2020-08-28T11:13:40.000Z
// ================== // @2017-09 by lanhin // ACSA, USTC // lanhin1@gmail.com // ================== #include "runtime.h" #include "constants.h" #include "json/json.h" #include "utils.h" #include <cassert> #include <iostream> #include <fstream> #include <sstream> #include <unistd.h> #include <cmath> namespace triplet{ //Class Runtime Runtime::Runtime(){ ETD = false; global_timer = 0.0; scheduler_ava_time = 0.0; scheduler_mean_cost = 0.0; deviceNum = 0; deviceInUse = 0; mem_full_dev = 0; OCT = NULL; max_devId = -1; task_total = 0; task_hit_counter = 0; dev_hit_counter = 0; dc_valid_counter = 0; mean_computing_power = 0; DCRatio = 0; max_parallel = 0; load_balance_threshold = 0; load_time = -1; with_conflicts = false; mem_full_threshold = 0.9; dev_full_threshold = 0.2; max_devCompute = 0.0; max_cpath_cc = 0.0; absCP = 0.0; min_execution_time = 0.0; min_transmission_time = 0.0; alpha_DON = 0.5; min_free_mem = -1; graph_init_time = 0.0; cluster_init_time = 0.0; oct_time = 0.0; rankoct_time = 0; rank_u_time = 0; rank_d_time = 0; ndon_time = 0; task_pick_time = 0; device_pick_time = 0; graph_file_name = ""; cluster_file_name = ""; //blockIdCounter = 0; } Runtime::~Runtime(){ global_timer = 0.0; deviceNum = 0; deviceInUse = 0; Cluster::iterator it = TaihuLight.begin(); for(; it != TaihuLight.end(); it++){ delete it->second; } TaihuLight.clear(); TaihuLightNetwork.Clear(); global_graph.Clear(); ready_queue.clear(); execution_queue.clear(); pending_list.clear(); } /** Init the global graph from configure JSON file. */ void Runtime::InitGraph(const char * graphFile){ Json::CharReaderBuilder reader; std::string errs; Json::Value root; log_start("Graph initialization..."); graph_file_name = graphFile; DECLARE_TIMING(graph); START_TIMING(graph); // check if the json file exists if (access(graphFile, F_OK) != 0){ std::cout<<"The json file "<<graphFile<<" doesn't exist!"<<std::endl; return; } std::ifstream jsondoc(graphFile, std::ifstream::binary); bool parsingStatusOK = Json::parseFromStream(reader, jsondoc, &root, &errs); if (!parsingStatusOK){ // report to the user the failure and their locations in the document. std::cout << "Failed to parse configuration\n" << errs; return; } for (int index = 0; index < root["nodes"].size(); index++){ std::string id = root["nodes"][index].get("id", "-1").asString(); std::string computeDemand = root["nodes"][index].get("comDmd", "-1.0").asString(); std::string dataDemand = root["nodes"][index].get("dataDmd", "1.0").asString(); std::string dataConsume = root["nodes"][index].get("c", "-1.0").asString(); std::string dataGenerate = root["nodes"][index].get("g", "-1.0").asString(); int id1 = std::stoi(id); float comDmd1 = std::stof(computeDemand, 0); float dataDmd1 = std::stof(dataDemand, 0); float dataConsume1 = std::stof(dataConsume, 0); float dataGenerate1 = std::stof(dataGenerate, 0); if (comDmd1 < 1){ comDmd1 = 0.1; } global_graph.AddNode(id1, comDmd1, dataDmd1, dataConsume1, dataGenerate1); idset.insert(id1); #if 0 std::cout<<"Node "<<id1<<", com demand: "<<comDmd1<<", data demand: "<<dataDmd1<<", data consume: "<<dataConsume1<<", data generate: "<<dataGenerate1<<std::endl; #endif } int i = 0; // Index for available edge weight for (int index = 0; index < root["edges"].size(); index++){ std::string src = root["edges"][index].get("src", "-1").asString(); std::string dst = root["edges"][index].get("dst", "-1").asString(); std::string comCost = root["edges"][index].get("weight", "-1").asString(); int src1 = std::stoi(src); int dst1 = std::stoi(dst); float comCost1 = std::stof(comCost); global_graph.AddEdge(src1, dst1, comCost1); #if 0 std::cout<<"Edge "<<src1<<" -> "<<dst1<<", cost: "<<global_graph.GetComCost(src1, dst1)<<std::endl; #endif } /** Add source and sink vertex if need. */ /** 1. Find the entry and exit vertex, if multiple, creat new "source" and "sink" vertice. */ int maxVertexId = 0; int sourceId, sinkId; std::set<int> entryVertexSet; std::set<int> exitVertexSet; for (std::set<int>::iterator iter = idset.begin(); iter != idset.end(); iter++){ if (maxVertexId < *iter){ maxVertexId = *iter; } int inputDegree = global_graph.GetNode(*iter)->GetInNum(); if (inputDegree == 0){ //an entry node entryVertexSet.insert(*iter); sourceId = *iter; } int outputDegree = global_graph.GetNode(*iter)->GetOutNum(); if (outputDegree == 0){ //an exit node exitVertexSet.insert(*iter); sinkId = *iter; } } if(entryVertexSet.size() > 1){ // Multiple entry vertices // create a new "source" vertex sourceId = ++maxVertexId; global_graph.AddNode(sourceId, 0.1, 0.1); idset.insert(sourceId); for (auto& it : entryVertexSet){ global_graph.AddEdge(sourceId, it, 0); } } if(exitVertexSet.size() > 1){ // Multiple exit vertices // create a new "sink" vertex sinkId = ++maxVertexId; global_graph.AddNode(sinkId, 0.1, 0.1); idset.insert(sinkId); for (auto& it : exitVertexSet){ global_graph.AddEdge(it, sinkId, 0); } } global_graph.SetSourceId(sourceId); global_graph.SetSinkId(sinkId); // Summary report of the graph global_graph.SummaryReport(); #if 0 // Check the constructed graph for (int index = 0; index < root["nodes"].size(); index++){ std::string id = root["nodes"][index].get("id", "-1").asString(); int id1 = std::stoi(id); triplet::Node* nd = global_graph.GetNode(id1); std::cout<<std::endl<<" Node id: "<<id1<<std::endl; std::cout<<" Node computing demand: "<<nd->GetCompDmd()<<std::endl; std::cout<<" Node data demand: "<<nd->GetDataDmd()<<std::endl; std::cout<<" Node occupied: "<<nd->GetOccupied()<<std::endl; std::cout<<" Node input: "<<nd->GetInNum()<<std::endl; std::cout<<" Node output: "<<nd->GetOutNum()<<std::endl; std::cout<<"==========================="<<std::endl; } #endif STOP_TIMING(graph); this->graph_init_time = GET_TIMING(graph); log_end("Graph initialization."); } /** Init the cluster "TaihuLight" from configure file. */ void Runtime::InitCluster(const char * clusterFile){ Json::CharReaderBuilder reader; std::string errs; Json::Value root; cluster_file_name = clusterFile; DECLARE_TIMING(cluster); START_TIMING(cluster); log_start("Cluster initialization..."); // check if the json file exists if (access(clusterFile, F_OK) != 0){ std::cout<<"The json file "<<clusterFile<<" doesn't exist!"<<std::endl; return; } std::ifstream jsondoc(clusterFile, std::ifstream::binary); bool parsingStatusOK = Json::parseFromStream(reader, jsondoc, &root, &errs); if (!parsingStatusOK){ // report to the user the failure and their locations in the document. std::cout << "Failed to parse configuration\n" << errs; return; } for (int index = 0; index < root["devices"].size(); index++){ std::string id = root["devices"][index].get("id", "-1").asString(); std::string compute = root["devices"][index].get("compute", "-1").asString(); std::string RAM = root["devices"][index].get("RAM", "-1").asString(); std::string bw = root["devices"][index].get("bw", "-1").asString(); std::string loc = root["devices"][index].get("loc", "-1").asString(); int id1 = std::stoi(id); float compute1 = std::stof(compute, 0); float RAM1 = std::stof(RAM); float bw1 = std::stof(bw, 0); int loc1 = std::stoi(loc); #if 0 std::cout<<id1<<' '<<compute1<<' '<<RAM1<<' '<<bw1<<' '<<loc1<<std::endl; #endif Device *dev = new Device(id1, compute1, RAM1, bw1, loc1); TaihuLight[id1] = dev; deviceNum ++; max_devId = std::max(max_devId, id1); mean_computing_power += (compute1 - mean_computing_power) / (deviceNum); computerset.insert(loc1); //Record the max compute power if(this->max_devCompute < compute1){ this->max_devCompute = compute1; this->max_computeDevId = id1; } } for (int index = 0; index < root["links"].size(); index++){ std::string src = root["links"][index].get("src", "-1").asString(); std::string dst = root["links"][index].get("dst", "-1").asString(); std::string bw = root["links"][index].get("bw", "-1").asString(); std::string btNodes = root["links"][index].get("BetweenNode", "flase").asString(); int src1 = std::stoi(src); int dst1 = std::stoi(dst); float bw1 = std::stof(bw, 0); bool btNodes1; std::istringstream(btNodes) >> std::boolalpha >> btNodes1; #if 0 std::cout<<src1<<' '<<dst1<<' '<<bw1<<' '<<btNodes1<<std::endl; #endif TaihuLightNetwork.NewLink(src1, dst1, bw1, btNodes1); } //TODO: Check the constructed cluster std::cout<<"-------- Cluster information --------"<<std::endl; std::cout<<" Total devices: "<<this->deviceNum<<std::endl; std::cout<<" Max device id: "<<this->max_devId<<std::endl; std::cout<<" Max device compute power: "<<this->max_devCompute<<std::endl; std::cout<<" Total computer nodes: "<<this->computerset.size()<<std::endl; std::cout<<" Links among computer nodes: "<<this->TaihuLightNetwork.GetNodeConNum()<<std::endl; std::cout<<" Links among devices: "<<this->TaihuLightNetwork.GetDevConNum()<<std::endl; std::cout<<"-------------------------------------"<<std::endl; STOP_TIMING(cluster); this->cluster_init_time = GET_TIMING(cluster); log_end("Cluster initialization."); } /** Init the runtime data structures: pending_list and ready_queue and calculate the OCT, RankOCT of the graph. */ void Runtime::InitRuntime(SchedulePolicy sch, float dc, bool wc){ log_start("Runtime initialization..."); // Init min_execution_time and min_transmission_time this->min_execution_time = 0.01; this->min_transmission_time = 0.01; std::cout<<" Scheduler: "<<sch<<std::endl; std::cout<<" DC ratio: "<<dc<<std::endl; Scheduler = sch; RRCounter = -1; // Always set it -1 at the beginning of execution? DCRatio = dc; this->with_conflicts = wc; if (Scheduler == PEFT){ DECLARE_TIMING(oct); log_start("OCT calculation..."); START_TIMING(oct); CalcOCT(); //OCT for PEFT STOP_TIMING(oct); this->oct_time = GET_TIMING(oct); std::cout<<" Execution time of CalcOCT():"<<GET_TIMING(oct)<<" s"<<std::endl; log_end("OCT calculation."); DECLARE_TIMING(rankoct); log_start("Rank OCT calculation..."); START_TIMING(rankoct); CalcRankOCT(); //RankOCT for PEFT STOP_TIMING(rankoct); this->rankoct_time = GET_TIMING(rankoct); std::cout<<" Execution time of CalcRankOCT():"<<GET_TIMING(rankoct)<<" s"<<std::endl; log_end("Rank OCT calculation."); } if (Scheduler == HSIP || Scheduler == HEFT || Scheduler == CPOP){ log_start("OCCW initialization..."); global_graph.InitAllOCCW(); //OCCW for HSIP log_end("OCCW initialization."); DECLARE_TIMING(ranku); log_start("Rank_u calculation..."); START_TIMING(ranku); CalcRank_u(); // Rank_u for HSIP and HEFT STOP_TIMING(ranku); this->rank_u_time = GET_TIMING(ranku); std::cout<<" Execution time of CalcRank_u():"<<GET_TIMING(ranku)<<" s"<<std::endl; log_end("Rank_u calculation."); DECLARE_TIMING(rankd); log_start("Rank_d calculation..."); START_TIMING(rankd); CalcRank_d(); // Rank_d for CPOP STOP_TIMING(rankd); this->rank_d_time = GET_TIMING(rankd); std::cout<<" Execution time of CalcRank_d():"<<GET_TIMING(rankd)<<" s"<<std::endl; log_end("Rank_d calculation."); // Calculate priority used in CPOP policy. this->absCP = global_graph.CalcPriorityCPOP(); } if (Scheduler == DONF || Scheduler == DONF2 || Scheduler == ADON || Scheduler == DONFM || Scheduler == DONFL || Scheduler == DONFL2 || Scheduler == ADONL){ DECLARE_TIMING(NDON); log_start("NDON calculation..."); START_TIMING(NDON); CalcNDON(); if(Scheduler == ADON || Scheduler == ADONL){ CalcADON(); } STOP_TIMING(NDON); this->ndon_time = GET_TIMING(NDON); std::cout<<" Execution time of CalcNDON():"<<GET_TIMING(NDON)<<" s"<<std::endl; log_end("NDON calculation."); } // Init ready_queue for (std::set<int>::iterator iter = idset.begin(); iter != idset.end(); iter++){ int pend = global_graph.GetNode(*iter)->GetInNum(); assert(pend >= 0); #if 0 std::cout<<"Node id "<<*iter<<", pending number:"<<pend<<std::endl; #endif pending_list[*iter] = pend; if (pend == 0){ //add it into ready_queue ready_queue.push_back(*iter); global_graph.GetNode(*iter)->SetStatus(READY); // Set node's status // Calculate Cpath computatin cost global_graph.CalcCpathCC(*iter, this->max_devCompute, this->min_execution_time); //Record the current time global_graph.GetNode(*iter)->SetWaitTime(this->global_timer); } } log_end("Runtime initialization."); } /** Calculate the OCT (Optimistic Cost Table) used in PEFT. This function cannot be moved into class Graph since it involves not only the graph topology but also the cluster configures. */ void Runtime::CalcOCT(){ /** Only for testing. May need to move this into the runtime class definition since some other member functions also need it. */ int CTM[][3] = {22, 21, 36, 22, 18, 18, 32, 27, 43, 7, 10, 4, 29, 27, 35, 26, 17, 24, 14, 25, 30, 29, 23, 36, 15, 21, 8, 13, 16, 33}; /** 1. Find the "sink" vertex. */ int sinkId = global_graph.GetSinkId(); /** 2. Traversing the DAG from the exit to the entry vertex and calculate the OCT. Deal the cross-level edges carefully. */ // 2.1 Create OCT: first tasks then processors /** TODO: Use the max task and device ids instead of the number of them. Or we need to preprocess the graph and device conf files to make them equal. */ int tasks = global_graph.MaxNodeId() + 1;//global_graph.Nodes(); int devs = this->max_devId + 1;//this->deviceNum; assert(tasks >= 1); assert(devs >= 1); OCT = new float*[tasks]; for(int i = 0; i < tasks; i++ ){ OCT[i] = new float[devs]; } // Init value: -1. for (int i = 0; i < tasks; i++) { for (int j = 0; j < devs; j++) { OCT[i][j] = -1; } } std::set<int> recent; // Store the vertex ids that calculated recently // 2.2 Calculate the sink vertex row for (int i = 0; i < devs; i++) { OCT[sinkId][i] = 0; } recent.insert(sinkId); // 2.3 Calculate the other rows while(!recent.empty()){ auto it = *(recent.begin());// The first value stored recent.erase(recent.begin()); //for (auto& it : recent){ Node* nd = global_graph.GetNode(it); for (auto& crtVertId : nd->input){ /** Calculate the whole row for crtVertId */ // 2.3.0 If it has already been calculated, continue! if (OCT[crtVertId][0] >= 0){ continue; } // 2.3.1 If not all of crtVertId's output has been calculated, continue! Node* crtNd = global_graph.GetNode(crtVertId); bool allSatisfied = true; for(auto& succ : crtNd->output){ if(OCT[succ][0] < 0){ allSatisfied = false; } } if (!allSatisfied){ continue; } // 2.3.2 Calculate the whole row in OCT float current, min, max; for (int devId = 0; devId < devs; devId++) { max = 0; for(auto& vertId : crtNd->output){ Node* vertex = global_graph.GetNode(vertId); min = -1; for(auto& dev : TaihuLight){ if(OCT[vertex->GetId()][dev.first] < 0){ // The OCT item has not been calculated continue; }else{ float meanct = CommunicationDataSize(crtVertId, vertId) / TaihuLightNetwork.GetMeanBW(); // The max op is for avoiding calculation time ignorance current = OCT[vertex->GetId()][dev.first] + std::max(((float)vertex->GetCompDmd()) / (dev.second)->GetCompPower(), (float)1.0) + ((dev.first == devId)?0:meanct); //current = OCT[vertex->GetId()][dev.first] + (CTM[vertId][dev.first]) + ((dev.first == devId)?0:global_graph.GetComCost(crtVertId, vertId)); if (min > current || min < 0) min = current; } } if (max < min){ max = min; } } OCT[crtVertId][devId] = max; } // 2.3.3 Add crtVertId into recent after calculation recent.insert(crtVertId); } } /** 3. Check the OCT if the macro DEBUG is defined. */ #if 0 std::cout<<"The OCT result:"<<std::endl; for (int i = 0; i < tasks; i++) { for (int j = 0; j < devs; j++) { std::cout<<OCT[i][j]<<" "; } std::cout<<std::endl; } #endif } /** Calculate the rank_oct used in PEFT based on OCT. */ // TODO: avoid overflow for big value void Runtime::CalcRankOCT(){ for (int ndId : idset){ Node* nd = global_graph.GetNode(ndId); float rowOCT = 0; for (int i = 0; i < this->deviceNum; i++) { //rowOCT += OCT[ndId][i]; rowOCT += (float(OCT[ndId][i]) - rowOCT) / (i+1); } nd->SetRankOCT( ((float)rowOCT)/this->deviceNum ); #if 0 std::cout<<"Vertex "<<ndId<<", rank oct: "<<nd->GetRankOCT()<<std::endl; #endif } } /** Calculate the computation cost mean value and standard deviation value of node ndId on different devices. For convinience, return weight_mean * sd directly. */ float Runtime::CalcWeightMeanSD(int ndId){ double SD = 0; // 1. Calculate the average weight and record it in node. float tmp_mean_weight; Node* nd = global_graph.GetNode(ndId); if ( (tmp_mean_weight = nd->GetMeanWeight()) < 0 ) { //The mean weight has not been calculated tmp_mean_weight = 0; int i = 0; for (auto& it : TaihuLight){ i++; tmp_mean_weight += (nd->GetCompDmd() / (it.second)->GetCompPower() - tmp_mean_weight) / i; } nd->SetMeanWeight(tmp_mean_weight); } // 2. Calculate the standard deviation value and return it. for (auto& it : TaihuLight) { SD += std::pow((double)(nd->GetCompDmd() / (it.second)->GetCompPower() - tmp_mean_weight), 2); } SD = std::sqrt(SD); // 3. Return result return (float)SD * tmp_mean_weight; } /** Calculate rank_u, which is used in HSIP policy. */ void Runtime::CalcRank_u(){ /** 1. Find the "sink" vertex. */ int sinkId = global_graph.GetSinkId(); /** 2. Traversing the DAG from the exit to the entry vertex and calculate the rank_u. Deal the cross-level edges carefully. */ std::set<int> recent; // Store the vertex ids that calculated recently float rank_HSIP, rank_HEFT; // 2.1 Calculate sink node's rank_u Node* nd = global_graph.GetNode(sinkId); rank_HSIP = CalcWeightMeanSD(sinkId); nd->SetRank_u_HSIP(rank_HSIP); nd->SetRank_u_HEFT(nd->GetMeanWeight()); recent.insert(sinkId); // 2.2 Calculate all the others while ( !recent.empty() ){ auto it = *(recent.begin());// The first value stored recent.erase(recent.begin()); Node* nd = global_graph.GetNode(it); for (auto& crtVertId : nd->input){ Node* crtNd = global_graph.GetNode(crtVertId); // 2.2.0 If it has already been calculated, continue if (crtNd->GetRank_u_HSIP() >= 0){ continue; } // 2.2.1 If not all of the output nodes' rank_u have been calculated, continue! bool allSatisfied = true; for(auto& succ : crtNd->output){ Node* succNd = global_graph.GetNode(succ); if (succNd->GetRank_u_HSIP() < 0){ allSatisfied = false; } } if (!allSatisfied){ continue; } // 2.2.2 Calculate rank_u for current vertex float max_ranku_HSIP = 0; float max_ranku_HEFT = 0; float tmp_ranku; for(auto& succ : crtNd->output){ Node* succNd = global_graph.GetNode(succ); if (max_ranku_HSIP < (succNd->GetRank_u_HSIP()) ){ max_ranku_HSIP = succNd->GetRank_u_HSIP(); } tmp_ranku = CommunicationDataSize(crtVertId, succ) / TaihuLightNetwork.GetMeanBW() + succNd->GetRank_u_HEFT(); if (max_ranku_HEFT < tmp_ranku){ max_ranku_HEFT = tmp_ranku; } } rank_HSIP = CalcWeightMeanSD(crtVertId) + crtNd->GetOCCW() + max_ranku_HSIP; rank_HEFT = crtNd->GetMeanWeight() + max_ranku_HEFT; crtNd->SetRank_u_HSIP(rank_HSIP); crtNd->SetRank_u_HEFT(rank_HEFT); // 2.2.3 Add crtVertId into recent after calculation recent.insert(crtVertId); } } } /** Calculate rank_d, which is used in CPOP policy. */ void Runtime::CalcRank_d(){ /** 1. Find the "source" vertex. */ int sourceId = global_graph.GetSourceId(); /** 2. Traversing the DAG from the source to the exit vertex and calculate the rank_d. */ std::set<int> recent; // Store the vertex ids that calculated recently // 2.1 Calculate source node's rank_d Node* nd = global_graph.GetNode(sourceId); nd->SetRank_d_CPOP(0); recent.insert(sourceId); // 2.2 Calculate all the others while ( !recent.empty() ){ auto it = *(recent.begin());// The first value stored recent.erase(recent.begin()); Node* nd = global_graph.GetNode(it); for (auto& crtVertId : nd->output){ Node* crtNd = global_graph.GetNode(crtVertId); // 2.2.0 If it has already been calculated, continue if (crtNd->GetRank_d_CPOP() >= 0){ continue; } // 2.2.1 If not all of the input nodes' rank_d have been calculated, continue! bool allSatisfied = true; for(auto& pred : crtNd->input){ Node* predNd = global_graph.GetNode(pred); if (predNd->GetRank_d_CPOP() < 0){ allSatisfied = false; } } if (!allSatisfied){ continue; } // 2.2.2 Calculate rank_d for current vertex float max_rankd_CPOP = 0; float tmp_rankd; for(auto& pred : crtNd->input){ Node* predNd = global_graph.GetNode(pred); tmp_rankd = CommunicationDataSize(pred, crtVertId) / TaihuLightNetwork.GetMeanBW() + predNd->GetMeanWeight() + predNd->GetRank_d_CPOP(); max_rankd_CPOP = std::max(max_rankd_CPOP, tmp_rankd); } crtNd->SetRank_d_CPOP(max_rankd_CPOP); // 2.2.3 Add crtVertId into recent after calculation recent.insert(crtVertId); } } } /** Calculate normalized degree of node. */ float Runtime::NDON(Node * nd, int degree){ // Only support degree = 1 or 2 at present. assert(degree >= 1 && degree <= 2); float normdegree = nd->GetNDON(); if(degree == 2){ for (auto it : nd->output) { normdegree += this->alpha_DON * global_graph.GetNode(it)->GetNDON(); } } #ifdef DEBUG std::cout<<"Norm degree of node "<<nd->GetId()<<": "<<normdegree<<std::endl; #endif return normdegree; } /** Calculate NDON for all nodes in initruntime(). */ void Runtime::CalcNDON(){ for (auto it : idset) { float normdegree = 0; Node* crtNd = global_graph.GetNode(it); for (auto succit : crtNd->output) { normdegree += 1.0 / global_graph.GetNode(succit)->GetInNum(); } crtNd->SetNDON(normdegree); } } /** Calculate ADON for all nodes in initruntime(). */ void Runtime::CalcADON(){ /** 1. Find the "sink" vertex. */ int sinkId = global_graph.GetSinkId(); /** 2. Traversing the DAG from the exit to the entry vertex and calculate the rank_ADON. */ std::set<int> recent; // Store the vertex ids that calculated recently // 2.1 Calculate sink node's rank_ADON Node* nd = global_graph.GetNode(sinkId); nd->SetRank_ADON(0); recent.insert(sinkId); // 2.2 Calculate all the others while ( !recent.empty() ){ auto it = *(recent.begin());// The first value stored recent.erase(recent.begin()); Node* nd = global_graph.GetNode(it); for (auto& crtVertId : nd->input){ Node* crtNd = global_graph.GetNode(crtVertId); // 2.2.0 If it has already been calculated, continue if (crtNd->GetRank_ADON() >= 0){ continue; } // 2.2.1 If not all of the output nodes' rank_ADON have been calculated, continue! bool allSatisfied = true; for(auto& succ : crtNd->output){ Node* succNd = global_graph.GetNode(succ); if (succNd->GetRank_ADON() < 0){ allSatisfied = false; } } if (!allSatisfied){ continue; } // 2.2.2 Calculate rank_ADON for current vertex float tmp_rank_ADON = crtNd->GetNDON(); for(auto& succ : crtNd->output){ Node* succNd = global_graph.GetNode(succ); tmp_rank_ADON += this->alpha_DON * succNd->GetRank_ADON(); } crtNd->SetRank_ADON(tmp_rank_ADON); // 2.2.3 Add crtVertId into recent after calculation recent.insert(crtVertId); } } } /** Output NodeStatus as enum items. */ std::ostream& operator<<(std::ostream& out, const NodeStatus values){ static std::map<NodeStatus, std::string> Nodestrings; if (Nodestrings.size() == 0){ #define INSERT_ELEMENT(p) Nodestrings[p] = #p INSERT_ELEMENT(INIT); INSERT_ELEMENT(READY); INSERT_ELEMENT(RUNNING); INSERT_ELEMENT(FINISHED); #undef INSERT_ELEMENT } return out << Nodestrings[values]; } /** The whole execution logic. */ // TODO: Count the schduling time itself void Runtime::Execute(){ log_start("Execution..."); DECLARE_TIMING(taskpick); DECLARE_TIMING(devicepick); // Execute until all three queues/lists are empty while (!ready_queue.empty() || !execution_queue.empty() || !block_free_queue.empty()) { /** 0. if a memory block's refer number can be decreased decrease it and check if we need to free the block. */ for (int i=block_free_queue.size()-1; i>=0; i--){ auto& it = block_free_queue[i]; if (it.second <= (global_timer + ZERO_POSITIVE)){ MemoryBlock * blk_pointer = BlocksMap[it.first]; if ( (blk_pointer->DecRefers()) <= 0 ){ // do the free blk_pointer->DoFree(TaihuLight); //Check if need to set mem_full_dev Device* dv = TaihuLight[blk_pointer->DeviceLocation()]; if((dv->GetFreeRAM() / dv->GetRAM() > this->mem_full_threshold) && dv->IsFull()){ dv->SetFull(false); this->mem_full_dev--; } //Remove the block entry from the BlockMap and block_free_queue delete BlocksMap[it.first]; BlocksMap.erase(it.first); } // Erase the block free tag from block_free_queue // once the time reached block_free_queue.erase(block_free_queue.begin()+i); } } /** 1. If a task finished execution, update pending_list, cluster and ready_queue */ std::map<int, float>::iterator it = execution_queue.begin(); for (; it != execution_queue.end();){ if (it->second <= (global_timer + ZERO_POSITIVE)){ // Set free the corresponding device Node* nd = global_graph.GetNode(it->first); // Record cpath computation cost summary this->max_cpath_cc = std::max(this->max_cpath_cc, nd->GetCpathCC()); int devId = nd->GetOccupied(); // Set the finished_tasks properly TaihuLight[devId]->IncreaseTasks(1); // Decrease load of the corresponding device TaihuLight[devId]->DecreaseLoad(1); if(TaihuLight[devId]->GetAvaTime() <= global_timer && TaihuLight[devId]->IsBusy()){ // Only set free the ones that are really free. TaihuLight[devId]->SetFree(); deviceInUse --; } //fill running_history map // TODO: do we really need this? I think it can be removed running_history[nd->GetId()] = devId; // update pending list and ready queue and success nodes' level std::set<int>::iterator ndit; for (ndit = nd->output.begin(); ndit != nd->output.end(); ndit ++){ int pendingNum = pending_list[*ndit]; pendingNum --; #ifdef DEBUG std::cout<<"Node: "<<*ndit<<", pending num:"<<pendingNum<<std::endl; #endif assert(pendingNum >= 0); pending_list[*ndit] = pendingNum; if (pendingNum == 0){ ready_queue.push_back(*ndit); global_graph.GetNode(*ndit)->SetStatus(READY); // Set node's status // Calculate Cpath computatin cost global_graph.CalcCpathCC(*ndit, this->max_devCompute, this->min_execution_time); //Record the current time global_graph.GetNode(*ndit)->SetWaitTime(this->global_timer); } global_graph.GetNode(*ndit)->SetLevel(nd->GetLevel() +1); } // erase the task from execution_queue execution_queue.erase(it++); nd->SetStatus(FINISHED); #if 0 std::cout<<"Node "<<it->first<<" finished execution at "<<global_timer<< ". It used device "<<devId<<", status:"<<nd->GetStatus()<<std::endl; #endif #if 0 // Output the execution_queue to check its contents std::cout<<"Execution queue: "<<std::endl; // TODO: empty queue compatibility for (auto& x: execution_queue) std::cout << " [" << x.first << ':' << x.second << ']'<< std::endl; #endif }else{ it++; } } /** 2. If the ready queue is not empty and the scheduler is available, process a new task from it and update global_timer, deviceInUse */ while ( (!ready_queue.empty()) && global_timer >= (scheduler_ava_time + ZERO_NEGATIVE) ) { /** For debug: check the task status in ready_queue and execution_queue */ for(auto& ite: ready_queue){ assert(global_graph.GetNode(ite)->IsReady()); } // TODO: 1. consider schedule time here; // 2.0 Update max_parallel value max_parallel = std::max(max_parallel, (int)(ready_queue.size() + execution_queue.size())); //2.1 pick a task from ready_queue (default: choose the first one element) START_TIMING(taskpick); int task_node_id = TaskPick(); STOP_TIMING(taskpick); /** Task counter: total tasks and tasks that DONF hits */ task_total++; int NODF_task_id = TaskPick(DONF); if(task_node_id == NODF_task_id){ task_hit_counter++; } // Erase the task id from the ready_queue std::vector<int>::iterator iter = ready_queue.begin(); for (; iter != ready_queue.end(); iter++){ if (*iter == task_node_id){ ready_queue.erase(iter); break; } } Node* nd = global_graph.GetNode(task_node_id); //2.2 choose a free device to execute the task (default: choose the first free device) /** If this is the only entry task and Scheduler is HSIP, then use entry task duplication policy. */ if ( ready_queue.size() == 1 && Scheduler == HSIP && nd->GetInNum() == 0){ //Entry task duplication EntryTaskDuplication(nd); nd->SetStatus(RUNNING); continue; } // Entry task duplication policy doesn't need this. START_TIMING(devicepick); Device* dev = DevicePick(task_node_id); STOP_TIMING(devicepick); /** Test if DATACENTRIC could hit this pick. */ Device* test_dev = DevicePick(task_node_id, DATACENTRIC); if(dev != NULL && test_dev != NULL && dev->GetId() == test_dev->GetId()){ dev_hit_counter++; } /** If dev == NULL, re-insert the node into ready_queue, and then calculate nearest finish time. TODO: dead loop detection. When no device's free RAM can cover any node's demand in ready_queue and execution_queue is empty, then a dead loop is detected. For a dead loop, report it and stop the simulation. */ //assert(dev != NULL); if ( dev == NULL ){ if ( DeadLoopDetect() ){ this->task_pick_time = GET_TOTAL_TIMING(taskpick); this->device_pick_time = GET_TOTAL_TIMING(devicepick); SimulationReport(); log_error("Execution interrupted, for dead loop detected."); exit(1); } ready_queue.push_back(task_node_id); global_timer = CalcNearestFinishTime(); break; // break the inner while loop } //2.3 do the schedule: busy the device, calc the finish time, allocate device memory and add the task into execution_queue /** Count deviceInUse. */ if ( dev->SetBusy() ){ deviceInUse ++; } nd->SetOccupied(dev->GetId()); nd->SetStatus(RUNNING); dev->IncreaseLoad(1); /** Note: since the scheduled tasks are ready tasks, global_timer + transmission_time is the EST of this task. */ float transmission_time = CalcTransmissionTime(*nd, *dev, true, true); float execution_time = CalcExecutionTime(*nd, *dev); // TODO: change all the time from second to microsecond // To avoid error, execution time should not be less than 1ms. execution_time = std::max(execution_time, this->min_execution_time); // This should be done in CalcTransmissionTime() //transmission_time = std::max(transmission_time, this->min_transmission_time); //Manage memory blocks data structures int block_id = nd->GetId(); MemoryBlock* block = new MemoryBlock(block_id, dev->GetId(), std::max(nd->GetDataDmd(), (float)0.0), nd->GetOutNum()); block->DoAlloc(TaihuLight); // TODO: check if the block id already exists, which is illegal BlocksMap[block_id] = block; //Check if need to set mem_full_dev if((dev->GetFreeRAM() / dev->GetRAM() <= this->mem_full_threshold) && !dev->IsFull()){ dev->SetFull(true); this->mem_full_dev++; } //Calc min_free_mem float sum_free_RAM = 0; for (auto& it: TaihuLight){ sum_free_RAM += (it.second)->GetFreeRAM(); } if(this->min_free_mem < 0 || this->min_free_mem > sum_free_RAM){ this->min_free_mem = sum_free_RAM; } for (std::set<int>::iterator iter = nd->input.begin(); iter != nd->input.end(); iter ++){ Node* input_nd = global_graph.GetNode(*iter); block_free_queue.push_back(std::pair<int, float>(input_nd->GetId(), (transmission_time + global_timer))); } // Process the execution time float AST = -1; // Actual Start Time if ( (AST = dev->FindSlot(global_timer+transmission_time, execution_time)) >= 0 ){// Insertion into ITS. // Update ITS dev->UpdateSlot(AST, execution_time, global_timer); }else{// Not insertion, normal execution. AST = std::max(dev->GetAvaTime(), global_timer + transmission_time); assert(AST >= ZERO_NEGATIVE); //Record the task waiting time nd->SetWaitTime(AST - nd->GetWaitTime()); //Record the available time of the corresponding device dev->SetAvaTime(AST + execution_time); if( AST > dev->GetAvaTime()){ // Set the ITS of the scheduled device dev->NewSlot(dev->GetAvaTime(), global_timer + transmission_time); } } // Fill the execution_queue execution_queue.emplace(task_node_id, (AST + execution_time)); // Set schduler_ava_time scheduler_ava_time = global_timer + scheduler_mean_cost; //Record the AFT of the node/vertex nd->SetAFT(AST + execution_time); dev->IncreaseTransTime(transmission_time); dev->IncreaseRunTime(execution_time); // TODO: add transmission here as well? #if 0 std::cout<<"Execution queue: "<<std::endl; for (auto& x: execution_queue) std::cout << " [" << x.first << ':' << x.second << ']'<< std::endl; std::cout<<"Block free queue: "<<std::endl; for (auto& x: block_free_queue) std::cout << " [" << x.first << ':' << x.second << ']'<< std::endl; #endif #if 1 //Debug std::cout<<"Node "<<task_node_id<<" on "<<dev->GetId(); std::cout<<" at "<<global_timer<<", trans "<<transmission_time<<", exe "<<execution_time<<", finish "<<nd->GetAFT()<<", status: "<<nd->GetStatus()<<", wait time:"<<nd->GetWaitTime()<<std::endl; #endif #if 0 std::cout<<"Device ava time updated to: "<<dev->GetAvaTime()<<"s, Node AFT updated to: "<<nd->GetAFT()<<std::endl; #endif } /** 3. Update global_timer to the nearest finish time */ global_timer = CalcNearestFinishTime(); /** For debug: check the task status in ready_queue and execution_queue */ for(auto& ite: ready_queue){ assert(global_graph.GetNode(ite)->IsReady()); } for(auto& ite: execution_queue){ assert(global_graph.GetNode(ite.first)->GetStatus() == RUNNING); } } this->task_pick_time = GET_TOTAL_TIMING(taskpick); this->device_pick_time = GET_TOTAL_TIMING(devicepick); // Finish running // Write simulation report. SimulationReport(); log_end("Execution."); } /** Pick a task from ready queue according to the scheduling policy. Erase the correspinding task index from ready_queue. */ int Runtime::TaskPick(SchedulePolicy sch){ #ifdef DEBUG std::cout<<"TaskPick: Scheduler "<<Scheduler<<std::endl; #endif SchedulePolicy InnerScheduler; if (sch == UNKNOWN){ InnerScheduler = this->Scheduler; }else{ InnerScheduler = sch; } int taskIdx = -1; switch(InnerScheduler){ case UNKNOWN: break; case FCFS: case RR: taskIdx = ready_queue.front(); break; case SJF:{ // Pick the shortest job int tmpComDmd, leastComDmd = -1; std::vector<int>::iterator iter = ready_queue.begin(); for (; iter != ready_queue.end(); iter++){ if (leastComDmd < 0){ // the first node in ready_queue Node * nd = global_graph.GetNode(*iter); leastComDmd = nd->GetCompDmd(); taskIdx = *iter; }else{ Node * nd = global_graph.GetNode(*iter); tmpComDmd = nd->GetCompDmd(); if (leastComDmd > tmpComDmd){ leastComDmd = tmpComDmd; taskIdx = *iter; } } } } break; case PRIORITY: break; case HEFT: case CPOP: case HSIP: case PEFT:{ /** Traverse all the tasks in the ready queue, pick the one with the max priority. */ float maxPriority = -1; std::vector<int>::iterator iter = ready_queue.begin(); for (; iter != ready_queue.end(); iter++){ Node* nd = global_graph.GetNode(*iter); if(Scheduler == PEFT){ //PEFT if (maxPriority < nd->GetRankOCT()){ maxPriority = nd->GetRankOCT(); taskIdx = *iter; } }else if(Scheduler == HSIP){ //HSIP if (maxPriority < nd->GetRank_u_HSIP()){ maxPriority = nd->GetRank_u_HSIP(); taskIdx = *iter; } }else if(Scheduler == HEFT){ //HEFT if (maxPriority < nd->GetRank_u_HEFT()){ maxPriority = nd->GetRank_u_HEFT(); taskIdx = *iter; } }else{ //CPOP if (maxPriority < nd->GetPriorityCPOP()){ maxPriority = nd->GetPriorityCPOP(); taskIdx = *iter; } } } } break; case DATACENTRIC: case DONF: case DONF2: case ADON: case DONFM: case DONFL: case DONFL2: case ADONL:{ if(InnerScheduler == DONFM){//this->mem_full_dev / this->deviceNum >= this->dev_full_threshold){ //RAM full pick /* int min_level = -1; std::vector<int>::iterator iter = ready_queue.begin(); for (; iter != ready_queue.end(); iter++){ Node* nd = global_graph.GetNode(*iter); if(min_level < 0 || min_level > nd->GetLevel()){ min_level = nd->GetLevel(); taskIdx = *iter; } }*/ //std::cout<<"RAM full pick."<<std::endl; //Pick a mem block (also a node), on a full device and min dependencies int min_deps = -1; int mem_block_id = -1; for (auto& it:BlocksMap) { Device* dv = TaihuLight[(it.second)->DeviceLocation()]; if(dv->IsFull() && (min_deps < 0 || min_deps > (it.second)->GetRefers())){ int readynum = 0; Node* nd_pointer = global_graph.GetNode(it.first); for(auto& innerit : nd_pointer->output){ if(global_graph.GetNode(innerit)->IsReady()){ readynum ++; } } if(readynum > 0){ min_deps = (it.second)->GetRefers(); mem_block_id = it.first; } } } //assert(mem_block_id >= 0); if(mem_block_id >= 0){ //traverse the ready queue, pick a task which is the seccess nodes of the picked node Node* nd_pointer = global_graph.GetNode(mem_block_id); std::vector<int>::iterator iter = ready_queue.begin(); for (; iter != ready_queue.end(); iter++){ if(nd_pointer->output.find(*iter) != nd_pointer->output.end()){//it's a success node taskIdx = *iter; break; } } } if(taskIdx < 0){//did not find a good task std::cout<<"RAM full pick: did not find a good task!"<<std::endl; taskIdx = ready_queue.front(); } }else{ float degree, maxOutDegree = -1; std::vector<int>::iterator iter = ready_queue.begin(); for (; iter != ready_queue.end(); iter++){ Node* nd = global_graph.GetNode(*iter); if( Scheduler == ADON || Scheduler == ADONL){ // ADON, ADONL degree = nd->GetRank_ADON(); }else if( Scheduler == DONF2 || Scheduler == DONFL2 ){ // DONF2, DONFL2 degree = NDON(nd, 2); }else{ // DC, DONF, DONFL degree = NDON(nd); } if (maxOutDegree < degree){ maxOutDegree = degree; taskIdx = *iter; } } } } break; case MULTILEVEL: break; //case DATACENTRIC: /** If device in use is small, fetch a task from the ready queue tail. Else, fetch a task from the head. We need a flag var. For example, ... */ //break; default: std::cout<<"Error: unrecognized scheduling policy "<<Scheduler<<std::endl; exit(1); } return taskIdx; } /** Pick a free device according to the task requirements and scheduling policy. */ Device* Runtime::DevicePick(int ndId, SchedulePolicy sch){ SchedulePolicy InnerScheduler; #ifdef DEBUG std::cout<<"DevicePick: Scheduler "<<Scheduler<<", node "<<ndId<<std::endl; #endif if (sch == UNKNOWN){ InnerScheduler = this->Scheduler; }else{ InnerScheduler = sch; } //int CTM[][3] = {22, 21, 36, 22, 18, 18, 32, 27, 43, 7, 10, 4, 29, 27, 35, 26, 17, 24, 14, 25, 30, 29, 23, 36, 15, 21, 8, 13, 16, 33}; Node * nd = global_graph.GetNode(ndId); Device * dev = NULL; float exeTime = -1.0; switch(InnerScheduler){ case UNKNOWN: break; /** Actually this is a very basic logic, try to use the EFT way. */ case PRIORITY: for (auto& it: TaihuLight){ if((nd->GetDataDmd()) <= (it.second)->GetFreeRAM() + ZERO_POSITIVE){ float tmpExeTime = CalcExecutionTime(*nd, *(it.second)); if (exeTime < 0.0){ exeTime = tmpExeTime; dev = it.second; }else{ if (exeTime > tmpExeTime){ exeTime = tmpExeTime; dev = it.second; } } } } break; case RR: for (int i = RRCounter+1; i<TaihuLight.size(); i++){ Device * tmpDev = TaihuLight[i]; if ( (nd->GetDataDmd()) <= tmpDev->GetFreeRAM() ){ dev = tmpDev; RRCounter = i; break; } } if (dev == NULL){// Haven't found a good device for (int i = 0; i<=RRCounter; i++){ Device * tmpDev = TaihuLight[i]; if ( (nd->GetDataDmd())<=tmpDev->GetFreeRAM() ){ dev = tmpDev; RRCounter = i; break; } } } break; case FCFS: case SJF: case HEFT: case CPOP: case HSIP: case PEFT: case DONFL: case DONFL2: case ADONL:{ /** For tasks on critical path, assign them to the fastest device. */ float dv = nd->GetPriorityCPOP() - this->absCP; if(InnerScheduler == CPOP && dv >= ZERO_NEGATIVE && dv <= ZERO_POSITIVE){ dev = TaihuLight[this->max_computeDevId]; if( (nd->GetDataDmd()) > dev->GetFreeRAM() + ZERO_POSITIVE ){ for (auto& it: TaihuLight){ if((nd->GetDataDmd()) < (it.second)->GetFreeRAM() + ZERO_NEGATIVE){ dev = it.second; break; } } } #ifdef DEBUG std::cout<<"[Info] Node "<<ndId<<" is a CP task, so pick device "<<this->max_computeDevId<<std::endl; #endif break; } /** Traverse all the devices, pick the one with the min EFT. */ float mean_load = CalcMeanLoad(); float min_OEFT = -1; // 1.Traverse all the devices for (auto& it: TaihuLight){ if( (nd->GetDataDmd()) > (it.second)->GetFreeRAM() + ZERO_POSITIVE ){ // The free memory of the device is too little, skip continue; } #ifdef DEBUG std::cout<<"lb_balance: "<<load_balance_threshold<<", mean load: "<<mean_load<<", dev load:"<<(it.second)->GetLoad()<<std::endl; #endif // DEBUG if(this->load_balance_threshold && (it.second)->GetLoad() > std::max(mean_load, float(this->load_balance_threshold))){ #ifdef DEBUG std::cout<<"a load balance pick"<<std::endl; #endif // DEBUG continue; } /* if(this->load_time >= ZERO_POSITIVE && ((it.second)->GetAvaTime() - global_timer) >= this->load_time){ continue; }*/ float w = nd->GetCompDmd() / (it.second)->GetCompPower(); // 2. Calculate EST by traversing all the pred(ndId) float EST = 0; float tmpEST; // TODO: The logic below can be replaced by CalcTransmissionTime() for (auto& pred : nd->input){ Node* predNd = global_graph.GetNode(pred); if (predNd->GetOccupied() == it.first || (predNd->GetInNum() == 0 && this->ETD) ){ /** Execute on the same device or the pred node is an entry node with ETD == true */ /** Note: since the scheduled tasks are ready tasks, tmpEST = global_timer */ tmpEST = std::max(predNd->GetAFT(), global_timer); }else{//on different device float ct;// Comunication time float ava_time;//The link available time ct = TaihuLightNetwork.GetBw((it.second)->GetId(), predNd->GetOccupied()); //bandwith if (ct <= BW_ZERO){//get bandwith between nodes ct = TaihuLightNetwork.GetBw((it.second)->GetLocation(), TaihuLight[predNd->GetOccupied()]->GetLocation(), true); ava_time = std::max((float)0.0, TaihuLightNetwork.GetConAvaTime((it.second)->GetLocation(), TaihuLight[predNd->GetOccupied()]->GetLocation(), true) - this->global_timer); }else{ ava_time = std::max((float)0.0, TaihuLightNetwork.GetConAvaTime((it.second)->GetId(), predNd->GetOccupied()) - this->global_timer); } ct = CommunicationDataSize(pred, ndId) / ct; ct = std::max(ct, this->min_transmission_time); /** Note: since the scheduled tasks are ready tasks, tmpEST = global_timer + ct */ tmpEST = std::max(predNd->GetAFT(), global_timer) + ct; if(Scheduler == DONFL || Scheduler == DONFL2 || Scheduler == ADONL){ tmpEST += ava_time; } } EST = std::max(tmpEST, EST); } // 3. Calculate EFT(nd, it) = EST + w // Two ways to calculate w for debugging if ( (it.second)->FindSlot(EST, w) >= ZERO_NEGATIVE ){ // Insertion into ITS EST = (it.second)->FindSlot(EST, w); }else{ // Not Insertion EST = std::max( EST, (it.second)->GetAvaTime() ); } float EFT = EST + w; //float EFT = EST + CTM[ndId][it.first]; // 4. Calculate OEFT = EFT + OCT for PEFT float OEFT; if (Scheduler == PEFT){ OEFT = EFT + OCT[ndId][it.first]; }else{ //HSIP and others OEFT = EFT; } if ( (min_OEFT < 0) || (min_OEFT > OEFT) ){ min_OEFT = OEFT; dev = it.second; } } #if 0 if(dev != NULL){ std::cout<<"ld: "<<dev->GetLoad()<<" "<<mean_load<<" t: "<<(dev->GetAvaTime() - global_timer)<<std::endl; } #endif } break; case DONF: case DONF2: case ADON: case DONFM:{ /** Traverse all the devices, pick the one with the min EFT. */ float min_EFT = -1; // 1.Traverse all the devices for (auto& it: TaihuLight){ if( (nd->GetDataDmd()) > (it.second)->GetFreeRAM() + ZERO_POSITIVE ){ // The free memory of the device is too little, skip continue; } float w = nd->GetCompDmd() / (it.second)->GetCompPower(); // 2. Calculate EST by traversing all the pred(ndId) float ct; if(this->with_conflicts){ ct = CalcTransmissionTime(*nd, *(it.second), true, false); }else{ ct = CalcTransmissionTime(*nd, *(it.second), false, false); } // Since all the scheduled tasks' preds has been finished, we don't consider their AFT here. float EST = std::max((it.second)->GetAvaTime(), global_timer + ct); float EFT = EST + w; if ( (min_EFT < 0) || (min_EFT > EFT) ){ min_EFT = EFT; dev = it.second; } } } break; case MULTILEVEL: break; case DATACENTRIC:{ /** Pick the device according to the data location or the min data transformation time. */ float comtime, caltime, tmpweight, maxweight = 0; int ndidx; for (auto it : nd->input) { if ((tmpweight = CommunicationDataSize(it, ndId)) > maxweight ){ maxweight = tmpweight; ndidx = it; } } comtime = maxweight / TaihuLightNetwork.GetMeanBW(); caltime = nd->GetCompDmd() / GetMeanCP(); if (comtime > (caltime * this->DCRatio)){// pick according to data location // Increase the counter and get the device dc_valid_counter++; dev = TaihuLight[global_graph.GetNode(ndidx)->GetOccupied()]; }else{// pick according to EFT float min_OEFT = -1; for (auto& it: TaihuLight){ if( (nd->GetDataDmd()) > (it.second)->GetFreeRAM() + ZERO_POSITIVE ){ // The free memory of the device is too little, skip continue; } float w = nd->GetCompDmd() / (it.second)->GetCompPower(); // 2. Calculate EST by traversing all the pred(ndId) float EST = 0; float tmpEST; // TODO: The logic below can be replaced by CalcTransmissionTime() for (auto& pred : nd->input){ Node* predNd = global_graph.GetNode(pred); if (predNd->GetOccupied() == it.first){ /** Execute on the same device */ /** Note: since the scheduled tasks are ready tasks, tmpEST = global_timer */ tmpEST = std::max(predNd->GetAFT(), global_timer); }else{//on different device float ct;// Comunication time ct = TaihuLightNetwork.GetBw((it.second)->GetId(), predNd->GetOccupied()); //bandwith if (ct <= BW_ZERO){//get bandwith between nodes ct = TaihuLightNetwork.GetBw((it.second)->GetLocation(), TaihuLight[predNd->GetOccupied()]->GetLocation(), true); } ct = CommunicationDataSize(pred, ndId) / ct; /** Note: since the scheduled tasks are ready tasks, tmpEST = global_timer + ct */ tmpEST = std::max(predNd->GetAFT(), global_timer) + ct; } EST = std::max(tmpEST, EST); } // 3. Calculate EFT(nd, it) = EST + w // Two ways to calculate w for debugging EST = std::max( EST, (it.second)->GetAvaTime() ); if ( (min_OEFT < 0) || (min_OEFT > EST + w) ){ min_OEFT = EST + w; dev = it.second; } } } } break; default: std::cout<<"Error: unrecognized scheduling policy "<<Scheduler<<std::endl; exit(1); } return dev; } /** Calculate mean load of all devices. */ float Runtime::CalcMeanLoad(){ float meanLoad = 0.0; int deviceNum = 1; for (auto& it: TaihuLight){ meanLoad += ((it.second)->GetLoad() - meanLoad) / deviceNum; deviceNum ++; } return meanLoad; } /** Calculate the nearest time that a new decision can be made. */ float Runtime::CalcNearestFinishTime(){ float NearestTime = -1.0; std::map<int, float>::iterator ite; // 1. Search the execution_queue for (ite = execution_queue.begin(); ite != execution_queue.end(); ite++){ if (NearestTime > ite->second || NearestTime < ZERO_NEGATIVE){ NearestTime = ite->second; } } // 2. Search the block_free_queue for (auto& ite: block_free_queue){ if (NearestTime > ite.second || NearestTime < ZERO_NEGATIVE){ NearestTime = ite.second; } } // 3. If scheduler_ava_time is larger than global_timer, consider it as well if (this->scheduler_ava_time >= global_timer + ZERO_POSITIVE){ if (NearestTime > this->scheduler_ava_time || NearestTime < ZERO_NEGATIVE){ NearestTime = this->scheduler_ava_time; } } if (NearestTime > ZERO_POSITIVE){ return NearestTime; } else{ return global_timer; } } /** Calculate the data transmission time if we put nd on dev, return the result as a float. */ float Runtime::CalcTransmissionTime(Node nd, Device dev, bool withConflicts, bool setAvaTime){ float data_transmission_time=0.0; //1. Calculate total_data_output float total_data_output = 0.0; for (std::set<int>::iterator iter = nd.input.begin(); iter != nd.input.end(); iter ++){ Node* input_nd = global_graph.GetNode(*iter); if(input_nd->GetDataGenerate() > ZERO_POSITIVE){ total_data_output += input_nd->GetDataGenerate(); }else{ total_data_output += std::max(input_nd->GetDataDmd(), (float)0.0); } } //2. Calculate data_trans_ratio float data_trans_ratio = 1.0; if(nd.GetDataConsume() > ZERO_POSITIVE){ if( total_data_output > nd.GetDataConsume() ){ data_trans_ratio = std::max(nd.GetDataConsume(), (float)0.0) / total_data_output; } }else{ if( total_data_output > nd.GetDataDmd() ){ data_trans_ratio = std::max(nd.GetDataDmd(), (float)0.0) / total_data_output; } } //3. Walk through all the input nodes of nd, and calc the transmission time std::map<int, float> TransSize; for (std::set<int>::iterator iter = nd.input.begin(); iter != nd.input.end(); iter ++){ Node* input_nd = global_graph.GetNode(*iter); int input_dev_id = input_nd->GetOccupied(); // On the same device, ignore the data transmission time // The input node is an entry node with entry task duplication, ignore the transmission time if (input_dev_id == dev.GetId() || (input_nd->GetInNum() == 0 && this->ETD)){ continue; } // Calculate the total transmission data size from input_dev_id to dev if(TransSize.find(input_dev_id) == TransSize.end()){ // There's not an entry, create one TransSize[input_dev_id] = 0.0; } if ( (global_graph.GetComCost( *iter, nd.GetId() )) >= 0 ) { // The edge has a weight TransSize[input_dev_id] += global_graph.GetComCost( *iter, nd.GetId() ); }else{ // The edge doesn't have a weight if(input_nd->GetDataGenerate() > ZERO_POSITIVE){ TransSize[input_dev_id] += std::max(input_nd->GetDataGenerate(), (float)0.0) * data_trans_ratio; }else{ TransSize[input_dev_id] += std::max(input_nd->GetDataDmd(), (float)0.0) * data_trans_ratio; } } } float network_bandwidth = 0.0; for(auto& dataSz : TransSize){ int input_dev_id = dataSz.first; float transmission_size = dataSz.second; // The quatity of time from now to the link avaliable time float ava_time = 0.0; // Get the bandwith between the two devices if ((network_bandwidth = TaihuLightNetwork.GetBw(dev.GetId(), input_dev_id)) <= BW_ZERO){ network_bandwidth = TaihuLightNetwork.GetBw(dev.GetLocation(), TaihuLight[input_dev_id]->GetLocation(), true); ava_time = std::max(ava_time, TaihuLightNetwork.GetConAvaTime(dev.GetLocation(), TaihuLight[input_dev_id]->GetLocation(), true) - this->global_timer); }else{//The devices are on the same node. ava_time = std::max(ava_time, TaihuLightNetwork.GetConAvaTime(dev.GetId(), input_dev_id) - this->global_timer); } float ct; // Communication time ct = transmission_size / network_bandwidth; ct = std::max(ct, this->min_transmission_time); if(withConflicts){ data_transmission_time = std::max(ct + ava_time, data_transmission_time); }else{ data_transmission_time = std::max(ct, data_transmission_time); } if(withConflicts && setAvaTime){ if ((TaihuLightNetwork.GetBw(dev.GetId(), input_dev_id)) <= BW_ZERO){ TaihuLightNetwork.IncConAvaTime(dev.GetLocation(), TaihuLight[input_dev_id]->GetLocation(), ct, this->global_timer, true); }else{//The devices are on the same node. TaihuLightNetwork.IncConAvaTime(dev.GetId(), input_dev_id, ct, this->global_timer); } } } #ifdef DEBUG std::cout<<"Data transmission time: "<<data_transmission_time<<std::endl; #endif return data_transmission_time; } /** Calculate the execution time if we put nd on dev, return the result as a float. */ float Runtime::CalcExecutionTime(Node nd, Device dev){ // TODO: More accurate exection time calculation float calc_time, data_time; //1. calculation time calc_time = nd.GetCompDmd() / dev.GetCompPower(); //2. data access time data_time = std::max(nd.GetDataDmd(), (float)0.0) / dev.GetBw(); return std::max(calc_time, data_time); } /** Get the data size need to be transfered from predId to succId. Return it as a float value. */ float Runtime::CommunicationDataSize(int predId, int succId){ float dataSize = global_graph.GetComCost(predId, succId); if (dataSize < 0){//No edge weight found, need to calculate float total_data_output = 0.0; float data_trans_ratio = 1.0; // Calculate the total output size of succId's all pred nodes Node* nd = global_graph.GetNode(succId); for (auto& it : nd->input){ Node* input_nd = global_graph.GetNode(it); if(input_nd->GetDataGenerate() > ZERO_POSITIVE){ total_data_output += input_nd->GetDataGenerate(); }else{ total_data_output += std::max(input_nd->GetDataDmd(), (float)0.0); } } // Get how much of the output data should be transfered. if(nd->GetDataConsume() > ZERO_POSITIVE){ if( total_data_output > nd->GetDataConsume() ){ data_trans_ratio = std::max(nd->GetDataConsume(), (float)0.0) / total_data_output; } }else{ if (total_data_output > nd->GetDataDmd()){ data_trans_ratio = std::max(nd->GetDataDmd(), (float)0.0) / total_data_output; } } if(global_graph.GetNode(predId)->GetDataGenerate() > ZERO_POSITIVE){ dataSize = std::max(global_graph.GetNode(predId)->GetDataGenerate(), (float)0.0) * data_trans_ratio; }else{ dataSize = std::max(global_graph.GetNode(predId)->GetDataDmd(), (float)0.0) * data_trans_ratio; } } return dataSize; } /** Use entry task duplication policy on nd. */ // TODO: Consider data transmission time of the succ nodes of the entry task. void Runtime::EntryTaskDuplication(Node* nd){ /** 1. Calculate execution time on every device, set every device's available time by it and get the min execution time. Set busy every device and update device in use counter. Add the min execution time into execution queue. */ float min_w = -1; //min execution time for (auto& it : TaihuLight) { float w = CalcExecutionTime(*nd, *(it.second)); (it.second)->SetAvaTime(w); (it.second)->SetBusy(); deviceInUse++; if (min_w < 0 || min_w > w){ // Record the min_w and occupied device min_w = w; nd->SetOccupied((it.second)->GetId()); } } assert(min_w >= ZERO_NEGATIVE); execution_queue.emplace(nd->GetId(), min_w); /** 2. Alloc memory block */ int block_id = nd->GetId(); MemoryBlock* block = new MemoryBlock(block_id, nd->GetOccupied(), std::max(nd->GetDataDmd(), (float)0.0), nd->GetOutNum()); block->DoAlloc(TaihuLight); // TODO: check if the block id already exists, which is illegal BlocksMap[block_id] = block; /** 3. Erase the task from the ready queue Actually I think ready_queue.clear() is good enough. */ for (std::vector<int>::iterator it = ready_queue.begin(); it != ready_queue.end();) { if (*it == nd->GetId()){ //std::cout<<*it<<std::endl; ready_queue.erase(it); }else{ it++; } } // 4. Set the ETD flag this->ETD = true; } /** Detect dead loop and return the result. If a dead loop is detected, report it and return true, otherwise return false. */ bool Runtime::DeadLoopDetect(){ /** 1. If the execution_queue is not empty or the ready_queue is empty, just return false. */ if ( (!execution_queue.empty()) || ready_queue.empty() ){ return false; } /** 2. Pick the min RAM demand from ready_queue */ float min_data_demand = -1; for (auto& it : ready_queue) { Node* nd = global_graph.GetNode(it); if ( min_data_demand < 0 || min_data_demand > nd->GetDataDmd()){ min_data_demand = nd->GetDataDmd(); } } /** 3. Traverse all the devices, if no free RAM covers the min RAM demand, report the dead loop and return true! */ bool dead_loop = true; for (auto& it : TaihuLight) { if ( (it.second)->GetFreeRAM() >= min_data_demand + ZERO_POSITIVE){ dead_loop = false; } } if (dead_loop){ // Dead loop report std::cout<< RED <<"\n****** Emergency! Dead loop detected ******"<< RESET <<std::endl; /** 1. Every device's free RAM size. */ for (auto& it : TaihuLight) { std::cout<<"| Device "<<it.first<<", free RAM: "<<it.second->GetFreeRAM()<<std::endl; } /** 2. Memory block output */ for (auto& it : BlocksMap) { std::cout<<"| Memory Block "<<it.first<<", on device:"<<(it.second)->DeviceLocation()<<", block size:"<<(it.second)->GetBlockSize()<<std::endl; } /** 3. Ready queue nodes' data demand */ for (auto& it : ready_queue) { std::cout<<"| Node "<<it<<", data demand:"<<global_graph.GetNode(it)->GetDataDmd()<<std::endl; } /** 4. Execution queue nodes */ for (auto& it : execution_queue) { std::cout<<"| Node "<<it.first<<", finish time:"<<it.second<<std::endl; } std::cout<< RED <<"******************"<< RESET <<std::endl; } return dead_loop; } /** Change the scheduling policy during running time. */ void Runtime::SetScheduler(SchedulePolicy sch){ this->Scheduler = sch; } /** Get mean computation power. */ float Runtime::GetMeanCP(){ return this->mean_computing_power; } /** Calculate mean wait time of all tasks. */ float Runtime::GetMeanWaitTime(){ float meanwaittime = 0; int numtasks = 0; for (auto it : idset) { numtasks++; meanwaittime += (global_graph.GetNode(it)->GetWaitTime() - meanwaittime) / numtasks; } return meanwaittime; } /** Get max parallel value. */ int Runtime::GetMaxParallel(){ return this->max_parallel; } /** Set scheduling mean cost. */ void Runtime::SetSchedulerCost(float sc){ assert(sc >= 0.0); scheduler_mean_cost = sc; } /** Set alpha value of ADON and DONF2 policies. */ void Runtime::SetAlpha(float alpha){ assert(alpha >= ZERO_NEGATIVE); this->alpha_DON = alpha; #ifdef DEBUG std::cout<<"Set alpha as: "<<alpha<<std::endl; std::cout<<"Check alpha: "<<this->alpha_DON<<std::endl; #endif } /** Set load balance threshold value. */ void Runtime::SetLoadBalanceThreshold(int threshold){ assert(threshold >= 0); this->load_balance_threshold = threshold; } /** Set mem_full_threshold */ void Runtime::SetMemFull(float full){ assert(full > ZERO_POSITIVE && full < 1.0 - ZERO_POSITIVE); this->mem_full_threshold = full; std::cout<<"Set mem full: "<<this->mem_full_threshold<<std::endl; } /** Set dev_full_threshold */ void Runtime::SetDevFull(float full){ assert(full > ZERO_POSITIVE && full < 1.0 - ZERO_POSITIVE); this->dev_full_threshold = full; } /** Output SchedulePolicy as enum items. */ std::ostream& operator<<(std::ostream& out, const SchedulePolicy value){ static std::map<SchedulePolicy, std::string> strings; if (strings.size() == 0){ #define INSERT_ELEMENT(p) strings[p] = #p INSERT_ELEMENT(UNKNOWN); INSERT_ELEMENT(FCFS); INSERT_ELEMENT(SJF); INSERT_ELEMENT(RR); INSERT_ELEMENT(PRIORITY); INSERT_ELEMENT(HEFT); INSERT_ELEMENT(CPOP); INSERT_ELEMENT(PEFT); INSERT_ELEMENT(HSIP); INSERT_ELEMENT(DONF); INSERT_ELEMENT(DONF2); INSERT_ELEMENT(ADON); INSERT_ELEMENT(DONFM); INSERT_ELEMENT(DONFL); INSERT_ELEMENT(DONFL2); INSERT_ELEMENT(ADONL); INSERT_ELEMENT(MULTILEVEL); INSERT_ELEMENT(DATACENTRIC); #undef INSERT_ELEMENT } return out << strings[value]; } /** Output the simlulation report. */ void Runtime::SimulationReport(){ float speedup = std::max(this->max_cpath_cc, (global_graph.GetTotalCost()/this->max_devCompute))/this->global_timer; std::cout<<"-------- Simulation Report --------"<<std::endl; std::cout<<" Graph file: "<<graph_file_name<<std::endl; std::cout<<" Cluster: "<<cluster_file_name<<std::endl; std::cout<<" Scheduling Policy: "<<Scheduler<<std::endl; std::cout<<" DC Ratio: "<<DCRatio<<std::endl; std::cout<<" Alpha: "<<alpha_DON<<std::endl; std::cout<<" With Conflicts: "<<with_conflicts<<std::endl; std::cout<<" Mem full threshold: "<<mem_full_threshold<<std::endl; std::cout<<" Dev full threshold: "<<dev_full_threshold<<std::endl; std::cout<<" Total nodes: "<<task_total<<std::endl; std::cout<<" Global timer: "<<global_timer<<std::endl; std::cout<<" Max parallelism: "<<this->max_parallel<<std::endl; std::cout<<" Mean wait time: "<<GetMeanWaitTime()<<std::endl; std::cout<<" Cpath cost summary: "<<this->max_cpath_cc<<std::endl; std::cout<<" Scheduler cost: "<<this->scheduler_mean_cost<<std::endl; // Note: This speedup value maybe not so accurate! std::cout<<" Speedup: "<<speedup<<std::endl; std::cout<<" Efficiency: "<<speedup / this->deviceNum<<std::endl; std::cout<<" SLR: "<<(this->global_timer/this->max_cpath_cc)<<std::endl; std::cout<<" Min free RAM size: "<<this->min_free_mem<<std::endl; int devId, tasks; float occupyTime, dataTransTime, totalRAM, freeRAM; Cluster::iterator it = TaihuLight.begin(); for(; it != TaihuLight.end(); it++){ devId = it->first; occupyTime = (it->second)->GetRunTime(); dataTransTime = (it->second)->GetTransTime(); tasks = (it->second)->GetTasks(); totalRAM = (it->second)->GetRAM(); freeRAM = (it->second)->GetFreeRAM(); assert(devId >= 0); assert(occupyTime >= 0.0); std::cout<<" Device id:"<<devId<<" occupied time:"<<occupyTime<<" proportion:"<<occupyTime/global_timer<<" data transfer time:"<<dataTransTime<<", finished number of tasks:"<<tasks<<", total RAM:"<<totalRAM<<", free RAM:"<<freeRAM<<std::endl; } std::cout<<"Total tasks:"<<this->task_total<<"\n\tDONF hit times:"<<this->task_hit_counter<<" propertion:"<<float(this->task_hit_counter)/this->task_total<<"\n\tDatacentric hit times:"<<this->dev_hit_counter<<" propertion:"<<float(this->dev_hit_counter)/this->task_total<<"\n\tDatacentric valid times:"<<this->dc_valid_counter<<" propertion:"<<float(this->dc_valid_counter)/this->task_total<<std::endl; std::cout<<"\nTiming info:"<<std::endl; std::cout<<"\tGraph init time: "<<this->graph_init_time<<" s"<<std::endl; std::cout<<"\tCluster init time: "<<this->cluster_init_time<<" s"<<std::endl; std::cout<<"\tCalcOCT time: "<<this->oct_time<<" s"<<std::endl; std::cout<<"\tRank OCT time: "<<this->rankoct_time<<" s"<<std::endl; std::cout<<"\tRank u time: "<<this->rank_u_time<<" s"<<std::endl; std::cout<<"\tRank d time: "<<this->rank_d_time<<" s"<<std::endl; std::cout<<"\tNDON time: "<<this->ndon_time<<" s"<<std::endl; std::cout<<"\tTask pick time: "<<this->task_pick_time<<" s"<<std::endl; std::cout<<"\tDevice pick time: "<<this->device_pick_time<<" s"<<std::endl; std::cout<<"-----------------------------------"<<std::endl; } /** Return the global_graph. Just for testing. */ Graph Runtime::GetGraph(){ return global_graph; } /** Return TaihuLight. Just for testing. */ Cluster Runtime::GetCluster(){ return TaihuLight; } /** Return TaihuLightNetwork. Just for testing. */ Connections Runtime::GetConnections(){ return TaihuLightNetwork; } /** Return the execution_queue. Just for testing. */ std::map<int, float> Runtime::GetExeQueue(){ return execution_queue; } /** Return the ready_queue. Just for testing. */ std::vector<int> Runtime::GetReadyQueue(){ return ready_queue; } // Class MemoryBlock // TODO: Add unit test for MemoryBlock and remove the DEBUG blocks. MemoryBlock::MemoryBlock() :BlockId(-1), DeviceId(-1), BlockSize(0), ReferNum(0){} MemoryBlock::MemoryBlock(int id, int devid, int size, int refers) :BlockId(id), DeviceId(devid), BlockSize(size), ReferNum(refers){} MemoryBlock::~MemoryBlock(){} /** Decrease the refer number and return the decreased number. */ int MemoryBlock::DecRefers(int number){ ReferNum -= number; ReferNum = std::max(0, ReferNum); return ReferNum; } /** Allocate the memory block physically */ void MemoryBlock::DoAlloc(Cluster TaihuLight){ assert(BlockId >= 0); assert(DeviceId >= 0); assert(BlockSize >= 0); assert(ReferNum >= 0); // The sink node has ReferNum=0 // At least 1KB for a block size, to avoid error. BlockSize = std::max(BlockSize, 1); #ifdef DEBUG std::cout<<"**Memory block allocate**"<<std::endl; std::cout<<"| BlockId:"<<BlockId<<std::endl; std::cout<<"| DeviceId:"<<DeviceId<<std::endl; std::cout<<"| BlockSize:"<<BlockSize<<std::endl; std::cout<<"| ReferNum:"<<ReferNum<<std::endl; std::cout<<"*************************"<<std::endl; #endif TaihuLight[DeviceId]->MemAlloc(BlockSize); } /** Free this memory block on corresponding device */ void MemoryBlock::DoFree(Cluster TaihuLight){ assert(DeviceId >= 0); assert(BlockSize >= 0); assert(ReferNum <= 0); #ifdef DEBUG std::cout<<"**Memory block Free**"<<std::endl; std::cout<<"| BlockId:"<<BlockId<<std::endl; std::cout<<"| DeviceId:"<<DeviceId<<std::endl; std::cout<<"| BlockSize:"<<BlockSize<<std::endl; std::cout<<"| ReferNum:"<<ReferNum<<std::endl; std::cout<<"*************************"<<std::endl; #endif TaihuLight[DeviceId]->MemFree(BlockSize); } /** Return the number of refers of this memory block */ int MemoryBlock::GetRefers(){ assert(ReferNum >= 0); return ReferNum; } /** Get device location. */ int MemoryBlock::DeviceLocation(){ return DeviceId; } /** Get block size. */ int MemoryBlock::GetBlockSize(){ return BlockSize; } }
31.169635
406
0.629009
[ "vector" ]
6d264ff711b53d8ca60062f8c4ed4b04e65c1f5d
2,435
cpp
C++
src/Game.cpp
SharkDX/Antek
02a79005dc63643158bb404d913c359fed5db0c1
[ "Apache-2.0" ]
1
2021-05-13T16:22:34.000Z
2021-05-13T16:22:34.000Z
src/Game.cpp
guymor4/Antek
02a79005dc63643158bb404d913c359fed5db0c1
[ "Apache-2.0" ]
null
null
null
src/Game.cpp
guymor4/Antek
02a79005dc63643158bb404d913c359fed5db0c1
[ "Apache-2.0" ]
null
null
null
#include "Game.h" #include <iostream> #include <string> #include <assert.h> #include <glm/glm.hpp> #include <glm/ext.hpp> Antek::Game::Game(GLFWwindow* window) { glfwGetWindowSize(window, &_screen_width, &_screen_height); _is_running = false; _window = window; } Antek::Game::~Game() { } void Antek::Game::LoadResources() { } void Antek::Game::Initialize() { _profiler = new Utils::Profiler(); _profiler->StartNewProfile("Total Init"); // OpenGL setup glClearColor(0.1f, 0.4f, 0.8f, 1); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glDisable(GL_CULL_FACE); // Input setup // TODO make a custom cursor glfwSetInputMode(_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); // Init basic mechanics BlockFactory::InitBlockTypes(); _camera = new Utils::Camera(_window); _profiler->StartNewProfile("World Generation"); _world = new World(128, 64, 128); _profiler->EndProfile("World Generation"); _profiler->StartNewProfile("Rendering Generation"); _block_renderer = new Renderers::BlockRenderer(); _block_renderer->Init(_world->GetBlocksForRenderer(), _world->GetSizeX(), _world->GetSizeY(), _world->GetSizeZ()); _profiler->EndProfile("Rendering Generation"); _profiler->EndProfile("Total Init"); } void Antek::Game::Update(float deltaTime) { _camera->Update(deltaTime); } void Antek::Game::Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4x4 mvp = _camera->getMVP(); _block_renderer->Render(mvp); } void Antek::Game::Run() { int frames = 0; double lastFrame = glfwGetTime(); double deltaTime = 0; double lastUpdate = glfwGetTime(); while (!glfwWindowShouldClose(_window) && glfwGetKey(_window, GLFW_KEY_ESCAPE) != GLFW_PRESS) { frames++; deltaTime = glfwGetTime() - lastUpdate; lastUpdate = glfwGetTime(); if (glfwGetTime() - lastFrame >= 1.0) { printf("FPS: %d, Ram: %d MB\n", frames, Utils::SystemResources::get_total_memory_usage() / 1000 / 1000); lastFrame = glfwGetTime(); frames = 0; } Update((float)deltaTime); Render(); glfwSwapBuffers(_window); glfwPollEvents(); //std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void Antek::Game::ScrollWheelCallback(double x, double y) { } void Antek::Game::KeyCallback(int key, int scancode, int action, int mods) { } void Antek::Game::MouseButtonCallback(int button, int action, int bits) { } void Antek::Game::CharCallback(unsigned int keycode) { }
21.173913
115
0.713758
[ "render" ]
6d2bd84977bfbb63910c68b6f831db95d08b24ab
1,445
cpp
C++
data_structures/BIT.cpp
Rodp63/CP
3fb14cab2cf340a183a77e978029147f59269020
[ "MIT" ]
null
null
null
data_structures/BIT.cpp
Rodp63/CP
3fb14cab2cf340a183a77e978029147f59269020
[ "MIT" ]
null
null
null
data_structures/BIT.cpp
Rodp63/CP
3fb14cab2cf340a183a77e978029147f59269020
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <vector> #include <queue> #include <stack> #include <algorithm> #include <set> #include <map> #include <deque> #include <math.h> #include <string.h> #include <iomanip> #include <locale> using namespace std; #define FORN(i,m,n) for(int i=m; i<(n); i++) #define PRINTVEC(v) FORN(i,0,v.size()) cout<<v[i]<<" "; cout<<endl #define PRINTMAT(m) FORN(j,0,m.size()) {PRINTVEC(m[j]);} #define p_b(x) push_back(x) #define m_p(a,b) make_pair(a,b) typedef long long ll; int n; vector<ll> v, parent, ans, bit; int Find(int u){return parent[u]==u ? u : parent[u] = Find(parent[u]);} void update(int u, int dif){ for(int i = u; i < bit.size(); i = i | (i + 1)) bit[i] += dif; } ll query(int u){ ll res = 0; for(int i = u; i >= 0; i = (i & (i + 1)) - 1) res += bit[i]; return res; } int get(ll val){ ll l = 0, r = n - 1, mid, res; while(r >= l){ mid = (l + r)/2; res = query(mid); if(res < val) l = mid + 1; else r = mid - 1; } return Find(l) + 1; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cin>>n; v = parent = ans = bit = vector<ll> (n); FORN(i,0,n) cin>>v[i]; FORN(i,0,n){ parent[i] = i; update(i, i); } for(int i = n - 1; i >= 0; i--){ int pos = get(v[i]); ans[i] = pos; if(pos < n) update(pos, -pos); parent[pos - 1] = pos; } PRINTVEC(ans); }
22.230769
72
0.530104
[ "vector" ]
6d2c6bb6d97d7732ddab49c94110dc828805052f
16,068
cpp
C++
ViAn/GUI/drawingwidget.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
1
2019-12-08T03:53:03.000Z
2019-12-08T03:53:03.000Z
ViAn/GUI/drawingwidget.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
182
2018-02-08T11:03:26.000Z
2019-06-27T15:27:47.000Z
ViAn/GUI/drawingwidget.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
null
null
null
#include "drawingwidget.h" #include "DrawingItems/arrowitem.h" #include "DrawingItems/circleitem.h" #include "DrawingItems/frameitem.h" #include "DrawingItems/lineitem.h" #include "DrawingItems/penitem.h" #include "DrawingItems/rectitem.h" #include "DrawingItems/textitem.h" #include "Project/videoproject.h" #include "Video/overlay.h" #include <QColorDialog> #include <QDebug> #include <QHeaderView> #include <QMenu> #include <QMessageBox> #include <QShortcut> DrawingWidget::DrawingWidget(QWidget *parent) : QTreeWidget(parent) { setContextMenuPolicy(Qt::CustomContextMenu); setColumnCount(3); header()->resizeSection(0, 170); header()->resizeSection(1, 40); header()->resizeSection(2, 35); headerItem()->setText(0, "Frame - Drawings"); headerItem()->setText(1, "Color"); headerItem()->setText(2, "Hide"); // Shortcut for deleting item QShortcut* delete_sc = new QShortcut(QKeySequence::Delete, this); delete_sc->setContext(Qt::WidgetWithChildrenShortcut); connect(delete_sc, &QShortcut::activated, this, &DrawingWidget::delete_item); // Connects for items clicked or changed in tree connect(this, &DrawingWidget::itemClicked, this, &DrawingWidget::tree_item_clicked); connect(this, &DrawingWidget::customContextMenuRequested, this, &DrawingWidget::context_menu); connect(this, &DrawingWidget::currentItemChanged, this, [this]{ tree_item_clicked(currentItem());}); connect(this, &DrawingWidget::itemChanged, this, &DrawingWidget::item_changed); } void DrawingWidget::set_overlay(Overlay* overlay) { clear_overlay(); m_overlay = overlay; update_from_overlay(); connect(m_overlay, &Overlay::new_drawing, this, &DrawingWidget::add_drawing); connect(m_overlay, &Overlay::clean_overlay, this, &DrawingWidget::clear_overlay); connect(m_overlay, &Overlay::select_current, this, &DrawingWidget::set_current_selected); connect(m_overlay, &Overlay::set_tool_zoom, this, &DrawingWidget::set_tool_zoom); connect(m_overlay, &Overlay::set_tool_edit, this, &DrawingWidget::set_tool_edit); } void DrawingWidget::clear_overlay() { if (m_overlay != nullptr) { m_overlay->set_current_drawing(nullptr); save_item_data(); disconnect(m_overlay, &Overlay::new_drawing, this, &DrawingWidget::add_drawing); disconnect(m_overlay, &Overlay::clean_overlay, this, &DrawingWidget::clear_overlay); disconnect(m_overlay, &Overlay::select_current, this, &DrawingWidget::set_current_selected); disconnect(m_overlay, &Overlay::set_tool_zoom, this, &DrawingWidget::set_tool_zoom); disconnect(m_overlay, &Overlay::set_tool_edit, this, &DrawingWidget::set_tool_edit); m_overlay = nullptr; } clear(); } void DrawingWidget::set_video_project(VideoProject *vid_proj) { if (m_vid_proj != vid_proj) { m_vid_proj = vid_proj; set_overlay(vid_proj->get_overlay()); } } /** * @brief DrawingWidget::update_from_overlay * Creates tree from drawings in the overlay */ void DrawingWidget::update_from_overlay() { if (m_overlay == nullptr) return; for (auto& overlay : m_overlay->get_overlays()) { if (overlay.second.size() != 0) { // Check if the frame nr already exist in widget tree if (findItems(QString::number(overlay.first), Qt::MatchFixedString).empty()) { FrameItem* frame_item = new FrameItem(overlay.first); insertTopLevelItem(topLevelItemCount(), frame_item); add_drawings_to_frame(frame_item); dynamic_cast<QTreeWidgetItem*>(frame_item)->setExpanded(true); } } } } /** * @brief DrawingWidget::add_drawings_to_frame * Adds all drawings to the drawing widget tree * @param f_item */ void DrawingWidget::add_drawings_to_frame(FrameItem* f_item) { std::vector<Shapes*> list; try { list = m_overlay->get_overlays().at(f_item->get_frame()); } catch (const std::out_of_range& e) { qWarning() << "Can't load drawings, frame out of range"; return; } for (auto shape : list) { ShapeItem* s_item; switch (shape->get_shape()) { case RECTANGLE: { s_item = new RectItem(dynamic_cast<Rectangle*>(shape)); f_item->addChild(s_item); break; } case CIRCLE: { s_item = new CircleItem(dynamic_cast<Circle*>(shape)); f_item->addChild(s_item); break; } case LINE: { s_item = new LineItem(dynamic_cast<Line*>(shape)); f_item->addChild(s_item); break; } case ARROW: { s_item = new ArrowItem(dynamic_cast<Arrow*>(shape)); f_item->addChild(s_item); break; } case TEXT: { s_item = new TextItem(dynamic_cast<Text*>(shape)); f_item->addChild(s_item); break; } case PEN: { s_item = new PenItem(dynamic_cast<Pen*>(shape)); f_item->addChild(s_item); break; } default: break; } } } /** * @brief DrawingWidget::add_drawing * Slot function for when a new drawing is created. * Adds the drawing to the treeitem with the correct frame number * @param shape * @param frame_nr */ void DrawingWidget::add_drawing(Shapes *shape, int frame_nr) { blockSignals(true); FrameItem* frame_item; QList<QTreeWidgetItem*> list = findItems(QString::number(frame_nr), Qt::MatchFixedString); if (list.empty()) { frame_item = new FrameItem(frame_nr); add_item_in_order(frame_item); } else { frame_item = dynamic_cast<FrameItem*>(list.at(0)); } switch (shape->get_shape()) { case RECTANGLE: { RectItem* rect_item = new RectItem(dynamic_cast<Rectangle*>(shape)); frame_item->addChild(rect_item); frame_item->setExpanded(true); setCurrentItem(rect_item); break; } case CIRCLE: { CircleItem* circle_item = new CircleItem(dynamic_cast<Circle*>(shape)); frame_item->addChild(circle_item); frame_item->setExpanded(true); setCurrentItem(circle_item); break; } case LINE: { LineItem* line_item = new LineItem(dynamic_cast<Line*>(shape)); frame_item->addChild(line_item); frame_item->setExpanded(true); setCurrentItem(line_item); break; } case ARROW: { ArrowItem* arrow_item = new ArrowItem(dynamic_cast<Arrow*>(shape)); frame_item->addChild(arrow_item); frame_item->setExpanded(true); setCurrentItem(arrow_item); break; } case TEXT: { TextItem* text_item = new TextItem(dynamic_cast<Text*>(shape)); frame_item->addChild(text_item); frame_item->setExpanded(true); setCurrentItem(text_item); break; } case PEN: { PenItem* pen_item = new PenItem(dynamic_cast<Pen*>(shape)); frame_item->addChild(pen_item); frame_item->setExpanded(true); setCurrentItem(pen_item); break; } default: break; } blockSignals(false); } /** * @brief DrawingWidget::add_item_in_order * Adds item to the tree widget is ascending order. * Expects the tree widget to be sorted ascendingly and that the items have numbers as names. * @param item */ void DrawingWidget::add_item_in_order(FrameItem *item) { for (int i = 0; i < topLevelItemCount(); ++i) { int number = topLevelItem(i)->text(0).toInt(); if (item->get_frame() < number) { insertTopLevelItem(i, item); return; } } insertTopLevelItem(topLevelItemCount(), item); } /** * @brief DrawingWidget::save_item_data * Stores GUI information of each tree item into its data member * @param item */ void DrawingWidget::save_item_data(QTreeWidgetItem *item) { if (item == nullptr) item = invisibleRootItem(); for (auto i = 0; i < item->childCount(); ++i){ auto child = item->child(i); switch (child->type()) { case FRAME_ITEM: save_item_data(child); break; case RECT_ITEM: case CIRCLE_ITEM: case LINE_ITEM: case ARROW_ITEM: case PEN_ITEM: case TEXT_ITEM: { auto a_item = dynamic_cast<ShapeItem*>(child); a_item->update_shape_name(); break; } default: break; } } } void DrawingWidget::set_current_selected(Shapes* shape, int frame_nr) { QList<QTreeWidgetItem*> list = findItems(QString::number(frame_nr), Qt::MatchFixedString); if (list.empty()) return; FrameItem* frame_item = dynamic_cast<FrameItem*>(list.at(0)); for (int i = 0; i != frame_item->childCount(); ++i) { ShapeItem* shape_item = dynamic_cast<ShapeItem*>(frame_item->child(i)); if (shape_item->get_shape() == shape) { blockSignals(true); setCurrentItem(shape_item); blockSignals(false); return; } } } /** * @brief DrawingWidget::tree_item_clicked * Slot function for when a tree item is clicked. * Performs different operations based of the drawing type * @param item * @param col */ void DrawingWidget::tree_item_clicked(QTreeWidgetItem *item, const int &col) { if (!item) return; switch (item->type()) { case FRAME_ITEM: { emit set_current_drawing(nullptr); FrameItem* frame_item = dynamic_cast<FrameItem*>(item); VideoState state; state = m_vid_proj->get_video()->state; state.frame = frame_item->get_frame(); // Reset these to default values so the zoomer will fit to viewport state.center = QPoint(-1, -1); state.scale_factor = -1; emit jump_to_frame(m_vid_proj, state); break; } case RECT_ITEM: case CIRCLE_ITEM: case ARROW_ITEM: case LINE_ITEM: case PEN_ITEM: case TEXT_ITEM: { ShapeItem* shape_item = dynamic_cast<ShapeItem*>(item); Shapes* shape = shape_item->get_shape(); if (col == 1) { QColor color = QColorDialog::getColor(); if (color.isValid()) { shape->set_color(color); shape_item->update_shape_color(); } } else if (col == 2) { shape_item->update_show_icon(shape->toggle_show()); } emit set_tool_edit(); emit set_current_drawing(shape); VideoState state; state = m_vid_proj->get_video()->state; state.frame = shape->get_frame(); // Reset these to default values so the zoomer will fit to viewport state.center = QPoint(-1, -1); state.scale_factor = -1; emit jump_to_frame(m_vid_proj, state); break; } default: break; } } /** * @brief DrawingWidget::context_menu * @param point * Slot function triggered by customContextMenuRequested * Creates a context menu */ void DrawingWidget::context_menu(const QPoint &point) { if (m_vid_proj == nullptr) return; QMenu menu(this); QTreeWidgetItem* item = itemAt(point); if (item == nullptr) return; switch (item->type()) { case FRAME_ITEM: menu.addAction("Delete", this, &DrawingWidget::remove_item); break; case RECT_ITEM: case CIRCLE_ITEM: case LINE_ITEM: case ARROW_ITEM: case PEN_ITEM: case TEXT_ITEM: menu.addAction("Rename", this, &DrawingWidget::rename_item); menu.addAction("Delete", this, &DrawingWidget::remove_item); break; default: break; } menu.exec(mapToGlobal(point)); } /** * @brief DrawingWidget::rename_item * Slot function to start edit the current item */ void DrawingWidget::rename_item() { editItem(currentItem()); } /** * @brief DrawingWidget::item_changed * @param item * Slot function called on the signal itemChanged. * Updates the item with the newly entered name */ void DrawingWidget::item_changed(QTreeWidgetItem* item) { auto a_item = dynamic_cast<ShapeItem*>(item); a_item->update_shape_name(); m_overlay->set_overlay_changed(); if (item->type() == TEXT_ITEM) { Text* text = dynamic_cast<TextItem*>(item)->get_shape(); emit update_text(text->get_name(), text); } } /** * @brief DrawingWidget::remove_item * Slot function for removing the current item from the tree */ void DrawingWidget::remove_item() { remove_from_tree(currentItem()); } /** * @brief DrawingWidget::remove_item_frame * Called when a frame is removed from a sequence. * Updates the drawings and widget with the new frame numbers * @param frame */ void DrawingWidget::remove_item_frame(int frame) { blockSignals(true); auto root = invisibleRootItem(); bool found = false; QTreeWidgetItem* item = nullptr; for (int i = 0; i < root->childCount(); i++) { QTreeWidgetItem* t_item = root->child(i); if (found) { // Lowering frame by one FrameItem* f_item = dynamic_cast<FrameItem*>(t_item); f_item->set_frame(f_item->get_frame()-1); // Update all shapes with the new frame for (int j = 0; j < t_item->childCount(); j++) { ShapeItem* s_item = dynamic_cast<ShapeItem*>(t_item->child(j)); Shapes* shape = s_item->get_shape(); shape->set_frame(shape->get_frame()-1); } } if (t_item->text(0) == QString::number(frame) && !found) { item = t_item; found = true; } } if (found) { remove_from_tree(item); } m_overlay->remove_frame(frame); blockSignals(false); } void DrawingWidget::delete_item() { if (!currentItem() || m_overlay->get_tool() != EDIT) return; ShapeItem* item = dynamic_cast<ShapeItem*>(currentItem()); if (item->type() == FRAME_ITEM) { FrameItem* f_item = dynamic_cast<FrameItem*>(item); if (f_item->get_frame() == m_overlay->get_current_frame()) { QMessageBox msg_box; msg_box.setIcon(QMessageBox::Warning); msg_box.setMinimumSize(300,130); msg_box.setText("Deleting drawings on frame "+QString::number(f_item->get_frame())+"\n" "This will delete all drawings on this frame"); msg_box.setInformativeText("Do you wish to continue?"); msg_box.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msg_box.setDefaultButton(QMessageBox::No); int reply = msg_box.exec(); if (reply == QMessageBox::No) return; remove_from_tree(f_item); clearSelection(); } } else if (item->get_shape() != m_overlay->get_current_drawing()) { return; } else { remove_from_tree(item); clearSelection(); emit set_current_drawing(nullptr); } } /** * @brief DrawingWidget::remove_from_tree * @param item * Deletes item from the drawing tree. * Calls itself recusively in case of a frame_item with multiple drawings. * Also deletes the frame_item in case the item of the last drawing of that frame */ void DrawingWidget::remove_from_tree(QTreeWidgetItem *item) { Shapes* shape; QTreeWidgetItem* parent; switch (item->type()) { case FRAME_ITEM: while (item->childCount() != 0) { remove_from_tree(item->child(0)); } blockSignals(true); delete item; blockSignals(false); break; case RECT_ITEM: case CIRCLE_ITEM: case LINE_ITEM: case ARROW_ITEM: case TEXT_ITEM: case PEN_ITEM: shape = dynamic_cast<ShapeItem*>(item)->get_shape(); emit delete_drawing(shape); parent = item->parent(); delete item; blockSignals(true); if (parent->childCount() == 0) delete parent; blockSignals(false); break; default: break; } }
32.200401
104
0.628516
[ "shape", "vector" ]
6d2ccdd875710da01044fa63e91588754dd50fe1
948
cpp
C++
CNN/feature_layer_proxy.cpp
suiyili/projects
29b4ab0435c8994809113c444b3dea4fff60b75c
[ "MIT" ]
null
null
null
CNN/feature_layer_proxy.cpp
suiyili/projects
29b4ab0435c8994809113c444b3dea4fff60b75c
[ "MIT" ]
null
null
null
CNN/feature_layer_proxy.cpp
suiyili/projects
29b4ab0435c8994809113c444b3dea4fff60b75c
[ "MIT" ]
null
null
null
#include "feature_layer_proxy.hpp" #include "vector_allocator.hpp" #include <stdexcept> namespace cnn::layer { feature_layer_proxy::feature_layer_proxy(neuron_array_i &prev_layer, const neuron_indices &indices) noexcept : neurons_(init_neurons(prev_layer, indices)) {} simple_neuron_i &feature_layer_proxy::operator[](size_t ordinal) noexcept { return neurons_[ordinal]; } size_t feature_layer_proxy::size() const noexcept { return neurons_.size(); } std::pmr::vector<std::reference_wrapper<simple_neuron_i>> feature_layer_proxy::init_neurons(neuron_array_i &prev_layer, const neuron_indices &indices) noexcept { auto &allocator = get_allocator(); auto neurons = allocator.allocate<std::reference_wrapper<simple_neuron_i>>( indices.size()); for (auto &i : indices) neurons.emplace_back(prev_layer[i]); return neurons; } } // namespace cnn::layer
36.461538
80
0.71308
[ "vector" ]
6d2ea3b522b32706d621e6d4126c8c032690ed55
1,821
hh
C++
montage-tech/src/kware/demux_mp/live555/liveMedia/include/AMRAudioFileSource.hh
kuikuitage/NewCool-UC-3.1.0-priv
16198d4eae1dd1a1bf4f4ba4b54652688078c018
[ "Apache-2.0" ]
null
null
null
montage-tech/src/kware/demux_mp/live555/liveMedia/include/AMRAudioFileSource.hh
kuikuitage/NewCool-UC-3.1.0-priv
16198d4eae1dd1a1bf4f4ba4b54652688078c018
[ "Apache-2.0" ]
null
null
null
montage-tech/src/kware/demux_mp/live555/liveMedia/include/AMRAudioFileSource.hh
kuikuitage/NewCool-UC-3.1.0-priv
16198d4eae1dd1a1bf4f4ba4b54652688078c018
[ "Apache-2.0" ]
3
2016-05-03T05:57:19.000Z
2021-11-10T21:34:00.000Z
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) 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 **********/ // "liveMedia" // Copyright (c) 1996-2012 Live Networks, Inc. All rights reserved. // A source object for AMR audio files (as defined in RFC 3267, section 5) // C++ header #ifndef _AMR_AUDIO_FILE_SOURCE_HH #define _AMR_AUDIO_FILE_SOURCE_HH #ifndef _AMR_AUDIO_SOURCE_HH #include "AMRAudioSource.hh" #endif #ifndef __LINUX__ #include "sys_types.h" #include "drv_dev.h" #include "ufs.h" #include "ff.h" #endif class AMRAudioFileSource: public AMRAudioSource { public: static AMRAudioFileSource* createNew(UsageEnvironment& env, char const* fileName); private: #ifdef __LINUX__ AMRAudioFileSource(UsageEnvironment& env, FILE* fid, Boolean isWideband, unsigned numChannels); #else AMRAudioFileSource(UsageEnvironment& env, UFILE* fid, Boolean isWideband, unsigned numChannels); #endif // called only by createNew() virtual ~AMRAudioFileSource(); private: // redefined virtual functions: virtual void doGetNextFrame(); private: #ifdef __LINUX__ FILE* fFid; #else UFILE* fFid; #endif }; #endif
28.015385
77
0.752334
[ "object" ]
6d311d34f33791f98a051caf2ffe64edc7680242
3,117
cpp
C++
Game/Source/Coins.cpp
IsmaUPC/PlataformerGame
2daadee9ef4261a625cf2edd07dab0d12249a89b
[ "MIT" ]
null
null
null
Game/Source/Coins.cpp
IsmaUPC/PlataformerGame
2daadee9ef4261a625cf2edd07dab0d12249a89b
[ "MIT" ]
null
null
null
Game/Source/Coins.cpp
IsmaUPC/PlataformerGame
2daadee9ef4261a625cf2edd07dab0d12249a89b
[ "MIT" ]
2
2020-10-19T11:24:18.000Z
2020-12-06T17:57:00.000Z
#include "App.h" #include "Coins.h" #include "Audio.h" #include "Player.h" Coins::Coins(iPoint pos) : Entity() { name.Create("coins"); position = pos; } Coins::Coins(TypeEntity pTypeEntity, iPoint pPosition, float pVelocity, SDL_Texture* pTexture) : Entity(pTypeEntity, pPosition, pVelocity, pTexture) { name.Create("coins"); position = pPosition; } Coins::~Coins() {} bool Coins::Start() { coinAnimation = new Animation(); particleAnimation = new Animation(); entityData->currentAnimation= new Animation(); entityData->state = IDLE; active = true; texCoin = entityData->texture; coinFx= app->audio->LoadFx("Assets/Audio/Fx/coin.wav"); numPoints = 4; pointsCollision = new iPoint[4]{ { 0, 0 }, { 48 , 0 }, { 48,-48 }, { 0 ,-48 } }; coinAnimation->loop = true; coinAnimation->speed = 0.20f; for (int i = 0; i < 16; i++) coinAnimation->PushBack({ 0,(40 * i), 40, 40 }); particleAnimation->loop = false; particleAnimation->speed = 0.20f; for (int i = 0; i < 7; i++) particleAnimation->PushBack({ 40,(60 * i), 60, 60 }); return true; } bool Coins::Awake(pugi::xml_node& config) { LOG("Loading Coins Parser"); bool ret = true; return ret; } bool Coins::PreUpdate() { CurrentCoinAnimation(); iPoint currentPositionPlayer = app->player->playerData.position; iPoint auxPositionCoin[4]; if (entityData->state == DEAD) { isCollected = true; pendingToDelete = true; } else { for (int i = 0; i < 4; i++) { auxPositionCoin[i] = { position.x + pointsCollision[i].x, position.y + pointsCollision[i].y }; } iPoint auxPositionPlayer[6]; for (int i = 0; i < 6; i++) { auxPositionPlayer[i] = { currentPositionPlayer.x + app->player->playerData.pointsCollision[i].x, -48 + currentPositionPlayer.y + app->player->playerData.pointsCollision[i].y }; } if (collision.IsInsidePolygons(auxPositionPlayer, app->player->playerData.numPoints, auxPositionCoin, numPoints) && collision.IsInsidePolygons(auxPositionCoin, numPoints, auxPositionPlayer, app->player->playerData.numPoints) && entityData->state == IDLE) { entityData->state = DEADING; app->audio->PlayFx(coinFx); app->player->CoinPlus(); } if (entityData->state == DEADING && entityData->currentAnimation->HasFinished()) entityData->state = DEAD; } return false; } bool Coins::Update(float dt) { entityData->currentAnimation->Update(); entityData->currentAnimation->speed = (dt * 9); return true; } bool Coins::PostUpdate() { SDL_Rect rectCoins; rectCoins = entityData->currentAnimation->GetCurrentFrame(); app->render->DrawTexture(texCoin, position.x, position.y, &rectCoins); return true; } bool Coins::CleanUp() { if (!active) return true; app->audio->Unload1Fx(coinFx); delete coinAnimation; delete particleAnimation; delete pointsCollision; pendingToDelete = true; active = false; return true; } void Coins::CurrentCoinAnimation() { switch (entityData->state) { case IDLE: entityData->currentAnimation = coinAnimation; break; case DEADING: entityData->currentAnimation = particleAnimation; break; default: break; } }
20.24026
144
0.686237
[ "render" ]
6d3954b61e4065f5f0e169b18480c32b1d8e28bd
11,244
hpp
C++
trunk/win/Source/Includes/Boost/date_time/time_parsing.hpp
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
460
2016-01-13T12:49:34.000Z
2022-02-20T04:10:40.000Z
external/windows/boost/include/boost/date_time/time_parsing.hpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
24
2016-11-07T04:59:49.000Z
2022-03-14T06:34:12.000Z
external/windows/boost/include/boost/date_time/time_parsing.hpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
148
2016-01-17T03:16:43.000Z
2022-03-17T12:20:36.000Z
#ifndef _DATE_TIME_TIME_PARSING_HPP___ #define _DATE_TIME_TIME_PARSING_HPP___ /* Copyright (c) 2002,2003,2005 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/tokenizer.hpp" #include "boost/lexical_cast.hpp" #include "boost/date_time/date_parsing.hpp" #include "boost/cstdint.hpp" #include <iostream> namespace boost { namespace date_time { //! computes exponential math like 2^8 => 256, only works with positive integers //Not general purpose, but needed b/c std::pow is not available //everywehere. Hasn't been tested with negatives and zeros template<class int_type> inline int_type power(int_type base, int_type exponent) { int_type result = 1; for(int i = 0; i < exponent; ++i){ result *= base; } return result; } //! Creates a time_duration object from a delimited string /*! Expected format for string is "[-]h[h][:mm][:ss][.fff]". * If the number of fractional digits provided is greater than the * precision of the time duration type then the extra digits are * truncated. * * A negative duration will be created if the first character in * string is a '-', all other '-' will be treated as delimiters. * Accepted delimiters are "-:,.". */ template<class time_duration, class char_type> inline time_duration str_from_delimited_time_duration(const std::basic_string<char_type>& s) { unsigned short min=0, sec =0; int hour =0; bool is_neg = (s.at(0) == '-'); boost::int64_t fs=0; int pos = 0; typedef typename std::basic_string<char_type>::traits_type traits_type; typedef boost::char_separator<char_type, traits_type> char_separator_type; typedef boost::tokenizer<char_separator_type, typename std::basic_string<char_type>::const_iterator, std::basic_string<char_type> > tokenizer; typedef typename boost::tokenizer<char_separator_type, typename std::basic_string<char_type>::const_iterator, typename std::basic_string<char_type> >::iterator tokenizer_iterator; char_type sep_chars[5] = {'-',':',',','.'}; char_separator_type sep(sep_chars); tokenizer tok(s,sep); for(tokenizer_iterator beg=tok.begin(); beg!=tok.end();++beg){ switch(pos) { case 0: { hour = boost::lexical_cast<int>(*beg); break; } case 1: { min = boost::lexical_cast<unsigned short>(*beg); break; } case 2: { sec = boost::lexical_cast<unsigned short>(*beg); break; }; case 3: { int digits = static_cast<int>(beg->length()); //Works around a bug in MSVC 6 library that does not support //operator>> thus meaning lexical_cast will fail to compile. #if (defined(BOOST_MSVC) && (_MSC_VER < 1300)) // msvc wouldn't compile 'time_duration::num_fractional_digits()' // (required template argument list) as a workaround a temp // time_duration object was used time_duration td(hour,min,sec,fs); int precision = td.num_fractional_digits(); // _atoi64 is an MS specific function if(digits >= precision) { // drop excess digits fs = _atoi64(beg->substr(0, precision).c_str()); } else { fs = _atoi64(beg->c_str()); } #else int precision = time_duration::num_fractional_digits(); if(digits >= precision) { // drop excess digits fs = boost::lexical_cast<boost::int64_t>(beg->substr(0, precision)); } else { fs = boost::lexical_cast<boost::int64_t>(*beg); } #endif if(digits < precision){ // trailing zeros get dropped from the string, // "1:01:01.1" would yield .000001 instead of .100000 // the power() compensates for the missing decimal places fs *= power(10, precision - digits); } break; } }//switch pos++; } if(is_neg) { return -time_duration(hour, min, sec, fs); } else { return time_duration(hour, min, sec, fs); } } //! Creates a time_duration object from a delimited string /*! Expected format for string is "[-]h[h][:mm][:ss][.fff]". * If the number of fractional digits provided is greater than the * precision of the time duration type then the extra digits are * truncated. * * A negative duration will be created if the first character in * string is a '-', all other '-' will be treated as delimiters. * Accepted delimiters are "-:,.". */ template<class time_duration> inline time_duration parse_delimited_time_duration(const std::string& s) { return str_from_delimited_time_duration<time_duration,char>(s); } //! Utility function to split appart string inline bool split(const std::string& s, char sep, std::string& first, std::string& second) { int sep_pos = static_cast<int>(s.find(sep)); first = s.substr(0,sep_pos); second = s.substr(sep_pos+1); return true; } template<class time_type> inline time_type parse_delimited_time(const std::string& s, char sep) { typedef typename time_type::time_duration_type time_duration; typedef typename time_type::date_type date_type; //split date/time on a unique delimiter char such as ' ' or 'T' std::string date_string, tod_string; split(s, sep, date_string, tod_string); //call parse_date with first string date_type d = parse_date<date_type>(date_string); //call parse_time_duration with remaining string time_duration td = parse_delimited_time_duration<time_duration>(tod_string); //construct a time return time_type(d, td); } //! Parse time duration part of an iso time of form: [-]hhmmss[.fff...] (eg: 120259.123 is 12 hours, 2 min, 59 seconds, 123000 microseconds) template<class time_duration> inline time_duration parse_undelimited_time_duration(const std::string& s) { int precision = 0; { // msvc wouldn't compile 'time_duration::num_fractional_digits()' // (required template argument list) as a workaround, a temp // time_duration object was used time_duration tmp(0,0,0,1); precision = tmp.num_fractional_digits(); } // 'precision+1' is so we grab all digits, plus the decimal int offsets[] = {2,2,2, precision+1}; int pos = 0, sign = 0; int hours = 0; short min=0, sec=0; boost::int64_t fs=0; // increment one position if the string was "signed" if(s.at(sign) == '-') { ++sign; } // stlport choked when passing s.substr() to tokenizer // using a new string fixed the error std::string remain = s.substr(sign); /* We do not want the offset_separator to wrap the offsets, we * will never want to process more than: * 2 char, 2 char, 2 char, frac_sec length. * We *do* want the offset_separator to give us a partial for the * last characters if there were not enough provided in the input string. */ bool wrap_off = false; bool ret_part = true; boost::offset_separator osf(offsets, offsets+4, wrap_off, ret_part); typedef boost::tokenizer<boost::offset_separator, std::basic_string<char>::const_iterator, std::basic_string<char> > tokenizer; typedef boost::tokenizer<boost::offset_separator, std::basic_string<char>::const_iterator, std::basic_string<char> >::iterator tokenizer_iterator; tokenizer tok(remain, osf); for(tokenizer_iterator ti=tok.begin(); ti!=tok.end();++ti){ switch(pos) { case 0: { hours = boost::lexical_cast<int>(*ti); break; } case 1: { min = boost::lexical_cast<short>(*ti); break; } case 2: { sec = boost::lexical_cast<short>(*ti); break; } case 3: { std::string char_digits(ti->substr(1)); // digits w/no decimal int digits = static_cast<int>(char_digits.length()); //Works around a bug in MSVC 6 library that does not support //operator>> thus meaning lexical_cast will fail to compile. #if (defined(BOOST_MSVC) && (_MSC_VER <= 1200)) // 1200 == VC++ 6.0 // _atoi64 is an MS specific function if(digits >= precision) { // drop excess digits fs = _atoi64(char_digits.substr(0, precision).c_str()); } else if(digits == 0) { fs = 0; // just in case _atoi64 doesn't like an empty string } else { fs = _atoi64(char_digits.c_str()); } #else if(digits >= precision) { // drop excess digits fs = boost::lexical_cast<boost::int64_t>(char_digits.substr(0, precision)); } else if(digits == 0) { fs = 0; // lexical_cast doesn't like empty strings } else { fs = boost::lexical_cast<boost::int64_t>(char_digits); } #endif if(digits < precision){ // trailing zeros get dropped from the string, // "1:01:01.1" would yield .000001 instead of .100000 // the power() compensates for the missing decimal places fs *= power(10, precision - digits); } break; } }; pos++; } if(sign) { return -time_duration(hours, min, sec, fs); } else { return time_duration(hours, min, sec, fs); } } //! Parse time string of form YYYYMMDDThhmmss where T is delimeter between date and time template<class time_type> inline time_type parse_iso_time(const std::string& s, char sep) { typedef typename time_type::time_duration_type time_duration; typedef typename time_type::date_type date_type; //split date/time on a unique delimiter char such as ' ' or 'T' std::string date_string, tod_string; split(s, sep, date_string, tod_string); //call parse_date with first string date_type d = parse_undelimited_date<date_type>(date_string); //call parse_time_duration with remaining string time_duration td = parse_undelimited_time_duration<time_duration>(tod_string); //construct a time return time_type(d, td); } } }//namespace date_time #endif
34.919255
143
0.595251
[ "object" ]
6d3b550405af32dacac3ee3b0fce01fdc06cdca7
7,562
cc
C++
CondCore/SiStripPlugins/plugins/SiStripLorentzAngle_PayloadInspector.cc
yihui-lai/cmssw
ec61da59bdebc84a58d07d7e6d993b74bb7709ee
[ "Apache-2.0" ]
2
2018-06-01T05:18:55.000Z
2021-04-08T21:44:06.000Z
CondCore/SiStripPlugins/plugins/SiStripLorentzAngle_PayloadInspector.cc
yihui-lai/cmssw
ec61da59bdebc84a58d07d7e6d993b74bb7709ee
[ "Apache-2.0" ]
26
2018-10-30T12:47:58.000Z
2022-03-29T08:39:00.000Z
CondCore/SiStripPlugins/plugins/SiStripLorentzAngle_PayloadInspector.cc
p2l1pfp/cmssw
9bda22bf33ecf18dd19a3af2b3a8cbdb1de556a9
[ "Apache-2.0" ]
2
2020-03-20T18:46:13.000Z
2021-03-12T09:23:07.000Z
/*! \file SiStripLorentzAngle_PayloadInspector \Payload Inspector Plugin for SiStrip Lorentz angles \author M. Musich \version $Revision: 1.0 $ \date $Date: 2017/09/21 10:59:56 $ */ #include "CondCore/Utilities/interface/PayloadInspectorModule.h" #include "CondCore/Utilities/interface/PayloadInspector.h" #include "CondCore/CondDB/interface/Time.h" #include "CondFormats/SiStripObjects/interface/SiStripDetSummary.h" #include "CondFormats/SiStripObjects/interface/SiStripLorentzAngle.h" #include "CommonTools/TrackerMap/interface/TrackerMap.h" #include "CondCore/SiStripPlugins/interface/SiStripPayloadInspectorHelper.h" #include "CalibTracker/StandaloneTrackerTopology/interface/StandaloneTrackerTopology.h" #include <memory> #include <sstream> // include ROOT #include "TH2F.h" #include "TLegend.h" #include "TCanvas.h" #include "TLine.h" #include "TStyle.h" #include "TLatex.h" #include "TPave.h" #include "TPaveStats.h" #include "TGaxis.h" namespace { /************************************************ 1d histogram of SiStripLorentzAngle of 1 IOV *************************************************/ // inherit from one of the predefined plot class: Histogram1D class SiStripLorentzAngleValue : public cond::payloadInspector::Histogram1D<SiStripLorentzAngle> { public: SiStripLorentzAngleValue() : cond::payloadInspector::Histogram1D<SiStripLorentzAngle>( "SiStrip LorentzAngle values", "SiStrip LorentzAngle values", 100, 0.0, 0.05) { Base::setSingleIov(true); } bool fill() override { auto tag = PlotBase::getTag<0>(); for (auto const &iov : tag.iovs) { std::shared_ptr<SiStripLorentzAngle> payload = Base::fetchPayload(std::get<1>(iov)); if (payload.get()) { std::map<uint32_t, float> LAMap_ = payload->getLorentzAngles(); for (const auto &element : LAMap_) { fillWithValue(element.second); } } // payload } // iovs return true; } // fill }; /************************************************ TrackerMap of SiStrip Lorentz Angle *************************************************/ class SiStripLorentzAngle_TrackerMap : public cond::payloadInspector::PlotImage<SiStripLorentzAngle> { public: SiStripLorentzAngle_TrackerMap() : cond::payloadInspector::PlotImage<SiStripLorentzAngle>("Tracker Map SiStrip Lorentz Angle") { setSingleIov(true); } bool fill(const std::vector<std::tuple<cond::Time_t, cond::Hash> > &iovs) override { auto iov = iovs.front(); std::shared_ptr<SiStripLorentzAngle> payload = fetchPayload(std::get<1>(iov)); std::unique_ptr<TrackerMap> tmap = std::unique_ptr<TrackerMap>(new TrackerMap("SiStripLorentzAngle")); tmap->setPalette(1); std::string titleMap = "TrackerMap of SiStrip Lorentz Angle per module, payload : " + std::get<1>(iov); tmap->setTitle(titleMap); std::map<uint32_t, float> LAMap_ = payload->getLorentzAngles(); for (const auto &element : LAMap_) { tmap->fill(element.first, element.second); } // loop over the LA MAP std::pair<float, float> extrema = tmap->getAutomaticRange(); std::string fileName(m_imageFileName); // protect against uniform values (LA values are defined positive) if (extrema.first != extrema.second) { tmap->save(true, 0, 0, fileName); } else { tmap->save(true, extrema.first * 0.95, extrema.first * 1.05, fileName); } return true; } }; /************************************************ Plot Lorentz Angle averages by partition *************************************************/ class SiStripLorentzAngleByRegion : public cond::payloadInspector::PlotImage<SiStripLorentzAngle> { public: SiStripLorentzAngleByRegion() : cond::payloadInspector::PlotImage<SiStripLorentzAngle>("SiStripLorentzAngle By Region"), m_trackerTopo{StandaloneTrackerTopology::fromTrackerParametersXMLFile( edm::FileInPath("Geometry/TrackerCommonData/data/trackerParameters.xml").fullPath())} { setSingleIov(true); } bool fill(const std::vector<std::tuple<cond::Time_t, cond::Hash> > &iovs) override { auto iov = iovs.front(); std::shared_ptr<SiStripLorentzAngle> payload = fetchPayload(std::get<1>(iov)); SiStripDetSummary summaryLA{&m_trackerTopo}; std::map<uint32_t, float> LAMap_ = payload->getLorentzAngles(); for (const auto &element : LAMap_) { summaryLA.add(element.first, element.second); } std::map<unsigned int, SiStripDetSummary::Values> map = summaryLA.getCounts(); //========================= TCanvas canvas("Partion summary", "partition summary", 1200, 1000); canvas.cd(); auto h1 = std::unique_ptr<TH1F>(new TH1F("byRegion", "SiStrip LA average by partition;; average SiStrip Lorentz Angle [rad]", map.size(), 0., map.size())); h1->SetStats(false); canvas.SetBottomMargin(0.18); canvas.SetLeftMargin(0.17); canvas.SetRightMargin(0.05); canvas.Modified(); std::vector<int> boundaries; unsigned int iBin = 0; std::string detector; std::string currentDetector; for (const auto &element : map) { iBin++; int count = element.second.count; double mean = (element.second.mean) / count; if (currentDetector.empty()) currentDetector = "TIB"; switch ((element.first) / 1000) { case 1: detector = "TIB"; break; case 2: detector = "TOB"; break; case 3: detector = "TEC"; break; case 4: detector = "TID"; break; } h1->SetBinContent(iBin, mean); h1->GetXaxis()->SetBinLabel(iBin, SiStripPI::regionType(element.first).second); h1->GetXaxis()->LabelsOption("v"); if (detector != currentDetector) { boundaries.push_back(iBin); currentDetector = detector; } } h1->GetYaxis()->SetRangeUser(0., h1->GetMaximum() * 1.30); h1->SetMarkerStyle(20); h1->SetMarkerSize(1); h1->Draw("HIST"); h1->Draw("Psame"); canvas.Update(); TLine l[boundaries.size()]; unsigned int i = 0; for (const auto &line : boundaries) { l[i] = TLine(h1->GetBinLowEdge(line), canvas.GetUymin(), h1->GetBinLowEdge(line), canvas.GetUymax()); l[i].SetLineWidth(1); l[i].SetLineStyle(9); l[i].SetLineColor(2); l[i].Draw("same"); i++; } TLegend legend = TLegend(0.52, 0.82, 0.95, 0.9); legend.SetHeader((std::get<1>(iov)).c_str(), "C"); // option "C" allows to center the header legend.AddEntry(h1.get(), ("IOV: " + std::to_string(std::get<0>(iov))).c_str(), "PL"); legend.SetTextSize(0.025); legend.Draw("same"); std::string fileName(m_imageFileName); canvas.SaveAs(fileName.c_str()); return true; } private: TrackerTopology m_trackerTopo; }; } // namespace PAYLOAD_INSPECTOR_MODULE(SiStripLorentzAngle) { PAYLOAD_INSPECTOR_CLASS(SiStripLorentzAngleValue); PAYLOAD_INSPECTOR_CLASS(SiStripLorentzAngle_TrackerMap); PAYLOAD_INSPECTOR_CLASS(SiStripLorentzAngleByRegion); }
33.312775
119
0.602751
[ "geometry", "vector" ]
6d3cbf0d269e12a08fa7ade19568cbda6ba357b9
19,594
cpp
C++
cpp/src/python/libio.cpp
tensorframe/tensorframe
acf82407917224e8c44d6efb7421949bcdd1881a
[ "MIT" ]
null
null
null
cpp/src/python/libio.cpp
tensorframe/tensorframe
acf82407917224e8c44d6efb7421949bcdd1881a
[ "MIT" ]
null
null
null
cpp/src/python/libio.cpp
tensorframe/tensorframe
acf82407917224e8c44d6efb7421949bcdd1881a
[ "MIT" ]
null
null
null
/* Copyright (C) 2018 Anthony Potappel, The Netherlands. All Rights Reserved. * This work is licensed under the terms of the MIT license (for details, see attached LICENSE file). */ #include "libio.h" #include "tf_types.h" #include <string> #include <sstream> using namespace std; PyObject* pyobj__gpu_halloc(PyObject* self, PyObject* args){ // TODO: function does not yet contain proper eror checking. PyObject *tmp; char *string; if(!(tmp=PyTuple_GetItem(args, 0)) || PyLong_Check(tmp) != true){ PyErr_SetString(PyExc_ValueError, "pyobj__gpu_halloc(), input arguments needs to be a pylong"); return(NULL); } if(PyLong_AsLong(tmp) < (1024*1024)){ //TODO: set this through defined PyErr_SetString(PyExc_ValueError, "pyobj__gpu_halloc(), value must me bigger than 1MB"); return(NULL); } cu_malloc_carr(&string, (unsigned long long) PyLong_AsLong(tmp)); return(PyCapsule_New(string, "hostmemory_ptr", NULL)); } PyObject* pyobj__read_csv(PyObject* self, PyObject* args){ // TODO: function does not yet contain proper eror checking. char *arg_str = NULL; char *tmp = NULL; void *dest; struct file_object fobj; uint64_t no_columns; uint64_t j_col; uint8_t *columns; uint8_t *column_default; column_default = (uint8_t*) malloc(sizeof(uint8_t)); PyObject_Print(args, stdout, 0); PyObject *capsule_mem; PyObject *dtype_dict; PyObject *dtype_dict_obj; PyObject *dtype_tmp; if(!PyArg_ParseTuple(args, "sOO", &arg_str, &capsule_mem, &dtype_dict)){ PyErr_SetString(PyExc_ValueError, "pyobj__read_csv(), arguments require (str, memory obj, dict)"); return(NULL); } if(PyDict_Check(dtype_dict) != true){ PyErr_SetString(PyExc_ValueError, "pyobj__read_csv(), arguments require (str, memory obj, dict)"); return(NULL); } cpp__read_csv(arg_str, &fobj); // TODO: infer from first line + samples no_columns = fobj.dims[1]; // assume first datatype in list to be the default // TODO: infer a datatype default based on pre-sampling *column_default = 0; columns = (uint8_t*) malloc(sizeof(uint8_t) * (no_columns+1)); // check for a default datatype if((dtype_dict_obj = PyDict_GetItemString(dtype_dict, "__default__"))){ if(PyUnicode_Check(dtype_dict_obj) == true){ if(!(tmp=(char*)PyUnicode_DATA(dtype_dict_obj))){ PyErr_SetString(PyExc_ValueError, "__default__ key must be a string."); return(NULL); } _datatype_column_typebyname(tmp, column_default); for(j_col=0; j_col<no_columns; j_col++){ columns[j_col] = column_default[0];} }else{ // other types not yet supported PyErr_SetString(PyExc_ValueError, "__default__ key must be a string."); return(NULL); } } // check for per column settings if((dtype_dict_obj = PyDict_GetItemString(dtype_dict, "__columns__"))){ if(PyDict_Check(dtype_dict_obj) == true){ // TODO. Parse based on column names PyErr_SetString(PyExc_ValueError, "__columns__ dict object not yet supported."); return(NULL); } else if(PyList_Check(dtype_dict_obj) == true){ // Parse based on list of datatypes if(PyList_Size(dtype_dict_obj) != (Py_ssize_t) no_columns){ PyErr_SetString( PyExc_ValueError, ("__columns__ number of datatypes does not match number of columns. Required:" + std::to_string(no_columns)).c_str() ); return(NULL); } for(j_col=0; j_col<no_columns; j_col++){ if(!(dtype_tmp = PyList_GetItem(dtype_dict_obj, (Py_ssize_t) j_col)) || (PyUnicode_Check(dtype_tmp) != true) || !(tmp=(char*)PyUnicode_DATA(dtype_tmp)) ){ PyErr_SetString( PyExc_ValueError, ("__columns__ cant retrieve list item_no:" + std::to_string(j_col)).c_str() ); } if(_datatype_column_typebyname(tmp, &columns[j_col]) != true){ PyErr_SetString( PyExc_ValueError, ("__columns__ cant find datatype match on column:" + std::to_string(j_col)).c_str() ); return(NULL); } } } } columns[no_columns] = pow(2, 8) - 1; dest = (void*) PyCapsule_GetPointer(capsule_mem, "hostmemory_ptr"); // Parse raw data and put it in location dest cpp__parse_csv(&fobj, dest, columns); PyObject *array_list; cpp__new_arraylist(dest, &array_list, fobj.dims[1], fobj.dims[0], columns); free(fobj.offsets); free(fobj.dims); return array_list; }; PyObject* pyobj__write_csv(PyObject* self, PyObject* args){ // TODO: function does not yet contain proper eror checking. PyObject *input_str; PyObject *input_frame; PyObject *pyobj; PyObject *list_item_0; PyObject *list_item_1; Py_buffer *memory_buf; void *memory_ptr; char *outputfile; char *tmp_ptr; uint64_t ii; uint64_t no_columns; uint64_t no_rows; uint64_t *ptr_data; uint64_t *ptr_na; uint8_t *datatypes; uint8_t *strides; uint8_t *functionmap; // Verify input if(!PyArg_ParseTuple(args, "OO", &input_str, &input_frame) || PyUnicode_Check(input_str) != true || !(outputfile=(char*)PyUnicode_DATA(input_str)) || PyDict_Check(input_frame) != true ){ PyErr_SetString(PyExc_ValueError, "pyobj__write_csv() requires (str, tframe dict) as input."); return(NULL); } // Extract no_columns if(!(pyobj = PyDict_GetItemString(input_frame, "no_columns")) || PyLong_Check(pyobj) != true || sizeof(PyLong_AsLong(pyobj)) != sizeof(uint64_t) ){ PyErr_SetString( PyExc_ValueError, "pyobj__write_csv(). Error parsing \"no_columns\" value" ); return(NULL); } no_columns = (uint64_t) PyLong_AsLong(pyobj); // Extract no_rows if(!(pyobj = PyDict_GetItemString(input_frame, "no_rows")) || PyLong_Check(pyobj) != true || sizeof(PyLong_AsLong(pyobj)) != sizeof(uint64_t) ){ PyErr_SetString( PyExc_ValueError, "pyobj__write_csv(). Error parsing \"no_rows\" value" ); return(NULL); } no_rows = (uint64_t) PyLong_AsLong(pyobj); // Extract columns.datatypes if(!(pyobj = PyDict_GetItemString(input_frame, "columns")) || PyDict_Check(pyobj) != true || !(pyobj = PyDict_GetItemString(pyobj, "datatypes")) || PyList_Check(pyobj) != true || (uint64_t) PyList_Size(pyobj) != no_columns ){ PyErr_SetString( PyExc_ValueError, "pyobj__write_csv(). Error parsing \"datatypes\" value" ); return(NULL); } // Extract column (data-) types datatypes = (uint8_t*) malloc(sizeof(uint8_t) * no_columns); strides = (uint8_t*) malloc(sizeof(uint8_t) * no_columns); functionmap = (uint8_t*) malloc(sizeof(uint8_t) * no_columns); for(ii = 0; ii < no_columns; ii++){ if(!(list_item_0 = PyList_GetItem(pyobj, (Py_ssize_t) ii)) || (PyUnicode_Check(list_item_0) != true) || PyUnicode_GET_LENGTH(list_item_0) > 4 || !(tmp_ptr=(char*)PyUnicode_DATA(list_item_0)) || _datatype_column_typebyname(tmp_ptr, &datatypes[ii]) != true ){ PyErr_SetString( PyExc_ValueError, ("pyobj__write_csv(). Error parsing datatype, list_no: " + std::to_string(ii)).c_str() ); free(datatypes); free(strides); free(functionmap); return(NULL); } functionmap[ii] = _datatype_column_nobyid(datatypes[ii]); strides[ii] = TF_TYPES[functionmap[ii]].size; } // Extract memory pointers to both NaN and Data if(!(pyobj = PyDict_GetItemString(input_frame, "memory_ptr")) || PyList_Check(pyobj) != true || (uint64_t) PyList_Size(pyobj) != no_columns ){ PyErr_SetString( PyExc_ValueError, "pyobj__write_csv(). Error parsing \"memory_ptr\" value" ); free(datatypes); free(strides); free(functionmap); return(NULL); } ptr_data = (uint64_t*) malloc(sizeof(uint64_t) * no_columns); ptr_na = (uint64_t*) malloc(sizeof(uint64_t) * no_columns); for(ii = 0; ii < no_columns; ii++){ // memory_ptr is a list of lists (list_item_0 = first level, list_item_1 = second level) if(!(list_item_0 = PyList_GetItem(pyobj, (Py_ssize_t) ii)) || PyList_Check(list_item_0) != true || (uint64_t) PyList_Size(list_item_0) != 2 // Note. Expecting format: [NaN ptr, Data ptr] ){ PyErr_SetString( PyExc_ValueError, ("pyobj__write_csv(). Error parsing \"memory_ptr\", list_no: " + std::to_string(ii)).c_str() ); free(ptr_data); free(ptr_na); free(datatypes); free(strides); free(functionmap); return(NULL); } // Retrieve memory point object to NaN if(!(list_item_1 = PyList_GetItem(list_item_0, 0)) || PyMemoryView_Check(list_item_1) != true || !(memory_buf = PyMemoryView_GET_BUFFER(list_item_1)) || !(memory_ptr = (void*) memory_buf->buf) ){ PyErr_SetString( PyExc_ValueError, ("pyobj__write_csv(). Error parsing \"memory_ptr: NaN\", list_no: " + std::to_string(ii)).c_str() ); free(ptr_data); free(ptr_na); free(datatypes); free(strides); free(functionmap); return(NULL); } ptr_na[ii] = (uint64_t) memory_ptr; // Retrieve memory point object to Data if(!(list_item_1 = PyList_GetItem(list_item_0, 1)) || PyMemoryView_Check(list_item_1) != true || !(memory_buf = PyMemoryView_GET_BUFFER(list_item_1)) || !(memory_ptr = (void*) memory_buf->buf) ){ PyErr_SetString( PyExc_ValueError, ("pyobj__write_csv(). Error parsing \"memory_ptr: Data\", list_no: " + std::to_string(ii)).c_str() ); free(ptr_data); free(ptr_na); free(datatypes); free(strides); free(functionmap); return(NULL); } ptr_data[ii] = (uint64_t) memory_ptr; } // Create the frame object for passing it to our writer tf__frame *frame = (tf__frame*) malloc(sizeof(tf__frame)); if(!frame){ free(ptr_data); free(ptr_na); free(datatypes); free(strides); free(functionmap); return PyErr_NoMemory(); }; frame->no_columns = no_columns; frame->no_rows = no_rows; frame->ptr_data = ptr_data; frame->ptr_na = ptr_na; frame->datatypes = datatypes; frame->strides = strides; frame->functionmap = functionmap; // Write to csv try{ cpp__write_csvfile(outputfile, frame);} catch(int error_code){ PyErr_SetString( PyExc_ValueError, ("pyobj__write_csv()::cpp_write_csvfile(),error=" + to_string(error_code)).c_str() ); free(ptr_data); free(ptr_na); free(datatypes); free(strides); free(functionmap); free(frame); return(NULL); } free(ptr_data); free(ptr_na); free(datatypes); free(strides); free(functionmap); free(frame); // Return success return Py_BuildValue("i", 0); } PyObject* pyobj__generate_arrays(PyObject* self, PyObject* args){ // TODO: function does not yet contain proper eror checking. PyObject *input_memory_ptr; PyObject *input_rows; PyObject *input_list; PyObject *list_item; PyObject *dict_item; PyObject *array_list; uint32_t ii; uint32_t no_columns; uint8_t datatype; uint8_t *columns; uint64_t data_offset; uint8_t column_size; uint64_t offset_round;; void *dest; char *char_ptr; uint64_t no_rows; uint64_t min_value; uint64_t max_value; // Parse all input arguments into PyObjects if(!PyArg_ParseTuple(args, "OOO", &input_memory_ptr, &input_rows, &input_list) || PyCapsule_CheckExact(input_memory_ptr) != true || PyLong_Check(input_rows) != true || PyList_Check(input_list) != true || sizeof(PyLong_AsLong( input_rows)) != sizeof(uint64_t) ){ PyErr_SetString(PyExc_ValueError, "pyobj__generate_arrays() requires (pointer, long, list) as an input."); return(NULL); } no_rows = (uint64_t) PyLong_AsLong(input_rows); if((uint64_t) PyList_Size(input_list) > UINT32_MAX){ PyErr_SetString( PyExc_ValueError, ("pyobj__generate_arrays(). Input list exceeded max number of arrays. Max:" + std::to_string(UINT32_MAX)).c_str() ); return(NULL); } if((no_columns = (uint32_t) PyList_Size(input_list)) == 0){ Py_INCREF(Py_None); return Py_None; } // Allocate a data structure to hold column information tf_column_meta *columns_meta = (tf_column_meta*) malloc(no_columns * sizeof(tf_column_meta)); if(!columns_meta){ return PyErr_NoMemory();}; columns = (uint8_t*) malloc(sizeof(uint8_t) * no_columns); data_offset = 0; offset_round = 0; for(ii = 0; ii < no_columns; ii++){ // List items should be dicts if(!(list_item = PyList_GetItem(input_list, ii)) || PyDict_Check(list_item) != true ){ PyErr_SetString( PyExc_ValueError, ("pyobj__generate_arrays(). Error parsing item from list, list_no: " + std::to_string(ii)).c_str() ); free(columns); free(columns_meta); return(NULL); } // Retrieve datatype if(!(dict_item = PyDict_GetItemString(list_item, "datatype")) || PyUnicode_Check(dict_item) != true || PyUnicode_GET_LENGTH(dict_item) > 4 || !(char_ptr=(char*)PyUnicode_DATA(dict_item)) || _datatype_column_typebyname(char_ptr, &datatype) != true ){ PyErr_SetString( PyExc_ValueError, ("pyobj__generate_arrays(). Error parsing datatype, list_no: " + std::to_string(ii)).c_str() ); free(columns); free(columns_meta); return(NULL); } // Retrieve min_value if(!(dict_item = PyDict_GetItemString(list_item, "min_value")) || PyLong_Check(dict_item) != true || sizeof(PyLong_AsLong(dict_item)) != sizeof(uint64_t) ){ PyErr_SetString( PyExc_ValueError, ("pyobj__generate_arrays(). Error parsing min_value, list_no: " + std::to_string(ii)).c_str() ); free(columns); free(columns_meta); return(NULL); } min_value = (uint64_t) PyLong_AsLong(dict_item); // Retrieve max_value // NOTE: TEMPORARILY DISABLED DUE TO SEGFAULT ERRORS WHEN UNSIGNED 64B // LIKELY FIX BY PROPERLY SEPARATING SIGNED FROM UNSIGNED LONG LONGS //if(!(dict_item = PyDict_GetItemString(list_item, "max_value")) // || PyLong_Check(dict_item) != true // || sizeof(PyLong_AsLong(dict_item)) != sizeof(uint64_t) //){ // PyErr_SetString( // PyExc_ValueError, // ("pyobj__generate_arrays(). Error parsing max_value, list_no: " + std::to_string(ii)).c_str() // ); // free(columns); // free(columns_meta); // return(NULL); //} max_value = 0; // Write to column_meta struct columns_meta[ii].datatype = datatype; columns_meta[ii].no_items = no_rows; columns_meta[ii].min_value = min_value; columns_meta[ii].max_value = max_value; columns_meta[ii].offset = data_offset; columns[ii] = datatype; // Calculate offsets for next round column_size = TF_TYPES[_datatype_column_nobyid(datatype)].size; offset_round = (8 - ((column_size * no_rows) % 8)); // Begin of NA data_offset = data_offset + (no_rows * column_size) + offset_round; columns_meta[ii].offset_na = data_offset; // End of NA data_offset = data_offset + ((no_rows / 32) * 4) + (8 - (((no_rows / 32) * 4) % 8)); } dest = (void*) PyCapsule_GetPointer(input_memory_ptr, "hostmemory_ptr"); cu__generate_arrays(columns_meta, dest, (uint64_t) no_columns, no_rows); //, )stride_dest, no_columns, no_items); free(columns_meta); cpp__new_arraylist(dest, &array_list, no_columns, no_rows, columns); free(columns); return array_list; } PyMODINIT_FUNC PyInit_libio(void) { import_array(); return PyModule_Create(&cModPyDem_libio); } void cpp__new_arraylist(void *data, PyObject **list_ptr, uint64_t no_columns, uint64_t no_rows, uint8_t *columns){ // TODO: function does not yet contain proper eror checking. PyObject *array_list; PyObject *tmp_tuple; PyObject *op; PyArray_Descr *descr; PyObject *result_col; PyObject *result_na; uint64_t data_offset; uint8_t column_size; uint64_t offset_round;; char column_name[32]; npy_intp dimension[1]; npy_intp dimension_na[1]; dimension[0] = (int) no_rows; dimension_na[0] = (int) (no_rows / 32 * 1 + 1); npy_intp strides[1]; array_list = PyList_New((Py_ssize_t) no_columns); data_offset = 0; offset_round = 0; for(uint64_t j_col = 0; j_col < no_columns; j_col++){ //COLUMNS sprintf(column_name, "COL_%lu", j_col); op = Py_BuildValue("[(s,s)]", column_name, TF_TYPES[_datatype_column_nobyid(columns[j_col])].name); PyArray_DescrConverter(op, &descr); Py_DECREF(op); column_size = TF_TYPES[_datatype_column_nobyid(columns[j_col])].size; strides[0] = column_size; result_col = PyArray_NewFromDescr(&PyArray_Type, descr, 1, dimension, strides, ((char*) data + data_offset), 0, NULL); offset_round = (8 - ((column_size * no_rows) % 8)); //Begin of NA data_offset = data_offset + (no_rows * column_size) + offset_round; //NA COLUMNS op = Py_BuildValue("[(s,s)]", "", "<i4"); PyArray_DescrConverter(op, &descr); Py_DECREF(op); result_na = PyArray_NewFromDescr(&PyArray_Type, descr, 1, dimension_na, NULL, ((char*) data + data_offset), 0, NULL); //PUT INTO LIST tmp_tuple = PyTuple_New(2); PyTuple_SetItem(tmp_tuple, 0, (PyObject *) result_col); PyTuple_SetItem(tmp_tuple, 1, (PyObject *) result_na); PyList_SetItem(array_list, j_col, (PyObject *) tmp_tuple); data_offset = data_offset + ((no_rows / 32) * 4) + (8 - (((no_rows / 32) * 4) % 8)); } *list_ptr = array_list; }
32.986532
140
0.596713
[ "object" ]
6d3ee095ee15cd66e2b6a1930baebb6ab3fbe60f
726
cpp
C++
oi/tyvj/P1066/commit1.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
oi/tyvj/P1066/commit1.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
oi/tyvj/P1066/commit1.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef unsigned ValueType; #define loop(n) for(unsigned __loop__=0;__loop__<n;__loop__++) int main(int argc, char *argv[]) { ios::sync_with_stdio(false); int n; cin>>n; vector<ValueType> heaps; heaps.reserve(n); ValueType tmp; loop(n){ cin>>tmp; heaps.push_back(tmp); } std::sort(heaps.begin(),heaps.end()); unsigned energyCount=0; unsigned need; for(int i=0;i<heaps.size()-1;i++){ need=heaps[i]+heaps[i+1]; energyCount+=need; heaps[i+1]=need; } cout<<energyCount; return 0; } // function main
18.15
63
0.568871
[ "vector" ]
6d48a1107d93b5bfd84e313fc13ee9adb22b50aa
4,593
cpp
C++
externals/binaryen/src/passes/LocalCSE.cpp
caokun8008/ckeos
889093599eb59c90e4cbcff2817f4421302fada1
[ "MIT" ]
40
2018-05-14T11:05:03.000Z
2020-10-20T03:03:06.000Z
externals/binaryen/src/passes/LocalCSE.cpp
dimensionofficial/Dimension-E
a39533d4a457ce358185b4d0a5af544e742fc0ab
[ "MIT" ]
4
2018-06-07T02:32:21.000Z
2019-02-24T13:09:55.000Z
externals/binaryen/src/passes/LocalCSE.cpp
dimensionofficial/Dimension-E
a39533d4a457ce358185b4d0a5af544e742fc0ab
[ "MIT" ]
40
2018-03-06T09:22:02.000Z
2019-05-15T11:22:50.000Z
/* * Copyright 2017 WebAssembly Community Group participants * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // Local CSE // // In each linear area of execution, // * track each relevant (big enough) expression // * if already seen, write to a local if not already, and reuse // * invalidate the list as we see effects // // TODO: global, inter-block gvn etc. // #include <wasm.h> #include <wasm-builder.h> #include <wasm-traversal.h> #include <pass.h> #include <ast_utils.h> #include <ast/hashed.h> namespace wasm { const Index UNUSED = -1; struct LocalCSE : public WalkerPass<LinearExecutionWalker<LocalCSE>> { bool isFunctionParallel() override { return true; } Pass* create() override { return new LocalCSE(); } // information for an expression we can reuse struct UsableInfo { Expression** item; Index index; // if not UNUSED, then the local we are assigned to, use that to reuse us EffectAnalyzer effects; UsableInfo(Expression** item, PassOptions& passOptions) : item(item), index(UNUSED), effects(passOptions, *item) {} }; // a list of usables in a linear execution trace typedef HashedExpressionMap<UsableInfo> Usables; // locals in current linear execution trace, which we try to sink Usables usables; static void doNoteNonLinear(LocalCSE* self, Expression** currp) { self->usables.clear(); } void checkInvalidations(EffectAnalyzer& effects) { // TODO: this is O(bad) std::vector<HashedExpression> invalidated; for (auto& sinkable : usables) { if (effects.invalidates(sinkable.second.effects)) { invalidated.push_back(sinkable.first); } } for (auto index : invalidated) { usables.erase(index); } } std::vector<Expression*> expressionStack; static void visitPre(LocalCSE* self, Expression** currp) { // pre operations Expression* curr = *currp; EffectAnalyzer effects(self->getPassOptions()); if (effects.checkPre(curr)) { self->checkInvalidations(effects); } self->expressionStack.push_back(curr); } static void visitPost(LocalCSE* self, Expression** currp) { auto* curr = *currp; // main operations if (self->isRelevant(curr)) { self->handle(currp, curr); } // post operations EffectAnalyzer effects(self->getPassOptions()); if (effects.checkPost(curr)) { self->checkInvalidations(effects); } self->expressionStack.pop_back(); } // override scan to add a pre and a post check task to all nodes static void scan(LocalCSE* self, Expression** currp) { self->pushTask(visitPost, currp); WalkerPass<LinearExecutionWalker<LocalCSE>>::scan(self, currp); self->pushTask(visitPre, currp); } bool isRelevant(Expression* curr) { if (curr->is<GetLocal>()) { return false; // trivial, this is what we optimize to! } if (!isConcreteWasmType(curr->type)) { return false; // don't bother with unreachable etc. } if (EffectAnalyzer(getPassOptions(), curr).hasSideEffects()) { return false; // we can't combine things with side effects } // check what we care about TODO: use optimize/shrink levels? return Measurer::measure(curr) > 1; } void handle(Expression** currp, Expression* curr) { HashedExpression hashed(curr); auto iter = usables.find(hashed); if (iter != usables.end()) { // already exists in the table, this is good to reuse auto& info = iter->second; if (info.index == UNUSED) { // we need to assign to a local. create a new one auto index = info.index = Builder::addVar(getFunction(), curr->type); (*info.item) = Builder(*getModule()).makeTeeLocal(index, *info.item); } replaceCurrent( Builder(*getModule()).makeGetLocal(info.index, curr->type) ); } else { // not in table, add this, maybe we can help others later usables.emplace(std::make_pair(hashed, UsableInfo(currp, getPassOptions()))); } } }; Pass *createLocalCSEPass() { return new LocalCSE(); } } // namespace wasm
29.254777
119
0.674722
[ "vector" ]
6d49e0a67008c72be182cd5bf278400f0d3454d1
7,883
cpp
C++
tests/0109-auto_create_topics.cpp
1414945241/librdkafka
655863482f07fbea15c90404540d3ed98c78e8f2
[ "BSD-2-Clause-NetBSD", "Zlib", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
6,046
2015-01-03T15:07:32.000Z
2022-03-31T13:22:43.000Z
tests/0109-auto_create_topics.cpp
1414945241/librdkafka
655863482f07fbea15c90404540d3ed98c78e8f2
[ "BSD-2-Clause-NetBSD", "Zlib", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
4,247
2015-05-20T15:59:38.000Z
2022-03-31T23:19:12.000Z
plugins/out_kafka/librdkafka-1.7.0/tests/0109-auto_create_topics.cpp
zhenyami/fluent-bit
79f04c6c2ac0f3179165db99c6becdfa65d17f0d
[ "Apache-2.0" ]
3,015
2015-01-12T13:52:46.000Z
2022-03-31T15:09:08.000Z
/* * librdkafka - Apache Kafka C library * * Copyright (c) 2020, Magnus Edenhill * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <map> #include <cstring> #include <cstdlib> #include "testcpp.h" /** * Test consumer allow.auto.create.topics by subscribing to a mix * of available, unauthorized and non-existent topics. * * The same test is run with and without allow.auto.create.topics * and with and without wildcard subscribes. * */ static void do_test_consumer (bool allow_auto_create_topics, bool with_wildcards) { Test::Say(tostr() << _C_MAG << "[ Test allow.auto.create.topics=" << (allow_auto_create_topics ? "true":"false") << " with_wildcards=" << (with_wildcards ? "true":"false") << " ]\n"); bool has_acl_cli = test_broker_version >= TEST_BRKVER(2,1,0,0) && !test_needs_auth(); /* We can't bother passing Java security config to * kafka-acls.sh */ bool supports_allow = test_broker_version >= TEST_BRKVER(0,11,0,0); std::string topic_exists = Test::mk_topic_name("0109-exists", 1); std::string topic_notexists = Test::mk_topic_name("0109-notexists", 1); std::string topic_unauth = Test::mk_topic_name("0109-unauthorized", 1); /* Create consumer */ RdKafka::Conf *conf; Test::conf_init(&conf, NULL, 20); Test::conf_set(conf, "group.id", topic_exists); Test::conf_set(conf, "enable.partition.eof", "true"); /* Quickly refresh metadata on topic auto-creation since the first * metadata after auto-create hides the topic due to 0 partition count. */ Test::conf_set(conf, "topic.metadata.refresh.interval.ms", "1000"); if (allow_auto_create_topics) Test::conf_set(conf, "allow.auto.create.topics", "true"); std::string bootstraps; if (conf->get("bootstrap.servers", bootstraps) != RdKafka::Conf::CONF_OK) Test::Fail("Failed to retrieve bootstrap.servers"); std::string errstr; RdKafka::KafkaConsumer *c = RdKafka::KafkaConsumer::create(conf, errstr); if (!c) Test::Fail("Failed to create KafkaConsumer: " + errstr); delete conf; /* Create topics */ Test::create_topic(c, topic_exists.c_str(), 1, 1); if (has_acl_cli) { Test::create_topic(c, topic_unauth.c_str(), 1, 1); /* Add denying ACL for unauth topic */ test_kafka_cmd("kafka-acls.sh --bootstrap-server %s " "--add --deny-principal 'User:*' " "--operation All --deny-host '*' " "--topic '%s'", bootstraps.c_str(), topic_unauth.c_str()); } /* Wait for topic to be fully created */ test_wait_topic_exists(NULL, topic_exists.c_str(), 10*1000); /* * Subscribe */ std::vector<std::string> topics; std::map<std::string,RdKafka::ErrorCode> exp_errors; topics.push_back(topic_notexists); if (has_acl_cli) topics.push_back(topic_unauth); if (with_wildcards) { topics.push_back("^" + topic_exists); topics.push_back("^" + topic_notexists); /* If the subscription contains at least one wildcard/regex * then no auto topic creation will take place (since the consumer * requests all topics in metadata, and not specific ones, thus * not triggering topic auto creation). * We need to handle the expected error cases accordingly. */ exp_errors["^" + topic_notexists] = RdKafka::ERR_UNKNOWN_TOPIC_OR_PART; exp_errors[topic_notexists] = RdKafka::ERR_UNKNOWN_TOPIC_OR_PART; if (has_acl_cli) { /* Unauthorized topics are not included in list-all-topics Metadata, * which we use for wildcards, so in this case the error code for * unauthorixed topics show up as unknown topic. */ exp_errors[topic_unauth] = RdKafka::ERR_UNKNOWN_TOPIC_OR_PART; } } else { topics.push_back(topic_exists); if (has_acl_cli) exp_errors[topic_unauth] = RdKafka::ERR_TOPIC_AUTHORIZATION_FAILED; } if (supports_allow && !allow_auto_create_topics) exp_errors[topic_notexists] = RdKafka::ERR_UNKNOWN_TOPIC_OR_PART; RdKafka::ErrorCode err; if ((err = c->subscribe(topics))) Test::Fail("subscribe failed: " + RdKafka::err2str(err)); /* Start consuming until EOF is reached, which indicates that we have an * assignment and any errors should have been reported. */ bool run = true; while (run) { RdKafka::Message *msg = c->consume(tmout_multip(1000)); switch (msg->err()) { case RdKafka::ERR__TIMED_OUT: case RdKafka::ERR_NO_ERROR: break; case RdKafka::ERR__PARTITION_EOF: run = false; break; default: Test::Say("Consume error on " + msg->topic_name() + ": " + msg->errstr() + "\n"); std::map<std::string,RdKafka::ErrorCode>::iterator it = exp_errors.find(msg->topic_name()); /* Temporary unknown-topic errors are okay for auto-created topics. */ bool unknown_is_ok = allow_auto_create_topics && !with_wildcards && msg->err() == RdKafka::ERR_UNKNOWN_TOPIC_OR_PART && msg->topic_name() == topic_notexists; if (it == exp_errors.end()) { if (unknown_is_ok) Test::Say("Ignoring temporary auto-create error for topic " + msg->topic_name() + ": " + RdKafka::err2str(msg->err()) + "\n"); else Test::Fail("Did not expect error for " + msg->topic_name() + ": got: " + RdKafka::err2str(msg->err())); } else if (msg->err() != it->second) { if (unknown_is_ok) Test::Say("Ignoring temporary auto-create error for topic " + msg->topic_name() + ": " + RdKafka::err2str(msg->err()) + "\n"); else Test::Fail("Expected '" + RdKafka::err2str(it->second) + "' for " + msg->topic_name() + ", got " + RdKafka::err2str(msg->err())); } else { exp_errors.erase(msg->topic_name()); } break; } delete msg; } /* Fail if not all expected errors were seen. */ if (!exp_errors.empty()) Test::Fail(tostr() << "Expecting " << exp_errors.size() << " more errors"); c->close(); delete c; } extern "C" { int main_0109_auto_create_topics (int argc, char **argv) { /* Parameters: * allow auto create, with wildcards */ do_test_consumer(true, true); do_test_consumer(true, false); do_test_consumer(false, true); do_test_consumer(false, false); return 0; } }
35.669683
79
0.646328
[ "vector" ]
6d4cd71b30e94151542ea476f7fd6fd7cdaab360
22,404
cpp
C++
Prenotazione viaggi/main.cpp
Pall1n/Info_scuola
a81587786ebe71e2b8474b8a0cceebd8176a9c21
[ "MIT" ]
1
2022-01-26T11:21:04.000Z
2022-01-26T11:21:04.000Z
Prenotazione viaggi/main.cpp
Pall1n/Informatica_scuola
c259626e84d2d142cde45d37b9b7fafa7cb9ff90
[ "MIT" ]
null
null
null
Prenotazione viaggi/main.cpp
Pall1n/Informatica_scuola
c259626e84d2d142cde45d37b9b7fafa7cb9ff90
[ "MIT" ]
null
null
null
/* Consegna: Un'agenzia di viaggi effettua le prenotazioni per i voli della compagnia Rapisardi Airlines, che applica delle tariffe standard per le seguenti destinazioni: 1) Catania-Roma 30€; 2) Catania-Praga 55€; 3) Catania-New York 400€. Al momento della prenotazione il cliente dovrà indicare il numero di passeggeri da prenotare e l'eventuale supplemento del bagaglio in stiva, che corrisponde a €20 per le destinazioni europee e €50 per i voli intercontinentali. Nel mese di Novembre l'agenzia applica uno sconto del 10% se il costo della prenotazione è superiore a €500. Sul costo della prenotazione bisognerà calcolare le imposte di imbarco del 10% per destinazioni europee e del 17% per destinazioni intercontinentali. Visualizzare: 1) Il totale lordo della prenotazione (con i bagagli); 2) Le imposte di imbarco; 3) Lo sconto; 4) Il totale netto da pagare; 5) Il messaggio "Sconto d'autunno" se è stato applicato lo sconto di Novembre. Alla fine il programma dovrà prevedere il controllo dell'input in modo tale che non possano essere inseriti codici di destinazione diversi da quelli stabiliti. Se il cliente ha bagagli in stiva, visualizzare il messaggio: "Recarsi per il check-in allo sportello 8". */ #include <iostream> #include <vector> //Per il vettore multidimensionale dei viaggi, lo uso al posto di un array per rendere dinamico l'uso della memoria #include <string> /*Per la funzione stoi(), serve a trasformare una stringa di numeri in intero, lo uso per trasformare la stringa del prezzo dei viaggi in un int*/ #include <time.h> //Per la verifica se è Novembre #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> #endif using namespace std; vector<vector<vector<string>>> viaggi = { { {"Catania Fontanarossa", "CTA"}, {"Roma Fiumicino", "FCO", "Europeo", "30"}, {"Praga Vàclav Havel", "PRG", "Europeo", "55"}, {"New York John F. Kennedy Int.", "JFK", "Intercontinentale", "400"} }, { {"Test 2nd partenza", "TEST 2nd"}, {"Test1", "Tested1", "Europeo", "80"}, {"Test2", "Tested2", "Intercontinentale", "65"}, {"test", "Tested3", "Intercontinentale", "90"} } }; char alfabeto_controllo[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; int partenza, destinazione, passeggeri, bagagli; string data_partenza, data_ritorno, scelta, codice_p, codice_d, aeroporto_p, aeroporto_d; bool andata_ritorno, sconto_novembre; string colore_reset = "\033[0m"; time_t theTime = time(NULL); struct tm *aTime = localtime(&theTime); int anno = aTime->tm_year + 1900; int mese = aTime->tm_mon + 1; int giorno = aTime->tm_mday; class Programma{ public: void clear(){ #ifdef _WIN32 system("cls"); #else system("clear"); #endif } int verifica_int(int scelta){ while(cin.fail()){ cin.clear(); cout<<"Inserisci un numero! "; cin.ignore(10000, '\n'); cin>>scelta; } return scelta; } bool verifica_data(int GG, int MM, int AA){ if((GG < giorno && (MM <= mese && AA <= anno)) || AA < anno || (MM < mese && (AA <= anno))) return false; else if(MM < 0 || MM > 12) return false; else if(MM == 2){ if(AA%4 == 0){ if(GG > 29 || GG < 0) return false; } else{ if(GG > 28 || GG < 0) return false; } } else if(MM == 1 || MM == 3 || MM == 5 || MM == 7 || MM == 8 || MM == 10 || MM == 12){ if(GG > 31 || GG < 0) return false; } else if(GG > 30 || GG < 0) return false; return true; } string sistema_data(int gg, int mm, int aa){ string data; if(gg < 10 && mm < 10) data = "0" + to_string(gg) + "/0" + to_string(mm) + "/" + to_string(aa); else if(gg < 10) data = "0" + to_string(gg) + "/" + to_string(mm) + "/" + to_string(aa); else if(mm < 10) data = to_string(gg) + "/0" + to_string(mm) + "/" + to_string(aa); else data = to_string(gg) + "/" + to_string(mm) + "/" + to_string(aa); return data; } int homepage(){ int scelta_home = 0; while(scelta_home != 3 || scelta_home != 2 || scelta_home != 1){ cout<<"\033[1;96m"<<"========================================\n" "| RAPISARDI AIRLINES |\n" "========================================\n\n"<<colore_reset<< "Benvenuto, scegli un'opzione:\n" "1) Prenota viaggio;\n" "2) Informazioni su un viaggio;\n" "3) Esci.\n\n" "Scelta (indica il numero): "; cin>>scelta_home; scelta_home = verifica_int(scelta_home); clear(); if(scelta_home == 1 && mese == 11){ clear(); schermata_offerte(); } else if(scelta_home == 1){ clear(); partenze_funz(); } else if(scelta_home == 2){ clear(); informazioni_viaggio(); } else if(scelta_home == 3) exit(0); else{ cout<<"\nScelta non valida, riprova!\n"; sleep(1); clear(); } } return 0; } void schermata_offerte(){ string sconto_ok; sconto_novembre = true; cout<<"\033[1;96m"<<"====================================\n" "| SCONTO D'AUTUNNO |\n" "====================================\n\n"<<colore_reset<< "Solo per questo mese riceverai uno\n" "sconto del 10% in fase di pagamento\n" "se spendi più di 500€!\n\n" "\033[95m"<<"Scrivi qualsiasi cosa per continuare: "; cin>>sconto_ok; cout<<colore_reset; clear(); partenze_funz(); } void partenze_funz(){ partenza = 0; while(partenza <= 0 || partenza > viaggi.size()){ cout<<"\033[1;92m"<<"================================\n" "| PARTENZE |\n" "================================\n"<<colore_reset; cout<<"\nBenvenuto, da dove vuoi partire?\n"; for(int i = 0; i < viaggi.size(); i++){ cout<<i+1<<") "<<viaggi[i][0][0]<<endl; } cout<<"\nIndica il numero della scelta: "; cin>>partenza; partenza = verifica_int(partenza); if(partenza <= 0 || partenza > viaggi.size()){ cout<<"Scelta non valida, riprova.\n"; sleep(1); clear(); } } partenza -= 1; clear(); destinazioni_funz(); } void destinazioni_funz(){ destinazione = 0; while(destinazione <= 0 || destinazione > viaggi[partenza].size()-1){ cout<<"\033[1;92m"<<"====================================\n" "| DESTINAZIONI |\n" "====================================\n"<<colore_reset; cout<<"\nDestinazioni disponibili da "<<viaggi[partenza][0][1]<<":\n"; for(int i = 1; i < viaggi[partenza].size(); i++){ cout<<i<<") "<<viaggi[partenza][i][0]<<endl; } cout<<"\nIndica il numero della scelta: "; cin>>destinazione; destinazione = verifica_int(destinazione); if(destinazione <= 0 || destinazione > viaggi[partenza].size()-1){ cout<<"Scelta non valida, riprova.\n"; sleep(1); clear(); } } clear(); andata_funz(); } void andata_funz(){ int gg_andata = 0; int mm_andata = 0; int aa_andata = 0; while(!verifica_data(gg_andata, mm_andata, aa_andata)){ cout<<"\033[1;92m"<<"==================================================\n" "| DATA PARTENZA |\n" "==================================================\n"<<colore_reset; cout<<"\nData della partenza (GG/MM/AAAA) o giorno: "; cin>>gg_andata; gg_andata = verifica_int(gg_andata); if(cin.get() != '/'){ cout<<"Inserisci il mese/anno o mese: "; } cin>>mm_andata; mm_andata = verifica_int(mm_andata); if(cin.get() != '/'){ cout<<"Inserisci l'anno: "; } cin>>aa_andata; aa_andata = verifica_int(aa_andata); if(!verifica_data(gg_andata, mm_andata, aa_andata)){ cout<<"\nData non valida, riprova.\n"; sleep(1); clear(); } } data_partenza = sistema_data(gg_andata, mm_andata, aa_andata); scelta = ""; while(scelta != "si" && scelta != "no"){ cout<<"Vuoi prenotare pure il ritorno (si/no)? "; cin>>scelta; if(scelta == "si"){ andata_ritorno = true; clear(); ritorno_funz(gg_andata, mm_andata, aa_andata); } else if(scelta == "no"){ andata_ritorno = false; clear(); passeggeri_funz(); } else{ cout<<"\nScelta non valida, riprova!\n"; sleep(1); clear(); } } } void ritorno_funz(int gg_andata, int mm_andata, int aa_andata){ int gg_ritorno = 0; int mm_ritorno = 0; int aa_ritorno = 0; while(!verifica_data(gg_ritorno, mm_ritorno, aa_ritorno) && !((gg_andata < gg_ritorno && (mm_andata <= mm_ritorno && aa_andata <= aa_ritorno)) || aa_andata < aa_ritorno || (mm_andata < mm_ritorno && (aa_andata <= aa_ritorno)))){ cout<<"\033[1;92m"<<"==================================================\n" "| DATA RITORNO |\n" "==================================================\n"<<colore_reset; cout<<"\nData del ritorno (GG/MM/AAAA) o giorno: "; cin>>gg_ritorno; gg_ritorno = verifica_int(gg_ritorno); if(cin.get() != '/'){ cout<<"Inserisci il mese/anno o mese: "; } cin>>mm_ritorno; mm_ritorno = verifica_int(mm_ritorno); if(cin.get() != '/'){ cout<<"Inserisci l'anno: "; } cin>>aa_ritorno; aa_ritorno = verifica_int(aa_ritorno); if(!verifica_data(gg_ritorno, mm_ritorno, aa_ritorno) || !((gg_andata < gg_ritorno && (mm_andata <= mm_ritorno && aa_andata <= aa_ritorno)) || aa_andata < aa_ritorno || (mm_andata < mm_ritorno && (aa_andata <= aa_ritorno)))){ cout<<"\nData non valida, riprova.\n"; sleep(1); clear(); } } data_ritorno = sistema_data(gg_ritorno, mm_ritorno, aa_ritorno); clear(); passeggeri_funz(); } void passeggeri_funz(){ passeggeri = 0; while(passeggeri <= 0 || passeggeri > 9){ cout<<"\033[1;92m"<<"==============================================\n" "| N. PASSEGGERI |\n" "==============================================\n"<<colore_reset; cout<<"\nN. passeggeri ("<<viaggi[partenza][destinazione][3]<<"€ a persona, max. 9): "; cin>>passeggeri; passeggeri = verifica_int(passeggeri); if(passeggeri <= 0 || passeggeri > 9){ cout<<"Scelta non valida, riprova.\n"; sleep(1); clear(); } } clear(); bagagli_func(); } void bagagli_func(){ bagagli = -1; while(bagagli < 0 || bagagli > 9){ cout<<"\033[1;92m"<<"==============================================\n" "| N. BAGAGLI |\n" "==============================================\n"<<colore_reset; cout<<"\nN. bagagli in stiva ("; if(viaggi[partenza][destinazione][2] == "Europeo") cout<<20; else cout<<50; cout<<"€ ognuno, max.9): "; cin>>bagagli; bagagli = verifica_int(bagagli); if(bagagli < 0 || bagagli > 9){ cout<<"Numero di bagagli non valido, riprova.\n"; sleep(1); clear(); } } clear(); totale_func(); } void totale_func(){ int bagagli_prezzo, sconto, imposta, totale_lordo, totale_netto; int totale_char = 0; string codice_viaggio; codice_p = viaggi[partenza][0][1]; codice_d = viaggi[partenza][destinazione][1]; aeroporto_p = viaggi[partenza][0][0]; aeroporto_d = viaggi[partenza][destinazione][0]; if(viaggi[partenza][destinazione][2] == "Europeo") bagagli_prezzo = 20; else bagagli_prezzo = 50; if(viaggi[partenza][destinazione][2] == "Europeo") imposta = 10; else imposta = 17; totale_lordo = (passeggeri*stoi(viaggi[partenza][destinazione][3]) + (bagagli*bagagli_prezzo)); if(sconto_novembre && totale_lordo > 500) sconto = 10; else sconto = 0; totale_netto = totale_lordo + (totale_lordo*imposta/100) + (totale_lordo*sconto/100); scelta = ""; while(scelta != "si" && scelta != "no"){ cout<<"\033[1;92m"<<"================================================\n" "| RIEPILOGO VIAGGIO |\n" "================================================\n\n"<<colore_reset; cout<<"Viaggio: "<<codice_p<<"-"<<codice_d<<endl; cout<<"Aeroporto di partenza: "<<aeroporto_p<<endl; cout<<"Aeroporto di destinazione: "<<aeroporto_d<<endl; cout<<"Numero passeggeri: "<<passeggeri<<endl; cout<<"Numero bagagli: "<<bagagli<<endl<<endl; cout<<"Andata e ritorno: "; if(andata_ritorno) cout<<"si"<<endl; else cout<<"no"<<endl; cout<<"Data partenza: "<<data_partenza<<endl; if(andata_ritorno) cout<<"Data ritorno: "<<data_ritorno<<endl<<endl; cout<<"Totale lordo prenotazione (bagagli inclusi): "<<totale_lordo<<"€"<<endl; cout<<"Imposte applicate: "<<imposta<<"%"<<endl; if(sconto) cout<<"Sconto applicato: "<<sconto<<"%"<<endl; cout<<"Totale da pagare (sconto applicato): "<<totale_netto<<"€"<<endl; cout<<"\nEffettuare pagamento (si/no)? "; cin>>scelta; if(scelta == "si"){ if(andata_ritorno)codice_viaggio = {data_ritorno[8], char(passeggeri + '0'), data_ritorno[3], codice_d[1], char(bagagli + '0'), data_partenza[0], codice_p[2], data_ritorno[0], data_partenza[6], codice_p[0], data_partenza[1], data_ritorno[1], data_ritorno[7], codice_d[0], data_partenza[3], data_partenza[4], codice_d[2], data_ritorno[4], data_partenza[7], data_ritorno[9], codice_p[1], data_ritorno[6], data_partenza[8], data_partenza[9]}; else codice_viaggio = {char(passeggeri + '0'), codice_d[1], char(bagagli + '0'), data_partenza[0], codice_p[2], data_partenza[6], codice_p[0], data_partenza[1], codice_d[0], data_partenza[3], data_partenza[4], codice_d[2], data_partenza[7], codice_p[1], data_partenza[8], data_partenza[9]}; for(char x : codice_viaggio){ if(isdigit(x)) totale_char += (x - '0'); else totale_char += x; } codice_viaggio += {alfabeto_controllo[totale_char%26]}; cout<<"\nComplimenti, il pagamento è stato effettuato!\n"; if(bagagli) cout<<"Per il check-in recati allo sportello 8."<<endl; cout<<"Il codice del tuo viaggio è: "<<codice_viaggio<<endl; cout<<"Inserisci qualsiasi cosa per continuare: "; cin>>scelta; cout<<"\nRitorno alla homepage...\n"; sleep(1.5); clear(); homepage(); } else if(scelta == "no"){ cout<<"\nOperazione annullata, ritorno alla home...\n"; sleep(1.5); clear(); homepage(); } else{ cout<<"\nScelta non valida, riprova!\n"; sleep(1); clear(); } } } bool verifica_codice(string c){ int totale_char = 0; if(c.length() == 17){ if(isdigit(c[0]) && isdigit(c[2]) && isdigit(c[3]) && isdigit(c[5]) && isdigit(c[7]) && isdigit(c[9]) && isdigit(c[10]) && isdigit(c[12]) && isdigit(c[14]) && isdigit(c[15])){ codice_p = {c[6], c[13], c[4]}; for(int i = 0; i < viaggi.size(); i++){ if(codice_p == viaggi[i][0][1]){ codice_d = {c[8], c[1], c[11]}; for(int n = 1; n < viaggi[i].size(); n++){ if(codice_d == viaggi[i][n][1]){ for(char x : c){ if(isdigit(x)) totale_char += (x - '0'); else totale_char += x; } totale_char -= c[16]; if(alfabeto_controllo[totale_char%26] == c[16]){ passeggeri = c[0] - '0'; bagagli = c[2] - '0'; aeroporto_p = viaggi[i][0][0]; aeroporto_d = viaggi[i][n][0]; data_partenza = {c[3], c[7], '/', c[9], c[10], '/', c[5], c[12], c[14], c[15]}; andata_ritorno = false; return true; } } } } } return false; } else return false; } else if(c.length() == 25){ if(isdigit(c[0]) && isdigit(c[1]) && isdigit(c[2]) && isdigit(c[4]) && isdigit(c[5]) && isdigit(c[7]) && isdigit(c[8]) && isdigit(c[10]) && isdigit(c[11]) && isdigit(c[12]) && isdigit(c[14]) && isdigit(c[15]) && isdigit(c[17]) && isdigit(c[18]) && isdigit(c[19]) && isdigit(c[21]) && isdigit(c[22]) && isdigit(c[23])){ for(int i = 0; i < viaggi.size(); i++){ codice_p = {c[9], c[20], c[6]}; if(codice_p == viaggi[i][0][1]){ for(int n = 1; n < viaggi[i].size(); n++){ codice_d = {c[13], c[3], c[16]}; if(codice_d == viaggi[i][n][1]){ for(char x : c){ if(isdigit(x)) totale_char += (x - '0'); else totale_char += x; } totale_char -= c[24]; if(alfabeto_controllo[totale_char%26] == c[24]){ passeggeri = c[1] - '0'; bagagli = c[4] - '0'; aeroporto_p = viaggi[i][0][0]; aeroporto_d = viaggi[i][n][0]; data_partenza = {c[5], c[10], '/', c[14], c[15], '/', c[8], c[18], c[22], c[23]}; data_ritorno = {c[7], c[11], '/', c[2], c[17], '/', c[21], c[12], c[0], c[19]}; andata_ritorno = true; return true; } } } } } return false; } else return false; } else return false; } void informazioni_viaggio(){ string codice_viaggio; scelta = ""; while(!verifica_codice(codice_viaggio)){ cout<<"\033[1;92m"<<"========================================================\n" "| VERIFICA VIAGGIO |\n" "========================================================\n"<<colore_reset; cout<<"Inserisci il codice viaggio (maiuscolo): "; cin>>codice_viaggio; if(!verifica_codice(codice_viaggio)){ cout<<"\nCodice viaggio non valido, riprova! \n"; sleep(1); clear(); } } cout<<"\nViaggio: "<<codice_p<<"-"<<codice_d<<endl; cout<<"Aeroporto di partenza: "<<aeroporto_p<<endl; cout<<"Aeroporto di destinazione: "<<aeroporto_d<<endl; cout<<"Numero passeggeri: "<<passeggeri<<endl; cout<<"Numero bagagli: "<<bagagli<<endl<<endl; cout<<"Andata e ritorno: "; if(andata_ritorno) cout<<"si"<<endl; else cout<<"no"<<endl; cout<<"Data partenza: "<<data_partenza<<endl; if(andata_ritorno) cout<<"Data ritorno: "<<data_ritorno<<endl<<endl; cout<<"Inserisci qualsiasi cosa per tornare alla home: "; cin>>scelta; clear(); homepage(); } }; int main() { Programma programma; programma.homepage(); return 0; }
41.032967
455
0.447733
[ "vector" ]
6d50a9088848464308e5601fc6b6fe6ecae5000a
33,704
cpp
C++
gffread.cpp
ryomastumoto/Osara
6f5ffc8994c397af6015055edad702c3235d3fdb
[ "MIT" ]
null
null
null
gffread.cpp
ryomastumoto/Osara
6f5ffc8994c397af6015055edad702c3235d3fdb
[ "MIT" ]
null
null
null
gffread.cpp
ryomastumoto/Osara
6f5ffc8994c397af6015055edad702c3235d3fdb
[ "MIT" ]
null
null
null
#include "GArgs.h" #include "gff_utils.h" #include <ctype.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> #define VERSION "0.12.1" #define USAGE "gffread v" VERSION ". Usage:\n\ gffread <input_gff> [-g <genomic_seqs_fasta> | <dir>][-s <seq_info.fsize>] \n\ [-o <outfile>] [-t <trackname>] [-r [[<strand>]<chr>:]<start>..<end> [-R]]\n\ [-CTVNJMKQAFPGUBHZWTOLE] [-w <exons.fa>] [-x <cds.fa>] [-y <tr_cds.fa>]\n\ [-i <maxintron>] [--stream] [--bed] [--table <attrlist>] [--sort-by <ref.lst>]\n\ \n\ Filter, convert or cluster GFF/GTF/BED records, extract the sequence of\n\ transcripts (exon or CDS) and more.\n\ By default (i.e. without -O) only transcripts are processed, discarding any\n\ other non-transcript features. Default output is a simplified GFF3 with only\n\ the basic attributes.\n\ \n\ <input_gff> is a GFF file, use '-' for stdin\n\ \n\ Options:\n\ -i discard transcripts having an intron larger than <maxintron>\n\ -l discard transcripts shorter than <minlen> bases\n\ -r only show transcripts overlapping coordinate range <start>..<end>\n\ (on chromosome/contig <chr>, strand <strand> if provided)\n\ -R for -r option, discard all transcripts that are not fully \n\ contained within the given range\n\ -U discard single-exon transcripts\n\ -C coding only: discard mRNAs that have no CDS features\n\ --nc non-coding only: discard mRNAs that have CDS features\n\ --ignore-locus : discard locus features and attributes found in the input\n\ -A use the description field from <seq_info.fsize> and add it\n\ as the value for a 'descr' attribute to the GFF record\n\ -s <seq_info.fsize> is a tab-delimited file providing this info\n\ for each of the mapped sequences:\n\ <seq-name> <seq-length> <seq-description>\n\ (useful for -A option with mRNA/EST/protein mappings)\n\ Sorting: (by default, chromosomes are kept in the order they were found)\n\ --sort-alpha : chromosomes (reference sequences) are sorted alphabetically\n\ --sort-by : sort the reference sequences by the order in which their\n\ names are given in the <refseq.lst> file\n\ Misc options: \n\ -F preserve all GFF attributes (for non-exon features)\n\ --keep-exon-attrs : for -F option, do not attempt to reduce redundant\n\ exon/CDS attributes\n\ -G do not keep exon attributes, move them to the transcript feature\n\ (for GFF3 output)\n\ --keep-genes : in transcript-only mode (default), also preserve gene records\n\ --keep-comments: for GFF3 input/output, try to preserve comments\n\ -O process other non-transcript GFF records (by default non-transcript\n\ records are ignored)\n\ -V discard any mRNAs with CDS having in-frame stop codons (requires -g)\n\ -H for -V option, check and adjust the starting CDS phase\n\ if the original phase leads to a translation with an \n\ in-frame stop codon\n\ -B for -V option, single-exon transcripts are also checked on the\n\ opposite strand (requires -g)\n\ -P add transcript level GFF attributes about the coding status of each\n\ transcript, including partialness or in-frame stop codons (requires -g)\n\ --add-hasCDS : add a \"hasCDS\" attribute with value \"true\" for transcripts\n\ that have CDS features\n\ --adj-stop stop codon adjustment: enables -P and performs automatic\n\ adjustment of the CDS stop coordinate if premature or downstream\n\ -N discard multi-exon mRNAs that have any intron with a non-canonical\n\ splice site consensus (i.e. not GT-AG, GC-AG or AT-AC)\n\ -J discard any mRNAs that either lack initial START codon\n\ or the terminal STOP codon, or have an in-frame stop codon\n\ (i.e. only print mRNAs with a complete CDS)\n\ --no-pseudo: filter out records matching the 'pseudo' keyword\n\ --in-bed: input should be parsed as BED format (automatic if the input\n\ filename ends with .bed*)\n\ --in-tlf: input GFF-like one-line-per-transcript format without exon/CDS\n\ features (see --tlf option below); automatic if the input\n\ filename ends with .tlf)\n\ --stream: fast processing of input GFF/BED transcripts as they are received\n\ ((no sorting, exons must be grouped by transcript in the input data)\n\ Clustering:\n\ -M/--merge : cluster the input transcripts into loci, discarding\n\ \"duplicated\" transcripts (those with the same exact introns\n\ and fully contained or equal boundaries)\n\ -d <dupinfo> : for -M option, write duplication info to file <dupinfo>\n\ --cluster-only: same as -M/--merge but without discarding any of the\n\ \"duplicate\" transcripts, only create \"locus\" features\n\ -K for -M option: also discard as redundant the shorter, fully contained\n\ transcripts (intron chains matching a part of the container)\n\ -Q for -M option, no longer require boundary containment when assessing\n\ redundancy (can be combined with -K); only introns have to match for\n\ multi-exon transcripts, and >=80% overlap for single-exon transcripts\n\ -Y for -M option, enforce -Q but also discard overlapping single-exon \n\ transcripts, even on the opposite strand (can be combined with -K)\n\ Output options:\n\ --force-exons: make sure that the lowest level GFF features are considered\n\ \"exon\" features\n\ --gene2exon: for single-line genes not parenting any transcripts, add an\n\ exon feature spanning the entire gene (treat it as a transcript)\n\ --t-adopt: try to find a parent gene overlapping/containing a transcript\n\ that does not have any explicit gene Parent\n\ -D decode url encoded characters within attributes\n\ -Z merge very close exons into a single exon (when intron size<4)\n\ -g full path to a multi-fasta file with the genomic sequences\n\ for all input mappings, OR a directory with single-fasta files\n\ (one per genomic sequence, with file names matching sequence names)\n\ -w write a fasta file with spliced exons for each transcript\n\ --w-add <N> for the -w option, extract additional <N> bases\n\ both upstream and downstream of the transcript boundaries\n\ -x write a fasta file with spliced CDS for each GFF transcript\n\ -y write a protein fasta file with the translation of CDS for each record\n\ -W for -w and -x options, write in the FASTA defline all the exon\n\ coordinates projected onto the spliced sequence;\n\ -S for -y option, use '*' instead of '.' as stop codon translation\n\ -L Ensembl GTF to GFF3 conversion (implies -F; should be used with -m)\n\ -m <chr_replace> is a name mapping table for converting reference \n\ sequence names, having this 2-column format:\n\ <original_ref_ID> <new_ref_ID>\n\ -t use <trackname> in the 2nd column of each GFF/GTF output line\n\ -o write the records into <outfile> instead of stdout\n\ -T main output will be GTF instead of GFF3\n\ --bed output records in BED format instead of default GFF3\n\ --tlf output \"transcript line format\" which is like GFF\n\ but exons, CDS features and related data are stored as GFF \n\ attributes in the transcript feature line, like this:\n\ exoncount=N;exons=<exons>;CDSphase=<N>;CDS=<CDScoords> \n\ <exons> is a comma-delimited list of exon_start-exon_end coordinates;\n\ <CDScoords> is CDS_start:CDS_end coordinates or a list like <exons>\n\ --table output a simple tab delimited format instead of GFF, with columns\n\ having the values of GFF attributes given in <attrlist>; special\n\ pseudo-attributes (prefixed by @) are recognized:\n\ @id, @geneid, @chr, @start, @end, @strand, @numexons, @exons, \n\ @cds, @covlen, @cdslen\n\ If any of -w/-y/-x FASTA output files are enabled, the same fields\n\ (excluding @id) are appended to the definition line of corresponding\n\ FASTA records\n\ -v,-E expose (warn about) duplicate transcript IDs and other potential\n\ problems with the given GFF/GTF records\n\ " /* FILE* ffasta=NULL; FILE* f_in=NULL; FILE* f_out=NULL; FILE* f_w=NULL; //writing fasta with spliced exons (transcripts) int wPadding = 0; //padding for -w option FILE* f_x=NULL; //writing fasta with spliced CDS FILE* f_y=NULL; //wrting fasta with translated CDS bool wCDSonly=false; bool wNConly=false; int minLen=0; //minimum transcript length bool validCDSonly=false; // translation with no in-frame STOP bool bothStrands=false; //for single-exon mRNA validation, check the other strand too bool altPhases=false; //if original phase fails translation validation, //try the other 2 phases until one makes it bool addCDSattrs=false; bool add_hasCDS=false; //bool streamIn=false; // --stream option bool adjustStop=false; //automatic adjust the CDS stop coordinate bool covInfo=false; // --cov-info : only report genome coverage GStr tableFormat; //list of "attributes" to print in tab delimited format bool spliceCheck=false; //only known splice-sites bool decodeChars=false; //decode url-encoded chars in attrs (-D) bool StarStop=false; //use * instead of . for stop codon translation bool fullCDSonly=false; // starts with START, ends with STOP codon */ GStr sortBy; //file name with chromosomes listed in the desired order bool BEDinput=false; bool TLFinput=false; //--- output options /* extern bool fmtGFF3=true; //default output: GFF3 //other formats only make sense in transcriptOnly mode extern bool fmtGTF=false; extern bool fmtBED=false; extern bool fmtTLF=false; extern bool fmtTable=false; bool multiExon=false; bool writeExonSegs=false; char* tracklabel=NULL; char* rfltGSeq=NULL; char rfltStrand=0; uint rfltStart=0; uint rfltEnd=MAX_UINT; bool rfltWithin=false; //check for full containment within given range bool addDescr=false; */ //bool protmap=false; //int maxintron=999000000; //bool mergeCloseExons=false; //range filter: GffLoader gffloader; GList<GenomicSeqData> g_data(true,true,true); //list of GFF records by genomic seq void loadSeqInfo(FILE* f, GHash<SeqInfo> &si) { GLineReader fr(f); while (!fr.isEof()) { char* line=fr.getLine(); if (line==NULL) break; char* id=line; char* lenstr=NULL; char* text=NULL; char* p=line; while (*p!=0 && !isspace(*p)) p++; if (*p==0) continue; *p=0;p++; while (*p==' ' || *p=='\t') p++; if (*p==0) continue; lenstr=p; while (*p!=0 && !isspace(*p)) p++; if (*p!=0) { *p=0;p++; } while (*p==' ' || *p=='\t') p++; if (*p!=0) text=p; //else text remains NULL int len=0; if (!parseInt(lenstr,len)) { GMessage("Warning: could not parse sequence length: %s %s\n", id, lenstr); continue; } // --- here we have finished parsing the line si.Add(id, new SeqInfo(len,text)); } //while lines } void setTableFormat(GStr& s) { if (s.is_empty()) return; GHash<ETableFieldType> specialFields; specialFields.Add("chr", new ETableFieldType(ctfGFF_chr)); specialFields.Add("id", new ETableFieldType(ctfGFF_ID)); specialFields.Add("geneid", new ETableFieldType(ctfGFF_geneID)); specialFields.Add("genename", new ETableFieldType(ctfGFF_geneName)); specialFields.Add("parent", new ETableFieldType(ctfGFF_Parent)); specialFields.Add("feature", new ETableFieldType(ctfGFF_feature)); specialFields.Add("start", new ETableFieldType(ctfGFF_start)); specialFields.Add("end", new ETableFieldType(ctfGFF_end)); specialFields.Add("strand", new ETableFieldType(ctfGFF_strand)); specialFields.Add("numexons", new ETableFieldType(ctfGFF_numexons)); specialFields.Add("exons", new ETableFieldType(ctfGFF_exons)); specialFields.Add("cds", new ETableFieldType(ctfGFF_cds)); specialFields.Add("covlen", new ETableFieldType(ctfGFF_covlen)); specialFields.Add("cdslen", new ETableFieldType(ctfGFF_cdslen)); s.startTokenize(" ,;.:", tkCharSet); GStr w; while (s.nextToken(w)) { if (w[0]=='@') { w=w.substr(1); w.lower(); ETableFieldType* v=specialFields.Find(w.chars()); if (v!=NULL) { CTableField tcol(*v); tableCols.Add(tcol); } else GMessage("Warning: table field '@%s' not recognized!\n",w.chars()); continue; } if (w=="ID" || w=="transcript_id") { CTableField tcol(ctfGFF_ID); tableCols.Add(tcol); continue; } if (w=="geneID" || w=="gene_id") { CTableField tcol(ctfGFF_geneID); tableCols.Add(tcol); continue; } if (w=="geneID" || w=="gene_id") { CTableField tcol(ctfGFF_geneID); tableCols.Add(tcol); continue; } if (w=="Parent") { CTableField tcol(ctfGFF_Parent); tableCols.Add(tcol); continue; } CTableField col(w); tableCols.Add(col); } } void loadRefTable(FILE* f, GHash<RefTran>& rt) { GLineReader fr(f); char* line=NULL; while ((line=fr.getLine())) { char* orig_id=line; char* p=line; while (*p!=0 && !isspace(*p)) p++; if (*p==0) continue; *p=0;p++;//split the line here while (*p==' ' || *p=='\t') p++; if (*p==0) continue; rt.Add(orig_id, new RefTran(p)); } //while lines } void openfw(FILE* &f, GArgs& args, char opt) { GStr s=args.getOpt(opt); if (!s.is_empty()) { if (s=='-') f=stdout; else { f=fopen(s,"w"); if (f==NULL) GError("Error creating file: %s\n", s.chars()); } } } #define FWCLOSE(fh) if (fh!=NULL && fh!=stdout) fclose(fh) void printGff3Header(FILE* f, GArgs& args) { if (gffloader.keepGff3Comments) { for (int i=0;i<gffloader.headerLines.Count();i++) { fprintf(f, "%s\n", gffloader.headerLines[i]); } } else { fprintf(f, "##gff-version 3\n"); fprintf(f, "# gffread v" VERSION "\n"); fprintf(f, "# ");args.printCmdLine(f); } } void printGSeqHeader(FILE* f, GenomicSeqData* gdata) { if (f && gffloader.keepGff3Comments && gdata->seqreg_start>0 && gdata->seqreg_end>0) fprintf(f, "##sequence-region %s %d %d\n", gdata->gseq_name, gdata->seqreg_start, gdata->seqreg_end); } void processGffComment(const char* cmline, GfList* gflst) { if (cmline[0]!='#') return; const char* p=cmline; while (*p=='#') p++; GStr s(p); //this can be called only after gffloader initialization // so we can use gffloader.names->gseqs.addName() s.startTokenize("\t ", tkCharSet); GStr w; if (s.nextToken(w) && w=="sequence-region") { GStr chr, wend; if (s.nextToken(chr) && s.nextToken(w) && s.nextToken(wend)) { int gseq_id=gffloader.names->gseqs.addName(chr.chars()); if (gseq_id>=0) { GenomicSeqData* gseqdata=getGSeqData(g_data, gseq_id); gseqdata->seqreg_start=w.asInt(); gseqdata->seqreg_end=wend.asInt(); } else GError("Error adding ref seq ID %s\n", chr.chars()); } return; } if (gflst->Count()==0) { //initial Gff3 header, store it char* hl=Gstrdup(cmline); gffloader.headerLines.Add(hl); } } void printGffObj(FILE* f, GffObj* gfo, GStr& locname, GffPrintMode exonPrinting, int& out_counter) { GffObj& t=*gfo; GTData* tdata=(GTData*)(t.uptr); if (tdata->replaced_by!=NULL || !T_PRINTABLE(t.udata)) return; //if (t.exons.Count()==0 && t.children.Count()==0 && forceExons) // t.addExonSegment(t.start,t.end); T_NO_PRINT(t.udata); if (!fmtGFF3 && !gfo->isTranscript()) return; //only GFF3 prints non-transcript records (incl. parent genes) t.addAttr("locus", locname.chars()); out_counter++; if (fmtGFF3) { //print the parent first, if any and if not printed already if (t.parent!=NULL && T_PRINTABLE(t.parent->udata)) { GTData* pdata=(GTData*)(t.parent->uptr); if (pdata && pdata->geneinfo!=NULL) pdata->geneinfo->finalize(); t.parent->addAttr("locus", locname.chars()); t.parent->printGxf(f, exonPrinting, tracklabel, NULL, decodeChars); T_NO_PRINT(t.parent->udata); } } t.printGxf(f, exonPrinting, tracklabel, NULL, decodeChars); } void printAsTable(FILE* f, GffObj* gfo, int* out_counter=NULL) { GffObj& t=*gfo; GTData* tdata=(GTData*)(t.uptr); if (tdata->replaced_by!=NULL || !T_PRINTABLE(t.udata)) return; T_NO_PRINT(t.udata); if (out_counter!=NULL) (*out_counter)++; //print the parent first, if any and if not printed already if (t.parent!=NULL && T_PRINTABLE(t.parent->udata)) { GTData* pdata=(GTData*)(t.parent->uptr); if (pdata && pdata->geneinfo!=NULL) pdata->geneinfo->finalize(); //t.parent->addAttr("locus", locname.chars()); //(*out_counter)++; ? printTableData(f, *t.parent); T_NO_PRINT(t.parent->udata); } printTableData(f, *gfo); } void shutDown() { seqinfo.Clear(); //if (faseq!=NULL) delete faseq; //if (gcdb!=NULL) delete gcdb; GFREE(rfltGSeq); FWCLOSE(f_out); FWCLOSE(f_w); FWCLOSE(f_x); FWCLOSE(f_y); } int main(int argc, char* argv[]) { GArgs args(argc, argv, "version;debug;merge;stream;adj-stop;bed;in-bed;tlf;in-tlf;cluster-only;nc;cov-info;help;" "sort-alpha;keep-genes;w-add=;keep-comments;keep-exon-attrs;force-exons;t-adopt;gene2exon;" "ignore-locus;no-pseudo;table=sort-by=hvOUNHPWCVJMKQYTDARSZFGLEBm:g:i:r:s:l:t:o:w:x:y:d:"); args.printError(USAGE, true); if (args.getOpt('h') || args.getOpt("help")) { GMessage("%s",USAGE); exit(1); } debugMode=(args.getOpt("debug")!=NULL); decodeChars=(args.getOpt('D')!=NULL); gffloader.forceExons=(args.getOpt("force-exons")!=NULL); gffloader.streamIn=(args.getOpt("stream")!=NULL); gffloader.noPseudo=(args.getOpt("no-pseudo")!=NULL); gffloader.ignoreLocus=(args.getOpt("ignore-locus")!=NULL); gffloader.transcriptsOnly=(args.getOpt('O')==NULL); //sortByLoc=(args.getOpt('S')!=NULL); addDescr=(args.getOpt('A')!=NULL); verbose=(args.getOpt('v')!=NULL || args.getOpt('E')!=NULL); wCDSonly=(args.getOpt('C')!=NULL); wNConly=(args.getOpt("nc")!=NULL); addCDSattrs=(args.getOpt('P')!=NULL); add_hasCDS=(args.getOpt("add-hasCDS")!=NULL); adjustStop=(args.getOpt("adj-stop")!=NULL); if (adjustStop) addCDSattrs=true; validCDSonly=(args.getOpt('V')!=NULL); altPhases=(args.getOpt('H')!=NULL); fmtGTF=(args.getOpt('T')!=NULL); //switch output format to GTF fmtBED=(args.getOpt("bed")!=NULL); fmtTLF=(args.getOpt("tlf")!=NULL); if (fmtGTF || fmtBED || fmtTLF) { if (!gffloader.transcriptsOnly) { GMessage("Error: option -O is only supported with GFF3 output"); exit(1); } fmtGFF3=false; } BEDinput=(args.getOpt("in-bed")!=NULL); TLFinput=(args.getOpt("in-tlf")!=NULL); bothStrands=(args.getOpt('B')!=NULL); fullCDSonly=(args.getOpt('J')!=NULL); spliceCheck=(args.getOpt('N')!=NULL); StarStop=(args.getOpt('S')!=NULL); gffloader.keepGenes=(args.getOpt("keep-genes")!=NULL); gffloader.trAdoption=(args.getOpt("t-adopt")!=NULL); gffloader.keepGff3Comments=(args.getOpt("keep-comments")!=NULL); gffloader.sortRefsAlpha=(args.getOpt("sort-alpha")!=NULL); if (args.getOpt("sort-by")!=NULL) { if (gffloader.sortRefsAlpha) GError("Error: options --sort-by and --sort-alpha are mutually exclusive!\n"); sortBy=args.getOpt("sort-by"); } if (!sortBy.is_empty()) gffloader.loadRefNames(sortBy); gffloader.gene2exon=(args.getOpt("gene2exon")!=NULL); gffloader.matchAllIntrons=(args.getOpt('K')==NULL); gffloader.fuzzSpan=(args.getOpt('Q')!=NULL); gffloader.dOvlSET=(args.getOpt('Y')!=NULL); if (args.getOpt('M') || args.getOpt("merge")) { gffloader.doCluster=true; gffloader.collapseRedundant=true; } else { if (!gffloader.matchAllIntrons || gffloader.fuzzSpan || gffloader.dOvlSET) { GMessage("%s",USAGE); GMessage("Error: options -K,-Q,-Y require -M/--merge option!\n"); exit(1); } } if (args.getOpt("cluster-only")) { gffloader.doCluster=true; gffloader.collapseRedundant=false; if (!gffloader.matchAllIntrons || gffloader.fuzzSpan || gffloader.dOvlSET) { GMessage("%s",USAGE); GMessage("Error: option -K,-Q,-Y have no effect with --cluster-only.\n"); exit(1); } } if (gffloader.dOvlSET) gffloader.fuzzSpan=true; //-Q enforced by -Y covInfo=(args.getOpt("cov-info")); if (covInfo) gffloader.doCluster=true; //need to collapse overlapping exons if (fullCDSonly) validCDSonly=true; if (verbose) { fprintf(stderr, "Command line was:\n"); args.printCmdLine(stderr); } if (args.getOpt("version")) { GMessage(VERSION"\n"); exit(0); } gffloader.fullAttributes=(args.getOpt('F')!=NULL); gffloader.keep_AllExonAttrs=(args.getOpt("keep-exon-attrs")!=NULL); if (gffloader.keep_AllExonAttrs && !gffloader.fullAttributes) { GMessage("Error: option --keep-exon-attrs requires option -F !\n"); exit(0); } if (args.getOpt('G')==NULL) gffloader.gatherExonAttrs=!gffloader.fullAttributes; else { gffloader.gatherExonAttrs=true; gffloader.fullAttributes=true; } if (gffloader.noPseudo && !gffloader.fullAttributes) { gffloader.gatherExonAttrs=true; gffloader.fullAttributes=true; } ensembl_convert=(args.getOpt('L')!=NULL); if (ensembl_convert) { gffloader.fullAttributes=true; gffloader.gatherExonAttrs=false; //sortByLoc=true; } tableFormat=args.getOpt("table"); if (!tableFormat.is_empty()) { setTableFormat(tableFormat); fmtTable=true; fmtGFF3=false; gffloader.fullAttributes=true; } gffloader.mergeCloseExons=(args.getOpt('Z')!=NULL); multiExon=(args.getOpt('U')!=NULL); writeExonSegs=(args.getOpt('W')!=NULL); tracklabel=args.getOpt('t'); if (args.getOpt('g')) gfasta.init(args.getOpt('g')); //if (gfasta.fastaPath!=NULL) // sortByLoc=true; //enforce sorting by chromosome/contig GStr s=args.getOpt('i'); if (!s.is_empty()) maxintron=s.asInt(); s=args.getOpt('l'); if (!s.is_empty()) minLen=s.asInt(); TFilters=(multiExon || wCDSonly || wNConly); //TODO: all transcript filters should be included here through validateGffRec() FILE* f_repl=NULL; //duplicate/collapsing info output file s=args.getOpt('d'); if (!s.is_empty()) { if (s=="-") f_repl=stdout; else { f_repl=fopen(s.chars(), "w"); if (f_repl==NULL) GError("Error creating file %s\n", s.chars()); } } rfltWithin=(args.getOpt('R')!=NULL); s=args.getOpt('r'); if (!s.is_empty()) { s.trim(); if (s[0]=='+' || s[0]=='-') { rfltStrand=s[0]; s.cut(0,1); } int isep=s.index(':'); if (isep>0) { //gseq name given if (rfltStrand==0 && (s[isep-1]=='+' || s[isep-1]=='-')) { isep--; rfltStrand=s[isep]; s.cut(isep,1); } if (isep>0) rfltGSeq=Gstrdup((s.substr(0,isep)).chars()); s.cut(0,isep+1); } GStr gsend; char slast=s[s.length()-1]; if (rfltStrand==0 && (slast=='+' || slast=='-')) { s.chomp(slast); rfltStrand=slast; } if (s.index("..")>=0) gsend=s.split(".."); else gsend=s.split('-'); if (!s.is_empty()) rfltStart=(uint)s.asInt(); if (!gsend.is_empty()) { rfltEnd=(uint)gsend.asInt(); if (rfltEnd==0) rfltEnd=MAX_UINT; } } //gseq/range filtering else { if (rfltWithin) GError("Error: option -R requires -r!\n"); //if (rfltWholeTranscript) // GError("Error: option -P requires -r!\n"); } s=args.getOpt('m'); if (!s.is_empty()) { FILE* ft=fopen(s,"r"); if (ft==NULL) GError("Error opening reference table: %s\n",s.chars()); loadRefTable(ft, reftbl); fclose(ft); } s=args.getOpt('s'); if (!s.is_empty()) { FILE* fsize=fopen(s,"r"); if (fsize==NULL) GError("Error opening info file: %s\n",s.chars()); loadSeqInfo(fsize, seqinfo); fclose(fsize); } openfw(f_out, args, 'o'); //if (f_out==NULL) f_out=stdout; if (gfasta.fastaPath==NULL && (validCDSonly || spliceCheck || args.getOpt('w')!=NULL || args.getOpt('x')!=NULL || args.getOpt('y')!=NULL)) GError("Error: -g option is required for options -w, -x, -y, -V, -N, -M !\n"); openfw(f_w, args, 'w'); openfw(f_x, args, 'x'); openfw(f_y, args, 'y'); s=args.getOpt("w-add"); if (!s.is_empty()) { if (f_w==NULL) GError("Error: --w-add option requires -w option!\n"); wPadding=s.asInt(); } if (f_out==NULL && f_w==NULL && f_x==NULL && f_y==NULL && !covInfo) f_out=stdout; //if (f_y!=NULL || f_x!=NULL) wCDSonly=true; //useBadCDS=useBadCDS || (fgtfok==NULL && fgtfbad==NULL && f_y==NULL && f_x==NULL); int numfiles = args.startNonOpt(); //GList<GffObj> gfkept(false,true); //unsorted, free items on delete int out_counter=0; //number of records printed if (fmtGTF) exonPrinting = gffloader.forceExons ? pgtfBoth : pgtfAny; else if (fmtBED) exonPrinting=pgffBED; else if (fmtTLF) exonPrinting=pgffTLF; else { //printing regular GFF3 exonPrinting = gffloader.forceExons ? pgffBoth : pgffAny; } while (true) { GStr infile; if (numfiles) { infile=args.nextNonOpt(); if (infile.is_empty()) break; if (infile=="-") { f_in=stdin; infile="stdin"; } else if ((f_in=fopen(infile, "r"))==NULL) GError("Error: cannot open input file %s!\n",infile.chars()); else fclose(f_in); numfiles--; } else infile="-"; const char* fext=getFileExt(infile.chars()); if (BEDinput || (Gstricmp(fext, "bed")==0)) gffloader.BEDinput=true; if (TLFinput || (Gstricmp(fext, "tlf")==0)) gffloader.TLFinput=true; gffloader.openFile(infile); if (gffloader.streamIn) { //streaming in - disable all bulk load features gffloader.transcriptsOnly=true; gffloader.doCluster=false; covInfo=false; } gffloader.load(g_data, &processGffComment); if (gffloader.streamIn) { //we're done, GffLoader::load() took care of everything shutDown(); return 0; } // will also place the transcripts in loci, if doCluster is enabled if (gffloader.doCluster) collectLocusData(g_data, covInfo); if (numfiles==0) break; } if (covInfo) { //report coverage info at STDOUT uint64 f_bases=0; uint64 r_bases=0; uint64 u_bases=0; for (int g=0;g<g_data.Count();g++) { f_bases+=g_data[g]->f_bases; r_bases+=g_data[g]->r_bases; u_bases+=g_data[g]->u_bases; } fprintf(stdout, "Total bases covered by transcripts:\n"); if (f_bases>0) fprintf(stdout, "\t%" PRIu64 " on + strand\n", f_bases); if (r_bases>0) fprintf(stdout, "\t%" PRIu64 " on - strand\n", r_bases); if (u_bases>0) fprintf(stdout, "\t%" PRIu64 " on . strand\n", u_bases); } GStr loctrack("gffcl"); if (tracklabel) loctrack=tracklabel; if (gffloader.sortRefsAlpha) g_data.setSorted(&gseqCmpName); bool firstGff3Print=fmtGFF3; if (gffloader.doCluster) { //grouped in loci for (int g=0;g<g_data.Count();g++) { GenomicSeqData* gdata=g_data[g]; bool firstGSeqHeader=fmtGFF3; if (f_out && fmtGFF3 && gffloader.keepGff3Comments && gdata->seqreg_start>0) fprintf(f_out, "##sequence-region %s %d %d\n", gdata->gseq_name, gdata->seqreg_start, gdata->seqreg_end); for (int l=0;l<gdata->loci.Count();l++) { bool firstLocusPrint=true; GffLocus& loc=*(gdata->loci[l]); //check all non-replaced transcripts in this locus: int numvalid=0; int idxfirstvalid=-1; for (int i=0;i<loc.rnas.Count();i++) { GffObj& t=*(loc.rnas[i]); GTData* tdata=(GTData*)(t.uptr); if (tdata->replaced_by!=NULL) { if (f_repl && T_DUPSHOWABLE(t.udata)) { fprintf(f_repl, "%s", t.getID()); GTData* rby=tdata; while (rby->replaced_by!=NULL) { fprintf(f_repl," => %s", rby->replaced_by->getID()); T_NO_DUPSHOW(rby->rna->udata); rby=(GTData*)(rby->replaced_by->uptr); } fprintf(f_repl, "\n"); } T_NO_PRINT(t.udata); if (verbose) { GMessage("Info: %s discarded: superseded by %s\n", t.getID(), tdata->replaced_by->getID()); } continue; } //restore strand for dOvlSET char orig_strand=T_OSTRAND(t.udata); if (orig_strand!=0) t.strand=orig_strand; if (process_transcript(gfasta, t)) { numvalid++; if (idxfirstvalid<0) idxfirstvalid=i; } } //for each transcript int rnas_i=0; if (idxfirstvalid>=0) rnas_i=idxfirstvalid; int gfs_i=0; if (f_out) { GStr locname("RLOC_"); locname.appendfmt("%08d",loc.locus_num); //GMessage("Locus: %s (%d-%d), %d rnas, %d gfs\n", locname.chars(), loc.start, loc.end, // loc.rnas.Count(), loc.gfs.Count()); while (gfs_i<loc.gfs.Count() || rnas_i<loc.rnas.Count()) { if (gfs_i<loc.gfs.Count() && (rnas_i>=loc.rnas.Count() || loc.gfs[gfs_i]->start<=loc.rnas[rnas_i]->start) ) { //print the gene object first if (fmtGFF3) { //BED, TLF and GTF: only show transcripts if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } if (firstGSeqHeader) { printGSeqHeader(f_out, gdata); firstGSeqHeader=false; } if (firstLocusPrint) { loc.print(f_out, idxfirstvalid, locname, loctrack); firstLocusPrint=false; } printGffObj(f_out, loc.gfs[gfs_i], locname, exonPrinting, out_counter); } ++gfs_i; continue; } if (rnas_i<loc.rnas.Count()) { //loc.rnas[rnas_i]->printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); if (fmtGFF3) { if (firstGff3Print) { printGff3Header(f_out, args); firstGff3Print=false; } if (firstGSeqHeader) { printGSeqHeader(f_out, gdata); firstGSeqHeader=false; } if (firstLocusPrint) { loc.print(f_out, idxfirstvalid, locname, loctrack); firstLocusPrint=false; } } if (fmtTable) printAsTable(f_out, loc.rnas[rnas_i], &out_counter); else printGffObj(f_out, loc.rnas[rnas_i], locname, exonPrinting, out_counter); ++rnas_i; } } } }//for each locus } //for each genomic sequence } //if Clustering enabled else { //no clustering //not grouped into loci, print the rnas with their parents, if any int numvalid=0; for (int g=0;g<g_data.Count();g++) { GenomicSeqData* gdata=g_data[g]; bool firstGSeqHeader=fmtGFF3; int gfs_i=0; for (int m=0;m<gdata->rnas.Count();m++) { GffObj& t=*(gdata->rnas[m]); if (f_out && (fmtGFF3 || fmtTable)) { //print other non-transcript (gene?) feature that might be there before t while (gfs_i<gdata->gfs.Count() && gdata->gfs[gfs_i]->start<=t.start) { GffObj& gfst=*(gdata->gfs[gfs_i]); if (TFilters && gfst.isGene() && gfst.children.Count()==0) // gene with no children left, skip it if filters were applied { ++gfs_i; continue; } if T_PRINTABLE(gfst.udata) { //never printed T_NO_PRINT(gfst.udata); if (fmtGFF3) { if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } if (firstGSeqHeader) { printGSeqHeader(f_out, gdata); firstGSeqHeader=false; } gfst.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } else printTableData(f_out, gfst); } ++gfs_i; } } GTData* tdata=(GTData*)(t.uptr); if (tdata->replaced_by!=NULL) continue; if (process_transcript(gfasta, t)) { numvalid++; if (f_out && T_PRINTABLE(t.udata) ) { T_NO_PRINT(t.udata); if (fmtGFF3 || fmtTable || t.isTranscript()) { if (tdata->geneinfo) tdata->geneinfo->finalize(); out_counter++; if (fmtGFF3) { if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } if (firstGSeqHeader) { printGSeqHeader(f_out, gdata); firstGSeqHeader=false; } } //for GFF3 && table output, print the parent first, if any if ((fmtGFF3 || fmtTable) && t.parent!=NULL && T_PRINTABLE(t.parent->udata)) { //GTData* pdata=(GTData*)(t.parent->uptr); //if (pdata && pdata->geneinfo!=NULL) // pdata->geneinfo->finalize(); if (fmtTable) printTableData(f_out, *(t.parent)); else { //GFF3 output t.parent->printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } T_NO_PRINT(t.parent->udata); } if (fmtTable) printTableData(f_out, t); else t.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } }//GFF/GTF output requested } //valid transcript } //for each rna //print the rest of the isolated pseudo/gene/region features not printed yet if (f_out && (fmtGFF3 || fmtTable)) { while (gfs_i<gdata->gfs.Count()) { GffObj& gfst=*(gdata->gfs[gfs_i]); if T_PRINTABLE(gfst.udata) { //never printed T_NO_PRINT(gfst.udata); if (fmtGFF3) { if (firstGff3Print) { printGff3Header(f_out, args); firstGff3Print=false; } if (firstGSeqHeader) { printGSeqHeader(f_out, gdata); firstGSeqHeader=false; } gfst.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } else printTableData(f_out, gfst); } ++gfs_i; } } } //for each genomic seq } //no clustering if (f_repl && f_repl!=stdout) fclose(f_repl); shutDown(); }
37.869663
139
0.64028
[ "object" ]
6d51bb56f8d75ef6bf4c08a5f5f750291a713d96
1,860
cpp
C++
codes/mock/26/2.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/mock/26/2.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/mock/26/2.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
//misaka will carry me to master #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <utility> #include <cassert> #include <algorithm> #include <vector> #include <functional> #include <numeric> #include <set> #include <map> #define ll long long #define lb long double #define sz(vec) ((int)(vec.size())) #define all(x) x.begin(), x.end() #define pb push_back #define mp make_pair const lb eps = 1e-9; const ll mod = 1e9 + 7, ll_max = 1e18; //const ll mod = (1 << (23)) * 119 +1; const int MX = 3e5 +10, int_max = 0x3f3f3f3f; using namespace std; #define int ll ll arr[MX]; ll cnt[60]; int n; ll xall(ll x){ ll ans = 0; for(int j = 0; j < 31; j++){ if(x&(1 << j)){ ans += 1ll * (n - cnt[j]) * (1ll << j); } else{ ans += 1ll * cnt[j] * (1ll << j); } } return ans; } int check(ll x, ll y){ ll tot1 = 0, tot2 = 0; if(n < 2e3){ for(int i = 0; i<n; i++) tot1 += arr[i]^x; for(int i = 0; i<n; i++) tot2 += arr[i]^y; }else{ tot1 = xall(x); tot2 = xall(y); } return tot1 < tot2; } void reset(){ memset(cnt, 0, sizeof(cnt)); for(int i = 0; i<n; i++){ for(int j = 0; (1 << j) <= arr[i]; j++){ if(arr[i]&(1 << j)) cnt[j]++; } } } void solve(){ cin >> n; for(int i = 0; i<n; i++) cin >> arr[i]; ll cur = 1; while(cur < (1ll << 40)){ ll best = 0; reset(); for(int j = 0; j<n; j++){ if(arr[j] >= cur && check(best, arr[j])){ best = arr[j]; } } //cout << best << "\n"; if(best != 0){ for(int j = 0; j<n; j++) arr[j] ^= best; }else{ break; } ////for(int j = 0; j<n; j++) cout << arr[j] << " "; cout << "\n"; while(cur <= best) cur *= 2ll; } ll ans = 0; for(int i = 0; i<n; i++){ ans += arr[i]; } cout << ans << "\n"; } signed main(){ cin.tie(0) -> sync_with_stdio(0); int T = 1; //cin >> T; while(T--){ solve(); } return 0; }
16.607143
67
0.514516
[ "vector" ]
6d5669fe8a9e99d6a2f17d0e4b3c88473a075479
4,169
hpp
C++
SU2-Quantum/SU2_CFD/include/interfaces/cfd/CMixingPlaneInterface.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/include/interfaces/cfd/CMixingPlaneInterface.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/include/interfaces/cfd/CMixingPlaneInterface.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file CMixingPlaneInterface.cpp * \brief Declaration and inlines of the class to transfer average variables * needed for MixingPlane computation from a generic zone into another one. * \author S. Vitale * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "../CInterface.hpp" class CMixingPlaneInterface : public CInterface { public: /*! * \brief Constructor of the class. */ CMixingPlaneInterface(void); /*! * \overload * \param[in] val_nVar - Number of variables that need to be transferred. * \param[in] config - Definition of the particular problem. */ CMixingPlaneInterface(unsigned short val_nVar, unsigned short val_nConst, CConfig *donor_config, CConfig *target_config); /*! * \brief Destructor of the class. */ ~CMixingPlaneInterface(void) override; /*! * \brief Initialize quantities for spanwise sections for interpolation. * \param[in] donor_config - Definition of the problem at the donor mesh. * \param[in] target_config - Definition of the problem at the target mesh. */ void SetSpanWiseLevels(CConfig *donor_config, CConfig *target_config) override; /*! * \brief Retrieve the variable that will be sent from donor mesh to target mesh. * \param[in] donor_solution - Solution from the donor mesh. * \param[in] donor_geometry - Geometry of the donor mesh. * \param[in] donor_config - Definition of the problem at the donor mesh. * \param[in] Marker_Donor - Index of the donor marker. * \param[in] Vertex_Donor - Index of the donor vertex. * \param[in] Point_Donor - Index of the donor point. */ void GetDonor_Variable(CSolver *donor_solution, CGeometry *donor_geometry, CConfig *donor_config, unsigned long Marker_Donor, unsigned long val_Span, unsigned long Point_Donor) override; /*! * \brief Set the variable that has been received from the target mesh into the target mesh. * \param[in] target_solution - Solution from the target mesh. * \param[in] target_geometry - Geometry of the target mesh. * \param[in] target_config - Definition of the problem at the target mesh. * \param[in] Marker_Target - Index of the target marker. * \param[in] Vertex_Target - Index of the target vertex. * \param[in] Point_Target - Index of the target point. */ void SetTarget_Variable(CSolver *target_solution, CGeometry *target_geometry, CConfig *target_config, unsigned long Marker_Target, unsigned long val_Span, unsigned long Point_Target) override; /*! * \brief Store all the turboperformance in the solver in ZONE_0. * \param[in] donor_solution - Solution from the donor mesh. * \param[in] target_solution - Solution from the target mesh. * \param[in] donorZone - counter of the donor solution */ void SetAverageValues(CSolver *donor_solution, CSolver *target_solution, unsigned short donorZone) override; /*! * \brief Store all the turboperformance in the solver in ZONE_0. * \param[in] donor_geometry - Solution from the donor mesh. * \param[in] target_geometry - Solution from the target mesh. * \param[in] donorZone - counter of the donor solution */ void SetAverageTurboGeoValues(CGeometry *donor_geometry, CGeometry *target_geometry, unsigned short donorZone) override; };
39.704762
123
0.720796
[ "mesh", "geometry" ]
6d5dbdbfa8cc14af72049563b2c7be0002f06b2a
2,479
cpp
C++
Crypto/Ciphers/Substitution Ciphers/Homophonic Substitution Cipher.cpp
Anmol-Singh-Jaggi/Crypto
4cdc3a9f43b80adcffc7debda746d6ba0aef0e8b
[ "MIT" ]
null
null
null
Crypto/Ciphers/Substitution Ciphers/Homophonic Substitution Cipher.cpp
Anmol-Singh-Jaggi/Crypto
4cdc3a9f43b80adcffc7debda746d6ba0aef0e8b
[ "MIT" ]
null
null
null
Crypto/Ciphers/Substitution Ciphers/Homophonic Substitution Cipher.cpp
Anmol-Singh-Jaggi/Crypto
4cdc3a9f43b80adcffc7debda746d6ba0aef0e8b
[ "MIT" ]
null
null
null
#include<iostream> #include<map> #include<utility> #include<algorithm> #include<cstdlib> #include<ctime> #include<cassert> #include<set> using namespace std; const int alphabet_size = 26; // 'a'-'z'... const int codomain_size=126-33+1; // ASCII 33-126... vector<vector<char> > mapping(alphabet_size); map<char,char> inverse_mapping; void permute(vector<char>& char_order) { int n=(int)char_order.size(); for(int i=0; i<n; i++) { int j=(rand()%(n-i))+i; swap(char_order[j],char_order[i]); } } void init() { int max_per_char=codomain_size/alphabet_size; vector<char> char_order(codomain_size); for(int i=0; i<codomain_size; i++) { char_order[i]=i+33; // First place them in their original ASCII order... } permute(char_order); // Randomly permute them... int char_order_iterator=0; for(int i=0; i<alphabet_size; i++) { mapping[i].resize((rand()%max_per_char)+1); for(int j=0; j<(int)mapping[i].size(); j++) { assert(char_order_iterator<(int)char_order.size()); // For debugging... mapping[i][j]=char_order[char_order_iterator++]; // For encryption... inverse_mapping[mapping[i][j]]=i+'a'; // For decryption... } } } void encrypt(string& message) { for(int i=0; i<(int)message.size(); i++) { if(message[i]>='a'&&message[i]<='z') { message[i]=mapping[message[i]-'a'][rand()%mapping[message[i]-'a'].size()]; } else { cout<<"Illegal alphabet '"<<message[i]<<"' in the message!!\n\nExiting\n\n"; exit(1); } } } void decrypt(string& message) { for(int i=0; i<(int)message.size(); i++) { message[i]=inverse_mapping[message[i]]; } } void show_details() { for(int i=0; i<26; i++) { cout<<"mapping["<<char('a'+i)<<"] = { "; for(int j=0; j<(int)mapping[i].size(); j++) { cout<<mapping[i][j]<<" "; } cout<<"}\n"; } cout<<"\n\n"; for(const auto& it:inverse_mapping) { cout<<"\ninv_mapping["<<it.first<<"] = "<<it.second; } } int main() { srand(time(NULL)); init(); string message; cout<<"\n\nEnter message to encrypt [a-z] - "; getline(cin,message); encrypt(message); cout<<"The encrypted message is - "<<message<<"\n"; decrypt(message); cout<<"The decrypted message is - "<<message<<"\n"; }
23.836538
88
0.553046
[ "vector" ]
6d63b1aa378e38f3ef822abbdee96686260d736a
2,434
cpp
C++
rps-cpp/src/main.cpp
Adrien-Luxey/cyclon-rps
28667b064ce0ef418fad34b54f3e0765e83434dd
[ "Unlicense" ]
null
null
null
rps-cpp/src/main.cpp
Adrien-Luxey/cyclon-rps
28667b064ce0ef418fad34b54f3e0765e83434dd
[ "Unlicense" ]
null
null
null
rps-cpp/src/main.cpp
Adrien-Luxey/cyclon-rps
28667b064ce0ef418fad34b54f3e0765e83434dd
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <thread> #include <chrono> #include <csignal> #include <memory> #include <cxxopts.hpp> #include "rps/Descriptor.hpp" #include "rps/RPS.hpp" void splitString(const std::string& str, const std::string& delim, std::vector<std::string> &ret); int main(int argc, char* argv[]) { // register signals to stop auto dieAlready = [](int signum) { exit(signum); }; signal(SIGINT, dieAlready); signal(SIGTERM, dieAlready); signal(SIGABRT, dieAlready); cxxopts::Options options("rps-cpp", "The best (the only) implementation of Cyclon in C++!"); int debug = 1; int rpsPeriod = 5000, rpsViewSize = 6, rpsGossipSize = 4; std::string ip, name, bsIpsStr; options.add_options() ("help", "Print help", cxxopts::value<int>()) ("d,debug", "Enable debugging", cxxopts::value<int>(debug)) ("p,period", "The RPS period (ms)", cxxopts::value<int>(rpsPeriod)) ("vs", "The RPS view size", cxxopts::value<int>(rpsViewSize)) ("gs", "The RPS gossip size", cxxopts::value<int>(rpsGossipSize)) ("ip", "This node's IP", cxxopts::value<std::string>(ip)) ("name", "This node's ID", cxxopts::value<std::string>(name)) ("bs_ips", "Other nodes' IPs for bootstrap (comma separated)", cxxopts::value<std::string>(bsIpsStr)) ; auto opts = options.parse(argc, argv); if (opts.count("help")) { std::cout << options.help() << std::endl; return 0; } std::vector<std::string> bsIPs; splitString(bsIpsStr, std::string(","), bsIPs); auto myself = std::make_shared<Descriptor>(ip, name); std::cout << "I am: " << myself->String() << std::endl; std::cout << "Launching RPS..." << std::endl; auto rps = std::make_shared<RPS>(myself, bsIPs, rpsViewSize, rpsGossipSize, rpsPeriod, debug); //RPS(myself, bsIPs, rpsViewSize, rpsGossipSize, rpsPeriod, debug); while (true) std::this_thread::sleep_for(std::chrono::seconds(1)); return EXIT_SUCCESS; } void splitString(const std::string& str, const std::string& delim, std::vector<std::string> &ret) { if (str.size() == 0) return; auto start = 0U; auto end = str.find(delim); while (end != std::string::npos) { ret.push_back(str.substr(start, end - start)); start = end + delim.length(); end = str.find(delim, start); } if (start != end) ret.push_back(str.substr(start, end - start)); }
29.682927
96
0.636812
[ "vector" ]
6d6530b8b96e05a8668feed884ba8fe3a4ee512c
11,243
cpp
C++
source/opt/cfg.cpp
iburinoc/SPIRV-Tools
48326d443e434f55eb50a7cfc9acdc968daad5e3
[ "Apache-2.0" ]
null
null
null
source/opt/cfg.cpp
iburinoc/SPIRV-Tools
48326d443e434f55eb50a7cfc9acdc968daad5e3
[ "Apache-2.0" ]
null
null
null
source/opt/cfg.cpp
iburinoc/SPIRV-Tools
48326d443e434f55eb50a7cfc9acdc968daad5e3
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "cfg.h" #include "cfa.h" #include "ir_builder.h" #include "ir_context.h" #include "module.h" namespace spvtools { namespace opt { namespace { // Universal Limit of ResultID + 1 const int kMaxResultId = 0x400000; } // namespace CFG::CFG(opt::Module* module) : module_(module), pseudo_entry_block_(std::unique_ptr<opt::Instruction>( new opt::Instruction(module->context(), SpvOpLabel, 0, 0, {}))), pseudo_exit_block_(std::unique_ptr<opt::Instruction>(new opt::Instruction( module->context(), SpvOpLabel, 0, kMaxResultId, {}))) { for (auto& fn : *module) { for (auto& blk : fn) { RegisterBlock(&blk); } } } void CFG::AddEdges(opt::BasicBlock* blk) { uint32_t blk_id = blk->id(); // Force the creation of an entry, not all basic block have predecessors // (such as the entry blocks and some unreachables). label2preds_[blk_id]; const auto* const_blk = blk; const_blk->ForEachSuccessorLabel( [blk_id, this](const uint32_t succ_id) { AddEdge(blk_id, succ_id); }); } void CFG::RemoveNonExistingEdges(uint32_t blk_id) { std::vector<uint32_t> updated_pred_list; for (uint32_t id : preds(blk_id)) { const opt::BasicBlock* pred_blk = block(id); bool has_branch = false; pred_blk->ForEachSuccessorLabel([&has_branch, blk_id](uint32_t succ) { if (succ == blk_id) { has_branch = true; } }); if (has_branch) updated_pred_list.push_back(id); } label2preds_.at(blk_id) = std::move(updated_pred_list); } void CFG::ComputeStructuredOrder(opt::Function* func, opt::BasicBlock* root, std::list<opt::BasicBlock*>* order) { assert(module_->context()->get_feature_mgr()->HasCapability( SpvCapabilityShader) && "This only works on structured control flow"); // Compute structured successors and do DFS. ComputeStructuredSuccessors(func); auto ignore_block = [](cbb_ptr) {}; auto ignore_edge = [](cbb_ptr, cbb_ptr) {}; auto get_structured_successors = [this](const opt::BasicBlock* b) { return &(block2structured_succs_[b]); }; // TODO(greg-lunarg): Get rid of const_cast by making moving const // out of the cfa.h prototypes and into the invoking code. auto post_order = [&](cbb_ptr b) { order->push_front(const_cast<opt::BasicBlock*>(b)); }; CFA<opt::BasicBlock>::DepthFirstTraversal( root, get_structured_successors, ignore_block, post_order, ignore_edge); } void CFG::ForEachBlockInPostOrder(BasicBlock* bb, const std::function<void(BasicBlock*)>& f) { std::vector<BasicBlock*> po; std::unordered_set<BasicBlock*> seen; ComputePostOrderTraversal(bb, &po, &seen); for (BasicBlock* current_bb : po) { if (!IsPseudoExitBlock(current_bb) && !IsPseudoEntryBlock(current_bb)) { f(current_bb); } } } void CFG::ForEachBlockInReversePostOrder( BasicBlock* bb, const std::function<void(BasicBlock*)>& f) { std::vector<BasicBlock*> po; std::unordered_set<BasicBlock*> seen; ComputePostOrderTraversal(bb, &po, &seen); for (auto current_bb = po.rbegin(); current_bb != po.rend(); ++current_bb) { if (!IsPseudoExitBlock(*current_bb) && !IsPseudoEntryBlock(*current_bb)) { f(*current_bb); } } } void CFG::ComputeStructuredSuccessors(opt::Function* func) { block2structured_succs_.clear(); for (auto& blk : *func) { // If no predecessors in function, make successor to pseudo entry. if (label2preds_[blk.id()].size() == 0) block2structured_succs_[&pseudo_entry_block_].push_back(&blk); // If header, make merge block first successor and continue block second // successor if there is one. uint32_t mbid = blk.MergeBlockIdIfAny(); if (mbid != 0) { block2structured_succs_[&blk].push_back(block(mbid)); uint32_t cbid = blk.ContinueBlockIdIfAny(); if (cbid != 0) { block2structured_succs_[&blk].push_back(block(cbid)); } } // Add true successors. const auto& const_blk = blk; const_blk.ForEachSuccessorLabel([&blk, this](const uint32_t sbid) { block2structured_succs_[&blk].push_back(block(sbid)); }); } } void CFG::ComputePostOrderTraversal(BasicBlock* bb, vector<BasicBlock*>* order, unordered_set<BasicBlock*>* seen) { seen->insert(bb); static_cast<const BasicBlock*>(bb)->ForEachSuccessorLabel( [&order, &seen, this](const uint32_t sbid) { BasicBlock* succ_bb = id2block_[sbid]; if (!seen->count(succ_bb)) { ComputePostOrderTraversal(succ_bb, order, seen); } }); order->push_back(bb); } BasicBlock* CFG::SplitLoopHeader(opt::BasicBlock* bb) { assert(bb->GetLoopMergeInst() && "Expecting bb to be the header of a loop."); Function* fn = bb->GetParent(); IRContext* context = fn->context(); // Find the insertion point for the new bb. Function::iterator header_it = std::find_if( fn->begin(), fn->end(), [bb](BasicBlock& block_in_func) { return &block_in_func == bb; }); assert(header_it != fn->end()); const std::vector<uint32_t>& pred = preds(bb->id()); // Find the back edge opt::BasicBlock* latch_block = nullptr; Function::iterator latch_block_iter = header_it; while (++latch_block_iter != fn->end()) { // If blocks are in the proper order, then the only branch that appears // after the header is the latch. if (std::find(pred.begin(), pred.end(), latch_block_iter->id()) != pred.end()) { break; } } assert(latch_block_iter != fn->end() && "Could not find the latch."); latch_block = &*latch_block_iter; RemoveSuccessorEdges(bb); // Create the new header bb basic bb. // Leave the phi instructions behind. auto iter = bb->begin(); while (iter->opcode() == SpvOpPhi) { ++iter; } std::unique_ptr<opt::BasicBlock> newBlock( bb->SplitBasicBlock(context, context->TakeNextId(), iter)); // Insert the new bb in the correct position auto insert_pos = header_it; ++insert_pos; opt::BasicBlock* new_header = &*insert_pos.InsertBefore(std::move(newBlock)); new_header->SetParent(fn); uint32_t new_header_id = new_header->id(); context->AnalyzeDefUse(new_header->GetLabelInst()); // Update cfg RegisterBlock(new_header); // Update bb mappings. context->set_instr_block(new_header->GetLabelInst(), new_header); new_header->ForEachInst([new_header, context](opt::Instruction* inst) { context->set_instr_block(inst, new_header); }); // Adjust the OpPhi instructions as needed. bb->ForEachPhiInst([latch_block, bb, new_header, context](Instruction* phi) { std::vector<uint32_t> preheader_phi_ops; std::vector<Operand> header_phi_ops; // Identify where the original inputs to original OpPhi belong: header or // preheader. for (uint32_t i = 0; i < phi->NumInOperands(); i += 2) { uint32_t def_id = phi->GetSingleWordInOperand(i); uint32_t branch_id = phi->GetSingleWordInOperand(i + 1); if (branch_id == latch_block->id()) { header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {def_id}}); header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {branch_id}}); } else { preheader_phi_ops.push_back(def_id); preheader_phi_ops.push_back(branch_id); } } // Create a phi instruction if and only if the preheader_phi_ops has more // than one pair. if (preheader_phi_ops.size() > 2) { opt::InstructionBuilder builder( context, &*bb->begin(), opt::IRContext::kAnalysisDefUse | opt::IRContext::kAnalysisInstrToBlockMapping); opt::Instruction* new_phi = builder.AddPhi(phi->type_id(), preheader_phi_ops); // Add the OpPhi to the header bb. header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {new_phi->result_id()}}); header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {bb->id()}}); } else { // An OpPhi with a single entry is just a copy. In this case use the same // instruction in the new header. header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {preheader_phi_ops[0]}}); header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {bb->id()}}); } phi->RemoveFromList(); std::unique_ptr<opt::Instruction> phi_owner(phi); phi->SetInOperands(std::move(header_phi_ops)); new_header->begin()->InsertBefore(std::move(phi_owner)); context->set_instr_block(phi, new_header); context->AnalyzeUses(phi); }); // Add a branch to the new header. opt::InstructionBuilder branch_builder( context, bb, opt::IRContext::kAnalysisDefUse | opt::IRContext::kAnalysisInstrToBlockMapping); bb->AddInstruction(MakeUnique<opt::Instruction>( context, SpvOpBranch, 0, 0, std::initializer_list<opt::Operand>{ {SPV_OPERAND_TYPE_ID, {new_header->id()}}})); context->AnalyzeUses(bb->terminator()); context->set_instr_block(bb->terminator(), bb); label2preds_[new_header->id()].push_back(bb->id()); // Update the latch to branch to the new header. latch_block->ForEachSuccessorLabel([bb, new_header_id](uint32_t* id) { if (*id == bb->id()) { *id = new_header_id; } }); opt::Instruction* latch_branch = latch_block->terminator(); context->AnalyzeUses(latch_branch); label2preds_[new_header->id()].push_back(latch_block->id()); auto& block_preds = label2preds_[bb->id()]; auto latch_pos = std::find(block_preds.begin(), block_preds.end(), latch_block->id()); assert(latch_pos != block_preds.end() && "The cfg was invalid."); block_preds.erase(latch_pos); // Update the loop descriptors if (context->AreAnalysesValid(opt::IRContext::kAnalysisLoopAnalysis)) { LoopDescriptor* loop_desc = context->GetLoopDescriptor(bb->GetParent()); Loop* loop = (*loop_desc)[bb->id()]; loop->AddBasicBlock(new_header_id); loop->SetHeaderBlock(new_header); loop_desc->SetBasicBlockToLoop(new_header_id, loop); loop->RemoveBasicBlock(bb->id()); loop->SetPreHeaderBlock(bb); Loop* parent_loop = loop->GetParent(); if (parent_loop != nullptr) { parent_loop->AddBasicBlock(bb->id()); loop_desc->SetBasicBlockToLoop(bb->id(), parent_loop); } else { loop_desc->SetBasicBlockToLoop(bb->id(), nullptr); } } return new_header; } unordered_set<BasicBlock*> CFG::FindReachableBlocks(BasicBlock* start) { std::unordered_set<BasicBlock*> reachable_blocks; ForEachBlockInReversePostOrder(start, [&reachable_blocks](BasicBlock* bb) { reachable_blocks.insert(bb); }); return reachable_blocks; } } // namespace opt } // namespace spvtools
34.80805
80
0.67482
[ "vector" ]
6d6a2e2474e5c07612a4dd7ea72ffb834d52d901
4,822
cc
C++
RecoBTag/PerformanceDB/plugins/PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV.cc
amecca/cmssw
4d5c91a05629d9124806e310501fac8c303c84c2
[ "Apache-2.0" ]
1
2018-08-28T16:51:36.000Z
2018-08-28T16:51:36.000Z
RecoBTag/PerformanceDB/plugins/PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV.cc
amecca/cmssw
4d5c91a05629d9124806e310501fac8c303c84c2
[ "Apache-2.0" ]
25
2016-06-24T20:55:32.000Z
2022-02-01T19:24:45.000Z
RecoBTag/PerformanceDB/plugins/PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV.cc
amecca/cmssw
4d5c91a05629d9124806e310501fac8c303c84c2
[ "Apache-2.0" ]
8
2016-03-25T07:17:43.000Z
2021-07-08T17:11:21.000Z
#include <memory> #include <string> #include <fstream> #include <iostream> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "CondCore/DBOutputService/interface/PoolDBOutputService.h" #include "CondFormats/PhysicsToolsObjects/interface/PerformancePayloadFromTable.h" #include "CondFormats/PhysicsToolsObjects/interface/PerformanceWorkingPoint.h" class PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV : public edm::EDAnalyzer { public: PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV(const edm::ParameterSet&); void beginJob() override; void analyze(const edm::Event&, const edm::EventSetup&) override {} void endJob() override {} ~PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV() override {} private: std::string inputTxtFile; std::string rec1, rec2; unsigned long long iovBegin, iovEnd; }; PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV::PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV( const edm::ParameterSet& p) { inputTxtFile = p.getUntrackedParameter<std::string>("inputTxtFile"); rec1 = p.getUntrackedParameter<std::string>("RecordPayload"); rec2 = p.getUntrackedParameter<std::string>("RecordWP"); iovBegin = p.getParameter<unsigned long long>("IOVBegin"); iovEnd = p.getParameter<unsigned long long>("IOVEnd"); } void PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV::beginJob() { // // read object from file // // // File Format is // - tagger name // - cut // - concrete class name // - how many results and how many binning // - their values // - vector<float> // std::ifstream in; in.open(inputTxtFile.c_str()); std::string tagger; float cut; std::string concreteType; std::string comment; std::vector<float> pl; int stride; in >> tagger; edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << "WP Tagger is " << tagger; in >> cut; edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << "WP Cut is " << cut; in >> concreteType; edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << "concrete Type is " << concreteType; // return ; // read # of results int nres, nbin; in >> nres; in >> nbin; edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << " Results: " << nres << " Binning variables: " << nbin; stride = nres + nbin * 2; int number = 0; std::vector<PerformanceResult::ResultType> res; std::vector<BinningVariables::BinningVariablesType> bin; while (number < nres && !in.eof()) { int tmp; in >> tmp; res.push_back((PerformanceResult::ResultType)(tmp)); number++; } if (number != nres) { edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << " Table not well formed"; } number = 0; while (number < nbin && !in.eof()) { int tmp; in >> tmp; bin.push_back((BinningVariables::BinningVariablesType)(tmp)); number++; } if (number != nbin) { edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << " Table not well formed"; } number = 0; while (!in.eof()) { float temp; in >> temp; edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << " Inserting " << temp << " in position " << number; number++; pl.push_back(temp); } // // CHECKS // if (stride != nbin * 2 + nres) { edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << " Table not well formed"; } if (stride != 0 && (number % stride) != 0) { edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << " Table not well formed"; } in.close(); /* for (int k=0;k<(number/stride); k++){ for (int j=0; j<stride; j++){ std::cout << "Pos["<<k<<","<<j<<"] = "<<pl[k*stride+j]<<std::endl; } } */ // // now create pl etc etc // PerformanceWorkingPoint wp(cut, tagger); PerformancePayloadFromTable btagpl; if (concreteType == "PerformancePayloadFromTable") { btagpl = PerformancePayloadFromTable(res, bin, stride, pl); } else { edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << " Non existing request: " << concreteType; } edm::LogInfo("PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV") << " Created the " << concreteType << " object"; edm::Service<cond::service::PoolDBOutputService> s; if (s.isAvailable()) { s->writeOneIOV(btagpl, iovBegin, rec1); // write also the WP s->writeOneIOV(wp, iovBegin, rec2); } } DEFINE_FWK_MODULE(PhysicsPerformanceDBWriterFromFile_WPandPayload_IOV);
29.224242
118
0.699917
[ "object", "vector" ]
6d6bdd6100f9c1e22039f9144dd71e31d51546e2
2,683
cpp
C++
UVa/uva_196_Spreadsheet_memoization.cpp
bishoy-magdy/Competitive-Programming
689daac9aeb475da3c28aba4a69df394c68a9a34
[ "MIT" ]
2
2020-04-23T17:47:27.000Z
2020-04-25T19:40:50.000Z
UVa/uva_196_Spreadsheet_memoization.cpp
bishoy-magdy/Competitive-Programming
689daac9aeb475da3c28aba4a69df394c68a9a34
[ "MIT" ]
null
null
null
UVa/uva_196_Spreadsheet_memoization.cpp
bishoy-magdy/Competitive-Programming
689daac9aeb475da3c28aba4a69df394c68a9a34
[ "MIT" ]
1
2020-06-14T20:52:39.000Z
2020-06-14T20:52:39.000Z
#include<bits/stdc++.h> #include<iostream> #include<string> #include<vector> #include<cmath> #include<list> #include <algorithm> #include<vector> #include<set> #include <cctype> #include <cstring> #include <cstdio> #include<queue> #include<stack> #include<bitset> #include<time.h> #include<fstream> /******************************************************/ using namespace std; /********************define***************************/ #define ll long long #define ld long double #define all(v) ((v).begin()), ((v).end()) #define for_(vec) for(int i=0;i<(int)vec.size();i++) #define lp(j,n) for(int i=j;i<(int)(n);i++) #define clr(arr,x) memset(arr,x,sizeof(arr)) #define fillstl(arr,X) fill(arr.begin(),arr.end(),X) #define pb push_back #define mp make_pair #define print_vector(X) for(int i=0;i<X.size();i++) /********************************************************/ typedef vector<int> vi; typedef vector<pair<int, int>> vii; typedef vector<vector<int>> vvi; typedef vector<ll> vl; /***********************function************************/ void fast(){ios_base::sync_with_stdio(NULL);cin.tie(0); cout.tie(0);} void online_judge(){freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);} const int flag_max=0x3f3f3f3f; const ll OO=1e9 ; const double EPS = (1e-7); int dcmp(double x, double y) { return fabs(x-y) <= EPS ? 0 : x < y ? -1 : 1; } ll gcd(ll a, ll b) {return !b ? a : gcd(b, a % b);} ll lcm(ll a, ll b) { return (a / gcd(a, b)) * b;} /***********************main_problem****************************/ int dx[8]={1,-1,0,0,1,1,-1,-1}; int dy[8]={0,0,-1,1,1,-1,1,-1}; string grid[1000][18278]; int dp[1000][10000]; int go(int x,int y) { if(dp[x][y]!=OO) return dp[x][y]; if(grid[x][y][0]!='=') return dp[x][y]=stoi(grid[x][y]); int r=0,c=0,res=0; for(int i=1;i<=grid[x][y].size();i++) { if(isdigit(grid[x][y][i])) r=r*10+grid[x][y][i]-'0'; else { if(isalpha(grid[x][y][i])) c=c*26+grid[x][y][i]-'A'+1; else { res+=go(r-1,c-1); r=c=0; } } } return dp[x][y]=res; } /**************************Bisho_O*****************************************/ int main() { fast(); int t; cin>>t; while(t--){ int n,m; cin>>m>>n; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cin>>grid[i][j]; dp[i][j]=OO; } } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cout<<go(i,j); if(j!=m-1){cout<<' ';} } {cout<<'\n';} } } return 0; }
19.028369
89
0.456578
[ "vector" ]
6d6bddbf312d03e72da012378ad6569e5fe3507f
21,389
cc
C++
third_party/blink/renderer/core/html/html_iframe_element.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
third_party/blink/renderer/core/html/html_iframe_element.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
third_party/blink/renderer/core/html/html_iframe_element.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2000 Simon Hausmann (hausmann@kde.org) * (C) 2001 Dirk Mueller (mueller@kde.org) * Copyright (C) 2004, 2006, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2009 Ericsson AB. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "third_party/blink/renderer/core/html/html_iframe_element.h" #include "base/metrics/histogram_macros.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/web_sandbox_flags.h" #include "services/network/public/mojom/trust_tokens.mojom-blink.h" #include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h" #include "third_party/blink/public/mojom/permissions_policy/permissions_policy.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/v8_html_iframe_element.h" #include "third_party/blink/renderer/core/css/css_property_names.h" #include "third_party/blink/renderer/core/css/style_change_reason.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/fetch/trust_token_issuance_authorization.h" #include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/html/html_document.h" #include "third_party/blink/renderer/core/html/trust_token_attribute_parsing.h" #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/layout/layout_iframe.h" #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/permissions_policy/document_policy_parser.h" #include "third_party/blink/renderer/core/permissions_policy/iframe_policy.h" #include "third_party/blink/renderer/core/permissions_policy/permissions_policy_parser.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" #include "third_party/blink/renderer/platform/json/json_parser.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { HTMLIFrameElement::HTMLIFrameElement(Document& document) : HTMLFrameElementBase(html_names::kIFrameTag, document), collapsed_by_client_(false), sandbox_(MakeGarbageCollected<HTMLIFrameElementSandbox>(this)), referrer_policy_(network::mojom::ReferrerPolicy::kDefault) {} void HTMLIFrameElement::Trace(Visitor* visitor) const { visitor->Trace(sandbox_); visitor->Trace(policy_); HTMLFrameElementBase::Trace(visitor); Supplementable<HTMLIFrameElement>::Trace(visitor); } HTMLIFrameElement::~HTMLIFrameElement() = default; const AttrNameToTrustedType& HTMLIFrameElement::GetCheckedAttributeTypes() const { DEFINE_STATIC_LOCAL(AttrNameToTrustedType, attribute_map, ({{"srcdoc", SpecificTrustedType::kHTML}})); return attribute_map; } void HTMLIFrameElement::SetCollapsed(bool collapse) { if (collapsed_by_client_ == collapse) return; collapsed_by_client_ = collapse; // This is always called in response to an IPC, so should not happen in the // middle of a style recalc. DCHECK(!GetDocument().InStyleRecalc()); // Trigger style recalc to trigger layout tree re-attachment. SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create( style_change_reason::kFrame)); } DOMTokenList* HTMLIFrameElement::sandbox() const { return sandbox_.Get(); } DOMFeaturePolicy* HTMLIFrameElement::featurePolicy() { if (!policy_ && GetExecutionContext()) { policy_ = MakeGarbageCollected<IFramePolicy>( GetExecutionContext(), GetFramePolicy().container_policy, GetOriginForPermissionsPolicy()); } return policy_.Get(); } bool HTMLIFrameElement::IsPresentationAttribute( const QualifiedName& name) const { if (name == html_names::kWidthAttr || name == html_names::kHeightAttr || name == html_names::kAlignAttr || name == html_names::kFrameborderAttr) return true; return HTMLFrameElementBase::IsPresentationAttribute(name); } void HTMLIFrameElement::CollectStyleForPresentationAttribute( const QualifiedName& name, const AtomicString& value, MutableCSSPropertyValueSet* style) { if (name == html_names::kWidthAttr) { AddHTMLLengthToStyle(style, CSSPropertyID::kWidth, value); } else if (name == html_names::kHeightAttr) { AddHTMLLengthToStyle(style, CSSPropertyID::kHeight, value); } else if (name == html_names::kAlignAttr) { ApplyAlignmentAttributeToStyle(value, style); } else if (name == html_names::kFrameborderAttr) { // LocalFrame border doesn't really match the HTML4 spec definition for // iframes. It simply adds a presentational hint that the border should be // off if set to zero. if (!value.ToInt()) { // Add a rule that nulls out our border width. AddPropertyToPresentationAttributeStyle( style, CSSPropertyID::kBorderWidth, 0, CSSPrimitiveValue::UnitType::kPixels); } } else { HTMLFrameElementBase::CollectStyleForPresentationAttribute(name, value, style); } } void HTMLIFrameElement::ParseAttribute( const AttributeModificationParams& params) { const QualifiedName& name = params.name; const AtomicString& value = params.new_value; if (name == html_names::kNameAttr) { auto* document = DynamicTo<HTMLDocument>(GetDocument()); if (document && IsInDocumentTree()) { document->RemoveNamedItem(name_); document->AddNamedItem(value); } AtomicString old_name = name_; name_ = value; if (name_ != old_name) FrameOwnerPropertiesChanged(); } else if (name == html_names::kSandboxAttr) { sandbox_->DidUpdateAttributeValue(params.old_value, value); network::mojom::blink::WebSandboxFlags current_flags = network::mojom::blink::WebSandboxFlags::kNone; if (!value.IsNull()) { using network::mojom::blink::WebSandboxFlags; WebSandboxFlags ignored_flags = !RuntimeEnabledFeatures::StorageAccessAPIEnabled() ? WebSandboxFlags::kStorageAccessByUserActivation : WebSandboxFlags::kNone; auto parsed = network::ParseWebSandboxPolicy(sandbox_->value().Utf8(), ignored_flags); current_flags = parsed.flags; if (!parsed.error_message.empty()) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, WebString::FromUTF8( "Error while parsing the 'sandbox' attribute: " + parsed.error_message))); } } SetSandboxFlags(current_flags); UseCounter::Count(GetDocument(), WebFeature::kSandboxViaIFrame); } else if (name == html_names::kReferrerpolicyAttr) { referrer_policy_ = network::mojom::ReferrerPolicy::kDefault; if (!value.IsNull()) { SecurityPolicy::ReferrerPolicyFromString( value, kSupportReferrerPolicyLegacyKeywords, &referrer_policy_); UseCounter::Count(GetDocument(), WebFeature::kHTMLIFrameElementReferrerPolicyAttribute); } } else if (name == html_names::kAllowfullscreenAttr) { bool old_allow_fullscreen = allow_fullscreen_; allow_fullscreen_ = !value.IsNull(); if (allow_fullscreen_ != old_allow_fullscreen) { // TODO(iclelland): Remove this use counter when the allowfullscreen // attribute state is snapshotted on document creation. crbug.com/682282 if (allow_fullscreen_ && ContentFrame()) { UseCounter::Count( GetDocument(), WebFeature:: kHTMLIFrameElementAllowfullscreenAttributeSetAfterContentLoad); } FrameOwnerPropertiesChanged(); UpdateContainerPolicy(); } } else if (name == html_names::kAllowpaymentrequestAttr) { bool old_allow_payment_request = allow_payment_request_; allow_payment_request_ = !value.IsNull(); if (allow_payment_request_ != old_allow_payment_request) { FrameOwnerPropertiesChanged(); UpdateContainerPolicy(); } } else if (name == html_names::kCspAttr) { static const size_t kMaxLengthCSPAttribute = 4096; if (value && (value.Contains('\n') || value.Contains('\r') || !MatchesTheSerializedCSPGrammar(value.GetString()))) { // TODO(antoniosartori): It would be safer to block loading iframes with // invalid 'csp' attribute. required_csp_ = g_null_atom; GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "'csp' attribute is invalid: " + value)); } else if (value && value.length() > kMaxLengthCSPAttribute) { // TODO(antoniosartori): It would be safer to block loading iframes with // invalid 'csp' attribute. required_csp_ = g_null_atom; GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, String::Format("'csp' attribute too long. The max length for the " "'csp' attribute is %zu bytes.", kMaxLengthCSPAttribute))); } else if (required_csp_ != value) { required_csp_ = value; DidChangeAttributes(); UseCounter::Count(GetDocument(), WebFeature::kIFrameCSPAttribute); } } else if (name == html_names::kAnonymousAttr && RuntimeEnabledFeatures::AnonymousIframeEnabled()) { bool new_value = !value.IsNull(); if (anonymous_ != new_value) { anonymous_ = new_value; DidChangeAttributes(); } } else if (name == html_names::kAllowAttr) { if (allow_ != value) { allow_ = value; UpdateContainerPolicy(); if (!value.IsEmpty()) { UseCounter::Count(GetDocument(), WebFeature::kFeaturePolicyAllowAttribute); } } } else if (name == html_names::kPolicyAttr) { if (required_policy_ != value) { required_policy_ = value; UpdateRequiredPolicy(); } } else if (name == html_names::kTrusttokenAttr) { UseCounter::Count(GetDocument(), WebFeature::kTrustTokenIframe); trust_token_ = value; } else { // Websites picked up a Chromium article that used this non-specified // attribute which ended up changing shape after the specification process. // This error message and use count will help developers to move to the // proper solution. // To avoid polluting the console, this is being recorded only once per // page. if (name == "gesture" && value == "media" && GetDocument().Loader() && !GetDocument().Loader()->GetUseCounter().IsCounted( WebFeature::kHTMLIFrameElementGestureMedia)) { UseCounter::Count(GetDocument(), WebFeature::kHTMLIFrameElementGestureMedia); GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::ConsoleMessageSource::kOther, mojom::ConsoleMessageLevel::kWarning, "<iframe gesture=\"media\"> is not supported. " "Use <iframe allow=\"autoplay\">, " "https://goo.gl/ximf56")); } if (name == html_names::kSrcAttr) LogUpdateAttributeIfIsolatedWorldAndInDocument("iframe", params); HTMLFrameElementBase::ParseAttribute(params); } } DocumentPolicyFeatureState HTMLIFrameElement::ConstructRequiredPolicy() const { if (!RuntimeEnabledFeatures::DocumentPolicyNegotiationEnabled( GetExecutionContext())) return {}; if (!required_policy_.IsEmpty()) { UseCounter::Count( GetDocument(), mojom::blink::WebFeature::kDocumentPolicyIframePolicyAttribute); } PolicyParserMessageBuffer logger; DocumentPolicy::ParsedDocumentPolicy new_required_policy = DocumentPolicyParser::Parse(required_policy_, logger) .value_or(DocumentPolicy::ParsedDocumentPolicy{}); for (const auto& message : logger.GetMessages()) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, message.level, message.content)); } if (!new_required_policy.endpoint_map.empty()) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kWarning, "Iframe policy attribute cannot specify reporting endpoint.")); } for (const auto& policy_entry : new_required_policy.feature_state) { mojom::blink::DocumentPolicyFeature feature = policy_entry.first; if (!GetDocument().DocumentPolicyFeatureObserved(feature)) { UMA_HISTOGRAM_ENUMERATION( "Blink.UseCounter.DocumentPolicy.PolicyAttribute", feature); } } return new_required_policy.feature_state; } ParsedPermissionsPolicy HTMLIFrameElement::ConstructContainerPolicy() const { if (!GetExecutionContext()) return ParsedPermissionsPolicy(); scoped_refptr<const SecurityOrigin> src_origin = GetOriginForPermissionsPolicy(); scoped_refptr<const SecurityOrigin> self_origin = GetExecutionContext()->GetSecurityOrigin(); PolicyParserMessageBuffer logger; // Start with the allow attribute ParsedPermissionsPolicy container_policy = PermissionsPolicyParser::ParseAttribute(allow_, self_origin, src_origin, logger, GetExecutionContext()); // Process the allow* attributes. These only take effect if the corresponding // feature is not present in the allow attribute's value. // If allowfullscreen attribute is present and no fullscreen policy is set, // enable the feature for all origins. if (AllowFullscreen()) { bool policy_changed = AllowFeatureEverywhereIfNotPresent( mojom::blink::PermissionsPolicyFeature::kFullscreen, container_policy); if (!policy_changed) { logger.Warn( "Allow attribute will take precedence over 'allowfullscreen'."); } } // If the allowpaymentrequest attribute is present and no 'payment' policy is // set, enable the feature for all origins. if (AllowPaymentRequest()) { bool policy_changed = AllowFeatureEverywhereIfNotPresent( mojom::blink::PermissionsPolicyFeature::kPayment, container_policy); if (!policy_changed) { logger.Warn( "Allow attribute will take precedence over 'allowpaymentrequest'."); } } // Update the JavaScript policy object associated with this iframe, if it // exists. if (policy_) policy_->UpdateContainerPolicy(container_policy, src_origin); for (const auto& message : logger.GetMessages()) { GetDocument().AddConsoleMessage( MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, message.level, message.content), /* discard_duplicates */ true); } return container_policy; } bool HTMLIFrameElement::LayoutObjectIsNeeded(const ComputedStyle& style) const { return ContentFrame() && !collapsed_by_client_ && HTMLElement::LayoutObjectIsNeeded(style); } LayoutObject* HTMLIFrameElement::CreateLayoutObject(const ComputedStyle&, LegacyLayout) { return MakeGarbageCollected<LayoutIFrame>(this); } Node::InsertionNotificationRequest HTMLIFrameElement::InsertedInto( ContainerNode& insertion_point) { InsertionNotificationRequest result = HTMLFrameElementBase::InsertedInto(insertion_point); auto* html_doc = DynamicTo<HTMLDocument>(GetDocument()); if (html_doc && insertion_point.IsInDocumentTree()) html_doc->AddNamedItem(name_); LogAddElementIfIsolatedWorldAndInDocument("iframe", html_names::kSrcAttr); return result; } void HTMLIFrameElement::RemovedFrom(ContainerNode& insertion_point) { HTMLFrameElementBase::RemovedFrom(insertion_point); auto* html_doc = DynamicTo<HTMLDocument>(GetDocument()); if (html_doc && insertion_point.IsInDocumentTree()) html_doc->RemoveNamedItem(name_); } bool HTMLIFrameElement::IsInteractiveContent() const { return true; } network::mojom::ReferrerPolicy HTMLIFrameElement::ReferrerPolicyAttribute() { return referrer_policy_; } network::mojom::blink::TrustTokenParamsPtr HTMLIFrameElement::ConstructTrustTokenParams() const { if (!trust_token_) return nullptr; JSONParseError parse_error; std::unique_ptr<JSONValue> parsed_attribute = ParseJSON(trust_token_, &parse_error); if (!parsed_attribute) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "iframe trusttoken attribute was invalid JSON: " + parse_error.message + String::Format(" (line %d, col %d)", parse_error.line, parse_error.column))); return nullptr; } network::mojom::blink::TrustTokenParamsPtr parsed_params = internal::TrustTokenParamsFromJson(std::move(parsed_attribute)); if (!parsed_params) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "Couldn't parse iframe trusttoken attribute (was it missing a " "field?)")); return nullptr; } // Trust token redemption and signing (but not issuance) require that the // trust-token-redemption permissions policy be present. bool operation_requires_permissions_policy = parsed_params->type == network::mojom::blink::TrustTokenOperationType::kRedemption || parsed_params->type == network::mojom::blink::TrustTokenOperationType::kSigning; if (operation_requires_permissions_policy && (!GetExecutionContext()->IsFeatureEnabled( mojom::blink::PermissionsPolicyFeature::kTrustTokenRedemption))) { GetExecutionContext()->AddConsoleMessage( MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "Trust Tokens: Attempted redemption or signing without the " "trust-token-redemption Permissions Policy feature present.")); return nullptr; } if (parsed_params->type == network::mojom::blink::TrustTokenOperationType::kIssuance && !IsTrustTokenIssuanceAvailableInExecutionContext( *GetExecutionContext())) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "Trust Tokens issuance is disabled except in " "contexts with the TrustTokens Origin Trial enabled.")); return nullptr; } return parsed_params; } void HTMLIFrameElement::DidChangeAttributes() { // Don't notify about updates if ContentFrame() is null, for example when // the subframe hasn't been created yet; or if we are in the middle of // swapping one frame for another, in which case the final state // will be propagated at the end of the swapping operation. if (is_swapping_frames() || !ContentFrame()) return; // ParseContentSecurityPolicies needs a url to resolve report endpoints and // for matching the keyword 'self'. However, the csp attribute does not allow // report endpoints. Moreover, in the csp attribute, 'self' should not match // the owner's url, but rather the frame src url. This is taken care by the // Content-Security-Policy Embedded Enforcement algorithm, implemented in the // NavigationRequest. That's why we pass an empty url here. Vector<network::mojom::blink::ContentSecurityPolicyPtr> csp = ParseContentSecurityPolicies( required_csp_, network::mojom::blink::ContentSecurityPolicyType::kEnforce, network::mojom::blink::ContentSecurityPolicySource::kHTTP, KURL()); DCHECK_LE(csp.size(), 1u); GetDocument().GetFrame()->GetLocalFrameHostRemote().DidChangeIframeAttributes( ContentFrame()->GetFrameToken(), csp.IsEmpty() ? nullptr : std::move(csp[0]), anonymous_); } } // namespace blink
42.021611
93
0.712656
[ "object", "shape", "vector" ]
6d6c99aecf75ce730db8a81f044427b744529294
18,203
cpp
C++
libretro/retro.cpp
AzureWinter/mrboom-libretro
aebf6c7aea64af6bf75bdadfa357913670f78d66
[ "MIT" ]
null
null
null
libretro/retro.cpp
AzureWinter/mrboom-libretro
aebf6c7aea64af6bf75bdadfa357913670f78d66
[ "MIT" ]
null
null
null
libretro/retro.cpp
AzureWinter/mrboom-libretro
aebf6c7aea64af6bf75bdadfa357913670f78d66
[ "MIT" ]
null
null
null
#include <memalign.h> #include <vector> #include "mrboom.h" #include "common.hpp" #include "retro.hpp" #include "MrboomHelper.hpp" #include "BotTree.hpp" #include <errno.h> #include <time/rtime.h> static uint32_t *frame_buf; static struct retro_log_callback logging; retro_log_printf_t log_cb; static char retro_save_directory[4096]; static char retro_base_directory[4096]; static retro_video_refresh_t video_cb; static retro_audio_sample_t audio_cb; static retro_environment_t environ_cb; static retro_input_poll_t input_poll_cb; static retro_input_state_t input_state_cb; static bool libretro_supports_bitmasks = false; static unsigned aspect_option; float libretro_music_volume = 1.0; int libretro_sfx_volume = 50; static int team_mode = 0; static int noMonster_mode = 0; static int level_select = -1; // Global core options static const struct retro_variable var_mrboom_teammode = { "mrboom-teammode", "Team mode; Selfie|Color|Sex|Skynet" }; static const struct retro_variable var_mrboom_nomonster = { "mrboom-nomonster", "Monsters; ON|OFF" }; static const struct retro_variable var_mrboom_levelselect = { "mrboom-levelselect", "Level select; Normal|Candy|Penguins|Pink|Jungle|Board|Soccer|Sky|Aliens|Random" }; static const struct retro_variable var_mrboom_autofire = { "mrboom-autofire", "Drop bomb autofire; OFF|ON" }; static const struct retro_variable var_mrboom_aspect = { "mrboom-aspect", "Aspect ratio; Native|4:3|16:9" }; static const struct retro_variable var_mrboom_musicvolume = { "mrboom-musicvolume", "Music volume; 100|0|5|10|15|20|25|30|35|40|45|50|55|60|65|70|75|80|85|90|95" }; static const struct retro_variable var_mrboom_sfxvolume = { "mrboom-sfxvolume", "Sfx volume; 50|55|60|65|70|75|80|85|90|95|100|0|5|10|15|20|25|30|35|40|45" }; static const struct retro_variable var_empty = { NULL, NULL }; // joypads #define DESC_NUM_PORTS(desc) ((desc)->port_max - (desc)->port_min + 1) #define DESC_NUM_INDICES(desc) ((desc)->index_max - (desc)->index_min + 1) #define DESC_NUM_IDS(desc) ((desc)->id_max - (desc)->id_min + 1) #define DESC_OFFSET(desc, port, index, id) ( \ port * ((desc)->index_max - (desc)->index_min + 1) * ((desc)->id_max - (desc)->id_min + 1) + \ index * ((desc)->id_max - (desc)->id_min + 1) + \ id \ ) #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) struct descriptor { int device; int port_min; int port_max; int index_min; int index_max; int id_min; int id_max; uint16_t *value; }; static struct descriptor joypad; static struct descriptor *descriptors[] = { &joypad }; static void fallback_log(enum retro_log_level level, const char *fmt, ...) { (void)level; va_list va; va_start(va, fmt); vfprintf(stderr, fmt, va); va_end(va); } void retro_init(void) { int size; unsigned i; struct descriptor *desc = NULL; const char * dir = NULL; if (environ_cb(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &logging)) { log_cb = logging.log; } else { log_cb = fallback_log; } std::vector <const retro_variable *> vars_systems; // Add the Global core options vars_systems.push_back(&var_mrboom_teammode); vars_systems.push_back(&var_mrboom_nomonster); vars_systems.push_back(&var_mrboom_levelselect); vars_systems.push_back(&var_mrboom_autofire); vars_systems.push_back(&var_mrboom_aspect); vars_systems.push_back(&var_mrboom_musicvolume); vars_systems.push_back(&var_mrboom_sfxvolume); #define NB_VARS_SYSTEMS 7 assert(vars_systems.size() == NB_VARS_SYSTEMS); // Add the System core options int idx_var = 0; struct retro_variable vars[NB_VARS_SYSTEMS + 1]; // + 1 for the empty ending retro_variable for (i = 0; i < NB_VARS_SYSTEMS; i++, idx_var++) { vars[idx_var] = *vars_systems[i]; log_cb(RETRO_LOG_INFO, "retro_variable (SYSTEM) { '%s', '%s' }\n", vars[idx_var].key, vars[idx_var].value); } vars[idx_var] = var_empty; environ_cb(RETRO_ENVIRONMENT_SET_VARIABLES, (void *)vars); joypad.device = RETRO_DEVICE_JOYPAD; joypad.port_min = 0; joypad.port_max = 7; joypad.index_min = 0; joypad.index_max = 0; joypad.id_min = RETRO_DEVICE_ID_JOYPAD_B; joypad.id_max = RETRO_DEVICE_ID_JOYPAD_R3; num_samples_per_frame = SAMPLE_RATE / FPS_RATE; frame_sample_buf = (int16_t *)memalign_alloc(128, num_samples_per_frame * 2 * sizeof(int16_t)); memset(frame_sample_buf, 0, num_samples_per_frame * 2 * sizeof(int16_t)); log_cb(RETRO_LOG_DEBUG, "retro_init"); sprintf(retro_base_directory, "/tmp"); if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir) { if (strlen(dir)) { sprintf(retro_base_directory, "%s", dir); } } if (environ_cb(RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY, &dir) && dir) { // If save directory is defined use it, otherwise use system directory if (strlen(dir)) { sprintf(retro_save_directory, "%s", dir); } else { sprintf(retro_save_directory, "%s", retro_base_directory); } } frame_buf = (uint32_t *)calloc(WIDTH * HEIGHT, sizeof(uint32_t)); mrboom_init(); /* joypads Allocate descriptor values */ for (i = 0; i < ARRAY_SIZE(descriptors); i++) { desc = descriptors[i]; size = DESC_NUM_PORTS(desc) * DESC_NUM_INDICES(desc) * DESC_NUM_IDS(desc); descriptors[i]->value = (uint16_t *)calloc(size, sizeof(uint16_t)); } if (environ_cb(RETRO_ENVIRONMENT_GET_INPUT_BITMASKS, NULL)) libretro_supports_bitmasks = true; rtime_init(); } void retro_deinit(void) { unsigned i; free(frame_buf); memalign_free(frame_sample_buf); frame_buf = NULL; /* Free descriptor values */ for (i = 0; i < ARRAY_SIZE(descriptors); i++) { free(descriptors[i]->value); descriptors[i]->value = NULL; } mrboom_deinit(); libretro_supports_bitmasks = false; rtime_deinit(); } unsigned retro_api_version(void) { return(RETRO_API_VERSION); } void retro_set_controller_port_device(unsigned port, unsigned device) { log_cb(RETRO_LOG_INFO, "%s: Plugging device %u into port %u.\n", GAME_NAME, device, port); } void retro_get_system_info(struct retro_system_info *info) { memset(info, 0, sizeof(*info)); info->library_name = GAME_NAME; #ifdef GIT_VERSION info->library_version = GAME_VERSION GIT_VERSION; #else info->library_version = GAME_VERSION; #endif info->need_fullpath = false; info->valid_extensions = NULL; } void retro_get_system_av_info(struct retro_system_av_info *info) { float aspect = 16.0f / 10.0f; float sampling_rate = SAMPLE_RATE; if (aspect_option == 1) { aspect = 4.0f / 3.0f; } else if (aspect_option == 2) { aspect = 16.0f / 9.0f; } info->timing.fps = FPS_RATE; info->timing.sample_rate = sampling_rate; info->geometry.base_width = WIDTH; info->geometry.base_height = HEIGHT; info->geometry.max_width = WIDTH; info->geometry.max_height = HEIGHT; info->geometry.aspect_ratio = aspect; } void retro_set_environment(retro_environment_t cb) { environ_cb = cb; bool no_content = true; cb(RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME, &no_content); } void retro_set_audio_sample(retro_audio_sample_t cb) { audio_cb = cb; } void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; } void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; } void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; } void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; } void retro_reset(void) { pressESC(); } static void set_game_options(void) { if (inTheMenu() == true) { setTeamMode(team_mode); setNoMonsterMode(noMonster_mode); if (level_select >= 0) { chooseLevel(level_select); } else if (level_select == -2) { chooseLevel(frameNumber() % 8); } } } static void update_input(void) { uint16_t state, state_joypad = 0; int offset; int port; int index; int id; unsigned i; /* Poll input */ input_poll_cb(); /* Parse descriptors */ for (i = 0; i < ARRAY_SIZE(descriptors); i++) { /* Get current descriptor */ struct descriptor *desc = descriptors[i]; /* Go through range of ports/indices/IDs */ for (port = desc->port_min; port <= desc->port_max; port++) { for (index = desc->index_min; index <= desc->index_max; index++) { if (desc->device == RETRO_DEVICE_JOYPAD && libretro_supports_bitmasks) state_joypad = input_state_cb(port, RETRO_DEVICE_JOYPAD, index, RETRO_DEVICE_ID_JOYPAD_MASK); for (id = desc->id_min; id <= desc->id_max; id++) { /* Compute offset into array */ offset = DESC_OFFSET(desc, port, index, id); if (desc->device == RETRO_DEVICE_JOYPAD && libretro_supports_bitmasks) state = state_joypad & (1 << id) ? 1 : 0; else /* Get new state */ state = input_state_cb(port, desc->device, index, id); /* Update state */ if (desc->value[offset] != state) { mrboom_update_input(id, port, state, false); } desc->value[offset] = state; } } } } } void update_vga(uint32_t *buf, unsigned stride) { static uint32_t matrixPalette[NB_COLORS_PALETTE]; unsigned x, y; int z = 0; uint32_t * line = buf; do { matrixPalette[z / 3] = ((m.vgaPalette[z+0] << 2) | (m.vgaPalette[z+0] >> 4)) << 16; matrixPalette[z / 3] |= ((m.vgaPalette[z+1] << 2) | (m.vgaPalette[z+1] >> 4)) << 8; matrixPalette[z / 3] |= ((m.vgaPalette[z+2] << 2) | (m.vgaPalette[z+2] >> 4)) << 0; z += 3; } while (z != NB_COLORS_PALETTE * 3); for (y = 0; y < HEIGHT; y++, line += stride) { for (x = 0; x < WIDTH; x++) { if (y < HEIGHT) { if (m.affiche_pal != 1) { m.vgaRam[x + y * WIDTH] = m.buffer[x + y * WIDTH]; } line[x] = matrixPalette[m.vgaRam[x + y * WIDTH]]; } } } } static void render_checkered(void) { mrboom_sound(); /* Try rendering straight into VRAM if we can. */ uint32_t *buf = NULL; unsigned stride = 0; struct retro_framebuffer fb = { 0 }; fb.width = WIDTH; fb.height = HEIGHT; fb.access_flags = RETRO_MEMORY_ACCESS_WRITE; if (environ_cb(RETRO_ENVIRONMENT_GET_CURRENT_SOFTWARE_FRAMEBUFFER, &fb) && fb.format == RETRO_PIXEL_FORMAT_XRGB8888) { buf = (uint32_t *)fb.data; stride = fb.pitch >> 2; } else { buf = frame_buf; stride = WIDTH; } update_vga(buf, stride); video_cb(buf, WIDTH, HEIGHT, stride << 2); } static void update_geometry(void) { struct retro_system_av_info av_info; retro_get_system_av_info(&av_info); environ_cb(RETRO_ENVIRONMENT_SET_GEOMETRY, &av_info); } static void check_variables(void) { struct retro_variable var = { 0 }; var.key = var_mrboom_teammode.key; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) { if (strcmp(var.value, "Color") == 0) { team_mode = 1; } else if (strcmp(var.value, "Sex") == 0) { team_mode = 2; } else if (strcmp(var.value, "Skynet") == 0) { team_mode = 4; } else { team_mode = 0; } } var.key = var_mrboom_nomonster.key; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) { if (strcmp(var.value, "OFF") == 0) { noMonster_mode = 1; } else { noMonster_mode = 0; } } var.key = var_mrboom_levelselect.key; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) { if (strcmp(var.value, "Candy") == 0) { level_select = 0; } else if (strcmp(var.value, "Penguins") == 0) { level_select = 1; } else if (strcmp(var.value, "Pink") == 0) { level_select = 2; } else if (strcmp(var.value, "Jungle") == 0) { level_select = 3; } else if (strcmp(var.value, "Board") == 0) { level_select = 4; } else if (strcmp(var.value, "Soccer") == 0) { level_select = 5; } else if (strcmp(var.value, "Sky") == 0) { level_select = 6; } else if (strcmp(var.value, "Aliens") == 0) { level_select = 7; } else if (strcmp(var.value, "Random") == 0) { level_select = -2; } else { level_select = -1; } } var.key = var_mrboom_autofire.key; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) { if (strcmp(var.value, "ON") == 0) { setAutofire(true); } else { setAutofire(false); } } var.key = var_mrboom_aspect.key; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) { unsigned aspect_old = aspect_option; if (strcmp(var.value, "4:3") == 0) { aspect_option = 1; } else if (strcmp(var.value, "16:9") == 0) { aspect_option = 2; } else { aspect_option = 0; } if (aspect_old != aspect_option) { update_geometry(); } } var.key = var_mrboom_musicvolume.key; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) { char *err; long val; errno = 0; val = strtol (var.value, &err, 10); if (var.value != err && errno == 0) { libretro_music_volume = (float) val / 100.0f; } } var.key = var_mrboom_sfxvolume.key; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) { char *err; long val; errno = 0; val = strtol (var.value, &err, 10); if (var.value != err && errno == 0) { libretro_sfx_volume = val; } } } void retro_run(void) { static int frame = 0; int newFrameNumber = frameNumber(); frame++; if (frame != newFrameNumber) { if ((frame) && (newFrameNumber)) { log_cb(RETRO_LOG_ERROR, "Network resynched: %d -> %d\n", frame, newFrameNumber); } } frame = newFrameNumber; bool updated = false; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated) { check_variables(); } set_game_options(); update_input(); mrboom_deal_with_autofire(); mrboom_loop(); render_checkered(); audio_callback(); if (m.executionFinished) { log_cb(RETRO_LOG_INFO, "Exit.\n"); environ_cb(RETRO_ENVIRONMENT_SHUTDOWN, NULL); } } bool retro_load_game(const struct retro_game_info *info) { enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_XRGB8888; if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) { log_cb(RETRO_LOG_INFO, "XRGB8888 is not supported.\n"); return(false); } check_variables(); (void)info; return(true); } void retro_unload_game(void) { } unsigned retro_get_region(void) { return(RETRO_REGION_NTSC); } bool retro_load_game_special(unsigned type, const struct retro_game_info *info, size_t num) { return(retro_load_game(NULL)); } #define HARDCODED_RETRO_SERIALIZE_SIZE SIZE_SER + 13 * 8 size_t retro_serialize_size(void) { size_t result = HARDCODED_RETRO_SERIALIZE_SIZE; assert(tree[0] != NULL); if (tree[0] != NULL) { result = (SIZE_SER + tree[0]->serialize_size() * nb_dyna); assert(HARDCODED_RETRO_SERIALIZE_SIZE == result); } else { log_cb(RETRO_LOG_ERROR, "retro_serialize_size returning hardcoded value.\n"); } assert(SIZE_MEM_MAX > result); return(result); } bool retro_serialize(void *data_, size_t size) { memcpy(data_, &m.FIRST_RW_VARIABLE, SIZE_SER); if (is_little_endian() == false) { fixBigEndian(data_); } size_t offset = SIZE_SER; for (int i = 0; i < nb_dyna; i++) { assert(tree[i] != NULL); tree[i]->serialize(((char *)data_) + offset); offset += tree[i]->serialize_size(); } return(true); } bool retro_unserialize(const void *data_, size_t size) { if (size != retro_serialize_size()) { log_cb(RETRO_LOG_ERROR, "retro_unserialize error %d/%d\n", size, retro_serialize_size()); return(false); } if (is_little_endian() == false) { char dataTmp[SIZE_MEM_MAX]; memcpy(dataTmp, data_, SIZE_SER); fixBigEndian(dataTmp); memcpy(&m.FIRST_RW_VARIABLE, dataTmp, SIZE_SER); } else { memcpy(&m.FIRST_RW_VARIABLE, data_, SIZE_SER); } size_t offset = SIZE_SER; for (int i = 0; i < nb_dyna; i++) { assert(tree[i] != NULL); tree[i]->unserialize(((char *)data_) + offset); offset += tree[i]->serialize_size(); } return(true); } void *retro_get_memory_data(unsigned id) { (void)id; return(NULL); } size_t retro_get_memory_size(unsigned id) { (void)id; return(0); } void retro_cheat_reset(void) { } void retro_cheat_set(unsigned index, bool enabled, const char *code) { (void)index; (void)enabled; (void)code; } void show_message(const char *message) { struct retro_message msg; msg.msg = message; msg.frames = 80; environ_cb(RETRO_ENVIRONMENT_SET_MESSAGE, (void *)&msg); }
25.317107
167
0.604131
[ "geometry", "vector" ]
6d6f72713901e6ba8852d328afede46faa803d6f
80,745
cpp
C++
src/Test/UnitTests.cpp
maxmcguire/rocket
d7df8a698da25ed0aae125579fd2a58e3f07c48b
[ "MIT" ]
6
2015-10-07T22:43:18.000Z
2021-12-20T05:48:54.000Z
src/Test/UnitTests.cpp
maxmcguire/rocket
d7df8a698da25ed0aae125579fd2a58e3f07c48b
[ "MIT" ]
null
null
null
src/Test/UnitTests.cpp
maxmcguire/rocket
d7df8a698da25ed0aae125579fd2a58e3f07c48b
[ "MIT" ]
3
2015-06-19T04:58:50.000Z
2020-01-19T16:19:22.000Z
/* * RocketVM * Copyright (c) 2011 Max McGuire * * See copyright notice in COPYRIGHT */ #include "Test.h" #include "LuaTest.h" #include <string.h> #include <stdlib.h> #include <stdio.h> static size_t GetTotalBytes(lua_State* L) { return lua_gc(L, LUA_GCCOUNT, 0) * 1024 + lua_gc(L, LUA_GCCOUNTB, 0); } TEST(GcTest) { lua_State* L = luaL_newstate(); lua_pushstring(L, "garbage string"); lua_pop(L, 1); lua_gc(L, LUA_GCCOLLECT, 0); size_t bytes1 = GetTotalBytes(L); CHECK(bytes1 > 0); // Create a piece of garbage. int table = lua_gettop(L); lua_newtable(L); lua_pop(L, 1); // Check that the garbage is cleaned up. lua_gc(L, LUA_GCCOLLECT, 0); size_t bytes2 = GetTotalBytes(L); CHECK( bytes2 <= bytes1 ); lua_close(L); } TEST_FIXTURE(ToCFunction, LuaFixture) { struct Locals { static int F(lua_State* L) { return 0; } }; lua_pushcfunction(L, Locals::F); CHECK( lua_tocfunction(L, -1) == Locals::F ); const char* code = "function f() end\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "f"); CHECK( lua_tocfunction(L, -1) == NULL ); lua_pushstring(L, "test"); CHECK( lua_tocfunction(L, -1) == NULL ); lua_pushnumber(L, 1.0); CHECK( lua_tocfunction(L, -1) == NULL ); } TEST_FIXTURE(ConcatTest, LuaFixture) { int top = lua_gettop(L); lua_pushstring(L, "Hello "); lua_pushnumber(L, 5.0); lua_pushstring(L, " goodbye"); lua_concat(L, 3); const char* result = lua_tostring(L, -1); CHECK( strcmp(result, "Hello 5 goodbye") == 0 ); CHECK( lua_gettop(L) - top == 1 ); } TEST_FIXTURE(InsertTest, LuaFixture) { int top = lua_gettop(L); lua_pushinteger(L, 1); lua_pushinteger(L, 3); lua_pushinteger(L, 2); lua_insert(L, -2); CHECK( lua_tointeger(L, -3) == 1 ); CHECK( lua_tointeger(L, -2) == 2 ); CHECK( lua_tointeger(L, -1) == 3 ); CHECK( lua_gettop(L) - top == 3 ); } TEST_FIXTURE(Replace, LuaFixture) { int top = lua_gettop(L); lua_pushinteger(L, 1); lua_pushinteger(L, 3); lua_pushinteger(L, 2); lua_replace(L, -3); CHECK( lua_tointeger(L, -2) == 2 ); CHECK( lua_tointeger(L, -1) == 3 ); CHECK( lua_gettop(L) - top == 2 ); } TEST_FIXTURE(RawEqual, LuaFixture) { lua_pushinteger(L, 1); lua_pushinteger(L, 3); CHECK( lua_rawequal(L, -1, -2) == 0 ); lua_pop(L, 2); lua_pushinteger(L, 1); lua_pushinteger(L, 1); CHECK( lua_rawequal(L, -1, -2) == 1 ); lua_pop(L, 2); lua_pushstring(L, "test1"); lua_pushstring(L, "test2"); CHECK( lua_rawequal(L, -1, -2) == 0 ); lua_pop(L, 2); lua_pushstring(L, "test1"); lua_pushstring(L, "test1"); CHECK( lua_rawequal(L, -1, -2) == 1 ); lua_pop(L, 2); lua_pushvalue(L, LUA_GLOBALSINDEX); CHECK( lua_rawequal(L, lua_gettop(L), LUA_GLOBALSINDEX) == 1 ); lua_pop(L, 1); lua_pushvalue(L, LUA_REGISTRYINDEX); CHECK( lua_rawequal(L, LUA_REGISTRYINDEX, lua_gettop(L)) == 1 ); lua_pop(L, 1); } TEST_FIXTURE(Less, LuaFixture) { lua_pushinteger(L, 1); lua_pushinteger(L, 3); CHECK( lua_lessthan(L, -2, -1) == 1 ); lua_pop(L, 2); lua_pushinteger(L, 3); lua_pushinteger(L, 1); CHECK( lua_lessthan(L, -2, -1) == 0 ); lua_pop(L, 2); lua_pushinteger(L, 3); lua_pushinteger(L, 3); CHECK( lua_lessthan(L, -2, -1) == 0 ); lua_pop(L, 2); // TODO: Test metamethods. } TEST_FIXTURE(PCallTest, LuaFixture) { struct Locals { static int ErrorFunction(lua_State* L) { lua_pushstring(L, "Error message"); lua_error(L); return 0; } }; lua_pushstring(L, "dummy"); int top = lua_gettop(L); lua_pushcfunction(L, Locals::ErrorFunction); CHECK( lua_pcall(L, 0, 0, 0) == LUA_ERRRUN ); CHECK( strcmp( lua_tostring(L, -1), "Error message") == 0 ); CHECK( lua_gettop(L) - top == 1 ); } TEST_FIXTURE(ErrorRestore, LuaFixture) { struct Locals { static int ErrorFunction(lua_State* L) { lua_pushnumber(L, 3.0); lua_pushnumber(L, 4.0); lua_pushnumber(L, 5.0); lua_pushstring(L, "Error message"); lua_error(L); return 0; } }; lua_pushstring(L, "test"); int top = lua_gettop(L); lua_pushcfunction(L, Locals::ErrorFunction); lua_pushnumber(L, 1.0); lua_pushnumber(L, 2.0); CHECK( lua_pcall(L, 2, 0, 0) == LUA_ERRRUN ); CHECK( lua_gettop(L) - top == 1 ); CHECK( lua_isstring(L, -1) ); CHECK( strcmp( lua_tostring(L, -1), "Error message") == 0 ); // Check that the stack is in the correct state. CHECK( lua_isstring(L, -2) ); CHECK( strcmp( lua_tostring(L, -2), "test") == 0); } TEST_FIXTURE(ErrorRestore2, LuaFixture) { lua_pushstring(L, "dummy"); int top = lua_gettop(L); int result = luaL_loadbuffer(L, "x", 1, NULL); CHECK( result != 0); CHECK (lua_gettop(L) - top == 1 ); } TEST_FIXTURE(ErrorHandler, LuaFixture) { // Test an error handler for lua_pcall. struct Locals { static int ErrorFunction(lua_State* L) { lua_pushnumber(L, 3); lua_pushnumber(L, 4); lua_pushstring(L, "Error message"); lua_error(L); return 0; } static int ErrorHandler(lua_State* L) { const char* msg = lua_tostring(L, 1); if (msg != NULL && strcmp(msg, "Error message") == 0) { lua_pushstring(L, "Error handler"); } return 1; } }; lua_pushcfunction(L, Locals::ErrorHandler ); int err = lua_gettop(L); int top = lua_gettop(L); lua_pushcfunction(L, Locals::ErrorFunction); lua_pushnumber(L, 1); lua_pushnumber(L, 2); CHECK( lua_pcall(L, 2, 0, err) == LUA_ERRRUN ); CHECK( strcmp( lua_tostring(L, -1), "Error handler") == 0 ); CHECK( lua_gettop(L) - top == 1 ); } TEST_FIXTURE(ErrorHandlerError, LuaFixture) { // Test generating an error from inside the error handler for lua_pcall. struct Locals { static int ErrorFunction(lua_State* L) { lua_pushnumber(L, 3); lua_pushnumber(L, 4); lua_pushstring(L, "Error message"); lua_error(L); return 0; } static int ErrorHandler(lua_State* L) { lua_pushnumber(L, 5); lua_pushnumber(L, 6); lua_pushstring(L, "Error handler error"); lua_error(L); return 1; } }; lua_pushcfunction(L, Locals::ErrorHandler ); int err = lua_gettop(L); int top = lua_gettop(L); lua_pushcfunction(L, Locals::ErrorFunction); lua_pushnumber(L, 1); lua_pushnumber(L, 2); CHECK( lua_pcall(L, 2, 0, err) == LUA_ERRERR ); CHECK( lua_isstring(L, -1) ); CHECK( lua_gettop(L) - top == 1 ); } TEST_FIXTURE(GetTable, LuaFixture) { lua_newtable(L); int table = lua_gettop(L); lua_pushstring(L, "key"); lua_pushstring(L, "value"); lua_settable(L, table); int top = lua_gettop(L); lua_pushstring(L, "key"); lua_gettable(L, table); CHECK_EQ( lua_tostring(L, -1), "value" ); CHECK( lua_gettop(L) - top == 1 ); top = lua_gettop(L); lua_pushstring(L, "dummy"); lua_gettable(L, table); CHECK( lua_isnil(L, -1) ); CHECK( lua_gettop(L) - top == 1 ); } TEST_FIXTURE(GetTableMetamethod, LuaFixture) { struct Locals { static int Index(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); ++locals->calls; const char* key = lua_tostring(L, 2); if (key != NULL && strcmp(key, "key") == 0) { locals->success = true; } lua_pushstring(L, "value"); return 1; } int calls; bool success; }; Locals locals; locals.success = false; locals.calls = 0; lua_newtable(L); int table = lua_gettop(L); // Setup a metatable for the table. lua_newtable(L); lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Index, 1); lua_setfield(L, -2, "__index"); lua_setmetatable(L, table); lua_pushstring(L, "key"); lua_gettable(L, table); CHECK_EQ( lua_tostring(L, -1), "value" ); CHECK( locals.success ); CHECK( locals.calls == 1 ); } TEST_FIXTURE(UserDataGetTableMetamethod, LuaFixture) { struct Locals { static int Index(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); ++locals->calls; const char* key = lua_tostring(L, 2); if (key != NULL && strcmp(key, "key") == 0) { locals->success = true; } lua_pushstring(L, "value"); return 1; } int calls; bool success; }; Locals locals; locals.success = false; locals.calls = 0; lua_newuserdata(L, 10); int object = lua_gettop(L); // Setup a metatable for the object. lua_newtable(L); lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Index, 1); lua_setfield(L, -2, "__index"); lua_setmetatable(L, object); lua_pushstring(L, "key"); lua_gettable(L, object); CHECK_EQ( lua_tostring(L, -1), "value" ); CHECK( locals.success ); CHECK( locals.calls == 1 ); } TEST_FIXTURE(CallMetamethod, LuaFixture) { // Test the __call metamethod. struct Locals { static int Call(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); if (lua_gettop(L) == 3 && lua_touserdata(L, 1) == locals->userData && lua_tonumber(L, 2) == 1.0 && lua_tonumber(L, 3) == 2.0) { locals->success = true; } lua_pushstring(L, "result"); return 1; } bool success; void* userData; }; Locals locals; locals.success = false; locals.userData = lua_newuserdata(L, 10); int object = lua_gettop(L); lua_newtable(L); int mt = lua_gettop(L); lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Call, 1); lua_setfield(L, mt, "__call"); CHECK( lua_setmetatable(L, object) == 1 ); lua_pushnumber(L, 1.0); lua_pushnumber(L, 2.0); CHECK( lua_pcall(L, 2, 1, 0) == 0 ); CHECK( locals.success ); CHECK_EQ( lua_tostring(L, -1), "result" ); } TEST_FIXTURE(AddMetamethod, LuaFixture) { struct Locals { static int Op(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); if (lua_gettop(L) == 2 && lua_touserdata(L, 1) == locals->userData && lua_tonumber(L, 2) == 5.0) { locals->success = true; } lua_pushstring(L, "result"); return 1; } void* userData; bool success; }; Locals locals; locals.success = false; // Test the __add metamethod. locals.userData = lua_newuserdata(L, 10); int object = lua_gettop(L); lua_newtable(L); int mt = lua_gettop(L); lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Op, 1); lua_setfield(L, mt, "__add"); lua_setmetatable(L, object); lua_pushvalue(L, object); lua_setglobal(L, "ud"); const char* code = "result = ud + 5"; CHECK( DoString(L, code) ); lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "result" ); CHECK( locals.success ); } TEST_FIXTURE(UnaryMinusMetamethod, LuaFixture) { struct Locals { static int Op(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); if (lua_gettop(L) == 1 && lua_touserdata(L, 1) == locals->userData) { locals->success = true; } lua_pushstring(L, "result"); return 1; } void* userData; bool success; }; Locals locals; locals.success = false; // Test the __unm metamethod. locals.userData = lua_newuserdata(L, 10); int object = lua_gettop(L); lua_newtable(L); int mt = lua_gettop(L); lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Op, 1); lua_setfield(L, mt, "__unm"); lua_setmetatable(L, object); lua_pushvalue(L, object); lua_setglobal(L, "ud"); const char* code = "result = -ud"; CHECK( DoString(L, code) ); lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "result" ); CHECK( locals.success ); } TEST_FIXTURE(LessThanMetamethod, LuaFixture) { struct Locals { static int Op(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); if (lua_gettop(L) == 2 && lua_touserdata(L, 1) == locals->userData && lua_touserdata(L, 1) == locals->userData) { locals->success = true; } lua_pushboolean(L, 1); return 1; } void* userData; bool success; }; Locals locals; locals.success = false; // Test the __add metamethod. locals.userData = lua_newuserdata(L, 10); int object = lua_gettop(L); lua_newtable(L); int mt = lua_gettop(L); lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Op, 1); lua_setfield(L, mt, "__lt"); lua_setmetatable(L, object); lua_pushvalue(L, object); lua_setglobal(L, "ud"); const char* code = "result = ud < ud"; CHECK( DoString(L, code) ); lua_getglobal(L, "result"); CHECK( lua_toboolean(L, -1) ); CHECK( locals.success ); } TEST_FIXTURE(RawGetITest, LuaFixture) { lua_newtable(L); int table = lua_gettop(L); lua_pushstring(L, "extra"); lua_pushstring(L, "extra"); lua_settable(L, table); lua_pushinteger(L, 1); lua_pushstring(L, "one"); lua_settable(L, table); lua_rawgeti(L, table, 1); CHECK( strcmp( lua_tostring(L, -1), "one") == 0 ); } TEST_FIXTURE(RawGetTest, LuaFixture) { lua_newtable(L); int table = lua_gettop(L); lua_pushinteger(L, 1); lua_pushstring(L, "one"); lua_settable(L, table); int top = lua_gettop(L); lua_pushinteger(L, 1); lua_rawget(L, table); CHECK_EQ( lua_tostring(L, -1), "one" ); CHECK( lua_gettop(L) - top == 1 ); } TEST_FIXTURE(RawSetTest, LuaFixture) { struct Locals { static int Error(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); locals->called = true; return 0; } bool called; }; Locals locals; locals.called = false; lua_newtable(L); int table = lua_gettop(L); // Setup a metatable for the table. lua_newtable(L); lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Error, 1); lua_setfield(L, -2, "__index"); lua_setmetatable(L, table); lua_pushstring(L, "one"); lua_pushnumber(L, 1.0); lua_rawset(L, table); lua_pushstring(L, "two"); lua_pushnumber(L, 2.0); lua_rawset(L, table); lua_pushstring(L, "one"); lua_rawget(L, table); CHECK( lua_tonumber(L, -1) == 1.0 ); lua_pushstring(L, "two"); lua_rawget(L, table); CHECK( lua_tonumber(L, -1) == 2.0 ); } TEST_FIXTURE(RawSetITest, LuaFixture) { struct Locals { static int Error(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); locals->called = true; return 0; } bool called; }; Locals locals; locals.called = false; lua_newtable(L); int table = lua_gettop(L); // Setup a metatable for the table. lua_newtable(L); lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Error, 1); lua_setfield(L, -2, "__index"); lua_setmetatable(L, table); lua_pushstring(L, "one"); lua_rawseti(L, table, 1); lua_pushstring(L, "three"); lua_rawseti(L, table, 3); lua_rawgeti(L, table, 1); CHECK_EQ( lua_tostring(L, -1), "one" ); lua_rawgeti(L, table, 2); CHECK( lua_isnil(L, -1) ); lua_rawgeti(L, table, 3); CHECK_EQ( lua_tostring(L, -1), "three" ); } TEST_FIXTURE(NextTest, LuaFixture) { lua_newtable(L); int table = lua_gettop(L); lua_pushnumber(L, 1); lua_setfield(L, table, "first"); lua_pushnumber(L, 2); lua_setfield(L, table, "second"); lua_pushnumber(L, 3); lua_setfield(L, table, "third"); int top = lua_gettop(L); lua_pushnil(L); int count[3] = { 0 }; while (lua_next(L, table)) { CHECK( lua_gettop(L) - top == 2 ); const char* key = lua_tostring(L, -2); lua_Number value = lua_tonumber(L, -1); int index = -1; if (strcmp(key, "first") == 0) { CHECK(value == 1.0); index = 0; } else if (strcmp(key, "second") == 0) { CHECK(value == 2.0); index = 1; } else if (strcmp(key, "third") == 0) { CHECK(value == 3.0); index = 2; } // Check that we didn't get a key not in the table. CHECK(index != -1); ++count[index]; lua_pop(L, 1); } CHECK( lua_gettop(L) - top == 0 ); // Check each element was iterated exactly once. CHECK(count[0] == 1); CHECK(count[1] == 1); CHECK(count[2] == 1); } TEST_FIXTURE(RemoveTest, LuaFixture) { lua_pushinteger(L, 1); int start = lua_gettop(L); lua_pushinteger(L, 2); lua_pushinteger(L, 3); lua_pushinteger(L, 4); lua_remove(L, start); CHECK( lua_tointeger(L, start) == 2 ); lua_remove(L, -1); CHECK( lua_tointeger(L, -1) == 3 ); } TEST_FIXTURE(Metatable, LuaFixture) { lua_newtable(L); int table = lua_gettop(L); lua_pushinteger(L, 2); lua_setfield(L, table, "b"); lua_newtable(L); int mt = lua_gettop(L); lua_pushvalue(L, mt); lua_setfield(L, mt, "__index"); lua_pushinteger(L, 1); lua_setfield(L, mt, "a"); CHECK( lua_setmetatable(L, table) == 1 ); // Test the value in the metatable. lua_getfield(L, table, "a"); CHECK( lua_tointeger(L, -1) == 1 ); lua_pop(L, 1); // Test the value in the table. lua_getfield(L, table, "b"); CHECK( lua_tointeger(L, -1) == 2 ); lua_pop(L, 1); // Test a value that doesn't exist in either. lua_getfield(L, table, "c"); CHECK( lua_isnil(L, -1) == 1 ); lua_pop(L, 1); } TEST_FIXTURE(NewMetatable, LuaFixture) { CHECK( luaL_newmetatable(L, "test") == 1 ); CHECK( lua_istable(L, -1) ); lua_pop(L, 1); lua_getfield(L, LUA_REGISTRYINDEX, "test"); CHECK( lua_istable(L, -1) ); lua_pop(L, 1); CHECK( luaL_newmetatable(L, "test") == 0 ); CHECK( lua_istable(L, -1) ); lua_pop(L, 1); } TEST_FIXTURE(DefaultEnvTable, LuaFixture) { // Check that the globals table is used as the default environment. lua_newuserdata(L, 10); lua_getfenv(L, -1); CHECK( lua_istable(L, -1) ); lua_pushvalue(L, LUA_GLOBALSINDEX); CHECK( lua_rawequal(L, -1, -2) ); lua_pop(L, 3); } TEST_FIXTURE(EnvTable, LuaFixture) { lua_newtable(L); int env = lua_gettop(L); int top = lua_gettop(L); // Can't set the environment table on a table. lua_newtable(L); lua_pushvalue(L, env); CHECK( lua_setfenv(L, -2) == 0 ); CHECK( lua_gettop(L) - top == 1 ); lua_getfenv(L, -1); CHECK( lua_isnil(L, -1) ); lua_pop(L, 2); // Set the environment table on a user data. lua_newuserdata(L, 10); lua_pushvalue(L, env); CHECK( lua_setfenv(L, -2) == 1 ); CHECK( lua_gettop(L) - top == 1 ); lua_getfenv(L, -1); CHECK( lua_istable(L, -1) ); CHECK( lua_rawequal(L, -1, env) ); lua_pop(L, 2); } TEST_FIXTURE(SetFEnv, LuaFixture) { const char* code = "A = 5\n" "function F() return A end\n" "setfenv(F, {A=12})\n" "B = F()"; CHECK( DoString(L, code) ); lua_getglobal(L, "B"); CHECK_EQ( lua_tonumber(L, -1), 12 ); } TEST_FIXTURE(SetMetatableUserData, LuaFixture) { lua_newuserdata(L, 10); int object = lua_gettop(L); lua_newtable(L); int mt = lua_gettop(L); int top = lua_gettop(L); lua_pushvalue(L, mt); lua_setmetatable(L, object); CHECK( lua_gettop(L) - top == 0); top = lua_gettop(L); CHECK( lua_getmetatable(L, object) == 1 ); CHECK( lua_gettop(L) - top == 1); CHECK( lua_rawequal(L, -1, mt) ); } TEST_FIXTURE(SetMetatableNil, LuaFixture) { lua_newuserdata(L, 10); int object = lua_gettop(L); int top = lua_gettop(L); lua_pushnil(L); lua_setmetatable(L, object); CHECK( lua_gettop(L) - top == 0); top = lua_gettop(L); CHECK( lua_getmetatable(L, object) == 0 ); CHECK( lua_gettop(L) - top == 0 ); } TEST_FIXTURE(CClosure, LuaFixture) { struct Locals { static int Function(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); lua_Integer a = lua_tointeger(L, lua_upvalueindex(2)); lua_Integer b = lua_tointeger(L, lua_upvalueindex(3)); CHECK( a == 10 ); CHECK( b == 20 ); CHECK( lua_isnone(L, lua_upvalueindex(4)) == 1 ); locals->called = true; return 0; } bool called; }; int start = lua_gettop(L); Locals locals; locals.called = false; lua_pushlightuserdata(L, &locals); lua_pushinteger(L, 10); lua_pushinteger(L, 20); lua_pushcclosure(L, Locals::Function, 3); // The closure should be the only thing left. CHECK( lua_gettop(L) - start == 1 ); lua_call(L, 0, 0); CHECK( locals.called ); } TEST_FIXTURE(LightUserData, LuaFixture) { void* p = reinterpret_cast<void*>(0x12345678); lua_pushlightuserdata(L, p); CHECK( lua_type(L, -1) == LUA_TLIGHTUSERDATA ); CHECK( lua_touserdata(L, -1) == p ); lua_pop(L, 1); } TEST_FIXTURE(UserData, LuaFixture) { void* buffer = lua_newuserdata(L, 10); CHECK( buffer != NULL ); CHECK( lua_type(L, -1) == LUA_TUSERDATA ); CHECK( lua_touserdata(L, -1) == buffer ); lua_pop(L, 1); } TEST_FIXTURE(NewIndexMetamethod, LuaFixture) { struct Locals { static int NewIndex(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); CHECK( lua_gettop(L) == 3 ); CHECK_EQ( lua_tostring(L, 2), "key" ); CHECK_EQ( lua_tostring(L, 3), "value" ); locals->called = true; return 0; } bool called; }; lua_newtable(L); int table = lua_gettop(L); lua_newtable(L); int mt = lua_gettop(L); Locals locals; locals.called = false; lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, &Locals::NewIndex, 1); lua_setfield(L, mt, "__newindex"); CHECK( lua_setmetatable(L, table) == 1 ); lua_pushstring(L, "value"); lua_setfield(L, table, "key"); CHECK( locals.called ); lua_pop(L, 1); } TEST_FIXTURE(GetUpValueCFunction, LuaFixture) { struct Locals { static int F(lua_State* L) { return 0; } }; lua_pushstring(L, "test1"); lua_pushstring(L, "test2"); lua_pushcclosure(L, Locals::F, 2); int func = lua_gettop(L); CHECK_EQ( lua_getupvalue(L, func, 1), "" ); CHECK_EQ( lua_tostring(L, -1), "test1" ); lua_pop(L, 1); CHECK_EQ( lua_getupvalue(L, func, 2), "" ); CHECK_EQ( lua_tostring(L, -1), "test2" ); lua_pop(L, 1); CHECK( lua_getupvalue(L, func, 3) == NULL ); } TEST_FIXTURE(GetUpValueLuaFunction, LuaFixture) { const char* code = "local a = 'test1'\n" "local b = 'test2'\n" "function f()\n" " local x = a\n" " local y = b\n" "end"; CHECK( DoString(L, code) ); lua_getglobal(L, "f"); CHECK( lua_isfunction(L, -1) ); int func = lua_gettop(L); CHECK_EQ( lua_getupvalue(L, func, 1), "a" ); CHECK_EQ( lua_tostring(L, -1), "test1" ); lua_pop(L, 1); CHECK_EQ( lua_getupvalue(L, func, 2), "b" ); CHECK_EQ( lua_tostring(L, -1), "test2" ); lua_pop(L, 1); CHECK( lua_getupvalue(L, func, 3) == NULL ); } TEST_FIXTURE(GetStackEmpty, LuaFixture) { lua_Debug ar; CHECK( lua_getstack(L, 0, &ar) == 0); } TEST_FIXTURE(GetInfo, LuaFixture) { // Test the lua_getinfo function. struct Locals { static int F(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); if (lua_getstack(L, 0, &locals->top) == 1) { lua_getinfo(L, "lnS", &locals->top); } return 0; } lua_Debug top; }; Locals locals; lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, &Locals::F, 1); lua_call(L, 0, 0); } TEST_FIXTURE(GetInfoF, LuaFixture) { // Test the lua_getinfo function with the "f" parameter. struct Locals { static int F(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); lua_Debug ar; // Top of the stack should be this function. if (!lua_getstack(L, 0, &ar)) { locals->success = false; return 0; } lua_getinfo(L, "f", &ar); if (lua_tocfunction(L, -1) != F) { locals->success = false; return 0; } lua_pop(L, 1); // Next on the stack should be our Lua function. if (!lua_getstack(L, 1, &ar)) { locals->success = false; return 0; } lua_getinfo(L, "f", &ar); lua_getglobal(L, "G"); if (!lua_rawequal(L, -1, -2)) { locals->success = false; return 0; } lua_pop(L, 1); locals->success = true; return 0; } bool success; }; Locals locals; locals.success = false; lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, &Locals::F, 1); lua_setglobal(L, "F"); const char* code = "function G() F() end\n" "G()"; CHECK( DoString(L, code) ); CHECK( locals.success ); } TEST_FIXTURE(MultipleAssignment, LuaFixture) { const char* code = "a, b, c = 1, 2"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1 ); lua_getglobal(L, "b"); CHECK( lua_tonumber(L, -1) == 2 ); lua_getglobal(L, "c"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(MultipleAssignment2, LuaFixture) { struct Locals { static int Function(lua_State* L) { lua_pushnumber(L, 2.0); lua_pushnumber(L, 3.0); return 2; } }; const char* code = "a, b, c = 1, F()"; lua_register(L, "F", Locals::Function); CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1.0 ); lua_getglobal(L, "b"); CHECK( lua_tonumber(L, -1) == 2.0 ); lua_getglobal(L, "c"); CHECK( lua_tonumber(L, -1) == 3.0 ); } TEST_FIXTURE(MultipleAssignment3, LuaFixture) { const char* code = "local a = 10\n" "a, b = 5, a"; CHECK( DoString(L, code) ); lua_getglobal(L, "b"); CHECK_EQ( lua_tonumber(L, -1), 10 ); } TEST_FIXTURE(MultipleAssignment4, LuaFixture) { const char* code = "local a = 10\n" "b, a = a, 5"; CHECK( DoString(L, code) ); lua_getglobal(L, "b"); CHECK_EQ( lua_tonumber(L, -1), 10 ); } TEST_FIXTURE(MultipleAssignment5, LuaFixture) { const char* code = "x = 1, 2"; CHECK( DoString(L, code) ); lua_getglobal(L, "x"); CHECK_EQ( lua_tonumber(L, -1), 1 ); } TEST_FIXTURE(MultipleAssignment6, LuaFixture) { const char* code = "local a = { }\n" "a[1], a = 1, 1"; CHECK( DoString(L, code) ); } TEST_FIXTURE(AssignmentSideEffect, LuaFixture) { const char* code = "function F() b = 2 end\n" "a = 1, F(), 3"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1 ); lua_getglobal(L, "b"); CHECK( lua_tonumber(L, -1) == 2 ); } TEST_FIXTURE(LocalMultipleAssignment, LuaFixture) { const char* code = "local _a, _b, _c = 1, 2\n" "a = _a\n" "b = _b\n" "c = _c\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1 ); lua_getglobal(L, "b"); CHECK( lua_tonumber(L, -1) == 2 ); lua_getglobal(L, "c"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(LocalMultipleAssignment2, LuaFixture) { struct Locals { static int Function(lua_State* L) { lua_pushnumber(L, 2.0); lua_pushnumber(L, 3.0); return 2; } }; const char* code = "local _a, _b, _c = 1, F()\n" "a = _a\n" "b = _b\n" "c = _c\n"; lua_register(L, "F", Locals::Function); CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1.0 ); lua_getglobal(L, "b"); CHECK( lua_tonumber(L, -1) == 2.0 ); lua_getglobal(L, "c"); CHECK( lua_tonumber(L, -1) == 3.0 ); } TEST_FIXTURE(LocalMultipleAssignment3, LuaFixture) { const char* code = "local _a, _b = 1, _a\n" "a = _a\n" "b = _b"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1.0 ); // a should not be visible until after the declaration is complete. lua_getglobal(L, "b"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(AssignmentNoValue, LuaFixture) { const char* code = "function g() end\n" "function f() return g() end\n" "a = f()"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(TableConstructor, LuaFixture) { const char* code = "t = { 'one', three = 3, 'two', [2 + 2] = 'four', (function () return 3 end)() }"; CHECK( DoString(L, code) ); lua_getglobal(L, "t"); CHECK( lua_istable(L, -1) == 1 ); lua_rawgeti(L, -1, 1); CHECK( strcmp(lua_tostring(L, -1), "one") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 2); CHECK( strcmp(lua_tostring(L, -1), "two") == 0 ); lua_pop(L, 1); lua_getfield(L, -1, "three"); CHECK( lua_tonumber(L, -1) == 3.0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 4); CHECK( strcmp(lua_tostring(L, -1), "four") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 3); CHECK( lua_tonumber(L, -1) == 3.0 ); lua_pop(L, 1); } TEST_FIXTURE(TableConstructorVarArg, LuaFixture) { const char* code = "function f(...)\n" " t = { 'zero', ... }\n" "end\n" "f('one', 'two', 'three')"; CHECK( DoString(L, code) ); lua_getglobal(L, "t"); CHECK( lua_istable(L, -1) == 1 ); lua_rawgeti(L, -1, 1); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "zero") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 2); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "one") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 3); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "two") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 4); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "three") == 0 ); lua_pop(L, 1); } TEST_FIXTURE(TableConstructorFunction1, LuaFixture) { const char* code = "function f()\n" " return 'one', 'two', 'three'\n" "end\n" "t = { 'zero', f() }"; CHECK( DoString(L, code) ); lua_getglobal(L, "t"); CHECK( lua_istable(L, -1) == 1 ); lua_rawgeti(L, -1, 1); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "zero") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 2); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "one") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 3); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "two") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 4); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "three") == 0 ); lua_pop(L, 1); } TEST_FIXTURE(TableConstructorFunction2, LuaFixture) { const char* code = "function f()\n" " return 'success'\n" "end\n" "t = { f('test') }"; CHECK( DoString(L, code) ); lua_getglobal(L, "t"); lua_rawgeti(L, -1, 1); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(TableConstructorTrailingComma, LuaFixture) { // Lua allows for a trailing comma in a table, even though it doesn't // actually syntatically make sense. const char* code = "t = { 'one', }"; CHECK( DoString(L, code) ); lua_getglobal(L, "t"); CHECK( lua_istable(L, -1) == 1 ); lua_rawgeti(L, -1, 1); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "one") == 0 ); lua_pop(L, 1); } TEST_FIXTURE(TableConstructorFunctionTrailingComma, LuaFixture) { const char* code = "function f()\n" " return 'one', 'two', 'three'\n" "end\n" "t = { 'zero', f(), }"; CHECK( DoString(L, code) ); lua_getglobal(L, "t"); CHECK( lua_istable(L, -1) == 1 ); lua_rawgeti(L, -1, 1); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "zero") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 2); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "one") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 3); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "two") == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 4); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "three") == 0 ); lua_pop(L, 1); } TEST_FIXTURE(EmptyReturn, LuaFixture) { // Test parsing of an empty return from a block const char* code = "do\n" " return\n" "end\n"; CHECK( DoString(L, code) ); } TEST_FIXTURE(Return, LuaFixture) { const char* code = "function Foo()\n" " return 5\n" "end\n" "v = Foo()"; CHECK( DoString(L, code) ); lua_getglobal(L, "v"); CHECK( lua_tonumber(L, -1) == 5.0 ); } TEST_FIXTURE(ReturnMultiple, LuaFixture) { const char* code = "function Foo()\n" " return 5, 6\n" "end\n" "v1, v2 = Foo()"; CHECK( DoString(L, code) ); lua_getglobal(L, "v1"); CHECK( lua_tonumber(L, -1) == 5.0 ); lua_getglobal(L, "v2"); CHECK( lua_tonumber(L, -1) == 6.0 ); } TEST_FIXTURE(ReturnEmpty, LuaFixture) { const char* code = "function Foo()\n" " return ;\n" "end"; CHECK( DoString(L, code) ); } TEST_FIXTURE(ReturnTopLevel, LuaFixture) { const char* code = "return 'result'"; CHECK( luaL_loadstring(L, code) == 0); CHECK( lua_pcall(L, 0, 1, 0) == 0); CHECK_EQ( lua_tostring(L, -1), "result" ); lua_pop(L, 1); } TEST_FIXTURE(FunctionStringArgument, LuaFixture) { const char* code = "function Foo(arg1, arg2)\n" " s = arg1\n" " n = arg2\n" "end\n" "Foo 'test'"; CHECK( DoString(L, code) ); lua_getglobal(L, "s"); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "test") == 0 ); lua_getglobal(L, "n"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(FunctionTableArgument, LuaFixture) { const char* code = "function Foo(arg1, arg2)\n" " t = arg1\n" " n = arg2\n" "end\n" "Foo { }"; CHECK( DoString(L, code) ); lua_getglobal(L, "t"); CHECK( lua_istable(L, -1) ); lua_getglobal(L, "n"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(FunctionMethod, LuaFixture) { const char* code = "result = false\n" "Foo = { }\n" "function Foo:Bar()\n" " if self == Foo then result = true end\n" "end\n" "Foo:Bar()\n"; CHECK( DoString(L, code) ); // Check that the function was properly created. lua_getglobal(L, "Foo"); lua_getfield(L, -1, "Bar"); CHECK( lua_type(L, -1) == LUA_TFUNCTION ); lua_pop(L, 2); // Check that the function was properly called. lua_getglobal(L, "result"); CHECK( lua_toboolean(L, -1) == 1 ); } TEST_FIXTURE(FunctionMethodStringArg, LuaFixture) { const char* code = "result = false\n" "Foo = { }\n" "function Foo:Bar(_arg)\n" " if self == Foo then result = true end\n" " arg = _arg\n" "end\n" "Foo:Bar 'test'\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "result"); CHECK( lua_toboolean(L, -1) == 1 ); lua_getglobal(L, "arg"); CHECK( lua_isstring(L, -1) ); CHECK( strcmp(lua_tostring(L, -1), "test") == 0 ); } TEST_FIXTURE(FunctionDefinition, LuaFixture) { const char* code = "function Foo() end"; CHECK( luaL_dostring(L, code) == 0 ); lua_getglobal(L, "Foo"); CHECK( lua_type(L, -1) == LUA_TFUNCTION ); } TEST_FIXTURE(ScopedFunctionDefinition, LuaFixture) { const char* code = "Foo = { }\n" "Foo.Bar = { }\n" "function Foo.Bar.Baz() end"; CHECK( luaL_dostring(L, code) == 0 ); lua_getglobal(L, "Foo"); lua_getfield(L, -1, "Bar"); lua_getfield(L, -1, "Baz"); CHECK( lua_type(L, -1) == LUA_TFUNCTION ); } TEST_FIXTURE(FunctionMethodDefinition, LuaFixture) { const char* code = "Foo = { }\n" "function Foo:Bar() end"; CHECK( luaL_dostring(L, code) == 0 ); lua_getglobal(L, "Foo"); lua_getfield(L, -1, "Bar"); CHECK( lua_type(L, -1) == LUA_TFUNCTION ); } TEST_FIXTURE(LocalFunctionDefinition, LuaFixture) { const char* code = "local function Foo() end\n" "Bar = Foo"; CHECK( luaL_dostring(L, code) == 0 ); lua_getglobal(L, "Bar"); CHECK( lua_type(L, -1) == LUA_TFUNCTION ); lua_getglobal(L, "Foo"); CHECK( lua_type(L, -1) == LUA_TNIL ); } TEST_FIXTURE(LocalScopedFunctionDefinition, LuaFixture) { const char* code = "Foo = { }\n" "local function Foo.Bar() end"; // Scoping makes no sense when we're defining a local. CHECK( luaL_dostring(L, code) == 1 ); } TEST_FIXTURE(LocalMethod, LuaFixture) { const char* code = "local t = { }\n" "function t:c() return { d = 5 } end\n" "a = t:c().d"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 5 ); } TEST_FIXTURE(WhileLoop, LuaFixture) { const char* code = "result = 'failure'\n" "index = 0\n" "while index < 10 do\n" " index = index + 1\n" "end\n" "result = 'success'"; CHECK( DoString(L, code) ); lua_getglobal(L, "index"); CHECK( lua_type(L, -1) == LUA_TNUMBER ); CHECK( lua_tointeger(L, -1) == 10 ); // Make sure we execute the line immediately after the loop lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(ForLoop1, LuaFixture) { const char* code = "result = 'failure'\n" "index = 0\n" "for i = 1,10 do\n" " index = index + 1\n" "end\n" "result = 'success'"; CHECK( DoString(L, code) ); lua_getglobal(L, "index"); CHECK( lua_type(L, -1) == LUA_TNUMBER ); CHECK( lua_tointeger(L, -1) == 10 ); // The index for the loop shouldn't be in the global space. lua_getglobal(L, "i"); CHECK( lua_isnil(L, -1) != 0 ); // Make sure we execute the line immediately after the loop lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(ForLoop2, LuaFixture) { const char* code = "result = 'failure'\n" "index = 0\n" "for i = 1,10,2 do\n" " index = index + 1\n" "end\n" "result = 'success'"; CHECK( DoString(L, code) ); lua_getglobal(L, "index"); CHECK( lua_type(L, -1) == LUA_TNUMBER ); CHECK( lua_tointeger(L, -1) == 5 ); // The index for the loop shouldn't be in the global space. lua_getglobal(L, "i"); CHECK( lua_isnil(L, -1) != 0 ); // Make sure we execute the line immediately after the loop lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(ForLoop3, LuaFixture) { const char* code = "result = 'failure'\n" "values = { first=1, second=2 }\n" "results = { }\n" "index = 0\n" "for k,v in pairs(values) do\n" " index = index + 1\n" " results[v] = k\n" "end\n" "result = 'success'"; CHECK( DoString(L, code) ); lua_getglobal(L, "index"); CHECK( lua_type(L, -1) == LUA_TNUMBER ); CHECK( lua_tointeger(L, -1) == 2 ); // The index for the loop shouldn't be in the global space. lua_getglobal(L, "k"); CHECK( lua_isnil(L, -1) != 0 ); lua_getglobal(L, "v"); CHECK( lua_isnil(L, -1) != 0 ); lua_getglobal(L, "results"); lua_rawgeti(L, -1, 1); CHECK( lua_isstring(L, -1) ); CHECK( strcmp( lua_tostring(L, -1), "first" ) == 0 ); lua_pop(L, 1); lua_rawgeti(L, -1, 2); CHECK( lua_isstring(L, -1) ); CHECK( strcmp( lua_tostring(L, -1), "second" ) == 0 ); lua_pop(L, 1); // Make sure we execute the line immediately after the loop lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(ForLoop4, LuaFixture) { const char* code = "result = 'failure'\n" "_t = { 'one', 'two', 'three' }\n" "t = { }\n" "num = 1\n" "for i, v in ipairs(_t) do\n" " if i ~= num then break end\n" " t[num] = v\n" " num = num + 1\n" "end\n" "result = 'success'"; CHECK( DoString(L, code) ); lua_getglobal(L, "t"); int t = lua_gettop(L); lua_rawgeti(L, t, 1); CHECK_EQ( lua_tostring(L, -1), "one" ); lua_rawgeti(L, t, 2); CHECK_EQ( lua_tostring(L, -1), "two" ); lua_rawgeti(L, t, 3); CHECK_EQ( lua_tostring(L, -1), "three" ); // Make sure we execute the line immediately after the loop lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(ForLoop5, LuaFixture) { const char* code = "result = 'failure'\n" "index = 0\n" "for i = 9,0,-1 do\n" " index = index + 1\n" "end\n" "result = 'success'"; CHECK( DoString(L, code) ); lua_getglobal(L, "index"); CHECK( lua_type(L, -1) == LUA_TNUMBER ); CHECK( lua_tointeger(L, -1) == 10 ); // The index for the loop shouldn't be in the global space. lua_getglobal(L, "i"); CHECK( lua_isnil(L, -1) != 0 ); // Make sure we execute the line immediately after the loop lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(ForLoopScope, LuaFixture) { const char* code = "i = 5\n" "n = 0\n" "for i=i,10 do\n" " n = i\n" " break\n" "end\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "n"); CHECK_EQ( lua_tonumber(L, -1), 5.0 ); } TEST_FIXTURE(ForLoopEraseWhileIterating, LuaFixture) { const char* code = "local t = { 1, 2, 3, 4, 5 }\n" "n = 0\n" "for k, v in pairs( t ) do\n" " n = n+1\n" " t[k] = nil\n" "end"; CHECK( DoString(L, code) ); lua_getglobal(L, "n"); CHECK_EQ( lua_tonumber(L, -1), 5.0 ); } TEST_FIXTURE(RepeatLoop, LuaFixture) { const char* code = "result = 'failure'\n" "index = 0\n" "repeat\n" " index = index + 1\n" "until index == 10\n" "result = 'success'"; CHECK( DoString(L, code) ); lua_getglobal(L, "index"); CHECK( lua_type(L, -1) == LUA_TNUMBER ); CHECK( lua_tointeger(L, -1) == 10 ); // Make sure we execute the line immediately after the loop lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(WhileLoopBreak, LuaFixture) { const char* code = "result = 'failure'\n" "index = 0\n" "while true do\n" " index = index + 1\n" " break\n" "end\n" "result = 'success'"; CHECK( DoString(L, code) ); lua_getglobal(L, "index"); CHECK( lua_type(L, -1) == LUA_TNUMBER ); CHECK( lua_tointeger(L, -1) == 1 ); // Make sure we execute the line immediately after the loop lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(ForLoopBreak, LuaFixture) { const char* code = "result = 'failure'\n" "index = 0\n" "for i = 1,10 do\n" " index = index + 1\n" " break\n" "end\n" "result = 'success'"; CHECK( DoString(L, code) ); lua_getglobal(L, "index"); CHECK( lua_type(L, -1) == LUA_TNUMBER ); CHECK( lua_tointeger(L, -1) == 1 ); // Make sure we execute the line immediately after the loop lua_getglobal(L, "result"); CHECK_EQ( lua_tostring(L, -1), "success" ); } TEST_FIXTURE(RepeatLoopBreak, LuaFixture) { const char* code = "index = 0\n" "repeat\n" " index = index + 1\n" " break\n" "until index == 10"; CHECK( DoString(L, code) ); lua_getglobal(L, "index"); CHECK( lua_type(L, -1) == LUA_TNUMBER ); CHECK( lua_tointeger(L, -1) == 1 ); } TEST_FIXTURE(IllegalBreak, LuaFixture) { const char* code = "print('test')\n" "break"; CHECK( luaL_loadstring(L, code) != 0 ); } TEST_FIXTURE(FunctionCallStringArg, LuaFixture) { const char* code = "Function 'hello'"; struct Locals { static int Function(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); const char* arg = lua_tostring(L, 1); if (arg != NULL) { locals->passed = (strcmp(arg, "hello") == 0); } return 0; } bool passed; } locals; locals.passed = false; lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Function, 1); lua_setglobal(L, "Function"); CHECK( DoString(L, code) ); CHECK( locals.passed ); } TEST_FIXTURE(FunctionCallTableArgument, LuaFixture) { const char* code = "Function { }"; struct Locals { static int Function(lua_State* L) { Locals* locals = static_cast<Locals*>(lua_touserdata(L, lua_upvalueindex(1))); if (lua_istable(L, 1)) { locals->passed = true; } return 0; } bool passed; } locals; locals.passed = false; lua_pushlightuserdata(L, &locals); lua_pushcclosure(L, Locals::Function, 1); lua_setglobal(L, "Function"); CHECK( DoString(L, code) ); CHECK( locals.passed ); } TEST_FIXTURE(FunctionCallCompund, LuaFixture) { const char* code = "function f(s)\n" " a = s\n" " return function(n) b = n end\n" "end\n" "f 'test' (5)"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_EQ( lua_tostring(L, -1), "test"); lua_getglobal(L, "b"); CHECK( lua_tonumber(L, -1) == 5 ); } TEST_FIXTURE(FunctionCallFromLocal, LuaFixture) { // Check that calling a function doesn't corrupt the local variables. const char* code = "local a, b, r = nil\n" "r = function() return 10, 20 end\n" "a, b = r()\n" "A, B = a, b"; CHECK( DoString(L, code) ); lua_getglobal(L, "A"); CHECK_EQ( lua_tonumber(L, -1), 10 ); lua_pop(L, 1); lua_getglobal(L, "B"); CHECK_EQ( lua_tonumber(L, -1), 20 ); lua_pop(L, 1); } TEST_FIXTURE(LengthOperator, LuaFixture) { const char* code = "t = { 1 }\n" "l = #t"; CHECK( DoString(L, code) ); lua_getglobal(L, "l"); CHECK( lua_isnumber(L, -1) ); CHECK( lua_tonumber(L, -1) == 1 ); } TEST_FIXTURE(ConcatOperator, LuaFixture) { const char* code = "s = 'a' .. 'b' .. 'c'"; CHECK( DoString(L, code) ); lua_getglobal(L, "s"); const char* s = lua_tostring(L, -1); CHECK( s != NULL ); CHECK( strcmp(s, "abc") == 0 ); } TEST_FIXTURE(ConcatOperatorNumber, LuaFixture) { const char* code = "s = 4 .. 'h'"; CHECK( DoString(L, code) ); lua_getglobal(L, "s"); const char* s = lua_tostring(L, -1); CHECK( s != NULL ); CHECK( strcmp(s, "4h") == 0 ); } TEST_FIXTURE(VarArg1, LuaFixture) { const char* code = "function g(a, b, ...)\n" " w, x = ..., 5\n" "end\n" "g(1, 2, 3, 4)"; CHECK( DoString(L, code) ); lua_getglobal(L, "w"); CHECK( lua_tonumber(L, -1) == 3.0 ); lua_getglobal(L, "x"); CHECK( lua_tonumber(L, -1) == 5.0 ); } TEST_FIXTURE(VarArg2, LuaFixture) { const char* code = "function g(a, b, ...)\n" " w, x = ...\n" "end\n" "g(1, 2, 3, 4)"; CHECK( DoString(L, code) ); lua_getglobal(L, "w"); CHECK( lua_tonumber(L, -1) == 3.0 ); lua_getglobal(L, "x"); CHECK( lua_tonumber(L, -1) == 4.0 ); } TEST_FIXTURE(VarArg3, LuaFixture) { const char* code = "function f(a, b, c)\n" " x, y, z = a, b, c\n" "end\n" "function g(...)\n" " f(...)\n" "end\n" "g(1, 2)"; CHECK( DoString(L, code) ); lua_getglobal(L, "x"); CHECK( lua_tonumber(L, -1) == 1.0 ); lua_getglobal(L, "y"); CHECK( lua_tonumber(L, -1) == 2.0 ); lua_getglobal(L, "z"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(VarArg4, LuaFixture) { const char* code = "function f(a, b, c)\n" " x, y, z = a, b, c\n" "end\n" "function g(...)\n" " f(..., 3)\n" "end\n" "g(1, 2)"; CHECK( DoString(L, code) ); lua_getglobal(L, "x"); CHECK( lua_tonumber(L, -1) == 1.0 ); lua_getglobal(L, "y"); CHECK( lua_tonumber(L, -1) == 3.0 ); lua_getglobal(L, "z"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(VarArg5, LuaFixture) { const char* code = "function f(a, b)\n" " x = a\n" " y = b\n" "end\n" "function g()\n" " return 1, 2\n" "end\n" "f( g() )"; CHECK( DoString(L, code) ); lua_getglobal(L, "x"); CHECK( lua_tonumber(L, -1) == 1.0 ); lua_getglobal(L, "y"); CHECK( lua_tonumber(L, -1) == 2.0 ); } TEST_FIXTURE(VarArg6, LuaFixture) { // Test that ... can be used at file scope. const char* code = "a, b = ..."; int result = luaL_loadstring(L, code); if (result != 0) { fprintf(stderr, "%s\n", lua_tostring(L, -1)); } CHECK( result == 0 ); lua_pushstring(L, "arg1"); lua_pushstring(L, "arg2"); CHECK( lua_pcall(L, 2, 0, 0) == 0 ); lua_getglobal(L, "a"); CHECK_EQ( lua_tostring(L, -1), "arg1" ); lua_getglobal(L, "b"); CHECK_EQ( lua_tostring(L, -1), "arg2" ); } TEST_FIXTURE(VarArg7, LuaFixture) { const char* code = "function f(...) return ... end\n" "local _x, _y = f(1, 2)\n" "x = _x\n" "y = _y"; CHECK( DoString(L, code) ); lua_getglobal(L, "x"); CHECK_EQ( lua_tonumber(L, -1), 1 ); lua_getglobal(L, "y"); CHECK_EQ( lua_tonumber(L, -1), 2 ); } TEST_FIXTURE(DoBlock, LuaFixture) { const char* code = "local _a = 1\n" "do\n" " local _a, _b\n" " _a = 2\n" " _b = 3\n" "end\n" "a = _a\n" "b = _b"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1.0 ); lua_getglobal(L, "b"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(LocalUpValue, LuaFixture) { const char* code = "local a = 1\n" "do\n" " local p = 2\n" " f = function() return p end\n" "end\n" "local b = 3\n" "c = f()\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "c"); CHECK( lua_tonumber(L, -1) == 2.0 ); } TEST_FIXTURE(ShadowLocalUpValue, LuaFixture) { const char* code = "local a = 5\n" "function f()\n" " v = a\n" "end\n" "local a = 6\n" "f()"; CHECK( DoString(L, code) ); lua_getglobal(L, "v"); CHECK( lua_tonumber(L, -1) == 5.0 ); } TEST_FIXTURE(CloseUpValueOnReturn, LuaFixture) { const char* code = "function f()\n" " local x = 'one'\n" " local g = function() return x end\n" " return g, 'two'\n" // second value will overwrite over x "end\n" "local g = f()\n" "n = g()"; CHECK( DoString(L, code ) ); lua_getglobal(L, "n"); CHECK_EQ( lua_tostring(L, -1), "one" ); } TEST_FIXTURE(EmptyStatement, LuaFixture) { const char* code = "function g() end\n" "local a = f ; (g)()\n"; CHECK( DoString(L, code) ); } TEST_FIXTURE(CppCommentLine, LuaFixture) { const char* code = "// this is a comment\n" "a = 1"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1.0 ); } TEST_FIXTURE(CppCommentBlock, LuaFixture) { const char* code = "/* this is a comment\n" "that goes for multiple lines */\n" "a = 1\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1.0 ); } TEST_FIXTURE(LuaCommentBlock, LuaFixture) { const char* code = "--[[ this is a comment\n" "this is the second line ]]\n" "a = 1"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1.0 ); } TEST_FIXTURE(Equal, LuaFixture) { const char* code = "a = (5 == 6)\n" "b = (7 == 7)"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 0 ); lua_getglobal(L, "b"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 1 ); } TEST_FIXTURE(NotEqual, LuaFixture) { const char* code = "a = (5 ~= 6)\n" "b = (7 ~= 7)"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 1 ); lua_getglobal(L, "b"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 0 ); } TEST_FIXTURE(Number, LuaFixture) { const char* code = "a = 3\n" "b = 3.14\n" "c = -3.1416\n" "d = -.12\n" "e = 314.16e-2\n" "f = 0.31416E1\n" "g = 0xff\n" "h = 0x56"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 3.0 ); lua_getglobal(L, "b"); CHECK_CLOSE( lua_tonumber(L, -1), 3.14 ); lua_getglobal(L, "c"); CHECK_CLOSE( lua_tonumber(L, -1), -3.1416 ); lua_getglobal(L, "d"); CHECK_CLOSE( lua_tonumber(L, -1), -0.12); lua_getglobal(L, "e"); CHECK_CLOSE( lua_tonumber(L, -1), 314.16e-2 ); lua_getglobal(L, "f"); CHECK_CLOSE( lua_tonumber(L, -1), 0.31416e1 ); lua_getglobal(L, "g"); CHECK_CLOSE( lua_tonumber(L, -1), 0xFF ); lua_getglobal(L, "h"); CHECK_CLOSE( lua_tonumber(L, -1), 0x56 ); } TEST_FIXTURE(ElseIf, LuaFixture) { const char* code = "if false then\n" "elseif true then\n" " success = true\n" "end"; CHECK( DoString(L, code) ); lua_getglobal(L, "success"); CHECK( lua_toboolean(L, -1) ); } TEST_FIXTURE(DivideOperator, LuaFixture) { const char* code = "a = 10 / 2"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 5 ); } TEST_FIXTURE(SubtractOperator, LuaFixture) { // Check that the subtraction symbol is properly parsed and // not treated as part of the 4. const char* code = "v = 6-4"; CHECK( DoString(L, code) ); lua_getglobal(L, "v"); CHECK( lua_tonumber(L, -1) == 2 ); } TEST_FIXTURE(UnaryMinusOperator, LuaFixture) { const char* code = "local x = 5\n" "y = -x"; CHECK( DoString(L, code) ); lua_getglobal(L, "y"); CHECK( lua_tonumber(L, -1) == -5 ); } TEST_FIXTURE(UnaryMinusOperator2, LuaFixture) { const char* code = "local x = 5\n" "y = - -x"; CHECK( DoString(L, code) ); lua_getglobal(L, "y"); CHECK( lua_tonumber(L, -1) == 5 ); } TEST_FIXTURE(UnaryMinusOperatorConstant, LuaFixture) { const char* code = "x = -5"; CHECK( DoString(L, code) ); lua_getglobal(L, "x"); CHECK( lua_tonumber(L, -1) == -5 ); } TEST_FIXTURE(ModuloOperator, LuaFixture) { const char* code = "a = 10 % 3"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1 ); } TEST_FIXTURE(ExponentiationOperator, LuaFixture) { const char* code = "a = 2 ^ 3"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 8 ); } TEST_FIXTURE(EscapeCharacters, LuaFixture) { const char* code = "b = '\\01a\\002\\a\\b\\f\\n\\r\\t\\v\\\"\\\'\\0001'"; CHECK( DoString(L, code) ); lua_getglobal(L, "b"); CHECK( lua_isstring(L, -1) ); const char* buffer = lua_tostring(L, -1); CHECK( buffer[0] == 1 ); CHECK( buffer[1] == 'a' ); CHECK( buffer[2] == 2 ); CHECK( buffer[3] == '\a' ); CHECK( buffer[4] == '\b' ); CHECK( buffer[5] == '\f' ); CHECK( buffer[6] == '\n' ); CHECK( buffer[7] == '\r' ); CHECK( buffer[8] == '\t' ); CHECK( buffer[9] == '\v' ); CHECK( buffer[10] == '\"' ); CHECK( buffer[11] == '\'' ); CHECK( buffer[12] == '\0' ); CHECK( buffer[13] == '1' ); } TEST_FIXTURE(InvalidEscapeCharacters, LuaFixture) { const char* code = "b = '\\xyz"; CHECK( luaL_loadstring(L, code) != 0 ); } TEST_FIXTURE(NilConstant, LuaFixture) { const char* code = "c = nil\n" "if a == nil then\n" " b = 5\n" "end\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "b"); CHECK( lua_tonumber(L, -1) == 5 ); lua_getglobal(L, "c"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(ContinuedString, LuaFixture) { const char* code = "a = 'one\\\ntwo'"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isstring(L, -1) ); CHECK_EQ( lua_tostring(L, -1), "one\ntwo" ); } TEST_FIXTURE(LongString1, LuaFixture) { const char* code = "a = [[one\ntwo]]"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isstring(L, -1) ); CHECK_EQ( lua_tostring(L, -1), "one\ntwo" ); } TEST_FIXTURE(LongString2, LuaFixture) { const char* code = "a = [=[one\ntwo]=]"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isstring(L, -1) ); CHECK_EQ( lua_tostring(L, -1), "one\ntwo" ); } TEST_FIXTURE(LongStringNested, LuaFixture) { const char* code = "a = [=[one\n[==[embed]==]two]=]"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isstring(L, -1) ); CHECK_EQ( lua_tostring(L, -1), "one\n[==[embed]==]two" ); } TEST_FIXTURE(LongStringInitialNewLine, LuaFixture) { const char* code = "a = [[\ntest]]"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isstring(L, -1) ); CHECK_EQ( lua_tostring(L, -1), "test" ); } TEST_FIXTURE(LongStringIgnoreClose, LuaFixture) { const char* code = "a = [===[]=]===]"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isstring(L, -1) ); CHECK_EQ( lua_tostring(L, -1), "]=" ); } TEST_FIXTURE(Closure, LuaFixture) { const char* code = "local l = 5\n" "function f()\n" " v = l\n" "end\n" "f()"; CHECK( DoString(L, code) ); lua_getglobal(L, "v"); CHECK( lua_tonumber(L, -1) == 5 ); } TEST_FIXTURE(ClosureInClosure, LuaFixture) { const char* code = "local l = 5\n" "function f()\n" " local function g() v = l end\n" " g()\n" "end\n" "f()"; CHECK( DoString(L, code) ); lua_getglobal(L, "v"); CHECK( lua_tonumber(L, -1) == 5 ); } TEST_FIXTURE(ManyConstants, LuaFixture) { const char* code = "a = { }\n" "a[001]=001; a[002]=002; a[003]=003; a[004]=004; a[005]=005; a[006]=006\n" "a[007]=007; a[008]=008; a[009]=009; a[010]=010; a[011]=011; a[012]=012\n" "a[013]=013; a[014]=014; a[015]=015; a[016]=016; a[017]=017; a[018]=018\n" "a[019]=019; a[020]=020; a[021]=021; a[022]=022; a[023]=023; a[024]=024\n" "a[025]=025; a[026]=026; a[027]=027; a[028]=028; a[029]=029; a[030]=030\n" "a[031]=031; a[032]=032; a[033]=033; a[034]=034; a[035]=035; a[036]=036\n" "a[037]=037; a[038]=038; a[039]=039; a[040]=040; a[041]=041; a[042]=042\n" "a[043]=043; a[044]=044; a[045]=045; a[046]=046; a[047]=047; a[048]=048\n" "a[049]=049; a[050]=050; a[051]=051; a[052]=052; a[053]=053; a[054]=054\n" "a[055]=055; a[056]=056; a[057]=057; a[058]=058; a[059]=059; a[060]=060\n" "a[061]=061; a[062]=062; a[063]=063; a[064]=064; a[065]=065; a[066]=066\n" "a[067]=067; a[068]=068; a[069]=069; a[070]=070; a[071]=071; a[072]=072\n" "a[073]=073; a[074]=074; a[075]=075; a[076]=076; a[077]=077; a[078]=078\n" "a[079]=079; a[080]=080; a[081]=081; a[082]=082; a[083]=083; a[084]=084\n" "a[085]=085; a[086]=086; a[087]=087; a[088]=088; a[089]=089; a[090]=090\n" "a[091]=091; a[092]=092; a[093]=093; a[094]=094; a[095]=095; a[096]=096\n" "a[097]=097; a[098]=098; a[099]=099; a[100]=100; a[101]=101; a[102]=102\n" "a[103]=103; a[104]=104; a[105]=105; a[106]=106; a[107]=107; a[108]=108\n" "a[109]=109; a[110]=110; a[111]=111; a[112]=112; a[113]=113; a[114]=114\n" "a[115]=115; a[116]=116; a[117]=117; a[118]=118; a[119]=119; a[120]=120\n" "a[121]=121; a[122]=122; a[123]=123; a[124]=124; a[125]=125; a[126]=126\n" "a[127]=127; a[128]=128; a[129]=129; a[130]=130; a[131]=131; a[132]=132\n" "a[133]=133; a[134]=134; a[135]=135; a[136]=136; a[137]=137; a[138]=138\n" "a[139]=139; a[140]=140; a[141]=141; a[142]=142; a[143]=143; a[144]=144\n" "a[145]=145; a[146]=146; a[147]=147; a[148]=148; a[149]=149; a[150]=150\n" "a[151]=151; a[152]=152; a[153]=153; a[154]=154; a[155]=155; a[156]=156\n" "a[157]=157; a[158]=158; a[159]=159; a[160]=160; a[161]=161; a[162]=162\n" "a[163]=163; a[164]=164; a[165]=165; a[166]=166; a[167]=167; a[168]=168\n" "a[169]=169; a[170]=170; a[171]=171; a[172]=172; a[173]=173; a[174]=174\n" "a[175]=175; a[176]=176; a[177]=177; a[178]=178; a[179]=179; a[180]=180\n" "a[181]=181; a[182]=182; a[183]=183; a[184]=184; a[185]=185; a[186]=186\n" "a[187]=187; a[188]=188; a[189]=189; a[190]=190; a[191]=191; a[192]=192\n" "a[193]=193; a[194]=194; a[195]=195; a[196]=196; a[197]=197; a[198]=198\n" "a[199]=199; a[200]=200; a[201]=201; a[202]=202; a[203]=203; a[204]=204\n" "a[205]=205; a[206]=206; a[207]=207; a[208]=208; a[209]=209; a[210]=210\n" "a[211]=211; a[212]=212; a[213]=213; a[214]=214; a[215]=215; a[216]=216\n" "a[217]=217; a[218]=218; a[219]=219; a[220]=220; a[221]=221; a[222]=222\n" "a[223]=223; a[224]=224; a[225]=225; a[226]=226; a[227]=227; a[228]=228\n" "a[229]=229; a[230]=230; a[231]=231; a[232]=232; a[233]=233; a[234]=234\n" "a[235]=235; a[236]=236; a[237]=237; a[238]=238; a[239]=239; a[240]=240\n" "a[241]=241; a[242]=242; a[243]=243; a[244]=244; a[245]=245; a[246]=246\n" "a[247]=247; a[248]=248; a[249]=249; a[250]=250; a[251]=251; a[252]=252\n" "a[253]=253; a[254]=254; a[255]=255; a[256]=256"; CHECK( DoString(L, code) ); } TEST_FIXTURE(LocalInit, LuaFixture) { const char* code = "function f() end\n" "f(1, 2, 3, 4, 5, 6)\n" "do\n" " local _a\n" " a = _a\n" "end"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(LocalInit2, LuaFixture) { const char* code = "function f()\n" " local x\n" " return x\n" "end\n" "a = f(4)"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE(OperatorPrecedence, LuaFixture) { const char* code = "a = 1 + 2 * 3\n" "b = 1 + 4 / 2\n" "c = 1 - 2 * 3\n" "d = 1 - 4 / 2\n" "e = 2 * -3 ^ 4 * 5\n" "f = 'a' .. 'b' == 'ab'\n" "g = false and true or true"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_CLOSE( lua_tonumber(L, -1), 7); lua_getglobal(L, "b"); CHECK_CLOSE( lua_tonumber(L, -1), 3); lua_getglobal(L, "c"); CHECK_CLOSE( lua_tonumber(L, -1), -5); lua_getglobal(L, "d"); CHECK_CLOSE( lua_tonumber(L, -1), -1); lua_getglobal(L, "e"); CHECK_CLOSE( lua_tonumber(L, -1), -810); lua_getglobal(L, "f"); CHECK( lua_toboolean(L, -1) ); lua_getglobal(L, "g"); CHECK( lua_toboolean(L, -1) ); } TEST_FIXTURE(OperatorPrecedenceRightAssociative, LuaFixture) { const char* code = "assert( true or false and nil )"; CHECK( DoString(L, code) ); } TEST_FIXTURE(CallPreserveStack, LuaFixture) { // This test checks that calling a function doesn't corrupt the stack // downstream. const char* code = "function F()\n" "end\n" "local t = { }\n" "local mt = { __newindex = F }\n" "setmetatable(t, mt)\n" "F()\n" "local _a = 1\n" "t.test = 5\n" "a = _a"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_tonumber(L, -1) == 1.0 ); } TEST_FIXTURE(FunctionUpValue, LuaFixture) { const char* code = "local a = 1\n" "function F()\n" " _b = a\n" " a = 2\n" "end\n" "F()\n" "_a = a"; CHECK( DoString(L, code) ); lua_getglobal(L, "_a"); CHECK( lua_tonumber(L, -1) == 2.0 ); lua_getglobal(L, "_b"); CHECK( lua_tonumber(L, -1) == 1.0 ); } TEST_FIXTURE(Not0, LuaFixture) { const char* code = "a = not 0"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 0 ); } TEST_FIXTURE(NotNumber, LuaFixture) { const char* code = "a = not 1"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 0 ); } TEST_FIXTURE(NotNil, LuaFixture) { const char* code = "a = not nil"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 1); } TEST_FIXTURE(NotString, LuaFixture) { const char* code = "a = not 'test'"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 0); } TEST_FIXTURE(NotFalse, LuaFixture) { const char* code = "a = not false"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 1); } TEST_FIXTURE(NotTrue, LuaFixture) { const char* code = "a = not true"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 0); } TEST_FIXTURE(NotAnd1, LuaFixture) { const char* code = "local t\n" "a = not t and 'test'"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_EQ( lua_tostring(L, -1), "test" ); } TEST_FIXTURE(NotAnd2, LuaFixture) { const char* code = "a = not true and true"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( !lua_toboolean(L, -1) ); } TEST_FIXTURE(EqualAndTrue, LuaFixture) { const char* code = "a = (1 == 2) and true"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( !lua_toboolean(L, -1) ); } TEST_FIXTURE(EqualAndFalse, LuaFixture) { const char* code = "a = (1 == 1) and false"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( !lua_toboolean(L, -1) ); } TEST_FIXTURE(AndEqual, LuaFixture) { const char* code = "a = false and (1 == 1)"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( !lua_toboolean(L, -1) ); } TEST_FIXTURE(NotOr1, LuaFixture) { const char* code = "local t\n" "a = not t or 'test'"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_isboolean(L, -1) ); CHECK( lua_toboolean(L, -1) == 1 ); } TEST_FIXTURE(NegativeOr, LuaFixture) { const char* code = "a = -(1 or 2)"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_EQ( lua_tonumber(L, -1), -1 ); } TEST_FIXTURE(OrLhs, LuaFixture) { const char* code = "local a\n" "t = { } ;\n" "(a or t).x = 5"; CHECK( DoString(L, code) ); lua_getglobal(L, "t"); lua_getfield(L, -1, "x"); CHECK( lua_tonumber(L, -1) == 5 ); } TEST_FIXTURE(PrefixExp, LuaFixture) { // This should not be treated as a function call. const char* code = "local a = nil\n" "(function () end)()"; CHECK( DoString(L, code) ); } TEST_FIXTURE(Dump, LuaFixture) { struct Buffer { char data[1024]; size_t length; }; struct Locals { static int Writer(lua_State* L, const void* p, size_t sz, void* ud) { Buffer* buffer = static_cast<Buffer*>(ud); char* dst = buffer->data + buffer->length; buffer->length += sz; if (buffer->length > sizeof(buffer->data)) { return 1; } memcpy( dst, p, sz ); return 0; } }; Buffer buffer; buffer.length = 0; luaL_loadstring(L, "a = 'test'"); int top = lua_gettop(L); CHECK( lua_dump(L, &Locals::Writer, &buffer) == 0 ); CHECK( lua_gettop(L) == top ); lua_pop(L, 1); CHECK( luaL_loadbuffer(L, buffer.data, buffer.length, "mem") == 0 ); CHECK( lua_pcall(L, 0, 0, 0) == 0 ); lua_getglobal(L, "a"); CHECK_EQ( lua_tostring(L, -1), "test" ); lua_pop(L, 1); } TEST_FIXTURE(TableFromUnpack, LuaFixture) { const char* code = "local x, a\n" "a = { 1, 2, 3 }\n" "x = { unpack(a) }" "n = #x"; CHECK( DoString(L, code) ); lua_getglobal(L, "n"); CHECK_EQ( lua_tonumber(L, -1), 3 ); } TEST_FIXTURE(ReturnVarFunction, LuaFixture) { // Check that a properly return a variable number of return values // from a function. const char* code = "function g()\n" " return 2, 3, 4\n" "end\n" "function f()\n" " return 1, g()\n" "end\n" "a, b, c, d = f()\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_EQ( lua_tonumber(L, -1), 1 ); lua_getglobal(L, "b"); CHECK_EQ( lua_tonumber(L, -1), 2 ); lua_getglobal(L, "c"); CHECK_EQ( lua_tonumber(L, -1), 3 ); lua_getglobal(L, "d"); CHECK_EQ( lua_tonumber(L, -1), 4 ); } TEST_FIXTURE(ReturnLogic, LuaFixture) { const char* code = "function f(a,b)\n" " return a or b\n" "end\n" "a = f(true, false)"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK( lua_toboolean(L, -1) ); } TEST_FIXTURE(ReturnStackCleanup, LuaFixture) { // This function requires the stack to be cleaned up between each of the // return values. const char* code = "function f()\n" " local x = 1\n" " local y = 2\n" " return x * 2 + y * 3, 4\n" "end\n" "a, b = f()"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_EQ( lua_tonumber(L, -1), 8 ); lua_getglobal(L, "b"); CHECK_EQ( lua_tonumber(L, -1), 4 ); } TEST_FIXTURE(Assign2, LuaFixture) { const char* code = "function f() return 1,2,30,4 end\n" "function ret2(a,b) return a,b end\n" "local _a, _b, _c, _d\n" "_a, _b, _c, _d = ret2(f()), ret2(f())\n" "a = _a\n" "b = _b\n" "c = _c\n" "d = _d\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_EQ( lua_tonumber(L, -1), 1 ); lua_getglobal(L, "b"); CHECK_EQ( lua_tonumber(L, -1), 1 ); lua_getglobal(L, "c"); CHECK_EQ( lua_tonumber(L, -1), 2 ); lua_getglobal(L, "d"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE( AdjustReturn, LuaFixture ) { // Placing an expression that generates multiple values in parentheses // will adjust it to a single value. const char* code = "function f() return 1, 2 end\n" "a, b = (f())"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_EQ( lua_tonumber(L, -1), 1 ); lua_getglobal(L, "b"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE( AdjustReturnLogic, LuaFixture ) { // When calling a function as part of a logic expression, the number of // return values should be adjusted to 1. const char* code = "function f () return 1,2,3 end\n" "x1, x2 = true and f()\n" "y1, y2 = f() or false\n" "z1, z2 = false or f()"; CHECK( DoString(L, code) ); lua_getglobal(L, "x1"); CHECK_EQ( lua_tonumber(L, -1), 1.0 ); lua_getglobal(L, "x2"); CHECK( lua_isnil(L, -1) ); lua_getglobal(L, "y1"); CHECK_EQ( lua_tonumber(L, -1), 1.0 ); lua_getglobal(L, "y2"); CHECK( lua_isnil(L, -1) ); lua_getglobal(L, "z1"); CHECK_EQ( lua_tonumber(L, -1), 1.0 ); lua_getglobal(L, "z2"); CHECK( lua_isnil(L, -1) ); } TEST_FIXTURE( LoadTermination, LuaFixture ) { // Check that a reader setting the size to 0 (but returning a non-nil // value) will terminate loading. struct Locals { static const char* Reader(lua_State* L, void* data, size_t* size) { *size = 0; return "a = 'fail'"; } }; CHECK( lua_load(L, Locals::Reader, NULL, "test") == 0 ); } TEST_FIXTURE( SetUpValue, LuaFixture ) { const char* code = "local a = 1\n" "function f() return a + 1 end"; CHECK( DoString(L, code) ); lua_getglobal(L, "f"); int funcindex = lua_gettop(L); int top = lua_gettop(L); lua_pushnumber(L, 10); const char* name = lua_setupvalue(L, funcindex, 1); CHECK( lua_gettop(L) == top ); CHECK_EQ( name, "a" ); lua_pushvalue(L, funcindex); lua_pcall(L, 0, 1, 0); CHECK_EQ( lua_tonumber(L, -1), 11 ); lua_pop(L, 1); } TEST_FIXTURE( StringComparison, LuaFixture ) { const char* code = "t1 = 'alo' < 'alo1'\n" "t2 = '' < 'a'\n" "t3 = 'alo\\0alo' < 'alo\\0b'\n" "t4 = 'alo\\0alo\\0\\0' > 'alo\\0alo\\0'\n" "t5 = 'alo' < 'alo\\0'\n" "t6 = 'alo\\0' > 'alo'\n" "t7 = '\\0' < '\\1'\n" "t8 = '\\0\\0' < '\\0\\1'"; CHECK( DoString(L, code) ); lua_getglobal(L, "t1"); CHECK( lua_toboolean(L, -1) ); lua_getglobal(L, "t2"); CHECK( lua_toboolean(L, -1) ); lua_getglobal(L, "t3"); CHECK( lua_toboolean(L, -1) ); lua_getglobal(L, "t4"); CHECK( lua_toboolean(L, -1) ); lua_getglobal(L, "t5"); CHECK( lua_toboolean(L, -1) ); lua_getglobal(L, "t6"); CHECK( lua_toboolean(L, -1) ); lua_getglobal(L, "t7"); CHECK( lua_toboolean(L, -1) ); lua_getglobal(L, "t8"); CHECK( lua_toboolean(L, -1) ); } TEST_FIXTURE(ToNumber, LuaFixture) { int top = lua_gettop(L); lua_pushnumber(L, 10.3 ); CHECK( lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 10.3 ); lua_pop(L, 1); CHECK( lua_gettop(L) == top ); lua_pushstring(L, "10.3"); CHECK( lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 10.3 ); lua_pop(L, 1); CHECK( lua_gettop(L) == top ); lua_pushboolean(L, 1); CHECK( !lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 0 ); lua_pop(L, 1); CHECK( lua_gettop(L) == top ); lua_pushlightuserdata(L, (void*)0x12345678); CHECK( !lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 0 ); lua_pop(L, 1); CHECK( lua_gettop(L) == top ); } TEST_FIXTURE(ToNumberFromString, LuaFixture) { lua_pushstring(L, "10.3"); CHECK( lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 10.3 ); lua_pop(L, 1); lua_pushstring(L, "10.3 456"); CHECK( !lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 0 ); lua_pop(L, 1); lua_pushstring(L, " 10.3 "); CHECK( lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 10.3 ); lua_pop(L, 1); lua_pushstring(L, "0x123"); CHECK( lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 0x123 ); lua_pop(L, 1); lua_pushstring(L, " 0x123 "); CHECK( lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 0x123 ); lua_pop(L, 1); lua_pushstring(L, "123x"); CHECK( !lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 0 ); lua_pop(L, 1); lua_pushstring(L, "abcd"); CHECK( !lua_isnumber(L, -1) ); CHECK_EQ( lua_tonumber(L, -1), 0 ); lua_pop(L, 1); } TEST_FIXTURE(StringNumberCoercion, LuaFixture) { lua_pushnumber(L, 10); CHECK( lua_isstring(L, -1) ); } TEST_FIXTURE(StringNumberCoercionArithmetic, LuaFixture) { const char* code = "a = '1' + 2"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_EQ( lua_tonumber(L, -1), 3 ); } TEST_FIXTURE(StringNumberCoercionForLoop, LuaFixture) { const char* code = "a = 0\n" "for i='10','1','-2' do\n" " a = a + 1\n" "end\n"; CHECK( DoString(L, code) ); lua_getglobal(L, "a"); CHECK_EQ( lua_tonumber(L, -1), 5 ); } TEST_FIXTURE(Objlen, LuaFixture) { lua_newtable(L); lua_pushstring(L, "one"); lua_rawseti(L, -2, 1); lua_pushstring(L, "two"); lua_rawseti(L, -2, 2); lua_pushstring(L, "three"); lua_rawseti(L, -2, 3); CHECK( lua_objlen(L, -1) == 3 ); lua_pop(L, 1); lua_newuserdata(L, 100); CHECK( lua_objlen(L, -1) == 100 ); lua_pop(L, 1); lua_pushstring(L, "this is a test"); CHECK( lua_objlen(L, -1) == 14 ); lua_pop(L, 1); lua_pushnumber(L, 12); CHECK( lua_objlen(L, -1) == 2 ); CHECK( lua_isstring(L, -1) ); lua_pop(L, 1); } TEST_FIXTURE(TailCall, LuaFixture) { const char* code = "function g(x)\n" " return x\n" "end\n" "function f(x)\n" " return g(x)\n" "end\n" "x = f(5)"; CHECK( DoString(L, code) ); lua_getglobal(L, "x"); CHECK_EQ( lua_tonumber(L, -1), 5.0 ); }
21.434829
90
0.537086
[ "object" ]
6d6fefa26d3d7baa35a2f53c3304d9dba1c16a88
6,783
cpp
C++
display3droutines.cpp
avanindra/EPVH
4b114c63cde000dc052f7b2f7dbddaeebdc0ef06
[ "BSD-3-Clause" ]
10
2015-11-28T16:52:22.000Z
2021-12-06T06:34:36.000Z
display3droutines.cpp
avanindra/EPVH
4b114c63cde000dc052f7b2f7dbddaeebdc0ef06
[ "BSD-3-Clause" ]
10
2015-11-27T02:11:20.000Z
2020-03-13T20:15:43.000Z
display3droutines.cpp
avanindra/EPVH
4b114c63cde000dc052f7b2f7dbddaeebdc0ef06
[ "BSD-3-Clause" ]
12
2015-11-27T10:53:52.000Z
2022-03-03T07:09:43.000Z
/* Copyright (c) 2012, avanindra <email> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY avanindra <email> ''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 avanindra <email> 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 "display3droutines.h" #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkInteractorStyleTrackballCamera.h> #include <vtkRenderer.h> #include <vtkPolyDataMapper.h> #include "vtkProperty.h" #include <vtkIdList.h> #include <vtkTriangleFilter.h> #include "vtkVersion.h" namespace tr { Display3DRoutines::Display3DRoutines() { } void Display3DRoutines::displayPolyData( vtkSmartPointer< vtkPolyData > mesh ) { vtkSmartPointer< vtkRenderer > renderer = vtkSmartPointer< vtkRenderer >::New(); vtkSmartPointer< vtkPolyDataMapper > meshMapper = vtkSmartPointer< vtkPolyDataMapper >::New(); #if VTK_MAJOR_VERSION < 6 meshMapper->SetInput( mesh ); #else meshMapper->SetInputData( mesh ); #endif vtkSmartPointer< vtkActor > meshActor = vtkSmartPointer< vtkActor >::New(); meshActor->SetMapper( meshMapper ); renderer->AddActor( meshActor );/* meshActor->GetProperty()->SetAmbient(1.0); meshActor->GetProperty()->SetDiffuse(0.0); meshActor->GetProperty()->SetSpecular(0.0);*/ vtkSmartPointer< vtkRenderWindow > window = vtkSmartPointer< vtkRenderWindow >::New(); vtkSmartPointer< vtkRenderWindowInteractor > interactor = vtkSmartPointer< vtkRenderWindowInteractor >::New(); vtkSmartPointer< vtkInteractorStyleTrackballCamera > style = vtkSmartPointer< vtkInteractorStyleTrackballCamera >::New(); window->AddRenderer( renderer ); window->SetInteractor( interactor ); interactor->SetInteractorStyle( style ); window->Render(); interactor->Start(); } void Display3DRoutines::displayPolygons(vtkSmartPointer< vtkPolyData > mesh) { } //void Display3DRoutines::displayCarvePolyhedron( CarvePolyhedron& polyhedron ) //{ /* carve::mesh::MeshSet<3> *carveMesh = polyhedron.getPolyhedron(); int numVertices = carveMesh->vertex_storage.size(); vtkSmartPointer< vtkPoints > points = vtkSmartPointer< vtkPoints >::New(); points->Allocate( numVertices ); for( int vv = 0; vv < numVertices; vv++ ) { double p[ 3 ]; p[ 0 ] = carveMesh->vertex_storage[ vv ].v[ 0 ]; p[ 1 ] = carveMesh->vertex_storage[ vv ].v[ 1 ]; p[ 2 ] = carveMesh->vertex_storage[ vv ].v[ 2 ]; points->InsertNextPoint( p ); } int numMeshes = carveMesh->meshes.size(); int numFaces = 0; for( int mm = 0; mm < numMeshes; mm++ ) { numFaces += carveMesh->meshes[ mm ]->faces.size(); } vtkSmartPointer< vtkPolyData > polydataMesh = vtkSmartPointer< vtkPolyData >::New(); polydataMesh->Allocate( numFaces ); std::map<carve::mesh::MeshSet<3>::vertex_t*, unsigned int > vertexToIndex_map; std::vector<carve::mesh::MeshSet<3>::vertex_t>::iterator it = carveMesh->vertex_storage.begin(); for (int i = 0; it != carveMesh->vertex_storage.end(); ++i, ++it) { carve::mesh::MeshSet<3>::vertex_t *vertex = &(*it); vertexToIndex_map[vertex] = i; } vtkSmartPointer< vtkIdList > poly = vtkSmartPointer< vtkIdList >::New(); for( carve::mesh::MeshSet<3>::face_iter iter = carveMesh->faceBegin() ; iter != carveMesh->faceEnd(); iter++ ) { carve::mesh::MeshSet<3>::face_t *face = *iter; int numFacetPoints = face->nVertices(); std::vector< carve::mesh::Vertex<3>* > verts; face->getVertices(verts); poly->Reset(); for( int vv = 0; vv < numFacetPoints; vv++ ) { poly->InsertNextId( vertexToIndex_map[ verts[ vv ] ] ); } polydataMesh->InsertNextCell( VTK_POLYGON , poly ); } polydataMesh->SetPoints( points ); vtkSmartPointer< vtkTriangleFilter > triangulator = vtkSmartPointer< vtkTriangleFilter >::New(); #if VTK_MAJOR_VERSION < 6 triangulator->SetInput( polydataMesh ); #else triangulator->SetInputData( polydataMesh ); #endif triangulator->Update(); polydataMesh = triangulator->GetOutput(); displayPolyData( polydataMesh ); */ //} void Display3DRoutines::displayPointSet(std::vector< Eigen::Vector3d >& vertices, std::vector< Eigen::Vector3d >& colors) { vtkSmartPointer< vtkPolyData > dataSet = vtkSmartPointer< vtkPolyData >::New(); vtkSmartPointer< vtkPoints > points = vtkSmartPointer< vtkPoints >::New(); vtkSmartPointer< vtkUnsignedCharArray > vColors = vtkSmartPointer< vtkUnsignedCharArray >::New(); int numVerts = vertices.size(); points->Allocate(numVerts); dataSet->Allocate(numVerts); vColors->SetNumberOfComponents(3); vColors->SetName("Colors"); // Add the three colors we have created to the array vtkSmartPointer< vtkIdList > vert = vtkSmartPointer< vtkIdList >::New(); int id = 0; for (int vv = 0; vv < numVerts; vv++) { unsigned char col[] = {(unsigned char) (colors[vv](0) * 255), (unsigned char) (colors[vv](1) * 255), (unsigned char) (colors[vv](2) * 255) }; vColors->InsertNextTypedTuple(col); points->InsertNextPoint(vertices[vv](0), vertices[vv](1), vertices[vv](2)); vert->Reset(); vert->InsertNextId(vv); dataSet->InsertNextCell(VTK_VERTEX, vert); } dataSet->SetPoints(points); dataSet->GetPointData()->SetScalars(vColors); displayPolyData(dataSet); } Display3DRoutines::~Display3DRoutines() { } }
30.013274
125
0.695562
[ "mesh", "render", "vector" ]
6d706488da130696ee645cbdd212d9060c0731fb
24,820
cpp
C++
test/RpcTest.cpp
yusufketen/casper-cpp-sdk
5f65ee08e96285b15bb205b4387ecd2424502a2d
[ "Apache-2.0" ]
null
null
null
test/RpcTest.cpp
yusufketen/casper-cpp-sdk
5f65ee08e96285b15bb205b4387ecd2424502a2d
[ "Apache-2.0" ]
1
2022-03-20T17:56:36.000Z
2022-03-20T17:56:36.000Z
test/RpcTest.cpp
yusufketen/casper-cpp-sdk
5f65ee08e96285b15bb205b4387ecd2424502a2d
[ "Apache-2.0" ]
3
2022-01-29T01:47:23.000Z
2022-03-24T15:20:07.000Z
#define TEST_NO_MAIN 1 #include "RpcTest.hpp" #include "acutest.h" namespace Casper { void test1(void) { // function body TEST_ASSERT(true); } void test2(void) { // function body TEST_ASSERT(false); } /** * @brief Check the "info_get_peers" rpc function. The size of the return * value should be greater than 0. * */ void infoGetPeers_Test(void) { Client client(CASPER_TEST_ADDRESS); auto result = client.GetNodePeers(); size_t result_size = result.peers.size(); TEST_ASSERT(result_size > 0); } /** * @brief Check the "get_state_root_hash" rpc function with an example height. * Compare the result with the expected hash of the state. * */ void chainGetStateRootHash_with_blockHeightTest(void) { Client client(CASPER_TEST_ADDRESS); uint64_t block_height = 10; std::string result = client.GetStateRootHash(block_height).state_root_hash; std::string expected_result = "4d180287e6eb3dad5173864e30d7653c01fcdef8bc3ee31db4a0707367154ccf"; TEST_ASSERT(iequals(result, expected_result)); } /** * @brief Check "get_state_root_hash" rpc function with an * invalid height. * * */ void chainGetStateRootHash_with_invalidBlockHeightTest(void) { Client client(CASPER_TEST_ADDRESS); uint64_t block_height = 100000000; try { std::string result = client.GetStateRootHash(block_height).state_root_hash; } catch (const jsonrpccxx::JsonRpcException& e) { return; } TEST_ASSERT(false); } /** * @brief Check the "get_state_root_hash" rpc function with an example block * hash. Compare the result with the expected hash of the state. * */ void chainGetStateRootHash_with_blockHashTest(void) { Client client(CASPER_TEST_ADDRESS); std::string block_hash = "9511adf5ed36ccba48d71840fd558d4397c9eb0470d1e25711b5419632a6f55a"; std::string result = client.GetStateRootHash(block_hash).state_root_hash; std::string expected_result = "9aa3c10d4db2e02adb464458c7a09d1df2ed551be02d2c7bbdbe847d3731e84f"; TEST_ASSERT(iequals(result, expected_result)); } /** * @brief Check the "get_state_root_hash" rpc function without a variable. * Compare the result with an empty string. * */ void chainGetStateRootHash_with_emptyParameterTest(void) { Client client(CASPER_TEST_ADDRESS); std::string result = client.GetStateRootHash().state_root_hash; TEST_ASSERT(result != ""); } /** * @brief Check the "info_get_deploy" rpc function * */ void infoGetDeploy_with_deployHashTest(void) { Client client(CASPER_TEST_ADDRESS); std::string deploy_hash = "8e535d2baed76141ab47fd93b04dd61f65a07893b7c950022978a2b29628edd7"; nlohmann::json deploy_result = client.GetDeployInfo(deploy_hash); TEST_ASSERT(deploy_result.at("api_version") != ""); TEST_ASSERT(deploy_result.find("deploy") != deploy_result.end()); nlohmann::json& deploy_info = deploy_result.at("deploy"); TEST_ASSERT(iequals( deploy_info.at("hash"), "8e535d2baed76141ab47fd93b04dd61f65a07893b7c950022978a2b29628edd7")); nlohmann::json& deploy_header = deploy_info.at("header"); TEST_ASSERT(iequals( deploy_header.at("account"), "011fa7f49ed9887f1bd0bceac567dd6a38087e2896411d74d3f8d1c03a3f325828")); TEST_ASSERT(iequals( deploy_header.at("body_hash"), "11f5a10f791fd6ac8b12d52298b7d1db7bd91e8c15b5d1330fd16d792257693c")); TEST_ASSERT(iequals(deploy_header.at("chain_name"), "casper-test")); TEST_ASSERT(deploy_header.at("gas_price") == 1); } /** * @brief Check the "info_get_deploy" rpc function with an invalid deploy hash * parameter * */ void infoGetDeploy_with_invalidDeployHashTest(void) { Client client(CASPER_TEST_ADDRESS); std::string deploy_hash = "ffffffffffffffffffff"; try { nlohmann::json deploy_result = client.GetDeployInfo(deploy_hash); } catch (const jsonrpccxx::JsonRpcException& e) { return; } TEST_ASSERT(false); } /** * @brief Check the "info_get_status" rpc function. Check the result * variables. * */ void infoGetStatus_with_emptyParameterTest(void) { Client client(CASPER_TEST_ADDRESS); GetStatusResult result = client.GetStatusInfo(); TEST_ASSERT(result.api_version != ""); std::string expected_chainspec_name = "casper-test"; TEST_ASSERT(iequals(result.chainspec_name, expected_chainspec_name)); TEST_ASSERT(result.starting_state_root_hash != ""); if (result.our_public_signing_key.has_value()) { TEST_ASSERT(result.our_public_signing_key.value().ToString() != ""); } if (result.last_added_block_info.has_value()) { auto& last_block = result.last_added_block_info.value(); TEST_ASSERT(last_block.hash != ""); TEST_ASSERT(last_block.height >= 0); TEST_ASSERT(last_block.timestamp != ""); TEST_ASSERT(last_block.state_root_hash != ""); TEST_ASSERT(last_block.creator.ToString() != ""); } if (result.peers.size() > 0) { TEST_ASSERT(result.peers[0].address != ""); TEST_ASSERT(result.peers[0].node_id != ""); } TEST_ASSERT(result.build_version != ""); TEST_ASSERT(result.uptime != ""); } /** * @brief Check the "chain_get_block_transfers" rpc function. * */ void chainGetBlockTransfers_with_blockHashTest(void) { Client client(CASPER_TEST_ADDRESS); // Call the rpc function std::string block_hash = "35f86b6ab5e13b823daee5d23f3373f6b35048e0b0ea993adfadc5ba8ee7aae5"; GetBlockTransfersResult result = client.GetBlockTransfers(block_hash); // Expected Values std::string expected_block_hash = block_hash; uint512_t expected_amount = u512FromDec("199000000000"); std::string expected_deploy_hash = "8e535d2baed76141ab47fd93b04dd61f65a07893b7c950022978a2b29628edd7"; std::string expected_from = "account-hash-" "308d2a0eCF66bDAcAC5Cf6184C732D83DCeB48A859169e5680FE17cF32Bb974F"; uint512_t expected_gas = u512FromDec("0"); std::string expected_source = "uref-5ce1d189e8ccafdd5a959088ffd870f54b29bd5afeb05950dddcc12ec7dcbe90-" "007"; std::string expected_target = "uref-c9733355d61aa2a36721d9d1081eebcfe5dde94f82386b3d75163fee894d292a-" "007"; TEST_ASSERT(result.api_version != ""); TEST_ASSERT(result.block_hash.has_value()); TEST_ASSERT(iequals(result.block_hash.value(), expected_block_hash)); // check transfers TEST_ASSERT(result.transfers.has_value()); TEST_ASSERT(result.transfers.value().size() > 0); auto& transfers = result.transfers.value(); auto test_transfer = std::find_if(transfers.begin(), transfers.end(), [&](const Transfer& x) { return iequals(x.deploy_hash, expected_deploy_hash); }); TEST_ASSERT(test_transfer != transfers.end()); // Actual Values uint512_t current_amount = test_transfer->amount; std::string current_deploy_hash = test_transfer->deploy_hash; std::string current_from = test_transfer->from.ToString(); uint512_t current_gas = test_transfer->gas; std::string current_source = test_transfer->source.ToString(); std::string current_target = test_transfer->target.ToString(); // tests for the first transfer TEST_ASSERT(current_amount == expected_amount); TEST_ASSERT(iequals(current_deploy_hash, expected_deploy_hash)); TEST_ASSERT(iequals(current_from, expected_from)); TEST_ASSERT(current_gas == expected_gas); TEST_ASSERT(iequals(current_source, expected_source)); TEST_ASSERT(iequals(current_target, expected_target)); } /** * @brief Check the "chain_get_block" rpc function * */ void chainGetBlock_with_blockHashTest(void) { Client client(CASPER_TEST_ADDRESS); std::string block_hash = "acc4646f35cc1d59b24381547a4d2dc1c992a202b6165f3bf68d3f23c2b93330"; GetBlockResult blockResult = client.GetBlock(block_hash); TEST_ASSERT(blockResult.api_version != ""); TEST_ASSERT(blockResult.block.has_value()); auto& current_block = blockResult.block.value(); TEST_ASSERT(iequals( current_block.hash, "acc4646f35cc1d59b24381547a4d2dc1c992a202b6165f3bf68d3f23c2b93330")); // block header TEST_ASSERT(iequals( current_block.header.parent_hash, "e23b5f98258aff36716a8f60ca8d57c049216eedd88e6c7e14df7a6cfbadca73")); TEST_ASSERT(iequals( current_block.header.state_root_hash, "f5abb3964382e0dde4bc3ec38414f43f325f5dcc6493d5a7c4037972793fb302")); TEST_ASSERT(iequals( current_block.header.body_hash, "e1786ce884cf41abbc758b0795ee3223daec5fb8015791ced0f8ee66deec8ee3")); TEST_ASSERT(iequals( current_block.header.accumulated_seed, "35b5d33db0b43df3971831880f51023b37a468ad54494316ec26af4c61904532")); TEST_ASSERT(current_block.header.timestamp != ""); TEST_ASSERT(current_block.header.era_id != 0); TEST_ASSERT(current_block.header.height == 532041); TEST_ASSERT(current_block.header.protocol_version != ""); // block body TEST_ASSERT(current_block.body.deploy_hashes.size() >= 0); TEST_ASSERT(iequals( current_block.body.proposer.ToString(), "01cd807fb41345d8dD5A61da7991e1468173acbEE53920E4DFe0D28Cb8825AC664")); TEST_ASSERT(current_block.body.transfer_hashes.size() >= 0); // block proofs TEST_ASSERT(current_block.proofs.size() > 0); TEST_ASSERT(current_block.proofs[0].public_key.ToString() != ""); TEST_ASSERT(current_block.proofs[0].signature.ToString() != ""); } /** * @brief Check the "chain_get_era_info_by_switch_block" rpc function * */ void chainGetEraInfoBySwitchBlock_with_blockHashTest(void) { Client client(CASPER_TEST_ADDRESS); GetEraInfoResult result = client.GetEraInfoBySwitchBlock( "d2077716e5b8796723c5720237239720f54e6ada54e3357f2c4896f2a51a6d8f"); TEST_ASSERT(result.api_version != ""); TEST_ASSERT(result.era_summary.has_value()); TEST_ASSERT(result.era_summary.value().era_id != 0); TEST_ASSERT(result.era_summary.value().block_hash != ""); TEST_ASSERT(result.era_summary.value().merkle_proof != ""); TEST_ASSERT(result.era_summary.value().state_root_hash != ""); TEST_ASSERT(result.era_summary.value().stored_value.era_info.has_value()); TEST_ASSERT(result.era_summary.value() .stored_value.era_info.value() .seigniorage_allocations.size() > 0); int validator_cnt = 0; int delegator_cnt = 0; for (int i = 0; i < result.era_summary.value() .stored_value.era_info.value() .seigniorage_allocations.size(); i++) { if (delegator_cnt == 1 && validator_cnt == 1) { break; } bool is_delegator = result.era_summary.value() .stored_value.era_info.value() .seigniorage_allocations[i] .is_delegator; if (is_delegator == true && delegator_cnt == 0) { delegator_cnt++; TEST_ASSERT(result.era_summary.value() .stored_value.era_info.value() .seigniorage_allocations[i] .delegator_public_key.ToString() != ""); TEST_ASSERT(result.era_summary.value() .stored_value.era_info.value() .seigniorage_allocations[i] .amount >= 0); } else if (is_delegator == false && validator_cnt == 0) { validator_cnt++; TEST_ASSERT(result.era_summary.value() .stored_value.era_info.value() .seigniorage_allocations[i] .validator_public_key.ToString() != ""); TEST_ASSERT(result.era_summary.value() .stored_value.era_info.value() .seigniorage_allocations[i] .amount >= 0); } } } /** * @brief Check the "state_get_item" rpc function * */ void stateGetItem_with_keyTest(void) { Client client(CASPER_TEST_ADDRESS); std::string state_root_hash = "39f2800688b94f68ca640b26c7d0f50a90d2ce9af55c9484e66151b544345303"; std::string key = "transfer-" "9f5fe878c29fc3bf537c0509ec5abe1781a72bb6a3197a440e3e68247fba5909"; GetItemResult result = client.GetItem(state_root_hash, key); // tests TEST_ASSERT(result.api_version != ""); TEST_ASSERT(result.merkle_proof != ""); TEST_ASSERT(result.stored_value.transfer.has_value()); auto& current_transfer = result.stored_value.transfer.value(); TEST_ASSERT(iequals( current_transfer.deploy_hash, "8e535d2baed76141ab47fd93b04dd61f65a07893b7c950022978a2b29628edd7")); TEST_ASSERT(iequals( current_transfer.from.ToString(), "account-hash-" "308d2a0eCF66bDAcAC5Cf6184C732D83DCeB48A859169e5680FE17cF32Bb974F")); TEST_ASSERT(iequals( current_transfer.source.ToString(), "uref-5ce1d189e8ccafdd5a959088ffd870f54b29bd5afeb05950dddcc12ec7dcbe90-" "007")); TEST_ASSERT(iequals( current_transfer.target.ToString(), "uref-c9733355d61aa2a36721d9d1081eebcfe5dde94f82386b3d75163fee894d292a-" "007")); TEST_ASSERT(current_transfer.amount == 199000000000); TEST_ASSERT(current_transfer.gas == 0); } /** * @brief Check the "state_get_item" rpc function with an invalid key and a * state root hash * */ void stateGetItem_with_invalidKeyTest(void) { Client client(CASPER_TEST_ADDRESS); std::string state_root_hash = "NOT_EXIST_STATE_ROOT_HASH"; std::string key = "NON_EXISTING_KEY"; try { GetItemResult result = client.GetItem(state_root_hash, key); } catch (const jsonrpccxx::JsonRpcException& e) { return; } TEST_ASSERT(false); } /** * @brief Check the "state_get_dictionary_item" rpc function by URef * */ void stateGetDictionaryItem_with_keyTest(void) { Client client(CASPER_TEST_ADDRESS); std::string state_root_hash = "322b8d17faea2ee780b9b952a25a86520d36a78e20113f0658ae0b29a68a7384"; std::string item_key = "dictionary-" "5d3e90f064798d54e5e53643c4fce0cbb1024aadcad1586cc4b7c1358a530373"; nlohmann::json dictionaryItemResult = client.GetDictionaryItem(state_root_hash, item_key); TEST_ASSERT(dictionaryItemResult.at("api_version") != ""); TEST_ASSERT(dictionaryItemResult.at("dictionary_key") != ""); TEST_ASSERT(dictionaryItemResult.at("merkle_proof") != ""); TEST_ASSERT(!dictionaryItemResult.at("stored_value").at("CLValue").is_null()); TEST_ASSERT( iequals(dictionaryItemResult.at("stored_value").at("CLValue").at("bytes"), "090000006162635F76616c7565")); TEST_ASSERT(iequals( dictionaryItemResult.at("stored_value").at("CLValue").at("cl_type"), "String")); } /** * @brief Check the "state_get_balance" rpc function * */ void stateGetBalance_with_urefTest(void) { Client client(CASPER_TEST_ADDRESS); std::string purse_uref = "uref-54fd72455872082a254b0160e94a86245acd0c441f526688bda1261d0969057a-" "007"; std::string state_root_hash = "66eb7e43886c908aae8246ba2d22aa30d21e1c187a38fa3093f14e4a4219dd6c"; GetBalanceResult result = client.GetAccountBalance(purse_uref, state_root_hash); TEST_ASSERT(result.api_version != ""); TEST_ASSERT(result.balance_value >= 0); TEST_ASSERT(result.merkle_proof != ""); } /** * @brief Check the "state_get_balance" rpc function with an invalid uref and * a state root hash * */ void stateGetBalance_with_invalidUrefTest(void) { Client client(CASPER_TEST_ADDRESS); std::string purse_uref = "non-uref-ffff"; std::string state_root_hash = "ffff"; try { GetBalanceResult result = client.GetAccountBalance(purse_uref, state_root_hash); } catch (const jsonrpccxx::JsonRpcException& e) { return; } TEST_ASSERT(false); } /** * @brief Check the "state_get_auction_info" rpc function * */ void stateGetAuctionInfo_with_blockHashTest(void) { Client client(CASPER_TEST_ADDRESS); std::string block_hash = "a5ce9e1ea4ff786cf1eb9dfbe3a79f70ae33d723134a060910a2db80daf85bab"; GetAuctionInfoResult auction_result = client.GetAuctionInfo(block_hash); // tests TEST_ASSERT(auction_result.api_version != ""); TEST_ASSERT(iequals( auction_result.auction_state.state_root_hash, "fb9847a919b0745e3bea1cc25f3ad4ad5fee0e18fe4bebd303a9e7a93508ddb8")); TEST_ASSERT(auction_result.auction_state.block_height == 569706); TEST_ASSERT(auction_result.auction_state.era_validators.size() > 0); TEST_ASSERT(auction_result.auction_state.era_validators[0].era_id > 0); TEST_ASSERT( auction_result.auction_state.era_validators[0].validator_weights.size() > 0); TEST_ASSERT(auction_result.auction_state.era_validators[0] .validator_weights[0] .public_key.ToString() != ""); TEST_ASSERT(auction_result.auction_state.era_validators[0] .validator_weights[0] .weight > 0); TEST_ASSERT(auction_result.auction_state.bids.size() > 0); TEST_ASSERT(auction_result.auction_state.bids[0].public_key.ToString() != ""); TEST_ASSERT(auction_result.auction_state.bids[0] .bid.validator_public_key.ToString() != ""); TEST_ASSERT( auction_result.auction_state.bids[0].bid.bonding_purse.ToString() != ""); TEST_ASSERT(auction_result.auction_state.bids[0].bid.staked_amount > 0); TEST_ASSERT(auction_result.auction_state.bids[0].bid.delegation_rate > 0); } void PutDeploy_Transfer_Test(void) { using namespace Casper; /* using namespace std::chrono; const auto now_ms = time_point_cast<milliseconds>(system_clock::now()); const auto now_s = time_point_cast<seconds>(now_ms); const auto millis = now_ms - now_s; const auto c_now = system_clock::to_time_t(now_s); std::stringstream ss; ss << std::put_time(gmtime(&c_now), "%FT%T") << '.' << std::setfill('0') << std::setw(3) << millis.count() << 'Z'; */ // std::string timestamp_str2 = "2021-09-25T17:01:24.399Z"; // current date/time based on current system according to RFC3339 // std::cout << "timestamp: " << strToTimestamp(timestamp_str2); /*std::stringstream ss; auto tp = std::chrono::system_clock::now(); auto tt = std::chrono::system_clock::to_time_t(tp); ss << std::put_time(std::gmtime(&tt), "%FT%T") << std::setw(3) << std::millis.count() << 'Z'; */ using namespace std::chrono; const auto now_ms = time_point_cast<milliseconds>(system_clock::now()); const auto now_s = time_point_cast<seconds>(now_ms); const auto millis = now_ms - now_s; const auto c_now = system_clock::to_time_t(now_s); std::stringstream ss; ss << std::put_time(gmtime(&c_now), "%FT%T") << '.' << std::setfill('0') << std::setw(3) << millis.count() << 'Z'; std::string timestamp_str = ss.str(); // std::asctime(std::localtime(&tt)), DeployHeader header( Casper::PublicKey::FromHexString("0202a6e2d25621758e2c92900f842ff367bbb5e" "4b6a849cacb43c3eaebf371b24b85"), timestamp_str, "30m", 1, "", {}, "casper-test"); Casper::PublicKey tgt_key = Casper::PublicKey::FromHexString( "018afa98ca4be12d613617f7339a2d576950a2f9a92102ca4d6508ee31b54d2c02"); uint512_t amount = u512FromDec("1000000000"); // std::cout << "before payment" << std::endl; // std::cout << "amount: " << amount << std::endl; // create a payment ModuleBytes payment(amount); // create a payment executable deploy item // ExecutableDeployItem payment(paymentInner); // std::cout << "after payment" << std::endl; // create transfer executable deploy item TransferDeployItem session(u512FromDec("2845678925"), AccountHashKey(tgt_key), 123456789012345u, true); // ExecutableDeployItem session(sessionInner); // Create deploy object // std::cout << "before deploy" << std::endl; Deploy deploy(header, payment, session); // std::cout << "after deploy" << std::endl; std::string signer = "0202a6e2d25621758e2c92900f842ff367bbb5e4b6a849cacb43c3eaebf371b24b85"; // std::cout << "before approval" << std::endl; std::string privKeyPemFile = "/home/yusuf/casper-cpp-sdk/test/data/KeyPair/secp_secret_test2_key.pem"; Casper::Secp256k1Key secp256k1Key(privKeyPemFile); /* std::cout << "private key: " << secp256k1Key.getPrivateKeyStr() << std::endl; std::cout << "public key: " << secp256k1Key.getPublicKeyStr() << std::endl; std::string signature = secp256k1Key.sign(deploy.hash); std::cout << "signature: " << Casper::Secp256k1Key::signatureToString(signature) << std::endl; signature = Casper::Secp256k1Key::signatureToString(signature); DeployApproval approval(Casper::PublicKey::FromHexString(signer), Signature::FromHexString(signature)); std::cout << approval.signature.ToString() << std::endl; std::cout << approval.signer.ToString() << std::endl; std::cout << "after approval" << std::endl; deploy.AddApproval(approval); std::cout << "after add approval" << std::endl; */ Client client(CASPER_TEST_ADDRESS); Deploy dp(deploy.header, deploy.payment, deploy.session); dp.Sign(secp256k1Key); DeployByteSerializer sery; nlohmann::json j; to_json(j, dp); std::cout << j.dump(2) << std::endl; // std::cout << "\n\n\ntest\n\n\n"; // std::cout << "testttt:" << hexEncode(sery.ToBytes(dp)) << std::endl // << std::endl // << std::endl // << std::endl; PutDeployResult res = client.PutDeploy(dp); std::cout << "deploy id: " << res.deploy_hash << std::endl; } std::string getTimestampNow() { using namespace std::chrono; const auto now_ms = time_point_cast<milliseconds>(system_clock::now()); const auto now_s = time_point_cast<seconds>(now_ms); const auto millis = now_ms - now_s; const auto c_now = system_clock::to_time_t(now_s); std::stringstream ss; ss << std::put_time(gmtime(&c_now), "%FT%T") << '.' << std::setfill('0') << std::setw(3) << millis.count() << 'Z'; std::string timestamp_str = ss.str(); return timestamp_str; } void PutDeploy_StoredContractByName_Test(void) { std::string timestamp_str = getTimestampNow(); DeployHeader header( Casper::PublicKey::FromHexString("0202a6e2d25621758e2c92900f842ff367bbb5e" "4b6a849cacb43c3eaebf371b24b85"), timestamp_str, "30m", 1, "", {}, "casper-test"); uint512_t amount = u512FromDec("15000000000"); ModuleBytes payment(amount); NamedArg arg1( "target", CLValue::ByteArray( "9131b2356aa604ced1725bc2d1814683f4ccfc0050ccbd17991daf669c48d327")); uint512_t amount2 = u512FromDec("100000000000"); NamedArg arg2("amount", CLValue::U512(amount2)); std::vector<NamedArg> y_args = {arg1, arg2}; StoredContractByName scbn("faucet", "call_faucet", y_args); Deploy deploy(header, payment, scbn); std::string signer = "0202a6e2d25621758e2c92900f842ff367bbb5e4b6a849cacb43c3eaebf371b24b85"; std::string privKeyPemFile = "/home/yusuf/casper-cpp-sdk/test/data/KeyPair/secp_secret_test2_key.pem"; Casper::Secp256k1Key secp256k1Key(privKeyPemFile); Client client(CASPER_TEST_ADDRESS); Deploy dp(deploy.header, deploy.payment, deploy.session); dp.Sign(secp256k1Key); DeployByteSerializer sery; nlohmann::json j; to_json(j, dp); std::cout << j.dump(2) << std::endl; PutDeployResult res = client.PutDeploy(dp); std::cout << "deploy id: " << res.deploy_hash << std::endl; } void PutDeploy_StoredContractByHash_Test(void) { std::string timestamp_str = getTimestampNow(); DeployHeader header( Casper::PublicKey::FromHexString("0202a6e2d25621758e2c92900f842ff367bbb5e" "4b6a849cacb43c3eaebf371b24b85"), timestamp_str, "30m", 1, "", {}, "casper-test"); uint512_t amount = u512FromDec("5000000000"); ModuleBytes payment(amount); StoredContractByHash scbh( "e3523602448b6085b861890b1c214181e2c1a7bdd2b23424b1941d1301256517", "unlock_cspr", {NamedArg("receipient_publickey", CLValue::String("01f28f169dad17315a03d15e16aa93d5342303ae11f" "15c68aadfdab3df31b0fcbf")), NamedArg("bsc_transaction_hash", CLValue::String("0xd6e7f5aa561e069c385d0f63a3c8dc5501f63d3616c3" "61749e5efab9776fa33e")), NamedArg("amount", CLValue::U512("33780000000"))}); Deploy deploy(header, payment, scbh); std::string signer = "0202a6e2d25621758e2c92900f842ff367bbb5e4b6a849cacb43c3eaebf371b24b85"; std::string privKeyPemFile = "/home/yusuf/casper-cpp-sdk/test/data/KeyPair/secp_secret_test2_key.pem"; Casper::Secp256k1Key secp256k1Key(privKeyPemFile); Client client(CASPER_TEST_ADDRESS); Deploy dp(deploy.header, deploy.payment, deploy.session); dp.Sign(secp256k1Key); DeployByteSerializer sery; nlohmann::json j; to_json(j, dp); std::cout << j.dump(2) << std::endl; PutDeployResult res = client.PutDeploy(dp); std::cout << "deploy id: " << res.deploy_hash << std::endl; } } // namespace Casper
32.830688
80
0.709307
[ "object", "vector" ]
6d775b3a77c1856c87f56db62c533e3f995a24f6
9,030
cpp
C++
src/Nazara/Audio/Formats/drwavLoader.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
src/Nazara/Audio/Formats/drwavLoader.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
src/Nazara/Audio/Formats/drwavLoader.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Audio module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Audio/Formats/drwavLoader.hpp> #include <Nazara/Audio/Algorithm.hpp> #include <Nazara/Audio/Audio.hpp> #include <Nazara/Audio/Config.hpp> #include <Nazara/Audio/SoundBuffer.hpp> #include <Nazara/Audio/SoundStream.hpp> #include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/Endianness.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/File.hpp> #include <Nazara/Core/MemoryView.hpp> #include <Nazara/Core/Stream.hpp> #include <optional> #define DR_WAV_IMPLEMENTATION #define DR_WAV_NO_STDIO #include <dr_wav.h> #include <Nazara/Audio/Debug.hpp> namespace Nz { namespace { std::size_t ReadWavCallback(void* pUserData, void* pBufferOut, size_t bytesToRead) { Stream* stream = static_cast<Stream*>(pUserData); return static_cast<std::size_t>(stream->Read(pBufferOut, bytesToRead)); } drwav_bool32 SeekWavCallback(void* pUserData, int offset, drwav_seek_origin origin) { Stream* stream = static_cast<Stream*>(pUserData); switch (origin) { case drwav_seek_origin_start: return stream->SetCursorPos(offset); case drwav_seek_origin_current: return (stream->Read(nullptr, static_cast<std::size_t>(offset)) != 0); default: NazaraInternalError("Seek mode not handled"); return false; } } bool IsWavSupported(const std::string_view& extension) { return extension == "riff" || extension == "rf64" || extension == "wav" || extension == "w64"; } Ternary CheckWav(Stream& stream, const ResourceParameters& parameters) { bool skip; if (parameters.custom.GetBooleanParameter("SkipBuiltinWavLoader", &skip) && skip) return Ternary::False; drwav wav; if (!drwav_init(&wav, &ReadWavCallback, &SeekWavCallback, &stream, nullptr)) return Ternary::False; drwav_uninit(&wav); return Ternary::True; } std::shared_ptr<SoundBuffer> LoadWavSoundBuffer(Stream& stream, const SoundBufferParams& parameters) { drwav wav; if (!drwav_init(&wav, &ReadWavCallback, &SeekWavCallback, &stream, nullptr)) { NazaraError("failed to decode wav stream"); return {}; } CallOnExit uninitOnExit([&] { drwav_uninit(&wav); }); std::optional<AudioFormat> formatOpt = GuessAudioFormat(wav.channels); if (!formatOpt) { NazaraError("unexpected channel count: " + std::to_string(wav.channels)); return {}; } AudioFormat format = *formatOpt; UInt64 sampleCount = wav.totalPCMFrameCount * wav.channels; std::unique_ptr<Int16[]> samples = std::make_unique<Int16[]>(sampleCount); //< std::vector would default-init to zero if (drwav_read_pcm_frames_s16(&wav, wav.totalPCMFrameCount, samples.get()) != wav.totalPCMFrameCount) { NazaraError("failed to read stream content"); return {}; } if (parameters.forceMono && format != AudioFormat::I16_Mono) { MixToMono(samples.get(), samples.get(), static_cast<UInt32>(wav.channels), wav.totalPCMFrameCount); format = AudioFormat::I16_Mono; sampleCount = wav.totalPCMFrameCount; } return std::make_shared<SoundBuffer>(format, sampleCount, wav.sampleRate, samples.get()); } class drwavStream : public SoundStream { public: drwavStream() : m_readSampleCount(0) { std::memset(&m_decoder, 0, sizeof(m_decoder)); } ~drwavStream() { drwav_uninit(&m_decoder); } UInt32 GetDuration() const override { return m_duration; } AudioFormat GetFormat() const override { if (m_mixToMono) return AudioFormat::I16_Mono; else return m_format; } std::mutex& GetMutex() override { return m_mutex; } UInt64 GetSampleCount() const override { return m_sampleCount; } UInt32 GetSampleRate() const override { return m_sampleRate; } bool Open(const std::filesystem::path& filePath, bool forceMono) { std::unique_ptr<File> file = std::make_unique<File>(); if (!file->Open(filePath, OpenMode::ReadOnly)) { NazaraError("failed to open stream from file: " + Error::GetLastError()); return false; } m_ownedStream = std::move(file); return Open(*m_ownedStream, forceMono); } bool Open(const void* data, std::size_t size, bool forceMono) { m_ownedStream = std::make_unique<MemoryView>(data, size); return Open(*m_ownedStream, forceMono); } bool Open(Stream& stream, bool forceMono) { if (!drwav_init(&m_decoder, &ReadWavCallback, &SeekWavCallback, &stream, nullptr)) { NazaraError("failed to decode wav stream"); return {}; } CallOnExit resetOnError([this] { drwav_uninit(&m_decoder); std::memset(&m_decoder, 0, sizeof(m_decoder)); }); std::optional<AudioFormat> formatOpt = GuessAudioFormat(m_decoder.channels); if (!formatOpt) { NazaraError("unexpected channel count: " + std::to_string(m_decoder.channels)); return false; } m_format = *formatOpt; m_duration = static_cast<UInt32>(1000ULL * m_decoder.totalPCMFrameCount / m_decoder.sampleRate); m_sampleCount = m_decoder.totalPCMFrameCount * m_decoder.channels; m_sampleRate = m_decoder.sampleRate; // Mixing to mono will be done on the fly if (forceMono && m_format != AudioFormat::I16_Mono) { m_mixToMono = true; m_sampleCount = m_decoder.totalPCMFrameCount; } else m_mixToMono = false; resetOnError.Reset(); return true; } UInt64 Read(void* buffer, UInt64 sampleCount) override { // Convert to mono in the fly if necessary if (m_mixToMono) { // Keep a buffer to the side to prevent allocation m_mixBuffer.resize(sampleCount * m_decoder.channels); std::size_t readSample = drwav_read_pcm_frames_s16(&m_decoder, sampleCount, static_cast<Int16*>(m_mixBuffer.data())); m_readSampleCount += readSample; MixToMono(m_mixBuffer.data(), static_cast<Int16*>(buffer), m_decoder.channels, sampleCount); return readSample; } else { UInt64 readSample = drwav_read_pcm_frames_s16(&m_decoder, sampleCount / m_decoder.channels, static_cast<Int16*>(buffer)); m_readSampleCount += readSample * m_decoder.channels; return readSample * m_decoder.channels; } } void Seek(UInt64 offset) override { drwav_seek_to_pcm_frame(&m_decoder, (m_mixToMono) ? offset : offset / m_decoder.channels); m_readSampleCount = offset; } UInt64 Tell() override { return m_readSampleCount; } private: std::mutex m_mutex; std::unique_ptr<Stream> m_ownedStream; std::vector<Int16> m_mixBuffer; AudioFormat m_format; drwav m_decoder; UInt32 m_duration; UInt32 m_sampleRate; UInt64 m_readSampleCount; UInt64 m_sampleCount; bool m_mixToMono; }; std::shared_ptr<SoundStream> LoadWavSoundStreamFile(const std::filesystem::path& filePath, const SoundStreamParams& parameters) { std::shared_ptr<drwavStream> soundStream = std::make_shared<drwavStream>(); if (!soundStream->Open(filePath, parameters.forceMono)) { NazaraError("failed to open sound stream"); return {}; } return soundStream; } std::shared_ptr<SoundStream> LoadWavSoundStreamMemory(const void* data, std::size_t size, const SoundStreamParams& parameters) { std::shared_ptr<drwavStream> soundStream = std::make_shared<drwavStream>(); if (!soundStream->Open(data, size, parameters.forceMono)) { NazaraError("failed to open music stream"); return {}; } return soundStream; } std::shared_ptr<SoundStream> LoadWavSoundStreamStream(Stream& stream, const SoundStreamParams& parameters) { std::shared_ptr<drwavStream> soundStream = std::make_shared<drwavStream>(); if (!soundStream->Open(stream, parameters.forceMono)) { NazaraError("failed to open music stream"); return {}; } return soundStream; } } namespace Loaders { SoundBufferLoader::Entry GetSoundBufferLoader_drwav() { SoundBufferLoader::Entry loaderEntry; loaderEntry.extensionSupport = IsWavSupported; loaderEntry.streamChecker = [](Stream& stream, const SoundBufferParams& parameters) { return CheckWav(stream, parameters); }; loaderEntry.streamLoader = LoadWavSoundBuffer; return loaderEntry; } SoundStreamLoader::Entry GetSoundStreamLoader_drwav() { SoundStreamLoader::Entry loaderEntry; loaderEntry.extensionSupport = IsWavSupported; loaderEntry.streamChecker = [](Stream& stream, const SoundStreamParams& parameters) { return CheckWav(stream, parameters); }; loaderEntry.fileLoader = LoadWavSoundStreamFile; loaderEntry.memoryLoader = LoadWavSoundStreamMemory; loaderEntry.streamLoader = LoadWavSoundStreamStream; return loaderEntry; } } }
28.043478
129
0.692802
[ "vector" ]
6d7b3c4a6abc958f978a26cd94610313dfe6ffcb
3,240
hpp
C++
core/src/Kokkos_UniqueToken.hpp
ORNL-CEES/kokkos
70d113838b7dade09218a46c1e8aae44b6dbd321
[ "BSD-3-Clause" ]
1
2019-10-15T19:26:22.000Z
2019-10-15T19:26:22.000Z
core/src/Kokkos_UniqueToken.hpp
ORNL-CEES/kokkos
70d113838b7dade09218a46c1e8aae44b6dbd321
[ "BSD-3-Clause" ]
16
2019-04-15T20:52:05.000Z
2020-01-24T05:13:25.000Z
core/src/Kokkos_UniqueToken.hpp
ORNL-CEES/kokkos
70d113838b7dade09218a46c1e8aae44b6dbd321
[ "BSD-3-Clause" ]
1
2019-11-25T14:06:26.000Z
2019-11-25T14:06:26.000Z
/* //@HEADER // ************************************************************************ // // Kokkos v. 2.0 // Copyright (2014) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef KOKKOS_UNIQUE_TOKEN_HPP #define KOKKOS_UNIQUE_TOKEN_HPP #include <Kokkos_Macros.hpp> namespace Kokkos { namespace Experimental { enum class UniqueTokenScope : int { Instance, Global }; /// \brief class to generate unique ids base on the required amount of /// concurrency /// /// This object should behave like a ref-counted object, so that when the last /// instance is destroy resources are free if needed template <typename ExecutionSpace, UniqueTokenScope = UniqueTokenScope::Instance> class UniqueToken { public: using execution_space = ExecutionSpace; using size_type = typename execution_space::size_type; /// \brief create object size for concurrency on the given instance /// /// This object should not be shared between instances UniqueToken(execution_space const& = execution_space()); /// \brief upper bound for acquired values, i.e. 0 <= value < size() KOKKOS_INLINE_FUNCTION size_type size() const; /// \brief acquire value such that 0 <= value < size() KOKKOS_INLINE_FUNCTION size_type acquire() const; /// \brief release a value acquired by generate KOKKOS_INLINE_FUNCTION void release(size_type) const; }; } // namespace Experimental } // namespace Kokkos #endif // KOKKOS_UNIQUE_TOKEN_HPP
36.818182
78
0.71142
[ "object" ]
6d819f3503e313eb965bd53ce6a4ff18fdcbb510
1,557
hpp
C++
src/main/cpp/pistis/exceptions/StackFrame.hpp
tomault/pistis-exceptions
2ac2a506a456b7aaa8ba36deab991cb56cd3cbb5
[ "Apache-2.0" ]
null
null
null
src/main/cpp/pistis/exceptions/StackFrame.hpp
tomault/pistis-exceptions
2ac2a506a456b7aaa8ba36deab991cb56cd3cbb5
[ "Apache-2.0" ]
null
null
null
src/main/cpp/pistis/exceptions/StackFrame.hpp
tomault/pistis-exceptions
2ac2a506a456b7aaa8ba36deab991cb56cd3cbb5
[ "Apache-2.0" ]
null
null
null
#ifndef __PISTIS__EXCEPTIONS__STACKFRAME_HPP__ #define __PISTIS__EXCEPTIONS__STACKFRAME_HPP__ #include <iostream> #include <string> #include <vector> namespace pistis { namespace exceptions { class StackFrame { public: StackFrame(const std::string& functionSignature, const void* address, const std::string& module, const void* functionStart, const void* functionEnd); bool hasSignature() const { return !_sig.empty(); } bool hasModule() const { return !_module.empty(); } bool hasFunctionStart() const { return _fnStart != nullptr; } bool hasFunctionEnd() const { return _fnEnd != nullptr; } const std::string& signature() const { return _sig; } const void* address() const { return _address; } const std::string& module() const { return _module; } const void* functionStart() const { return _fnStart; } const void* functionEnd() const { return _fnEnd; } static std::vector<StackFrame> trace(size_t skip=0, size_t maxFrames=100); bool operator==(const StackFrame& other) const; bool operator!=(const StackFrame& other) const; private: std::string _sig; ///< Signature of function at this frame const void* _address; ///< Address of PC in this frame std::string _module; ///< Library or executable that contains the function const void* _fnStart; ///< Function start const void* _fnEnd; ///< Function end }; std::ostream& operator<<(std::ostream& out, const StackFrame& frame); } } #endif
31.77551
80
0.67052
[ "vector" ]
6d844490b93957fc4a67076dd1469be3c6de3b19
1,377
cpp
C++
kernel/tasks/thread.cpp
leakingmemory/jeokernel
7c2413921cc2d30eef2b340de4efed66d41afeb1
[ "MIT" ]
null
null
null
kernel/tasks/thread.cpp
leakingmemory/jeokernel
7c2413921cc2d30eef2b340de4efed66d41afeb1
[ "MIT" ]
null
null
null
kernel/tasks/thread.cpp
leakingmemory/jeokernel
7c2413921cc2d30eef2b340de4efed66d41afeb1
[ "MIT" ]
null
null
null
// // Created by sigsegv on 09.05.2021. // #include <core/scheduler.h> #include <core/cpu_mpfp.h> #include <std/thread.h> #include "../ApStartup.h" extern "C" { void thread_trampoline_start(std::threadimpl::thread_start_context *ctx); void thread_trampoline(std::threadimpl::thread_start_context *ctx) { ctx->invoke(); uint8_t cpu_num{0}; tasklist *scheduler = get_scheduler(); { critical_section cli{}; if (scheduler->is_multicpu()) { ApStartup *apStartup = GetApStartup(); cpu_num = apStartup->GetCpuNum(); } scheduler->exit(cpu_num, true); } while (true) { asm("hlt"); } } } namespace std { uint32_t thread::start() { tasklist *scheduler = get_scheduler(); { std::vector<task_resource *> resources{}; return scheduler->new_task((uint64_t) thread_trampoline_start, 0x8, (uint64_t) start_context, 0, 0, 0, 0, 0, resources); } } void thread::join() { if (start_context != nullptr && start_context->is_done()) { return; } get_scheduler()->join(id); } void thread::detach() { if (start_context != nullptr) { start_context->detach(); start_context = nullptr; } } }
25.036364
132
0.551198
[ "vector" ]
6d86d7f7fd4719e7c3d2984f0739d8adc29eb3f8
6,624
hpp
C++
opencv2.framework/Versions/A/Headers/xobjdetect.hpp
starbadboy/TotoScanner
c97bcf1f475b8c6da2664b6e2df817860864445a
[ "MIT" ]
150
2015-01-06T10:59:06.000Z
2017-02-25T15:49:36.000Z
opencv2.framework/Versions/A/Headers/xobjdetect.hpp
starbadboy/TotoScanner
c97bcf1f475b8c6da2664b6e2df817860864445a
[ "MIT" ]
1
2015-05-15T19:41:42.000Z
2015-05-15T19:41:42.000Z
opencv2.framework/Versions/A/Headers/xobjdetect.hpp
starbadboy/TotoScanner
c97bcf1f475b8c6da2664b6e2df817860864445a
[ "MIT" ]
46
2015-01-03T00:47:14.000Z
2017-03-10T19:05:34.000Z
/* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2013, OpenCV Foundation, all rights reserved. Third party copyrights are property of their respective owners. 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 names of the copyright holders nor the names of the 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 copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ #ifndef __OPENCV_XOBJDETECT_XOBJDETECT_HPP__ #define __OPENCV_XOBJDETECT_XOBJDETECT_HPP__ #include <opencv2/core.hpp> #include <vector> #include <string> namespace cv { namespace xobjdetect { /* Compute channel pyramid for acf features image — image, for which channels should be computed channels — output array for computed channels */ CV_EXPORTS void computeChannels(InputArray image, std::vector<Mat>& channels); class CV_EXPORTS FeatureEvaluator : public Algorithm { public: /* Set channels for feature evaluation */ virtual void setChannels(InputArrayOfArrays channels) = 0; /* Set window position */ virtual void setPosition(Size position) = 0; /* Evaluate feature with given index for current channels and window position */ virtual int evaluate(size_t feature_ind) const = 0; /* Evaluate all features for current channels and window position Returns matrix-column of features */ virtual void evaluateAll(OutputArray feature_values) const = 0; virtual void assertChannels() = 0; }; /* Construct feature evaluator, set features to evaluate type can "icf" or "acf" */ CV_EXPORTS Ptr<FeatureEvaluator> createFeatureEvaluator(const std::vector<std::vector<int> >& features, const std::string& type); /* Generate acf features window_size — size of window in which features should be evaluated type — type of features, can be "icf" or "acf" count — number of features to generate. Max number of features is min(count, # possible distinct features) Returns vector of distinct acf features */ std::vector<std::vector<int> > generateFeatures(Size window_size, const std::string& type, int count = INT_MAX, int channel_count = 10); struct CV_EXPORTS WaldBoostParams { int weak_count; float alpha; WaldBoostParams(): weak_count(100), alpha(0.02f) {} }; class CV_EXPORTS WaldBoost : public Algorithm { public: /* Train WaldBoost cascade for given data data — matrix of feature values, size M x N, one feature per row labels — matrix of sample class labels, size 1 x N. Labels can be from {-1, +1} Returns feature indices chosen for cascade. Feature enumeration starts from 0 */ virtual std::vector<int> train(const Mat& /*data*/, const Mat& /*labels*/) = 0; /* Predict object class given object that can compute object features feature_evaluator — object that can compute features by demand Returns confidence_value — measure of confidense that object is from class +1 */ virtual float predict( const Ptr<FeatureEvaluator>& /*feature_evaluator*/) const = 0; /* Write WaldBoost to FileStorage */ virtual void write(FileStorage& /*fs*/) const = 0; /* Read WaldBoost */ virtual void read(const FileNode& /*node*/) = 0; }; CV_EXPORTS Ptr<WaldBoost> createWaldBoost(const WaldBoostParams& params = WaldBoostParams()); struct CV_EXPORTS ICFDetectorParams { int feature_count; int weak_count; int model_n_rows; int model_n_cols; int bg_per_image; ICFDetectorParams(): feature_count(UINT_MAX), weak_count(100), model_n_rows(56), model_n_cols(56), bg_per_image(5) {} }; class CV_EXPORTS ICFDetector { public: ICFDetector(): waldboost_(), features_() {} /* Train detector pos_path — path to folder with images of objects bg_path — path to folder with background images params — parameters for detector training */ void train(const String& pos_path, const String& bg_path, ICFDetectorParams params = ICFDetectorParams()); /* Detect object on image image — image for detection object — output array of bounding boxes scaleFactor — scale between layers in detection pyramid minSize — min size of objects in pixels maxSize — max size of objects in pixels */ void detect(const Mat& image, std::vector<Rect>& objects, float scaleFactor, Size minSize, Size maxSize, float threshold); /* Write detector to FileStorage */ void write(FileStorage &fs) const; /* Read detector */ void read(const FileNode &node); private: Ptr<WaldBoost> waldboost_; std::vector<std::vector<int> > features_; int model_n_rows_; int model_n_cols_; }; CV_EXPORTS void write(FileStorage& fs, String&, const ICFDetector& detector); CV_EXPORTS void read(const FileNode& node, ICFDetector& d, const ICFDetector& default_value = ICFDetector()); } /* namespace xobjdetect */ } /* namespace cv */ #endif /* __OPENCV_XOBJDETECT_XOBJDETECT_HPP__ */
29.972851
80
0.712409
[ "object", "vector" ]
6d8784251a49810a19728d38b2efbe1ea60a669f
3,401
cpp
C++
tests/unit/geometry/patch.cpp
Andlon/crest
f79bf5a68f3eb86f5e3422881678bc6f9011730a
[ "MIT" ]
null
null
null
tests/unit/geometry/patch.cpp
Andlon/crest
f79bf5a68f3eb86f5e3422881678bc6f9011730a
[ "MIT" ]
5
2017-01-24T10:45:27.000Z
2017-01-27T16:21:37.000Z
tests/unit/geometry/patch.cpp
Andlon/crest
f79bf5a68f3eb86f5e3422881678bc6f9011730a
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <crest/geometry/indexed_mesh.hpp> #include <crest/geometry/patch.hpp> using crest::IndexedMesh; using ::testing::ElementsAreArray; using ::testing::ElementsAre; using ::testing::Pointwise; using ::testing::Eq; using ::testing::IsEmpty; typedef IndexedMesh<>::Vertex Vertex; typedef IndexedMesh<>::Element Element; TEST(patch_vertices_test, patch_vertices_for_triangles_in_16_element_mesh) { const std::vector<Vertex> vertices { Vertex(0.0, 0.0), Vertex(0.5, 0.0), Vertex(1.0, 0.0), Vertex(0.75, 0.25), Vertex(0.25, 0.25), Vertex(0.0, 0.5), Vertex(0.5, 0.5), Vertex(1.0, 0.5), Vertex(0.75, 0.75), Vertex(0.25, 0.75), Vertex(0.0, 1.0), Vertex(0.5, 1.0), Vertex(1.0, 1.0) }; const std::vector<Element> elements { Element({0, 4, 5}), Element({0, 1, 4}), Element({1, 3, 4}), Element({1, 2, 3}), Element({2, 7, 3}), Element({7, 8, 3}), Element({3, 8, 6}), Element({6, 4, 3}), Element({4, 6, 9}), Element({4, 9, 5}), Element({5, 9, 10}), Element({10, 9, 11}), Element({9, 8, 11}), Element({8, 12, 11}), Element({7, 12, 8}), Element({6, 8, 9}) }; const auto mesh = IndexedMesh<>(vertices, elements); const auto patch = crest::make_patch(mesh, { 3, 5, 8 }); EXPECT_THAT(patch.vertices(), ElementsAre(1, 2, 3, 4, 6, 7, 8, 9)); } TEST(patch_interior_test, patch_interior_for_triangles_in_16_element_mesh) { const std::vector<Vertex> vertices { Vertex(0.0, 0.0), Vertex(0.5, 0.0), Vertex(1.0, 0.0), Vertex(0.75, 0.25), Vertex(0.25, 0.25), Vertex(0.0, 0.5), Vertex(0.5, 0.5), Vertex(1.0, 0.5), Vertex(0.75, 0.75), Vertex(0.25, 0.75), Vertex(0.0, 1.0), Vertex(0.5, 1.0), Vertex(1.0, 1.0) }; const std::vector<Element> elements { Element({0, 4, 5}), Element({0, 1, 4}), Element({1, 3, 4}), Element({1, 2, 3}), Element({2, 7, 3}), Element({7, 8, 3}), Element({3, 8, 6}), Element({6, 4, 3}), Element({4, 6, 9}), Element({4, 9, 5}), Element({5, 9, 10}), Element({10, 9, 11}), Element({9, 8, 11}), Element({8, 12, 11}), Element({7, 12, 8}), Element({6, 8, 9}) }; const auto mesh = IndexedMesh<>(vertices, elements); { const auto interior = crest::make_patch(mesh, { }).interior(); EXPECT_THAT(interior, IsEmpty()); } { const auto interior = crest::make_patch(mesh, { 5, 6 }).interior(); EXPECT_THAT(interior, IsEmpty()); } { const auto interior = crest::make_patch(mesh, { 2, 3, 4, 5, 6, 7, 15 }).interior(); EXPECT_THAT(interior, ElementsAre(3)); } { const auto interior = crest::make_patch(mesh, { 0, 1, 2, 5, 6, 7, 8, 9, 12, 13, 14, 15 }).interior(); EXPECT_THAT(interior, ElementsAre(4, 6, 8)); } }
27.650407
109
0.478683
[ "mesh", "geometry", "vector" ]
6d91b7d347451a128e3961bc8750c05a60ff360c
2,260
cpp
C++
test/api/test_results.cpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
9
2021-09-08T13:13:03.000Z
2022-03-11T21:18:05.000Z
test/api/test_results.cpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
7
2020-08-25T22:24:16.000Z
2020-09-06T00:16:49.000Z
test/api/test_results.cpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
1
2022-01-18T09:38:19.000Z
2022-01-18T09:38:19.000Z
#include "catch.hpp" #include "test_helpers.hpp" using namespace duckdb; using namespace std; TEST_CASE("Test results API", "[api]") { DuckDB db(nullptr); Connection con(db); // result equality auto result = con.Query("SELECT 42"); auto result2 = con.Query("SELECT 42"); REQUIRE(result->Equals(*result2)); // result inequality result = con.Query("SELECT 42"); result2 = con.Query("SELECT 43"); REQUIRE(!result->Equals(*result2)); // stream query to string auto stream_result = con.SendQuery("SELECT 42"); auto str = stream_result->ToString(); REQUIRE(!str.empty()); // materialized query to string result = con.Query("SELECT 42"); str = result->ToString(); REQUIRE(!str.empty()); // error to string result = con.Query("SELEC 42"); str = result->ToString(); REQUIRE(!str.empty()); } TEST_CASE("Test iterating over results", "[api]") { DuckDB db(nullptr); Connection con(db); REQUIRE_NO_FAIL(con.Query("CREATE TABLE data(i INTEGER, j VARCHAR)")); REQUIRE_NO_FAIL(con.Query("INSERT INTO data VALUES (1, 'hello'), (2, 'test')")); vector<int> i_values = {1, 2}; vector<string> j_values = {"hello", "test"}; idx_t row_count = 0; auto result = con.Query("SELECT * FROM data;"); for (auto &row : *result) { REQUIRE(row.GetValue<int>(0) == i_values[row.row]); REQUIRE(row.GetValue<string>(1) == j_values[row.row]); row_count++; } REQUIRE(row_count == 2); } TEST_CASE("Error in streaming result after initial query", "[api]") { DuckDB db(nullptr); Connection con(db); // create a big table with strings that are numbers REQUIRE_NO_FAIL(con.Query("CREATE TABLE strings(v VARCHAR)")); for (size_t i = 0; i < STANDARD_VECTOR_SIZE * 2 - 1; i++) { REQUIRE_NO_FAIL(con.Query("INSERT INTO strings VALUES ('" + to_string(i) + "')")); } // now insert one non-numeric value REQUIRE_NO_FAIL(con.Query("INSERT INTO strings VALUES ('hello')")); // now create a streaming result auto result = con.SendQuery("SELECT CAST(v AS INTEGER) FROM strings"); REQUIRE_NO_FAIL(*result); // initial query does not fail! auto chunk = result->Fetch(); REQUIRE(chunk); // but subsequent query fails! chunk = result->Fetch(); REQUIRE(!chunk); REQUIRE(!result->success); auto str = result->ToString(); REQUIRE(!str.empty()); }
27.901235
84
0.681416
[ "vector" ]
6d95db23d075ae615c0289b87c35bbb5f7317d9f
2,753
cc
C++
lmctfy/cli/commands/spec.cc
claytonbrown/lmctfy
94729318edb06f7d149f67581a07a4c70ed29250
[ "Apache-2.0" ]
1,145
2015-01-01T22:07:47.000Z
2022-03-30T19:19:23.000Z
lmctfy/cli/commands/spec.cc
claytonbrown/lmctfy
94729318edb06f7d149f67581a07a4c70ed29250
[ "Apache-2.0" ]
9
2015-01-09T08:50:27.000Z
2020-02-11T09:16:20.000Z
lmctfy/cli/commands/spec.cc
claytonbrown/lmctfy
94729318edb06f7d149f67581a07a4c70ed29250
[ "Apache-2.0" ]
123
2015-01-02T12:10:08.000Z
2021-10-12T02:49:48.000Z
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lmctfy/cli/commands/spec.h" #include <stdio.h> #include <unistd.h> #include <memory> #include <string> using ::std::string; #include <vector> #include "gflags/gflags.h" #include "google/protobuf/text_format.h" #include "lmctfy/cli/command.h" #include "include/lmctfy.h" #include "include/lmctfy.pb.h" #include "util/errors.h" DECLARE_bool(lmctfy_binary); using ::std::unique_ptr; using ::std::vector; using ::util::Status; namespace containers { namespace lmctfy { namespace cli { // Command to get the ContainerSpec for a container. Status SpecContainer(const vector<string> &argv, const ContainerApi *lmctfy, OutputMap *output) { // Args: spec [<container name>] if (argv.size() < 1 || argv.size() > 2) { return Status(::util::error::INVALID_ARGUMENT, "See help for supported options."); } // Get container name. string container_name; if (argv.size() == 2) { container_name = argv[1]; } else { // Detect parent's container. container_name = RETURN_IF_ERROR(lmctfy->Detect(getppid())); } // Ensure the container exists. unique_ptr<Container> container( RETURN_IF_ERROR(lmctfy->Get(container_name))); // Get the container spec; ContainerSpec spec = RETURN_IF_ERROR(container->Spec()); // Output the stats as a proto in binary or ASCII format as specified. string spec_output; if (FLAGS_lmctfy_binary) { spec.SerializeToString(&spec_output); } else { ::google::protobuf::TextFormat::PrintToString(spec, &spec_output); } output->AddRaw(spec_output); return Status::OK; } void RegisterSpecCommand() { RegisterRootCommand( CMD("spec", "Get the resource isolation specification of the specified " "container. If no container is specified, the current one is " "assumed. The spec is output as a ContainerSpec proto in ASCII " "format. If -b is specified it is output in binary form.", "[-b] [<container name>]", CMD_TYPE_GETTER, 0, 1, &SpecContainer)); } } // namespace cli } // namespace lmctfy } // namespace containers
29.923913
77
0.684344
[ "vector" ]
6d978cdc249afbfb2d36ed2316514a6ee70c3a83
2,552
hpp
C++
include/eve/eve.hpp
clayne/eve
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
[ "MIT" ]
null
null
null
include/eve/eve.hpp
clayne/eve
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
[ "MIT" ]
null
null
null
include/eve/eve.hpp
clayne/eve
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
[ "MIT" ]
null
null
null
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once //================================================================================================== //! @defgroup simd EVE //! @brief This module defines all the types and functions provided by EVE //================================================================================================== //================================================================================================== //! @addtogroup simd //! @{ //================================================================================================== //================================================================================================ //! @defgroup simd_types SIMD related types //! @brief Types and functions wrappers for SIMD registers and related operations //================================================================================================ //================================================================================================== //! @defgroup functions Functions //! @brief This module provides all the numerical functions and function objects //================================================================================================== //================================================================================================== //! @namespace eve Main EVE namespace //================================================================================================== //================================================================================================== //! @} //================================================================================================== //================================================================================================== //! @addtogroup simd_types //! @{ //! @defgroup arch Architecture related Types and Helpers //! @brief This module defines the types and helpers functions to properly handle //! architecture specific components //! @} //================================================================================================== #include <eve/as.hpp> #include <eve/wide.hpp> #include <eve/logical.hpp> #include <eve/version.hpp> #include <eve/traits/cardinal.hpp>
49.076923
100
0.258621
[ "vector" ]
6dafed7802ae73d35ada531c105aacd5f50e75ed
3,884
cpp
C++
abstractball.cpp
andinsbing/BrickBreaker
cc93db7f4e294419c8884ca3f75bb239bbbf0edd
[ "MIT" ]
null
null
null
abstractball.cpp
andinsbing/BrickBreaker
cc93db7f4e294419c8884ca3f75bb239bbbf0edd
[ "MIT" ]
null
null
null
abstractball.cpp
andinsbing/BrickBreaker
cc93db7f4e294419c8884ca3f75bb239bbbf0edd
[ "MIT" ]
null
null
null
#include "abstractball.h" #include<QTimer> #include"gift.h" #include<QDebug> AbstractBall::AbstractBall(qreal movingSpeed,QGraphicsItem* parent): QGraphicsObject(parent), collidingState(notCollided), timer(new QTimer(this)), movingAngle(0,-1), movingSpeed(movingSpeed) { timer->setInterval(movingSpeed); this->connect(timer,SIGNAL(timeout()),this,SLOT(movingForward())); this->connect(this,SIGNAL(collidingWithItem(QList<QGraphicsItem*>,AbstractBall*)),this,SLOT(resetAngel(QList<QGraphicsItem*>))); timer->start(); } AbstractBall::~AbstractBall() { } QPainterPath AbstractBall::shape() const { QPainterPath shape; shape.addEllipse(this->boundingRect()); return shape; } void AbstractBall::offsetAngle(const qreal xOff, const qreal yOff) { this->movingAngle+={xOff,yOff}; movingAngle/=sqrt(movingAngle.x()*movingAngle.x()+movingAngle.y()*movingAngle.y()); if(movingAngle.y()<0)//使得y轴反向的移动速度最小是0.3个单位/每祯 { movingAngle.ry()=std::min(movingAngle.y(),-0.3); } else { movingAngle.ry()=std::max(movingAngle.y(),0.3); } } void AbstractBall::stopMoving() { if(timer->isActive()) { this->timer->stop(); } } void AbstractBall::startToMove() { if(!timer->isActive()) { this->timer->start(); } } void AbstractBall::resetAngel(QList<QGraphicsItem*> items) { enum { topLeftFlag=0b1000, topRightFlag=0b0100, bottomLeftFlag=0b0010, bottomRightFlag=0b0001 }; auto boundingRect=this->boundingRect(); auto topLeft=boundingRect.topLeft(); auto topRight=boundingRect.topRight(); auto bottomLeft=boundingRect.bottomLeft(); auto bottomRight=boundingRect.bottomRight(); int hitState{0b0000}; for(auto& i:items) { if(!(hitState&topLeftFlag)&&i->contains(i->mapFromItem(this,topLeft))) { hitState|=topLeftFlag; } if(!(hitState&topRightFlag)&&i->contains(i->mapFromItem(this,topRight))) { hitState|=topRightFlag; } if(!(hitState&bottomLeftFlag)&&i->contains(i->mapFromItem(this,bottomLeft))) { hitState|=bottomLeftFlag; } if(!(hitState&bottomRightFlag)&&i->contains(i->mapFromItem(this,bottomRight))) { hitState|=bottomRightFlag; } } switch(hitState) { case topLeftFlag: case topLeftFlag|topRightFlag|bottomLeftFlag: this->offsetAngle(sqrt(2)*2,sqrt(2)*2); break; case topRightFlag: case topLeftFlag|topRightFlag|bottomRightFlag: this->offsetAngle(-sqrt(2)*2,sqrt(2)*2); break; case bottomLeftFlag: case topLeftFlag|bottomLeftFlag|bottomRightFlag: this->offsetAngle(sqrt(2)*2,-sqrt(2)*2); break; case bottomRightFlag: case topRightFlag|bottomLeftFlag|bottomRightFlag: this->offsetAngle(-sqrt(2)*2,-sqrt(2)*2); break; case topLeftFlag|topRightFlag: case bottomLeftFlag|bottomRightFlag: this->offsetAngle(0,-2*movingAngle.y()); break; case topLeftFlag|bottomLeftFlag: case topRightFlag|bottomRightFlag: this->offsetAngle(-2*movingAngle.x(),0); break; default: static int i=0; qDebug()<<"error in matching state"<<i++; break; } } void AbstractBall::movingForward() { this->setPos(this->pos()+movingAngle); this->handleCollision(); } void AbstractBall::handleCollision() { auto collidingItems=this->collidingItems(Qt::IntersectsItemBoundingRect); for(auto& i:collidingItems)//球不与球碰撞,不与礼物碰撞 { if(dynamic_cast<AbstractBall*>(i)) { collidingItems.removeOne(i); } else if(dynamic_cast<Gift*>(i)) { collidingItems.removeOne(i); } } if(collidingItems==justCollidedItems)//排除相同元素连续碰撞的情况 { return; } if(collidingItems.empty()) { collidingState=notCollided; justCollidedItems.clear(); } else { collidingState=collided; justCollidedItems=collidingItems; emit collidingWithItem(justCollidedItems,this); } }
22.71345
130
0.685376
[ "shape" ]
6db221dcc550d31728fdaaeb8f11a349889d0139
3,691
cpp
C++
src/utils.cpp
lu1and10/SkellySim
6d319f2d1c1c85506d7debedc082747d89995045
[ "Apache-2.0" ]
null
null
null
src/utils.cpp
lu1and10/SkellySim
6d319f2d1c1c85506d7debedc082747d89995045
[ "Apache-2.0" ]
null
null
null
src/utils.cpp
lu1and10/SkellySim
6d319f2d1c1c85506d7debedc082747d89995045
[ "Apache-2.0" ]
null
null
null
#include <mpi.h> #include <skelly_sim.hpp> #include <utils.hpp> #include <cnpy.hpp> // Following the paper Calculation of weights in finite different formulas, // Bengt Fornberg, SIAM Rev. 40 (3), 685 (1998). // // Inputs: // s = grid points // M = order of the highest derivative to compute // n_s = support to compute the derivatives // // Outputs: // D_s = Mth derivative matrix Eigen::MatrixXd utils::finite_diff(ArrayRef &s, int M, int n_s) { int N = s.size() - 1; Eigen::MatrixXd D_s = Eigen::MatrixXd::Zero(N + 1, N + 1); int n_s_half = (n_s - 1) / 2; n_s = n_s - 1; for (int xi = 0; xi < s.size(); ++xi) { const auto &si = s[xi]; int xlow, xhigh; if (xi < n_s_half) { xlow = 0; xhigh = n_s + 1; } else if (xi > (s.size() - n_s_half - 2)) { xlow = -n_s - 1; xhigh = s.size(); } else { xlow = xi - n_s_half; xhigh = xi - n_s_half + n_s + 1; } xlow = xlow < 0 ? s.size() + xlow : xlow; CArrayMap x(s.data() + xlow, xhigh - xlow); // Computer coefficients of differential matrices double c1 = 1.0; double c4 = x[0] - si; Eigen::MatrixXd c = Eigen::MatrixXd::Zero(n_s + 1, M + 1); c(0, 0) = 1.0; for (int i = 1; i < n_s + 1; ++i) { int mn = std::min(i, M); double c2 = 1.0; double c5 = c4; c4 = x(i) - si; for (int j = 0; j < i; ++j) { double c3 = x(i) - x(j); c2 = c2 * c3; if (j == i - 1) { for (int k = mn; k > 0; --k) { c(i, k) = c1 * (k * c(i - 1, k - 1) - c5 * c(i - 1, k)) / c2; } c(i, 0) = -c1 * c5 * c(i - 1, 0) / c2; } for (int k = mn; k > 0; --k) { c(j, k) = (c4 * c(j, k) - k * c(j, k - 1)) / c3; } c(j, 0) = c4 * c(j, 0) / c3; } c1 = c2; } for (int i = 0; i < n_s + 1; ++i) { D_s(xi, xlow + i) = c(i, M); } } return D_s; } /// @brief Collects eigen arrays of potentially varying sizes across MPI ranks and returns them /// in one large array to root process. /// /// @param[in] local_vec vector to collect /// @returns Concatenated vector of local_vec on rank 0, empty vector otherwise Eigen::VectorXd utils::collect_into_global(VectorRef &local_vec) { int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); Eigen::VectorXi sizes(size); Eigen::VectorXd global_vec; const int local_vec_size = local_vec.size(); MPI_Gather(&local_vec_size, 1, MPI_INT, sizes.data(), 1, MPI_INT, 0, MPI_COMM_WORLD); Eigen::VectorXi displs(size + 1); if (rank == 0) { displs[0] = 0; int global_vec_size = 0; for (int i = 0; i < size; ++i) { displs[i + 1] = displs[i] + sizes[i]; global_vec_size += sizes[i]; } global_vec.resize(global_vec_size); } MPI_Gatherv(local_vec.data(), local_vec.size(), MPI_DOUBLE, global_vec.data(), sizes.data(), displs.data(), MPI_DOUBLE, 0, MPI_COMM_WORLD); return global_vec; } Eigen::MatrixXd utils::load_mat(cnpy::npz_t &npz, const char *var) { return Eigen::Map<Eigen::ArrayXXd>(npz[var].data<double>(), npz[var].shape[1], npz[var].shape[0]).matrix().transpose(); } Eigen::VectorXd utils::load_vec(cnpy::npz_t &npz, const char *var) { return Eigen::Map<Eigen::VectorXd>(npz[var].data<double>(), npz[var].shape[0]); }
31.818966
123
0.506909
[ "shape", "vector" ]
6db2d92b8d9ed043f5dedf14ea2c1f7c2fa4bd2b
908
cpp
C++
leetcode/word-search.cpp
bananaappletw/online-judge
aa5606ecce1b29bf071ec682ea152b1ee4417958
[ "MIT" ]
null
null
null
leetcode/word-search.cpp
bananaappletw/online-judge
aa5606ecce1b29bf071ec682ea152b1ee4417958
[ "MIT" ]
null
null
null
leetcode/word-search.cpp
bananaappletw/online-judge
aa5606ecce1b29bf071ec682ea152b1ee4417958
[ "MIT" ]
null
null
null
class Solution { public: int m; int n; bool solve(vector<vector<char>>& board, string& word,int idx,int i,int j) { if(idx==word.length()) return true; if(i<0||j<0||i>=m||j>=n||word[idx]!=board[i][j]) return false; board[i][j]='\0'; if(solve(board,word,idx+1,i+1,j) || solve(board,word,idx+1,i-1,j) || solve(board,word,idx+1,i,j+1) || solve(board,word,idx+1,i,j-1)) return true; board[i][j]=word[idx]; return false; } bool exist(vector<vector<char>>& board, string word) { m=board.size(); if(!m) return false; n=board.front().size(); if(!n) return false; for(int i=0; i<m; i++) for(int j=0; j<n; j++) if(solve(board,word,0,i,j)) return true; return false; } };
28.375
82
0.468062
[ "vector" ]
6db4f6c3ab08a24367582f8c499f4d23f73a177e
2,449
cpp
C++
src/graph/optimizer/rule/TopNRule.cpp
heyanlong/nebula
07ccfde198c978b8c86b7091773e3238bfcdf454
[ "Apache-2.0" ]
1
2021-12-25T07:00:48.000Z
2021-12-25T07:00:48.000Z
src/graph/optimizer/rule/TopNRule.cpp
heyanlong/nebula
07ccfde198c978b8c86b7091773e3238bfcdf454
[ "Apache-2.0" ]
2
2021-11-18T03:14:50.000Z
2021-11-18T07:38:06.000Z
src/graph/optimizer/rule/TopNRule.cpp
heyanlong/nebula
07ccfde198c978b8c86b7091773e3238bfcdf454
[ "Apache-2.0" ]
3
2021-11-08T16:21:16.000Z
2021-11-10T06:39:48.000Z
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "graph/optimizer/rule/TopNRule.h" #include "common/expression/BinaryExpression.h" #include "common/expression/ConstantExpression.h" #include "common/expression/Expression.h" #include "common/expression/FunctionCallExpression.h" #include "common/expression/LogicalExpression.h" #include "common/expression/UnaryExpression.h" #include "graph/optimizer/OptContext.h" #include "graph/optimizer/OptGroup.h" #include "graph/planner/plan/PlanNode.h" #include "graph/planner/plan/Query.h" #include "graph/visitor/ExtractFilterExprVisitor.h" using nebula::graph::Limit; using nebula::graph::PlanNode; using nebula::graph::QueryContext; using nebula::graph::Sort; using nebula::graph::TopN; namespace nebula { namespace opt { std::unique_ptr<OptRule> TopNRule::kInstance = std::unique_ptr<TopNRule>(new TopNRule()); TopNRule::TopNRule() { RuleSet::QueryRules().addRule(this); } const Pattern &TopNRule::pattern() const { static Pattern pattern = Pattern::create(graph::PlanNode::Kind::kLimit, {Pattern::create(graph::PlanNode::Kind::kSort)}); return pattern; } StatusOr<OptRule::TransformResult> TopNRule::transform(OptContext *ctx, const MatchedResult &matched) const { auto limitGroupNode = matched.node; auto sortGroupNode = matched.dependencies.front().node; auto limit = static_cast<const Limit *>(limitGroupNode->node()); auto sort = static_cast<const Sort *>(sortGroupNode->node()); // Currently, we cannot know the total amount of input data, // so only apply topn rule when offset of limit is 0 if (limit->offset() != 0) { return TransformResult::noTransform(); } auto qctx = ctx->qctx(); auto topn = TopN::make(qctx, nullptr, sort->factors(), limit->offset(), limit->count()); topn->setOutputVar(limit->outputVar()); topn->setInputVar(sort->inputVar()); topn->setColNames(sort->colNames()); auto topnNode = OptGroupNode::create(ctx, topn, limitGroupNode->group()); for (auto dep : sortGroupNode->dependencies()) { topnNode->dependsOn(dep); } TransformResult result; result.newGroupNodes.emplace_back(topnNode); result.eraseAll = true; return result; } std::string TopNRule::toString() const { return "TopNRule"; } } // namespace opt } // namespace nebula
34.013889
92
0.708044
[ "transform" ]
6dbb00a88a423628a32b4a5480b8f9fed382bbec
1,278
cpp
C++
lightoj.com/GeneratingPalindromes.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
6
2016-09-10T03:16:34.000Z
2020-04-07T14:45:32.000Z
lightoj.com/GeneratingPalindromes.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
null
null
null
lightoj.com/GeneratingPalindromes.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
2
2018-08-11T20:55:35.000Z
2020-01-15T23:23:11.000Z
/* By: facug91 From: http://www.lightoj.com/volume_showproblem.php?problem=1033 Name: Generating Palindromes Date: 23/05/2016 */ #include <bits/stdc++.h> #define endl "\n" #define EPS 1e-9 #define MP make_pair #define F first #define S second #define DB(x) cerr << " #" << (#x) << ": " << (x) #define DBL(x) cerr << " #" << (#x) << ": " << (x) << endl const double PI = acos(-1.0); #define INF 1000000000 #define MOD 100000007 //#define MAXN 30015 using namespace std; typedef long long ll; typedef unsigned long long llu; typedef pair<int, int> ii; typedef pair<ii, ii> iiii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<iiii> viiii; int DP[105][105]; string s; int dp (int l, int r) { if (l >= r) return 0; if (DP[l][r] != -1) return DP[l][r]; DP[l][r] = min(dp(l+1, r-1) + (s[l] != s[r]) * 2, min(dp(l+1, r) + 1, dp(l, r-1) + 1)); return DP[l][r]; } int main () { //#ifdef ONLINE_JUDGE ios_base::sync_with_stdio(0); cin.tie(0); //#endif //cout<<fixed<<setprecision(9); cerr<<fixed<<setprecision(2); //cin.ignore(INT_MAX, ' '); //cout<<setfill('0')<<setw(9) int tc = 1, i, j; cin>>tc; for (int it=1; it<=tc; it++) { cin>>s; memset(DP, -1, sizeof DP); cout<<"Case "<<it<<": "<<dp(0, s.length()-1)<<endl; } return 0; }
23.236364
120
0.596244
[ "vector" ]
6dca5da8b008b5d867681bd6579df24bc1fb6955
1,924
cpp
C++
examples/ros/src/wheel_vehicle_control/src/wheel_vehicle_control.cpp
tomd-tc/monodrive-client
95b6f2e02e081dcd2d66cc66dbf68c2f39da8ed6
[ "MIT" ]
null
null
null
examples/ros/src/wheel_vehicle_control/src/wheel_vehicle_control.cpp
tomd-tc/monodrive-client
95b6f2e02e081dcd2d66cc66dbf68c2f39da8ed6
[ "MIT" ]
null
null
null
examples/ros/src/wheel_vehicle_control/src/wheel_vehicle_control.cpp
tomd-tc/monodrive-client
95b6f2e02e081dcd2d66cc66dbf68c2f39da8ed6
[ "MIT" ]
1
2021-08-19T16:42:04.000Z
2021-08-19T16:42:04.000Z
#include <iostream> // std::cout #include <chrono> // std::chrono #include <thread> // std::thread #include <memory> #include <vector> #include <future> //monoDrive Includes #include "ros/ros.h" #include "ros/package.h" #include "monodrive_msgs/VehicleControl.h" #include <geometry_msgs/Twist.h> #include <sensor_msgs/Joy.h> #include <experimental/filesystem> namespace fs = std::experimental::filesystem; std::string vehicle_name = "subcompact_monoDrive_01"; std::shared_ptr<ros::NodeHandle> node_handle; ros::Publisher vehicle_control_pub; ros::Subscriber joy_sub_; std::vector<float> wheel_data = {0,0,0,0}; void control_vehicle(){ monodrive_msgs::VehicleControl msg; msg.name = vehicle_name; msg.throttle = wheel_data[0]; msg.brake = wheel_data[1]; msg.steer = wheel_data[2]; msg.drive_mode = wheel_data[3]; vehicle_control_pub.publish(msg); } void joyCallback(const sensor_msgs::Joy::ConstPtr& joy){ wheel_data[0] = (joy->axes[1] == -1) ? 0 : joy->axes[1]; //throttle wheel_data[1] = (joy->axes[2] == -1) ? 0 : joy->axes[2]; //brake wheel_data[2] = -1.0 * joy->axes[0]; // steering - Need to inverse to match movement wheel_data[3] = (joy->buttons[8]) == 0.0 ? 1.0 : -1.0; //drive_mode } int main(int argc, char** argv) { ros::init(argc, argv, "wheel_vehicle_control"); fs::path path(ros::package::getPath("wheel_vehicle_control")); fs::path configPath = path / "config"; // create vehicle controller publisher and sensor subscriber node_handle = std::make_shared<ros::NodeHandle>(ros::NodeHandle()); vehicle_control_pub = node_handle->advertise<monodrive_msgs::VehicleControl>("/monodrive/vehicle_control", 1); joy_sub_ = node_handle->subscribe("/joy", 1, &joyCallback); ros::Rate rate(100); while(ros::ok()){ control_vehicle(); ros::spinOnce(); rate.sleep(); } return 0; }
26.722222
114
0.671518
[ "vector" ]
6dca95d8e28942ed9e36d36312228d62b84b7ca3
6,696
cc
C++
mediapipe/calculators/tensor/tensors_to_classification_calculator.cc
mapleyuan/mediapipe
f15da632dec186f2c1d3c780f47086477e2286a9
[ "Apache-2.0" ]
3
2020-11-23T18:15:28.000Z
2020-11-29T15:51:10.000Z
mediapipe/calculators/tensor/tensors_to_classification_calculator.cc
mapleyuan/mediapipe
f15da632dec186f2c1d3c780f47086477e2286a9
[ "Apache-2.0" ]
1
2021-06-03T03:34:46.000Z
2021-06-03T03:34:46.000Z
mediapipe/calculators/tensor/tensors_to_classification_calculator.cc
mapleyuan/mediapipe
f15da632dec186f2c1d3c780f47086477e2286a9
[ "Apache-2.0" ]
3
2021-02-09T21:03:05.000Z
2021-05-17T03:43:48.000Z
// Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <unordered_map> #include <vector> #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "mediapipe/calculators/tensor/tensors_to_classification_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/classification.pb.h" #include "mediapipe/framework/formats/tensor.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/util/resource_util.h" #if defined(MEDIAPIPE_MOBILE) #include "mediapipe/util/android/file/base/file.h" #include "mediapipe/util/android/file/base/helpers.h" #else #include "mediapipe/framework/port/file_helpers.h" #endif namespace mediapipe { // Convert result tensors from classification models into MediaPipe // classifications. // // Input: // TENSORS - Vector of Tensors of type kFloat32 containing one // tensor, the size of which must be (1, * num_classes). // Output: // CLASSIFICATIONS - Result MediaPipe ClassificationList. The score and index // fields of each classification are set, while the label // field is only set if label_map_path is provided. // // Usage example: // node { // calculator: "TensorsToClassificationCalculator" // input_stream: "TENSORS:tensors" // output_stream: "CLASSIFICATIONS:classifications" // options: { // [mediapipe.TensorsToClassificationCalculatorOptions.ext] { // num_classes: 1024 // min_score_threshold: 0.1 // label_map_path: "labelmap.txt" // } // } // } class TensorsToClassificationCalculator : public CalculatorBase { public: static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; ::mediapipe::Status Close(CalculatorContext* cc) override; private: ::mediapipe::TensorsToClassificationCalculatorOptions options_; int top_k_ = 0; std::unordered_map<int, std::string> label_map_; bool label_map_loaded_ = false; }; REGISTER_CALCULATOR(TensorsToClassificationCalculator); ::mediapipe::Status TensorsToClassificationCalculator::GetContract( CalculatorContract* cc) { RET_CHECK(!cc->Inputs().GetTags().empty()); RET_CHECK(!cc->Outputs().GetTags().empty()); if (cc->Inputs().HasTag("TENSORS")) { cc->Inputs().Tag("TENSORS").Set<std::vector<Tensor>>(); } if (cc->Outputs().HasTag("CLASSIFICATIONS")) { cc->Outputs().Tag("CLASSIFICATIONS").Set<ClassificationList>(); } return ::mediapipe::OkStatus(); } ::mediapipe::Status TensorsToClassificationCalculator::Open( CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); options_ = cc->Options<::mediapipe::TensorsToClassificationCalculatorOptions>(); top_k_ = options_.top_k(); if (options_.has_label_map_path()) { std::string string_path; ASSIGN_OR_RETURN(string_path, PathToResourceAsFile(options_.label_map_path())); std::string label_map_string; MP_RETURN_IF_ERROR(file::GetContents(string_path, &label_map_string)); std::istringstream stream(label_map_string); std::string line; int i = 0; while (std::getline(stream, line)) { label_map_[i++] = line; } label_map_loaded_ = true; } return ::mediapipe::OkStatus(); } ::mediapipe::Status TensorsToClassificationCalculator::Process( CalculatorContext* cc) { const auto& input_tensors = cc->Inputs().Tag("TENSORS").Get<std::vector<Tensor>>(); RET_CHECK_EQ(input_tensors.size(), 1); int num_classes = input_tensors[0].shape().num_elements(); if (options_.binary_classification()) { RET_CHECK_EQ(num_classes, 1); // Number of classes for binary classification. num_classes = 2; } if (label_map_loaded_) { RET_CHECK_EQ(num_classes, label_map_.size()); } auto view = input_tensors[0].GetCpuReadView(); auto raw_scores = view.buffer<float>(); auto classification_list = absl::make_unique<ClassificationList>(); if (options_.binary_classification()) { Classification* class_first = classification_list->add_classification(); Classification* class_second = classification_list->add_classification(); class_first->set_index(0); class_second->set_index(1); class_first->set_score(raw_scores[0]); class_second->set_score(1. - raw_scores[0]); if (label_map_loaded_) { class_first->set_label(label_map_[0]); class_second->set_label(label_map_[1]); } } else { for (int i = 0; i < num_classes; ++i) { if (options_.has_min_score_threshold() && raw_scores[i] < options_.min_score_threshold()) { continue; } Classification* classification = classification_list->add_classification(); classification->set_index(i); classification->set_score(raw_scores[i]); if (label_map_loaded_) { classification->set_label(label_map_[i]); } } } // Note that partial_sort will raise error when top_k_ > // classification_list->classification_size(). CHECK_GE(classification_list->classification_size(), top_k_); auto raw_classification_list = classification_list->mutable_classification(); if (top_k_ > 0 && classification_list->classification_size() >= top_k_) { std::partial_sort(raw_classification_list->begin(), raw_classification_list->begin() + top_k_, raw_classification_list->end(), [](const Classification a, const Classification b) { return a.score() > b.score(); }); // Resizes the underlying list to have only top_k_ classifications. raw_classification_list->DeleteSubrange( top_k_, raw_classification_list->size() - top_k_); } cc->Outputs() .Tag("CLASSIFICATIONS") .Add(classification_list.release(), cc->InputTimestamp()); return ::mediapipe::OkStatus(); } ::mediapipe::Status TensorsToClassificationCalculator::Close( CalculatorContext* cc) { return ::mediapipe::OkStatus(); } } // namespace mediapipe
33.818182
81
0.703405
[ "shape", "vector" ]
6dcc3758cb06a0ad6fa07be6a6ed554598531f11
33,429
cpp
C++
modules/recognition/src/multiview_recognizer.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
2
2021-02-22T11:36:33.000Z
2021-07-20T11:31:08.000Z
modules/recognition/src/multiview_recognizer.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
null
null
null
modules/recognition/src/multiview_recognizer.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
3
2018-10-19T10:39:23.000Z
2021-04-07T13:39:03.000Z
#include <glog/logging.h> #include <v4r/common/graph_geometric_consistency.h> #include <v4r/common/miscellaneous.h> #include <v4r/recognition/local_recognition_pipeline.h> #include <v4r/recognition/multi_pipeline_recognizer.h> #include <v4r/recognition/multiview_recognizer.h> #include <omp.h> #include <pcl/common/time.h> #include <pcl/registration/transformation_estimation_svd.h> namespace po = boost::program_options; namespace v4r { template <typename PointT> void MultiviewRecognizer<PointT>::do_recognize(const std::vector<std::string> &model_ids_to_search) { local_obj_hypotheses_.clear(); View v; v.camera_pose_ = v4r::RotTrans2Mat4f(scene_->sensor_orientation_, scene_->sensor_origin_); recognition_pipeline_->setInputCloud(scene_); recognition_pipeline_->setSceneNormals(scene_normals_); if (table_plane_set_) recognition_pipeline_->setTablePlane(table_plane_); recognition_pipeline_->recognize(model_ids_to_search); v.obj_hypotheses_ = recognition_pipeline_->getObjectHypothesis(); table_plane_set_ = false; obj_hypotheses_ = v.obj_hypotheses_; std::set<size_t> hypotheses_ids; /// to make sure hypotheses are only transferred once // now add the old hypotheses for (int v_id = views_.size() - 1; v_id >= std::max<int>(0, views_.size() - param_.max_views_ + 1); v_id--) { const View &v_old = views_[v_id]; for (const ObjectHypothesesGroup &ohg_tmp : v_old.obj_hypotheses_) { bool do_hyp_to_transfer = false; if (param_.transfer_keypoint_correspondences_ && !ohg_tmp.global_hypotheses_) continue; for (const ObjectHypothesis::Ptr &oh_tmp : ohg_tmp.ohs_) { if (!param_.transfer_only_verified_hypotheses_ || oh_tmp->is_verified_) { // check if this hypotheses is not already transferred by any other view if (std::find(hypotheses_ids.begin(), hypotheses_ids.end(), oh_tmp->unique_id_) == hypotheses_ids.end()) { do_hyp_to_transfer = true; break; } } } if (do_hyp_to_transfer || !param_.transfer_only_verified_hypotheses_) { ObjectHypothesesGroup ohg; ohg.global_hypotheses_ = ohg_tmp.global_hypotheses_; for (const ObjectHypothesis::Ptr &oh_tmp : ohg_tmp.ohs_) { if (param_.transfer_only_verified_hypotheses_ && !oh_tmp->is_verified_) continue; if (std::find(hypotheses_ids.begin(), hypotheses_ids.end(), oh_tmp->unique_id_) != hypotheses_ids.end()) continue; hypotheses_ids.insert(oh_tmp->unique_id_); // create a copy (since we want to reset verification status and update transform but keep the status for old // view) ObjectHypothesis::Ptr oh_copy(new ObjectHypothesis(*oh_tmp)); oh_copy->is_verified_ = false; oh_copy->transform_ = v.camera_pose_.inverse() * v_old.camera_pose_ * oh_copy->pose_refinement_ * oh_copy->transform_; // oh_copy->transform_ = v_old.camera_pose_ * oh_copy->transform_; ///< ATTENTION: This // depends on the input cloud (i.e. in this case the input cloud is in the global reference // frame) ohg.ohs_.push_back(oh_copy); } obj_hypotheses_.push_back(ohg); } } } if (param_.transfer_keypoint_correspondences_) { // get local keypoints and feature matches typename MultiRecognitionPipeline<PointT>::Ptr mp_recognizer = std::dynamic_pointer_cast<MultiRecognitionPipeline<PointT>>(recognition_pipeline_); CHECK(mp_recognizer); std::vector<typename RecognitionPipeline<PointT>::Ptr> sv_rec_pipelines = mp_recognizer->getRecognitionPipelines(); for (const typename RecognitionPipeline<PointT>::Ptr &rec_pipeline : sv_rec_pipelines) { typename LocalRecognitionPipeline<PointT>::Ptr local_rec_pipeline = std::dynamic_pointer_cast<LocalRecognitionPipeline<PointT>>(rec_pipeline); if (local_rec_pipeline) { v.local_obj_hypotheses_ = local_rec_pipeline->getKeypointCorrespondences(); v.model_keypoints_ = local_rec_pipeline->getLocalObjectModelDatabase(); pcl::PointCloud<pcl::PointXYZ>::Ptr scene_cloud_xyz(new pcl::PointCloud<pcl::PointXYZ>); pcl::copyPointCloud(*scene_, *scene_cloud_xyz); v.scene_cloud_xyz_ = scene_cloud_xyz; v.scene_cloud_normals_.reset(new pcl::PointCloud<pcl::Normal>(*scene_normals_)); } } local_obj_hypotheses_ = v.local_obj_hypotheses_; model_keypoints_ = v.model_keypoints_; scene_cloud_xyz_merged_.reset(new pcl::PointCloud<pcl::PointXYZ>(*v.scene_cloud_xyz_)); scene_cloud_normals_merged_.reset(new pcl::PointCloud<pcl::Normal>(*v.scene_cloud_normals_)); // now add the old hypotheses for (int v_id = views_.size() - 1; v_id >= std::max<int>(0, views_.size() - param_.max_views_ + 1); v_id--) { const View &v_old = views_[v_id]; { pcl::PointCloud<pcl::PointXYZ> scene_cloud_xyz_aligned; pcl::PointCloud<pcl::Normal> scene_normals_aligned; const Eigen::Matrix4f tf2current = v.camera_pose_.inverse() * v_old.camera_pose_; pcl::transformPointCloud(*v_old.scene_cloud_xyz_, scene_cloud_xyz_aligned, tf2current); v4r::transformNormals(*v_old.scene_cloud_normals_, scene_normals_aligned, tf2current); size_t offset = scene_cloud_xyz_merged_->points.size(); VLOG(2) << "offset: " << offset; *scene_cloud_xyz_merged_ += scene_cloud_xyz_aligned; *scene_cloud_normals_merged_ += scene_normals_aligned; VLOG(2) << "scene_cloud_xyz_merged_: " << scene_cloud_xyz_merged_->points.size() << "scene_cloud_normals_merged_: " << scene_cloud_normals_merged_->points.size(); for (const auto &oh : v_old.local_obj_hypotheses_) // iterate through all models { const std::string &model_id = oh.first; const LocalObjectHypothesis<PointT> &loh = oh.second; pcl::PointCloud<pcl::PointXYZ>::Ptr model_keypoints = model_keypoints_[model_id]->keypoints_; pcl::PointCloud<pcl::Normal>::Ptr model_kp_normals = model_keypoints_[model_id]->kp_normals_; pcl::Correspondences new_corrs = *loh.model_scene_corresp_; size_t initial_corrs = new_corrs.size(); for (pcl::Correspondence &c : new_corrs) // add appropriate offset to correspondence index of the model keypoints { // CHECK( c.index_match < (int) scene_cloud_xyz_aligned.points.size() && // c.index_match >= 0 ) << "c.index_match: " << c.index_match << ", // scene_cloud_xyz_merged_->points.size(): " << // scene_cloud_xyz_merged_->points.size(); // CHECK( c.index_match < (int) scene_normals_aligned.points.size() && c.index_match // >= 0 ); // CHECK( c.index_query < (int) model_keypoints->points.size() && c.index_query >= 0 // ); // CHECK( c.index_query < (int) model_kp_normals->points.size() && c.index_query >= 0 // ); c.index_match += offset; // c.index_query += model_keypoints_[ model_id ]->keypoints_->points.size(); } // for (const pcl::Correspondence &c : new_corrs) // add appropriate offset to // correspondence index of the model keypoints // { // CHECK( c.index_match < (int) scene_cloud_xyz_merged_->points.size() && c.index_match // >= 0 ) << "c.index_match: " << c.index_match << ", // scene_cloud_xyz_merged_->points.size(): " << scene_cloud_xyz_merged_->points.size(); // CHECK( c.index_match < (int) scene_cloud_normals_merged_->points.size() && // c.index_match >= 0 ); // CHECK( c.index_query < (int) model_keypoints->points.size() && c.index_query >= 0 ); // CHECK( c.index_query < (int) model_kp_normals->points.size() && c.index_query >= 0 // ); // } const auto existing_kp_it = v_old.model_keypoints_.find(model_id); CHECK(existing_kp_it != v_old.model_keypoints_.end()); // const typename LocalObjectModel::ConstPtr old_model_kps = existing_kp_it->second; // *model_keypoints += *old_model_kps->keypoints_; // *model_kp_normals += *old_model_kps->kp_normals_; auto it_mp_oh = local_obj_hypotheses_.find(model_id); if (it_mp_oh == local_obj_hypotheses_.end()) // no feature correspondences exist yet local_obj_hypotheses_.insert(oh); else { pcl::Correspondences &old_corrs = *it_mp_oh->second.model_scene_corresp_; size_t kept = 0; // check for redundancy for (size_t new_corr_id = 0; new_corr_id < new_corrs.size(); new_corr_id++) { const pcl::Correspondence &new_c = new_corrs[new_corr_id]; const Eigen::Vector3f &new_scene_xyz = scene_cloud_xyz_merged_->points[new_c.index_match].getVector3fMap(); const Eigen::Vector3f &new_scene_normal = scene_cloud_normals_merged_->points[new_c.index_match].getNormalVector3fMap(); const Eigen::Vector3f &new_model_xyz = model_keypoints->points[new_c.index_query].getVector3fMap(); const Eigen::Vector3f &new_model_normal = model_kp_normals->points[new_c.index_query].getNormalVector3fMap(); size_t is_redundant = false; for (size_t old_corr_id = 0; old_corr_id < old_corrs.size(); old_corr_id++) { pcl::Correspondence &old_c = old_corrs[old_corr_id]; const Eigen::Vector3f &old_scene_xyz = scene_cloud_xyz_merged_->points[old_c.index_match].getVector3fMap(); const Eigen::Vector3f &old_scene_normal = scene_cloud_normals_merged_->points[old_c.index_match].getNormalVector3fMap(); const Eigen::Vector3f &old_model_xyz = model_keypoints->points[old_c.index_query].getVector3fMap(); const Eigen::Vector3f &old_model_normal = model_kp_normals->points[old_c.index_query].getNormalVector3fMap(); if ((old_scene_xyz - new_scene_xyz).norm() < param_.min_dist_ && (old_model_xyz - new_model_xyz).norm() < param_.min_dist_ && old_scene_normal.dot(new_scene_normal) > param_.max_dotp_ && old_model_normal.dot(new_model_normal) > param_.max_dotp_) { is_redundant = true; // take the correspondence with the smaller distance if (new_c.distance < old_c.distance) old_c = new_c; break; } } if (!is_redundant) new_corrs[kept++] = new_c; } LOG(INFO) << "Kept " << kept << " out of " << initial_corrs << " correspondences."; new_corrs.resize(kept); old_corrs.insert(old_corrs.end(), new_corrs.begin(), new_corrs.end()); } } } } if (param_.visualize_) visualize(); correspondenceGrouping(model_ids_to_search); } v.obj_hypotheses_ = obj_hypotheses_; views_.push_back(v); } template <typename PointT> void MultiviewRecognizer<PointT>::visualize() { size_t counter = 0; typename std::map<std::string, LocalObjectHypothesis<PointT>>::const_iterator it; for (it = local_obj_hypotheses_.begin(); it != local_obj_hypotheses_.end(); ++it) { pcl::visualization::PCLVisualizer::Ptr vis(new pcl::visualization::PCLVisualizer); int vp1, vp2, vp3; vis->createViewPort(0, 0, 0.0, 1, vp1); vis->createViewPort(0.0, 0, 0.0, 1, vp2); vis->createViewPort(0.0, 0, 1, 1, vp3); // static bool co_init = false; if (counter++ > 1000) // only show first three break; const std::string &model_id = it->first; const LocalObjectHypothesis<PointT> &loh = it->second; pcl::PointCloud<pcl::PointXYZ>::Ptr model_keypoints = model_keypoints_[model_id]->keypoints_; pcl::PointCloud<pcl::Normal>::Ptr model_kp_normals = model_keypoints_[model_id]->kp_normals_; bool found; typename Model<PointT>::ConstPtr model = m_db_->getModelById("", model_id, found); typename pcl::PointCloud<PointT>::ConstPtr model_cloud = model->getAssembled(3); vis->removeAllPointClouds(vp1); vis->removeAllPointClouds(vp2); vis->removeAllPointClouds(vp3); vis->removeAllShapes(); vis->removeAllShapes(vp1); vis->removeAllShapes(vp2); vis->removeAllShapes(vp3); vis->setBackgroundColor(1., 1., 1.); vis->addPointCloud(model_cloud, "model_cloud1", vp1); LOG(INFO) << "Visualizing keypoints for " << model_id; pcl::PointCloud<pcl::PointXYZ>::Ptr scene_cloud_xyz_merged_vis( new pcl::PointCloud<pcl::PointXYZ>(*scene_cloud_xyz_merged_)); scene_cloud_xyz_merged_vis->sensor_origin_ = Eigen::Vector4f::Zero(); scene_cloud_xyz_merged_vis->sensor_orientation_ = Eigen::Quaternionf::Identity(); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> black(scene_cloud_xyz_merged_vis, 0, 0, 0); // vis->addPointCloud(scene_cloud_xyz_merged_vis, black, "scene", vp2); typename pcl::PointCloud<pcl::PointXYZRGB>::Ptr model_kps_colored(new pcl::PointCloud<pcl::PointXYZRGB>); model_kps_colored->points.resize(loh.model_scene_corresp_->size()); typename pcl::PointCloud<pcl::PointXYZRGB>::Ptr scene_kps_colored(new pcl::PointCloud<pcl::PointXYZRGB>); scene_kps_colored->points.resize(loh.model_scene_corresp_->size()); typename pcl::PointCloud<pcl::Normal>::Ptr model_kps_normals(new pcl::PointCloud<pcl::Normal>); model_kps_normals->points.resize(loh.model_scene_corresp_->size()); typename pcl::PointCloud<pcl::Normal>::Ptr scene_kps_normals(new pcl::PointCloud<pcl::Normal>); scene_kps_normals->points.resize(loh.model_scene_corresp_->size()); for (size_t c_id = 0; c_id < loh.model_scene_corresp_->size(); c_id++) { const pcl::Correspondence &c = loh.model_scene_corresp_->at(c_id); pcl::PointXYZRGB &m = model_kps_colored->points[c_id]; pcl::PointXYZRGB &s = scene_kps_colored->points[c_id]; float r = 255; // rand() % 255; float g = 0; // rand() % 255; float b = 0; // rand() % 255; m.r = r; m.g = g; m.b = b; s.r = r; s.g = g; s.b = b; m.getVector3fMap() = model_keypoints_[model_id]->keypoints_->points.at(c.index_query).getVector3fMap(); s.getVector3fMap() = scene_cloud_xyz_merged_->points.at(c.index_match).getVector3fMap(); pcl::Normal &mn = model_kps_normals->points[c_id]; pcl::Normal &sn = scene_kps_normals->points[c_id]; mn.getNormalVector3fMap() = model_keypoints_[model_id]->kp_normals_->points.at(c.index_query).getNormalVector3fMap(); sn.getNormalVector3fMap() = scene_cloud_normals_merged_->points.at(c.index_match).getNormalVector3fMap(); } if (loh.model_scene_corresp_->size() < 3) continue; // CHECK CORRESPONDENCE GROUPING ========== typename pcl::PointCloud<pcl::PointXYZRGB>::Ptr clustered_model_kps(new pcl::PointCloud<pcl::PointXYZRGB>); typename pcl::PointCloud<pcl::PointXYZRGB>::Ptr clustered_scene_kps(new pcl::PointCloud<pcl::PointXYZRGB>); std::vector<pcl::Correspondences> corresp_clusters; { std::sort(loh.model_scene_corresp_->begin(), loh.model_scene_corresp_->end(), LocalObjectHypothesis<PointT>::gcGraphCorrespSorter); cg_algorithm_->setSceneCloud(scene_cloud_xyz_merged_); cg_algorithm_->setInputCloud(model_keypoints); // Graph-based correspondence grouping requires normals but interface does not exist in base class - so need to // try pointer casting typename GraphGeometricConsistencyGrouping<pcl::PointXYZ, pcl::PointXYZ>::Ptr gcg_algorithm = std::dynamic_pointer_cast<GraphGeometricConsistencyGrouping<pcl::PointXYZ, pcl::PointXYZ>>(cg_algorithm_); if (gcg_algorithm) gcg_algorithm->setInputAndSceneNormals(model_kp_normals, scene_cloud_normals_merged_); cg_algorithm_->setModelSceneCorrespondences(loh.model_scene_corresp_); cg_algorithm_->cluster(corresp_clusters); for (const pcl::Correspondences &cs : corresp_clusters) { float r = rand() % 255; float g = rand() % 255; float b = rand() % 255; for (const pcl::Correspondence &c : cs) { pcl::PointXYZRGB m; m.getVector3fMap() = model_keypoints->points[c.index_query].getVector3fMap(); pcl::PointXYZRGB s; s.getVector3fMap() = scene_cloud_xyz_merged_->points[c.index_match].getVector3fMap(); m.r = r; m.g = g; m.b = b; s.r = r; s.g = g; s.b = b; clustered_model_kps->points.push_back(m); clustered_scene_kps->points.push_back(s); } } } // Eigen::Vector4f model_centroid; // pcl::compute3DCentroid(*model_kps_colored, model_centroid); // for( pcl::PointXYZRGB &m : model_kps_colored->points) // m.getVector4fMap() -= model_centroid; // for( pcl::PointXYZRGB &m : clustered_model_kps->points) // m.getVector4fMap() -= model_centroid; Eigen::Vector4f scene_centroid; pcl::compute3DCentroid(*scene_, scene_centroid); for (pcl::PointXYZRGB &s : clustered_scene_kps->points) s.getVector4fMap() -= scene_centroid; for (pcl::PointXYZRGB &s : scene_kps_colored->points) s.getVector4fMap() -= scene_centroid; LOG(INFO) << "visualizing " << model_kps_colored->points.size() << " and " << scene_kps_colored->points.size() << " for " << model_id; vis->addPointCloud(model_kps_colored, "model_kps", vp1); vis->addPointCloud(scene_kps_colored, "scene_kps", vp2); vis->addPointCloudNormals<PointT, pcl::Normal>(model_kps_colored, model_kps_normals, 1, 0.02f, "model_kp_normals", vp1); vis->addPointCloudNormals<PointT, pcl::Normal>(scene_kps_colored, scene_kps_normals, 1, 0.02f, "scene_kp_normals", vp2); vis->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 15, "model_kps"); vis->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 15, "scene_kps"); vis->addPointCloud(clustered_model_kps, "model_kps_clustered", vp1); vis->addPointCloud(clustered_scene_kps, "scene_kps_clustered", vp2); vis->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 15, "model_kps_clustered"); vis->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 15, "scene_kps_clustered"); typename pcl::PointCloud<PointT>::Ptr scene_vis(new pcl::PointCloud<PointT>(*scene_)); scene_vis->sensor_origin_ = Eigen::Vector4f::Zero(); scene_vis->sensor_orientation_ = Eigen::Quaternionf::Identity(); vis->addPointCloud(scene_vis, "scene_current_view", vp2); vis->addPointCloud(scene_vis, "scene_current_view3", vp3); Eigen::Matrix4f tf = Eigen::Matrix4f::Identity(); if (!corresp_clusters.empty()) { typename pcl::registration::TransformationEstimationSVD<pcl::PointXYZ, pcl::PointXYZ> t_est; t_est.estimateRigidTransformation(*model_keypoints, *scene_cloud_xyz_merged_, corresp_clusters[0], tf); } tf(0, 3) -= 0.3f; tf(1, 3) -= 0.3f; tf(2, 3) -= 0.3f; typename pcl::PointCloud<PointT>::Ptr model_cloud_aligned(new pcl::PointCloud<PointT>); pcl::transformPointCloud(*model_cloud, *model_cloud_aligned, tf); vis->addPointCloud(model_cloud_aligned, "aligned_cloud", vp3); size_t unique_id = 0; pcl::PointCloud<pcl::PointXYZRGB>::Ptr pts(new pcl::PointCloud<pcl::PointXYZRGB>); for (const pcl::Correspondence &c : *(loh.model_scene_corresp_)) { pcl::PointXYZ m = model_keypoints->points[c.index_query]; m.getVector4fMap() = tf * m.getVector4fMap(); pcl::PointXYZ s = scene_cloud_xyz_merged_->points[c.index_match]; pcl::PointXYZRGB p1, p2; p1.getVector3fMap() = s.getVector3fMap(); p2.getVector3fMap() = m.getVector3fMap(); p1.r = p2.r = 255.; p1.g = p2.g = 0.; p1.b = p2.b = 0.; pts->points.push_back(p1); pts->points.push_back(p2); std::stringstream unique_ss; unique_ss << "Line_" << unique_id++; vis->addLine(m, s, 1., 0., 0., unique_ss.str(), vp3); vis->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 3, unique_ss.str()); } unique_id = 0; for (const pcl::Correspondences &cs : corresp_clusters) { for (const pcl::Correspondence &c : cs) { pcl::PointXYZ m = model_keypoints->points[c.index_query]; m.getVector4fMap() = tf * m.getVector4fMap(); pcl::PointXYZ s = scene_cloud_xyz_merged_->points[c.index_match]; pcl::PointXYZRGB p1, p2; p1.getVector3fMap() = s.getVector3fMap(); p2.getVector3fMap() = m.getVector3fMap(); p1.r = p2.r = 0.; p1.g = p2.g = 0.; p1.b = p2.b = 255.; pts->points.push_back(p1); pts->points.push_back(p2); std::stringstream unique_ss; unique_ss << "Line_gc_" << unique_id++; vis->addLine(m, s, 0., 0., 1., unique_ss.str(), vp3); vis->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 3, unique_ss.str()); } } vis->addPointCloud(pts, "colored_pts", vp3); vis->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "colored_pts"); Eigen::Matrix3f rot_tmp = tf.block<3, 3>(0, 0); Eigen::Vector3f trans_tmp = tf.block<3, 1>(0, 3); Eigen::Affine3f affine_trans; affine_trans.fromPositionOrientationScale(trans_tmp, rot_tmp, Eigen::Vector3f::Ones()); // if(co_init) // { // bool found = vis->updateCoordinateSystemPose("co", affine_trans); // std::cout << "found coordinate system: " << found << std::endl; // } // else // { // co_init = true; // vis->addCoordinateSystem(0.2f, affine_trans, "co", vp3); // } // vis->spin(); } } template <typename PointT> void MultiviewRecognizer<PointT>::correspondenceGrouping(const std::vector<std::string> &model_ids_to_search) { pcl::StopWatch t; //#pragma omp parallel for schedule(dynamic) typename std::map<std::string, LocalObjectHypothesis<PointT>>::const_iterator it; for (it = local_obj_hypotheses_.begin(); it != local_obj_hypotheses_.end(); ++it) { const std::string &model_id = it->first; if (!model_ids_to_search.empty() && std::find(model_ids_to_search.begin(), model_ids_to_search.end(), model_id) == model_ids_to_search.end()) { continue; } const LocalObjectHypothesis<PointT> &loh = it->second; std::stringstream desc; desc << "Correspondence grouping for " << model_id << " ( " << loh.model_scene_corresp_->size() << ")"; typename RecognitionPipeline<PointT>::StopWatch t(desc.str()); pcl::PointCloud<pcl::PointXYZ>::Ptr model_keypoints = model_keypoints_[model_id]->keypoints_; pcl::PointCloud<pcl::Normal>::Ptr model_kp_normals = model_keypoints_[model_id]->kp_normals_; if (loh.model_scene_corresp_->size() < 3) continue; std::sort(loh.model_scene_corresp_->begin(), loh.model_scene_corresp_->end(), LocalObjectHypothesis<PointT>::gcGraphCorrespSorter); std::vector<pcl::Correspondences> corresp_clusters; cg_algorithm_->setSceneCloud(scene_cloud_xyz_merged_); cg_algorithm_->setInputCloud(model_keypoints); // oh.visualize(*scene_, *scene_keypoints_); // Graph-based correspondence grouping requires normals but interface does not exist in base class - so need to try // pointer casting typename GraphGeometricConsistencyGrouping<pcl::PointXYZ, pcl::PointXYZ>::Ptr gcg_algorithm = std::dynamic_pointer_cast<GraphGeometricConsistencyGrouping<pcl::PointXYZ, pcl::PointXYZ>>(cg_algorithm_); if (gcg_algorithm) gcg_algorithm->setInputAndSceneNormals(model_kp_normals, scene_cloud_normals_merged_); // for ( const auto c : *(loh.model_scene_corresp_) ) // { // CHECK( c.index_match < (int) scene_cloud_xyz->points.size() && c.index_match >= 0 ); // CHECK( c.index_match < (int) scene_normals_->points.size() && c.index_match >= 0 ); // CHECK( c.index_query < (int) model_keypoints->points.size() && c.index_query >= 0 ); // CHECK( c.index_query < (int) model_kp_normals->points.size() && c.index_query >= 0 ); // } // we need to pass the keypoints_pointcloud and the specific object hypothesis cg_algorithm_->setModelSceneCorrespondences(loh.model_scene_corresp_); cg_algorithm_->cluster(corresp_clusters); std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> new_transforms(corresp_clusters.size()); typename pcl::registration::TransformationEstimationSVD<pcl::PointXYZ, pcl::PointXYZ> t_est; for (size_t cluster_id = 0; cluster_id < corresp_clusters.size(); cluster_id++) t_est.estimateRigidTransformation(*model_keypoints, *scene_cloud_xyz_merged_, corresp_clusters[cluster_id], new_transforms[cluster_id]); if (param_.merge_close_hypotheses_) { std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> merged_transforms( corresp_clusters.size()); std::vector<bool> cluster_has_been_taken(corresp_clusters.size(), false); const double angle_thresh_rad = param_.merge_close_hypotheses_angle_ * M_PI / 180.f; size_t kept = 0; for (size_t tf_id = 0; tf_id < new_transforms.size(); tf_id++) { if (cluster_has_been_taken[tf_id]) continue; cluster_has_been_taken[tf_id] = true; const Eigen::Vector3f centroid1 = new_transforms[tf_id].block<3, 1>(0, 3); const Eigen::Matrix3f rot1 = new_transforms[tf_id].block<3, 3>(0, 0); pcl::Correspondences merged_corrs = corresp_clusters[tf_id]; for (size_t j = tf_id + 1; j < new_transforms.size(); j++) { const Eigen::Vector3f centroid2 = new_transforms[j].block<3, 1>(0, 3); const Eigen::Matrix3f rot2 = new_transforms[j].block<3, 3>(0, 0); const Eigen::Matrix3f rot_diff = rot2 * rot1.transpose(); double rotx = std::abs(atan2(rot_diff(2, 1), rot_diff(2, 2))); double roty = std::abs(atan2(-rot_diff(2, 0), sqrt(rot_diff(2, 1) * rot_diff(2, 1) + rot_diff(2, 2) * rot_diff(2, 2)))); double rotz = std::abs(atan2(rot_diff(1, 0), rot_diff(0, 0))); double dist = (centroid1 - centroid2).norm(); if ((dist < param_.merge_close_hypotheses_dist_) && (rotx < angle_thresh_rad) && (roty < angle_thresh_rad) && (rotz < angle_thresh_rad)) { merged_corrs.insert(merged_corrs.end(), corresp_clusters[j].begin(), corresp_clusters[j].end()); cluster_has_been_taken[j] = true; } } t_est.estimateRigidTransformation(*model_keypoints, *scene_cloud_xyz_merged_, merged_corrs, merged_transforms[kept]); kept++; } merged_transforms.resize(kept); #pragma omp critical { for (size_t jj = 0; jj < merged_transforms.size(); jj++) { ObjectHypothesis::Ptr new_oh(new ObjectHypothesis); new_oh->model_id_ = loh.model_id_; new_oh->class_id_ = ""; new_oh->transform_ = merged_transforms[jj]; new_oh->confidence_ = corresp_clusters.size(); new_oh->corr_ = corresp_clusters[jj]; ObjectHypothesesGroup new_ohg; new_ohg.global_hypotheses_ = false; new_ohg.ohs_.push_back(new_oh); obj_hypotheses_.push_back(new_ohg); } LOG(INFO) << "Merged " << corresp_clusters.size() << " clusters into " << kept << " clusters. Total correspondences: " << loh.model_scene_corresp_->size() << " " << loh.model_id_; } } else { #pragma omp critical { for (size_t jj = 0; jj < new_transforms.size(); jj++) { ObjectHypothesis::Ptr new_oh(new ObjectHypothesis); new_oh->model_id_ = loh.model_id_; new_oh->class_id_ = ""; new_oh->transform_ = new_transforms[jj]; new_oh->confidence_ = corresp_clusters.size(); new_oh->corr_ = corresp_clusters[jj]; ObjectHypothesesGroup new_ohg; new_ohg.global_hypotheses_ = false; new_ohg.ohs_.push_back(new_oh); obj_hypotheses_.push_back(new_ohg); } } } } LOG(INFO) << "Correspondence Grouping took " << t.getTime(); } template <typename PointT> void MultiviewRecognizer<PointT>::doInit(const bf::path &trained_dir, bool retrain, const std::vector<std::string> &object_instances_to_load) { recognition_pipeline_->initialize(trained_dir, retrain, object_instances_to_load); if (param_.transfer_keypoint_correspondences_) // if correspondence grouping is done here, don't do it in // multi-pipeline { typename MultiRecognitionPipeline<PointT>::Ptr mp_recognizer = std::dynamic_pointer_cast<MultiRecognitionPipeline<PointT>>(recognition_pipeline_); CHECK(mp_recognizer); std::vector<typename RecognitionPipeline<PointT>::Ptr> sv_rec_pipelines = mp_recognizer->getRecognitionPipelines(); for (typename RecognitionPipeline<PointT>::Ptr &rec_pipeline : sv_rec_pipelines) { typename LocalRecognitionPipeline<PointT>::Ptr local_rec_pipeline = std::dynamic_pointer_cast<LocalRecognitionPipeline<PointT>>(rec_pipeline); if (local_rec_pipeline) local_rec_pipeline->disableHypothesesGeneration(); } } } void MultiviewRecognizerParameter::init(boost::program_options::options_description &desc, const std::string &section_name) { desc.add_options()( (section_name + ".transfer_only_verified_hypotheses").c_str(), po::value<bool>(&transfer_only_verified_hypotheses_)->default_value(transfer_only_verified_hypotheses_), "if true, transfers only verified hypotheses into multiview recognition"); desc.add_options()((section_name + ".max_views").c_str(), po::value<size_t>(&max_views_)->default_value(max_views_), "maximum number of views used for multi-view recognition (if more views are available, " "information from oldest views will be ignored)"); desc.add_options()( (section_name + ".transfer_keypoint_correspondences").c_str(), po::value<bool>(&transfer_keypoint_correspondences_)->default_value(transfer_keypoint_correspondences_), "if true, transfers keypoint correspondences instead of full hypotheses " "(requires correspondence grouping - see Faeulhammer et al, ICRA 2015)"); desc.add_options()((section_name + ".merge_close_hypotheses").c_str(), po::value<bool>(&merge_close_hypotheses_)->default_value(merge_close_hypotheses_), ""); desc.add_options()((section_name + ".merge_close_hypotheses_dist").c_str(), po::value<float>(&merge_close_hypotheses_dist_)->default_value(merge_close_hypotheses_dist_), "defines the maximum distance of the centroids in meter for clusters to be merged"); desc.add_options()((section_name + ".merge_close_hypotheses_angle").c_str(), po::value<float>(&merge_close_hypotheses_angle_)->default_value(merge_close_hypotheses_angle_), "defines the maximum angle in degrees for clusters to be merged"); desc.add_options()((section_name + ".min_dist").c_str(), po::value<float>(&min_dist_)->default_value(min_dist_), "minimum distance two points need to be apart to be counted as redundant"); desc.add_options()((section_name + ".max_dotp").c_str(), po::value<float>(&max_dotp_)->default_value(max_dotp_), "maximum dot-product between the surface normals of two oriented points to be counted redundant"); desc.add_options()((section_name + ".visualize").c_str(), po::value<bool>(&visualize_)->default_value(visualize_), "visualize keypoint correspondences"); } template class V4R_EXPORTS MultiviewRecognizer<pcl::PointXYZRGB>; } // namespace v4r
48.944363
120
0.650633
[ "object", "vector", "model", "transform" ]
6dcd82ddd821564a78d4f476861eef38ed4aadd1
14,174
cpp
C++
toonz/sources/toonz/mergecolumns.cpp
ken-taguma/opentoonz
01e8e736847773c34cd73a1cfb608ac0170d2135
[ "BSD-3-Clause" ]
1
2021-08-07T00:16:54.000Z
2021-08-07T00:16:54.000Z
toonz/sources/toonz/mergecolumns.cpp
LibrePhone/opentoonz
cb95a29db4c47ab1f36a6e85a039c4c9c901f88a
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonz/mergecolumns.cpp
LibrePhone/opentoonz
cb95a29db4c47ab1f36a6e85a039c4c9c901f88a
[ "BSD-3-Clause" ]
1
2021-08-07T00:16:58.000Z
2021-08-07T00:16:58.000Z
#include "tapp.h" #include "tpalette.h" #include "toonz/txsheet.h" #include "toonz/toonzscene.h" #include "toonz/levelset.h" #include "toonz/txshsimplelevel.h" #include "toonz/txshlevelcolumn.h" #include "toonz/txshcell.h" //#include "tw/action.h" #include "tropcm.h" #include "ttoonzimage.h" #include "matchline.h" #include "toonz/scenefx.h" #include "toonz/dpiscale.h" #include "toonz/txsheethandle.h" #include "toonz/palettecontroller.h" #include "toonz/tpalettehandle.h" #include "toonz/txshlevelhandle.h" #include "toonz/txshleveltypes.h" #include "toonz/tscenehandle.h" #include "toonz/tframehandle.h" #include "toonzqt/icongenerator.h" #include <map> #include <QRadioButton> #include <QPushButton> #include <QApplication> #include "tundo.h" #include "tools/toolutils.h" #include "timagecache.h" #include "tcolorstyles.h" #include "historytypes.h" using namespace DVGui; namespace { class MatchlinePair { public: const TXshCell *m_cell; TAffine m_imgAff; const TXshCell *m_mcell; TAffine m_matchAff; MatchlinePair(const TXshCell &cell, const TAffine &imgAff, const TXshCell &mcell, const TAffine &matchAff) : m_cell(&cell) , m_imgAff(imgAff) , m_mcell(&mcell) , m_matchAff(matchAff){}; }; //----------------------------------------------------------------------------------- void mergeRasterColumns(const std::vector<MatchlinePair> &matchingLevels) { if (matchingLevels.empty()) return; int i = 0; for (i = 0; i < (int)matchingLevels.size(); i++) { TRasterImageP img = (TRasterImageP)matchingLevels[i].m_cell->getImage(true); TRasterImageP match = (TRasterImageP)matchingLevels[i].m_mcell->getImage(false); if (!img || !match) throw TRopException("Can merge columns only on raster images!"); // img->lock(); TRaster32P ras = img->getRaster(); // img->getCMapped(false); TRaster32P matchRas = match->getRaster(); // match->getCMapped(true); if (!ras || !matchRas) { DVGui::warning(QObject::tr( "The merge command is not available for greytones images.")); return; } TAffine aff = matchingLevels[i].m_imgAff.inv() * matchingLevels[i].m_matchAff; int mlx = matchRas->getLx(); int mly = matchRas->getLy(); int rlx = ras->getLx(); int rly = ras->getLy(); TRectD in = convert(matchRas->getBounds()) - matchRas->getCenterD(); TRectD out = aff * in; TPoint offs((rlx - mlx) / 2 + tround(out.getP00().x - in.getP00().x), (rly - mly) / 2 + tround(out.getP00().y - in.getP00().y)); int lxout = tround(out.getLx()) + 1 + ((offs.x < 0) ? offs.x : 0); int lyout = tround(out.getLy()) + 1 + ((offs.y < 0) ? offs.y : 0); if (lxout <= 0 || lyout <= 0 || offs.x >= rlx || offs.y >= rly) { // tmsg_error("no intersections between matchline and level"); continue; } aff = aff.place((double)(in.getLx() / 2.0), (double)(in.getLy() / 2.0), (out.getLx()) / 2.0 + ((offs.x < 0) ? offs.x : 0), (out.getLy()) / 2.0 + ((offs.y < 0) ? offs.y : 0)); if (offs.x < 0) offs.x = 0; if (offs.y < 0) offs.y = 0; if (lxout + offs.x > rlx || lyout + offs.y > rly) { // PRINTF("TAGLIO L'IMMAGINE\n"); lxout = (lxout + offs.x > rlx) ? (rlx - offs.x) : lxout; lyout = (lyout + offs.y > rly) ? (rly - offs.y) : lyout; } if (!aff.isIdentity(1e-4)) { TRaster32P aux(lxout, lyout); TRop::resample(aux, matchRas, aff); matchRas = aux; } ras->lock(); matchRas->lock(); TRect raux = matchRas->getBounds() + offs; TRasterP r = ras->extract(raux); TRop::over(r, matchRas); ras->unlock(); matchRas->unlock(); img->setSavebox(img->getSavebox() + (matchRas->getBounds() + offs)); // img->setSavebox(rout); // img->unlock(); } } /*------------------------------------------------------------------------*/ /// verifica se tutta l'immagine e' gia' contenuta in un gruppo. bool needTobeGrouped(const TVectorImageP &vimg) { if (vimg->getStrokeCount() <= 1) return false; if (!vimg->isStrokeGrouped(0)) return true; for (int i = 1; i < vimg->getStrokeCount(); i++) { if (vimg->areDifferentGroup(0, false, i, false) == 0) return true; } return false; } //--------------------------------------------------------------------------------------- void mergeVectorColumns(const std::vector<MatchlinePair> &matchingLevels) { if (matchingLevels.empty()) return; int i = 0; for (i = 0; i < (int)matchingLevels.size(); i++) { TVectorImageP vimg = (TVectorImageP)matchingLevels[i].m_cell->getImage(true); TVectorImageP vmatch = (TVectorImageP)matchingLevels[i].m_mcell->getImage(false); if (!vimg || !vmatch) throw TRopException("Cannot merge columns of different image types!"); // img->lock(); if (needTobeGrouped(vimg)) vimg->group(0, vimg->getStrokeCount()); bool ungroup = false; if (needTobeGrouped(vmatch)) { ungroup = true; vmatch->group(0, vmatch->getStrokeCount()); } TAffine aff = matchingLevels[i].m_imgAff.inv() * matchingLevels[i].m_matchAff; vimg->mergeImage(vmatch, aff); if (ungroup) vmatch->ungroup(0); } } /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ } // namespace //----------------------------------------------------------------------------- class MergeColumnsUndo final : public TUndo { TXshLevelP m_xl; int m_matchlineSessionId; std::map<TFrameId, QString> m_images; TXshSimpleLevel *m_level; int m_column, m_mColumn; TPalette *m_palette; public: MergeColumnsUndo(TXshLevelP xl, int matchlineSessionId, int column, TXshSimpleLevel *level, const std::map<TFrameId, QString> &images, int mColumn, TPalette *palette) : TUndo() , m_xl(xl) , m_matchlineSessionId(matchlineSessionId) , m_level(level) , m_column(column) , m_mColumn(mColumn) , m_images(images) , m_palette(palette->clone()) {} void undo() const override { QApplication::setOverrideCursor(Qt::WaitCursor); std::map<TFrameId, QString>::const_iterator it = m_images.begin(); std::vector<TFrameId> fids; m_level->setPalette(m_palette->clone()); for (; it != m_images.end(); ++it) //, ++mit) { QString id = "MergeColumnsUndo" + QString::number(m_matchlineSessionId) + "-" + QString::number(it->first.getNumber()); TImageP img = TImageCache::instance()->get(id, false)->cloneImage(); m_level->setFrame(it->first, img); fids.push_back(it->first); } if (m_xl) invalidateIcons(m_xl.getPointer(), fids); m_level->setDirtyFlag(true); TApp::instance()->getCurrentXsheet()->notifyXsheetChanged(); QApplication::restoreOverrideCursor(); } void redo() const override { QApplication::setOverrideCursor(Qt::WaitCursor); mergeColumns(m_column, m_mColumn, true); QApplication::restoreOverrideCursor(); } int getSize() const override { return sizeof(*this); } ~MergeColumnsUndo() { std::map<TFrameId, QString>::const_iterator it = m_images.begin(); for (; it != m_images.end(); ++it) //, ++mit) { QString id = "MergeColumnsUndo" + QString::number(m_matchlineSessionId) + "-" + QString::number(it->first.getNumber()); TImageCache::instance()->remove(id); } } QString getHistoryString() override { return QObject::tr("Merge Raster Levels"); } int getHistoryType() override { return HistoryType::FilmStrip; } }; //----------------------------------------------------------------------------- void mergeColumns(const std::set<int> &columns) { QApplication::setOverrideCursor(Qt::WaitCursor); std::set<int>::const_iterator it = columns.begin(); int dstColumn = *it; ++it; TUndoManager::manager()->beginBlock(); for (; it != columns.end(); ++it) mergeColumns(dstColumn, *it, false); TUndoManager::manager()->endBlock(); QApplication::restoreOverrideCursor(); } //----------------------------------------------------------------------------- static int MergeColumnsSessionId = 0; void mergeColumns(int column, int mColumn, bool isRedo) { if (!isRedo) MergeColumnsSessionId++; TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet(); int start, end; xsh->getCellRange(column, start, end); if (start > end) return; std::vector<TXshCell> cell(end - start + 1); std::vector<TXshCell> mCell(end - start + 1); xsh->getCells(start, column, cell.size(), &(cell[0])); xsh->getCells(start, mColumn, cell.size(), &(mCell[0])); TXshColumn *col = xsh->getColumn(column); TXshColumn *mcol = xsh->getColumn(mColumn); std::vector<MatchlinePair> matchingLevels; std::set<TFrameId> alreadyDoneSet; TXshSimpleLevel *level = 0, *mLevel = 0; TXshLevelP xl; bool areRasters = false; std::map<TFrameId, QString> images; for (int i = 0; i < (int)cell.size(); i++) { if (cell[i].isEmpty() || mCell[i].isEmpty()) continue; if (!level) { level = cell[i].getSimpleLevel(); xl = cell[i].m_level; } else if (level != cell[i].getSimpleLevel()) { DVGui::warning( QObject::tr("It is not possible to perform a merging involving more " "than one level per column.")); return; } if (!mLevel) mLevel = mCell[i].getSimpleLevel(); else if (mLevel != mCell[i].getSimpleLevel()) { DVGui::warning( QObject::tr("It is not possible to perform a merging involving more " "than one level per column.")); return; } TImageP img = cell[i].getImage(true); TImageP match = mCell[i].getImage(false); TFrameId fid = cell[i].m_frameId; TFrameId mFid = mCell[i].m_frameId; if (!img || !match) continue; if (alreadyDoneSet.find(fid) == alreadyDoneSet.end()) { TRasterImageP timg = (TRasterImageP)img; TRasterImageP tmatch = (TRasterImageP)match; TVectorImageP vimg = (TVectorImageP)img; TVectorImageP vmatch = (TVectorImageP)match; if (timg) { if (!tmatch) { DVGui::warning(QObject::tr( "Only raster levels can be merged to a raster level.")); return; } areRasters = true; } else if (vimg) { if (!vmatch) { DVGui::warning(QObject::tr( "Only vector levels can be merged to a vector level.")); return; } } else { DVGui::warning( QObject::tr("It is possible to merge only Toonz vector levels or " "standard raster levels.")); return; } if (!isRedo) { QString id = "MergeColumnsUndo" + QString::number(MergeColumnsSessionId) + "-" + QString::number(fid.getNumber()); TImageCache::instance()->add( id, (timg) ? timg->cloneImage() : vimg->cloneImage()); images[fid] = id; } TAffine imgAff, matchAff; getColumnPlacement(imgAff, xsh, start + i, column, false); getColumnPlacement(matchAff, xsh, start + i, mColumn, false); TAffine dpiAff = getDpiAffine(level, fid); TAffine mdpiAff = getDpiAffine(mLevel, mFid); matchingLevels.push_back(MatchlinePair(cell[i], imgAff * dpiAff, mCell[i], matchAff * mdpiAff)); alreadyDoneSet.insert(fid); } } if (matchingLevels.empty()) { DVGui::warning( QObject::tr("It is possible to merge only Toonz vector levels or " "standard raster levels.")); return; } ToonzScene *sc = TApp::instance()->getCurrentScene()->getScene(); TXshSimpleLevel *simpleLevel = sc->getLevelSet()->getLevel(column)->getSimpleLevel(); if (!isRedo) TUndoManager::manager()->add( new MergeColumnsUndo(xl, MergeColumnsSessionId, column, level, images, mColumn, level->getPalette())); if (areRasters) { mergeRasterColumns(matchingLevels); for (int i = 0; i < (int)cell.size(); i++) // the saveboxes must be updated { if (cell[i].isEmpty() || mCell[i].isEmpty()) continue; if (!cell[i].getImage(false) || !mCell[i].getImage(false)) continue; ToolUtils::updateSaveBox(cell[i].getSimpleLevel(), cell[i].m_frameId); } } else mergeVectorColumns(matchingLevels); TXshLevel *sl = TApp::instance()->getCurrentScene()->getScene()->getLevelSet()->getLevel( column); std::vector<TFrameId> fidsss; sl->getFids(fidsss); invalidateIcons(sl, fidsss); sl->setDirtyFlag(true); level->setDirtyFlag(true); TApp::instance()->getCurrentXsheet()->notifyXsheetChanged(); } namespace { const TXshCell *findCell(int column, const TFrameId &fid) { TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet(); int i; for (i = 0; i < xsh->getColumn(column)->getMaxFrame(); i++) if (xsh->getCell(i, column).getFrameId() == fid) return &(xsh->getCell(i, column)); return 0; } bool contains(const std::vector<TFrameId> &v, const TFrameId &val) { int i; for (i = 0; i < (int)v.size(); i++) if (v[i] == val) return true; return false; } //----------------------------------------------------------------------------- QString indexes2string(const std::set<TFrameId> fids) { if (fids.empty()) return ""; QString str; std::set<TFrameId>::const_iterator it = fids.begin(); str = QString::number(it->getNumber()); while (it != fids.end()) { std::set<TFrameId>::const_iterator it1 = it; it1++; int lastVal = it->getNumber(); while (it1 != fids.end() && it1->getNumber() == lastVal + 1) { lastVal = it1->getNumber(); it1++; } if (lastVal != it->getNumber()) str += "-" + QString::number(lastVal); if (it1 == fids.end()) return str; str += ", " + QString::number(it1->getNumber()); it = it1; } return str; } } // namespace
30.416309
89
0.584027
[ "vector" ]
6dd015173c0ee7dbf43c326a70af829331360212
2,946
cpp
C++
delegate/src/test/GatherTest.cpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
856
2018-03-09T17:26:23.000Z
2022-03-24T21:31:33.000Z
delegate/src/test/GatherTest.cpp
Elm8116/armnn
e571cde8411803aec545b1070ed677e481f46f3f
[ "MIT" ]
623
2018-03-13T04:40:42.000Z
2022-03-31T09:45:17.000Z
delegate/src/test/GatherTest.cpp
Elm8116/armnn
e571cde8411803aec545b1070ed677e481f46f3f
[ "MIT" ]
284
2018-03-09T23:05:28.000Z
2022-03-29T14:42:28.000Z
// // Copyright © 2020 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include "GatherTestHelper.hpp" #include <armnn_delegate.hpp> #include <flatbuffers/flatbuffers.h> #include <tensorflow/lite/schema/schema_generated.h> #include <doctest/doctest.h> namespace armnnDelegate { // GATHER Operator void GatherUint8Test(std::vector<armnn::BackendId>& backends) { std::vector<int32_t> paramsShape{8}; std::vector<int32_t> indicesShape{3}; std::vector<int32_t> expectedOutputShape{3}; int32_t axis = 0; std::vector<uint8_t> paramsValues{1, 2, 3, 4, 5, 6, 7, 8}; std::vector<int32_t> indicesValues{7, 6, 5}; std::vector<uint8_t> expectedOutputValues{8, 7, 6}; GatherTest<uint8_t>(::tflite::TensorType_UINT8, backends, paramsShape, indicesShape, expectedOutputShape, axis, paramsValues, indicesValues, expectedOutputValues); } void GatherFp32Test(std::vector<armnn::BackendId>& backends) { std::vector<int32_t> paramsShape{8}; std::vector<int32_t> indicesShape{3}; std::vector<int32_t> expectedOutputShape{3}; int32_t axis = 0; std::vector<float> paramsValues{1.1f, 2.2f, 3.3f, 4.4f, 5.5f, 6.6f, 7.7f, 8.8f}; std::vector<int32_t> indicesValues{7, 6, 5}; std::vector<float> expectedOutputValues{8.8f, 7.7f, 6.6f}; GatherTest<float>(::tflite::TensorType_FLOAT32, backends, paramsShape, indicesShape, expectedOutputShape, axis, paramsValues, indicesValues, expectedOutputValues); } // GATHER Test Suite TEST_SUITE("GATHER_CpuRefTests") { TEST_CASE ("GATHER_Uint8_CpuRef_Test") { std::vector<armnn::BackendId> backends = {armnn::Compute::CpuRef}; GatherUint8Test(backends); } TEST_CASE ("GATHER_Fp32_CpuRef_Test") { std::vector<armnn::BackendId> backends = {armnn::Compute::CpuRef}; GatherFp32Test(backends); } } TEST_SUITE("GATHER_CpuAccTests") { TEST_CASE ("GATHER_Uint8_CpuAcc_Test") { std::vector<armnn::BackendId> backends = {armnn::Compute::CpuAcc}; GatherUint8Test(backends); } TEST_CASE ("GATHER_Fp32_CpuAcc_Test") { std::vector<armnn::BackendId> backends = {armnn::Compute::CpuAcc}; GatherFp32Test(backends); } } TEST_SUITE("GATHER_GpuAccTests") { TEST_CASE ("GATHER_Uint8_GpuAcc_Test") { std::vector<armnn::BackendId> backends = {armnn::Compute::GpuAcc}; GatherUint8Test(backends); } TEST_CASE ("GATHER_Fp32_GpuAcc_Test") { std::vector<armnn::BackendId> backends = {armnn::Compute::GpuAcc}; GatherFp32Test(backends); } } // End of GATHER Test Suite } // namespace armnnDelegate
25.179487
86
0.624236
[ "vector" ]
6dd41d9a29a84dd9dd234adba946686ea9295ea2
2,986
cpp
C++
src/dtw.cpp
vadimostanin2/sneeze-detector
2bac0d08cb4960b7dc16492b8c69ff1459dd9334
[ "MIT" ]
11
2015-04-18T23:42:44.000Z
2021-04-03T18:23:44.000Z
src/dtw.cpp
vadimostanin2/sneeze-detector
2bac0d08cb4960b7dc16492b8c69ff1459dd9334
[ "MIT" ]
null
null
null
src/dtw.cpp
vadimostanin2/sneeze-detector
2bac0d08cb4960b7dc16492b8c69ff1459dd9334
[ "MIT" ]
3
2017-06-02T17:07:08.000Z
2019-04-18T05:59:48.000Z
#include "dtw.h" #include <iostream> using namespace std; int DTW::min( int x, int y, int z ) { if( ( x <= y ) && ( x <= z ) ) return x; if( ( y <= x ) && ( y <= z ) ) return y; if( ( z <= x ) && ( z <= y ) ) return z; return 0; } double DTW::min( double x, double y, double z ) { if( ( x <= y ) && ( x <= z ) ) return x; if( ( y <= x ) && ( y <= z ) ) return y; if( ( z <= x ) && ( z <= y ) ) return z; return 0; } void calcDistance( std::vector< std::vector< float > > & table, const std::vector< float > &seq_1, const std::vector< float > &seq_2 ) { size_t len_1 = seq_1.size(); size_t len_2 = seq_2.size(); for( size_t i = 0; i< len_1; i++ ) { for( size_t j = 0; j < len_2; j++ ) { table[i][j] = fabs( seq_1.at(i) - seq_2.at(j) ); } } } void calcDistance( float ** table, float * seq_1, float * seq_2, unsigned int seq_1_size, unsigned int seq_2_size ) { for( size_t i = 0; i< seq_1_size; i++ ) { for( size_t j = 0; j < seq_2_size; j++ ) { table[i][j] = fabs( seq_1[i] - seq_2[j] ); } } } float DTW::run( float * v_1, float * v_2, unsigned int v_1_length, unsigned int v_2_length ) { // std::vector< std::vector< float > > table_distances( v_1_length, vector<float>( v_2_length, 0.0 ) ); float ** table_distances = new float*[v_1_length]; for( unsigned int i = 0; i < v_1_length ; i++ ) { table_distances[i] = new float[v_2_length]; } calcDistance( table_distances, v_1, v_2, v_1_length, v_2_length ); this->mGamma[0][0] = table_distances[0][0]; for( size_t i = 1; i < v_1_length; i++ ) { this->mGamma[i][0] = table_distances[i][0] + this->mGamma[i - 1][0]; } for( size_t i = 1; i < v_2_length; i++ ) { this->mGamma[0][i] = table_distances[0][i] + this->mGamma[0][i - 1]; } for( size_t i = 1; i < v_1_length; i++ ) { for( size_t j = 1; j < v_2_length; j++ ) { mGamma[i][j] = table_distances[i][j] + min( mGamma[i-1][j], mGamma[i][j-1], mGamma[i-1][j-1] ); } } for( unsigned int i = 0; i < v_1_length ; i++ ) { delete table_distances[i]; } delete table_distances; return mGamma[v_1_length - 1][v_2_length - 1]; } float DTW::run( vector<float> v_1, vector<float> v_2 ) { return run( &v_1[0], &v_2[0], v_1.size(), v_2.size() ); } double DTW::run( double** v, int vlength, double** w, int wlength, int dim ) { double cost = 0.0; for( int i = 1; i < wlength; i++ ) { this->mGamma_cont[0][i] = INF; } for( int i = 1; i < vlength; i++ ) { this->mGamma_cont[i][0] = INF; } this->mGamma_cont[0][0] = 0; for( int i = 1; i < vlength; i++ ) { for( int j = 1; j < wlength; j++ ) { cost = 0; for( int k = 0; k < dim; k++ ) { // cout << v[i][k] << " - " << w[j][k] << endl; cost += abs( v[i][k] - w[j][k] ) * abs( v[i][k] - w[j][k] ); } mGamma_cont[i][j] = cost + min( mGamma_cont[i-1][j], mGamma_cont[i][j-1], mGamma_cont[i-1][j-1] ); } } return mGamma_cont[vlength - 1][wlength - 1]; }
24.080645
134
0.539183
[ "vector" ]
6dd6fd262e35a192ba85eb3aa16660526d2ebca2
2,670
cc
C++
paddle/fluid/framework/details/ssa_graph_printer.cc
cjld/Paddle
ed9c19cc95cd4fd387037f1d1493e6a3eff776e7
[ "Apache-2.0" ]
1
2018-08-03T03:33:52.000Z
2018-08-03T03:33:52.000Z
paddle/fluid/framework/details/ssa_graph_printer.cc
cjld/Paddle
ed9c19cc95cd4fd387037f1d1493e6a3eff776e7
[ "Apache-2.0" ]
null
null
null
paddle/fluid/framework/details/ssa_graph_printer.cc
cjld/Paddle
ed9c19cc95cd4fd387037f1d1493e6a3eff776e7
[ "Apache-2.0" ]
1
2018-07-20T07:13:31.000Z
2018-07-20T07:13:31.000Z
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/details/ssa_graph_printer.h" #include <string> #include "paddle/fluid/framework/ir/graph.h" namespace paddle { namespace framework { namespace details { template <typename Callback> static inline void IterAllVar(const Graph &graph, Callback callback) { for (auto &each : graph.Get<GraphVars>("vars")) { for (auto &pair1 : each) { for (auto &pair2 : pair1.second) { callback(*pair2); } } } for (auto &var : graph.Get<GraphDepVars>("dep_vars")) { callback(*var); } } void GraphvizSSAGraphPrinter::Print(const Graph &graph, std::ostream &sout) const { size_t var_id = 0; std::unordered_map<const VarHandleBase *, size_t> vars; sout << "digraph G {\n"; IterAllVar(graph, [&](const VarHandleBase &var) { auto *var_ptr = &var; auto *var_handle_ptr = dynamic_cast<const VarHandle *>(var_ptr); auto *dummy_ptr = dynamic_cast<const DummyVarHandle *>(var_ptr); size_t cur_var_id = var_id++; vars[var_ptr] = cur_var_id; if (var_handle_ptr) { sout << "var_" << cur_var_id << " [label=\"" << var_handle_ptr->name_ << "\\n" << var_handle_ptr->place_ << "\\n" << var_handle_ptr->version_ << "\"]" << std::endl; } else if (dummy_ptr) { sout << "var_" << cur_var_id << " [label=\"dummy\"]" << std::endl; } }); size_t op_id = 0; for (auto &op : graph.Get<GraphOps>("ops")) { std::string op_name = "op_" + std::to_string(op_id++); sout << op_name << " [label=\"" << op->Name() << "\", shape=rect]" << std::endl; for (auto in : op->Inputs()) { std::string var_name = "var_" + std::to_string(vars[in]); sout << var_name << " -> " << op_name << std::endl; } for (auto out : op->Outputs()) { std::string var_name = "var_" + std::to_string(vars[out]); sout << op_name << " -> " << var_name << std::endl; } } sout << "}\n"; } } // namespace details } // namespace framework } // namespace paddle
31.785714
75
0.619476
[ "shape" ]
6dd9c9090e13cb40b05e4f4b0554bfe5ccdabf10
8,552
cpp
C++
database/TripleStore.cpp
gpl2021/triad
dfded62dfa0cc0329c99771142923fdf44a4902c
[ "Apache-2.0" ]
4
2018-07-09T07:53:14.000Z
2019-08-20T17:33:17.000Z
database/TripleStore.cpp
sairamgv/triad-rdf
fba91141362f347ae021ffe0d8da4921826393bd
[ "Apache-2.0" ]
2
2019-05-17T16:48:06.000Z
2021-07-06T09:27:57.000Z
database/TripleStore.cpp
gpl2021/triad
dfded62dfa0cc0329c99771142923fdf44a4902c
[ "Apache-2.0" ]
1
2019-05-29T07:58:02.000Z
2019-05-29T07:58:02.000Z
/* Copyright 2014 Sairam Gurajada Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "TripleStore.hpp" TripleStore::TripleStore() { // TODO Auto-generated constructor stub numTriples = 0; for(int i = 0; i < 6; i++) dataIndex[i] = new FastMap(); for(int i = 0; i < 3; i++) summaryIndex[i] = new FastMap(); plist.clear(); } TripleStore::~TripleStore() { // TODO Auto-generated destructor stub } LoggerPtr TripleStore::logger(Logger::getLogger("TriAD")); bool TripleStore::addTriple(Utilities::value32_t subject, Utilities::value32_t predicate, Utilities::value32_t object, unsigned cSize){ unsigned spart = (subject >> pbits), opart = (object >> pbits); unsigned sLoc = spart % cSize, oLoc = opart % cSize; tmpTripleVector[sLoc].push_back(0); tmpTripleVector[sLoc].push_back(subject); tmpTripleVector[sLoc].push_back(predicate); tmpTripleVector[sLoc].push_back(object); tmpTripleVector[oLoc].push_back(4); tmpTripleVector[oLoc].push_back(object); tmpTripleVector[oLoc].push_back(predicate); tmpTripleVector[oLoc].push_back(subject); properties.insert(predicate); numTriples++; return true; } void TripleStore::joinCardinality(vector<unsigned> & jCard, bool summary){ FastMap *idx2, *idx3; if(summary){ idx2 = summaryIndex[0]; //ps idx3 = summaryIndex[1]; //po }else{ idx2 = dataIndex[2]; //ps idx3 = dataIndex[3]; //po } unsigned path_card = 0, star1_card = 0, star2_card = 0; for(set<Utilities::value32_t>::iterator p1 = properties.begin(); p1 != properties.end(); p1++) for(set<Utilities::value32_t>::iterator p2 = properties.begin(); p2 != properties.end(); p2++){ std::pair<FastMap::iterator, FastMap::iterator> it_pair_1_so = idx2->find(*p1); std::pair<FastMap::iterator, FastMap::iterator> it_pair_1_os = idx3->find(*p1); std::pair<FastMap::iterator, FastMap::iterator> it_pair_2_so = idx2->find(*p2); std::pair<FastMap::iterator, FastMap::iterator> it_pair_2_os = idx3->find(*p2); unsigned path_card = 0, star1_card = 0, star2_card = 0; FastMap::iterator t1_so = it_pair_1_so.first; FastMap::iterator t1_os = it_pair_1_os.first; FastMap::iterator t2_so = it_pair_2_so.first; FastMap::iterator t2_os = it_pair_2_os.first; // Path cardinality while(it_pair_1_os.first != it_pair_1_os.second && it_pair_2_so.first != it_pair_2_so.second){ if(it_pair_1_os.first.value(2) < it_pair_2_so.first.value(2)) it_pair_1_os.first++; else if(it_pair_1_os.first.value(2) > it_pair_2_so.first.value(2)) it_pair_2_so.first++; else{ unsigned joinval = it_pair_1_os.first.value(2); unsigned c1 = 0, c2 = 0; while(it_pair_1_os.first != it_pair_1_os.second && it_pair_1_os.first.value(2) == joinval) {c1++;it_pair_1_os.first++;} while(it_pair_2_so.first != it_pair_2_so.second && it_pair_2_so.first.value(2) == joinval) {c2++;it_pair_2_so.first++;} path_card += (c1*c2); } } // Star1 cardinality it_pair_1_so.first = t1_so; it_pair_2_so.first = t2_so; while(it_pair_1_so.first != it_pair_1_so.second && it_pair_2_so.first != it_pair_2_so.second){ if(it_pair_1_so.first.value(2) < it_pair_2_so.first.value(2)) it_pair_1_so.first++; else if(it_pair_1_so.first.value(2) > it_pair_2_so.first.value(2)) it_pair_2_so.first++; else{ unsigned joinval = it_pair_1_so.first.value(2); unsigned c1 = 0, c2 = 0; while(it_pair_1_so.first != it_pair_1_so.second && it_pair_1_so.first.value(2) == joinval) {c1++;it_pair_1_so.first++;} while(it_pair_2_so.first != it_pair_2_so.second && it_pair_2_so.first.value(2) == joinval) {c2++;it_pair_2_so.first++;} star1_card += (c1*c2); } } // Star2 cardinality it_pair_1_os.first = t1_os; it_pair_2_os.first = t2_os; while(it_pair_1_os.first != it_pair_1_os.second && it_pair_2_os.first != it_pair_2_os.second){ if(it_pair_1_os.first.value(2) < it_pair_2_os.first.value(2)) it_pair_1_os.first++; else if(it_pair_1_os.first.value(2) > it_pair_2_os.first.value(2)) it_pair_2_os.first++; else{ unsigned joinval = it_pair_1_os.first->val2; unsigned c1 = 0, c2 = 0; while(it_pair_1_os.first != it_pair_1_os.second && it_pair_1_os.first.value(2) == joinval) {c1++;it_pair_1_os.first++;} while(it_pair_2_os.first != it_pair_2_os.second && it_pair_2_os.first.value(2) == joinval) {c2++;it_pair_2_os.first++;} star2_card += (c1*c2); } } jCard.push_back(*p1); jCard.push_back(*p2); jCard.push_back(path_card); jCard.push_back(star1_card); jCard.push_back(star2_card); } } bool TripleStore::add(VECTOR_INT_32 & vect){ for(int i = 0; i < 6; i++) dataIndex[i]->pbits = pbits; for(VECTOR_INT_32::iterator it = vect.begin(); it != vect.end();){ unsigned type = *(it++), val1 = *(it++); unsigned val2 = *(it++), val3 = *(it++); if(type == 0){ // S, P, O dataIndex[0]->insert(val1,val2,val3); // SPO dataIndex[1]->insert(val1,val3,val2); // SOP dataIndex[2]->insert(val2,val1,val3); // PSO if(pbits){ // Construct summaries only when pbits > 0 summaryIndex[0]->insert(val2,(val1>>pbits),(val3>>pbits)); //std::cout << "pbits.." << pbits << " adding summary triple.. " << val2 << " " << val1 << "("<< (val1>>pbits)<< ") " << val3 << "(" << (val3>>pbits) << ")" << endl; } }else if(type == 4){ // O, S , P dataIndex[3]->insert(val2,val1,val3); // POS dataIndex[4]->insert(val1,val2,val3); // OPS dataIndex[5]->insert(val1,val3,val2); // OSP } properties.insert(val2); } return true; } void TripleStore::computeCardinalities(FastMap *idx, vector<unsigned> & jCard){ unsigned card = 0, card1 = 0; FastMap::iterator it = idx->begin(); for(;it != idx->end(); it++){ if(it == idx->begin()){ jCard.push_back(it.value(1)); } else if((it-1).value(1) != it.value(1) ){ jCard.push_back((it-1).value(2)); jCard.push_back(card1); jCard.push_back(~0u); jCard.push_back(card); jCard.push_back(it.value(1)); card = 0; card1 = 0; }else if((it-1).value(2) != it.value(2)){ jCard.push_back((it-1).value(2)); jCard.push_back(card1); card1 = 0; } card++; card1++; } jCard.push_back((it-1).value(2)); jCard.push_back(card1); jCard.push_back(~0u); jCard.push_back(card); } void TripleStore::serializeSummary(vector<unsigned> & vect){ for(FastMap::iterator it = summaryIndex[0]->begin(); it != summaryIndex[0]->end(); it++){ vect.push_back(it.value(1)); vect.push_back(it.value(2)); vect.push_back(it.value(3)); } delete summaryIndex[0]; } void TripleStore::computeCardinalities(unsigned type, vector<unsigned> & jCard, bool summary){ (summary)? computeCardinalities(summaryIndex[type],jCard): computeCardinalities(dataIndex[type],jCard); } void TripleStore::sort(){ for(int type = 0; type < 6; type++) dataIndex[type]->optimize(0); for(int type = 0; type < 3; type++) summaryIndex[type]->optimize(0); } void TripleStore::stats(){ for(int type = 0; type < 6; type++){ LOG4CXX_INFO(logger, dataIndex[type]->size()); } for(int type = 0; type < 3; type++){ LOG4CXX_INFO(logger, summaryIndex[type]->size()); } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Distributed functions (each node executes concurrently) void TripleStore::computeQueryStatistics(vector<unsigned> & stats_req, vector<unsigned> & stats){ unsigned order, val1, val2, card; pair<FastMap::iterator, FastMap::iterator> iter; for(vector<unsigned>::iterator it = stats_req.begin(); it != stats_req.end(); it++){ if(*it == 0){ // type: single cardinality order = *(++it); val1 = *(++it); iter = dataIndex[order]->find(val1); stats.push_back(iter.second-iter.first); //std::cout << 0 << "::"<< order << " " << val1 << " card:" << (iter.second-iter.first) << endl; } if(*it == 1){ // type: pair cardinality order = *(++it); val1 = *(++it); val2 = *(++it); iter = dataIndex[order]->find(val1,val2); stats.push_back(iter.second-iter.first); //std::cout << 1 << "::"<< order << " " << val1<< " " << val2 << " card:"<< (iter.second-iter.first) << endl; } } }
34.208
169
0.664757
[ "object", "vector" ]
6ddcc1994fdf8497ed4de8d129fdf46298e5534a
2,397
cpp
C++
Engine/source/materials/baseMatInstance.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
2,113
2015-01-01T11:23:01.000Z
2022-03-28T04:51:46.000Z
Engine/source/materials/baseMatInstance.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
948
2015-01-02T01:50:00.000Z
2022-02-27T05:56:40.000Z
Engine/source/materials/baseMatInstance.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
944
2015-01-01T09:33:53.000Z
2022-03-15T22:23:03.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "platform/platform.h" #include "materials/baseMatInstance.h" #include "core/util/safeDelete.h" BaseMatInstance::~BaseMatInstance() { deleteAllHooks(); } void BaseMatInstance::addHook( MatInstanceHook *hook ) { AssertFatal( hook, "BaseMatInstance::addHook() - Got null hook!" ); const MatInstanceHookType &type = hook->getType(); while ( mHooks.size() <= type ) mHooks.push_back( NULL ); delete mHooks[type]; mHooks[type] = hook; } MatInstanceHook* BaseMatInstance::getHook( const MatInstanceHookType &type ) const { if ( type >= mHooks.size() ) return NULL; return mHooks[ type ]; } void BaseMatInstance::deleteHook( const MatInstanceHookType &type ) { if ( type >= mHooks.size() ) return; delete mHooks[ type ]; mHooks[ type ] = NULL; } U32 BaseMatInstance::deleteAllHooks() { U32 deleteCount = 0; Vector<MatInstanceHook*>::iterator iter = mHooks.begin(); for ( ; iter != mHooks.end(); iter++ ) { if ( *iter ) { delete (*iter); (*iter) = NULL; ++deleteCount; } } return deleteCount; }
29.9625
82
0.652482
[ "vector" ]
6de0e3175dacddd33705d78b3a9a94eaf81f8a11
709
cpp
C++
jni/application/Game_states/Instructions_state.cpp
gdewald/Spacefrog
eae9bd5c91670f7d13442740b5d801286ba41e5e
[ "BSD-2-Clause" ]
null
null
null
jni/application/Game_states/Instructions_state.cpp
gdewald/Spacefrog
eae9bd5c91670f7d13442740b5d801286ba41e5e
[ "BSD-2-Clause" ]
null
null
null
jni/application/Game_states/Instructions_state.cpp
gdewald/Spacefrog
eae9bd5c91670f7d13442740b5d801286ba41e5e
[ "BSD-2-Clause" ]
null
null
null
#include "Instructions_state.h" using namespace Zeni; Zeni::String Instructions_state::image_name = "goals"; void Instructions_state::on_key(const SDL_KeyboardEvent &event) { if (event.state == SDL_PRESSED && event.keysym.sym == SDLK_ESCAPE) get_Game().pop_state(); else Widget_Gamestate::on_key(event); } void Instructions_state::render() { Widget_Gamestate::render(); Zeni::Font &fr = get_Fonts()["title"]; Zeni::Video& vr = get_Video(); int w = get_Window().get_height(); //fr.render_text("Controls", // Point2f(400.0f, 300.0f - 0.5f * fr.get_text_height()), // get_Colors()["title_text"], // ZENI_CENTER); render_image(image_name, Point2f(0.0f, 120.0f), Point2f(1920.0f, 1080.0f)); }
25.321429
76
0.706629
[ "render" ]
6de24e18feb25baf57089c816e76d30f933ad970
8,352
cc
C++
linux/raspberry_pi/hy_srf05_ultrasonic_ranging_sensor.cc
drichardson/examples
d8b285db4ad1cfd9a92091deab2eb385748f97c8
[ "Unlicense" ]
33
2015-04-21T20:10:42.000Z
2021-09-28T05:54:37.000Z
linux/raspberry_pi/hy_srf05_ultrasonic_ranging_sensor.cc
drichardson/examples
d8b285db4ad1cfd9a92091deab2eb385748f97c8
[ "Unlicense" ]
1
2020-03-15T18:54:19.000Z
2020-03-15T18:54:19.000Z
linux/raspberry_pi/hy_srf05_ultrasonic_ranging_sensor.cc
drichardson/examples
d8b285db4ad1cfd9a92091deab2eb385748f97c8
[ "Unlicense" ]
19
2015-01-09T13:39:06.000Z
2021-09-15T05:39:33.000Z
// Example using HY-SRF05 ultrasonic ranging sensor breakout // board, which has 5 pins: Vcc (5V), GND, OUT, TRIG, and ECHO. // OUT is used to put it into a mode that combines TRIG and ECHO // on a single pin, but is not used in this example. // TRIG must be held high (low?) long enough to start the output // pulse. After the echo is receieved (if any) the ECHO line is held // high in proportion to the delay between the time the TRIG pin was // signaled and the echo was received. // // On my prototype board, I'm driving the HY-SRF05 with a Raspberry Pi. // I'm driving the TRIG pin directly with a RPi GPIO pin, since 3.3v // appears to be able to signal the 5V HY-SRF05 input pin. // However, when reading the 5V response, I'm level shifting it down // to 3.3V because RPi pins are not 5V tolerant. I'm using a 7417 hex // buffer driver with open collector output. The open collector output // has a pull up resistor wired to RPis 3.3V output pin and the corresponding // input pin is wired to the output of the HY-SRF05's ECHO pin. #include "file_descriptor.hpp" #include "pins.hpp" #include <cmath> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <iostream> #include <poll.h> #include <thread> #include <unistd.h> void usage(char const* msg) { using namespace std; cout << msg << "\nUsage:\n" << " hy-srf05-ultrasonic-ranging-sensor.cc <gpio_trig> <gpio_echo> <air_temperature>\n" << " where air_temperature is in degrees celcius\n" << flush; } int do_range(std::string const & trigger_pin, std::string const & echo_pin, double temperature_c); int main(int argc, char *argv[]) { using std::cout; using std::cerr; using namespace std::literals::chrono_literals; if (argc < 4) { usage("missing arguments"); return 1; } std::string trig = argv[1]; std::string echo = argv[2]; auto temperature_c = std::atof(argv[3]); return do_range(trig, echo, temperature_c); } // Get the velocity sound travels through dry air at a given temperature. // Returns velocity in meters/second. double velocity_of_sound_in_dry_air(double temperature_c) { // Convert to centimeters using formula taken from Sound Speed in Gases // at http://hyperphysics.phy-astr.gsu.edu/hbase/sound/souspe3.html#c1 // which is v = sqrt((yRT)/M), where // y = adiabatic constant // R = gas constant // M = molecular mass of gas // T = absolute temperature // The average molecular mass of dry air is 28.95 gm/mol. // This leads to: // v = 20.05*sqrt(T) // for dry air, where T is in Kelvin. auto temperature_k = temperature_c + 273.15; return 20.05*std::sqrt(temperature_k); // in m/s } int do_range(std::string const & trigger_pin, std::string const & echo_pin, double temperature_c) { using std::cerr; using std::cout; using std::endl; using namespace std::literals::chrono_literals; gpio::PinExporter export_trigger(trigger_pin); if (!export_trigger.ok()) { cerr << "Error exporting trigger pin " << trigger_pin << endl; return 1; } if (!gpio::set_pin_direction(trigger_pin, gpio::pin_direction::out)) { cerr << "Error setting trigger pin direction to output" << endl; return 1; } gpio::PinExporter export_echo(echo_pin); if (!export_echo.ok()) { cerr << "Error exporting echo pin " << echo_pin << endl; return 1; } if (!gpio::set_pin_direction(echo_pin, gpio::pin_direction::in)) { cerr << "Error setting trigger pin direction to output" << endl; return 1; } if (!gpio::set_pin_edge_trigger(echo_pin, "both")) { cerr << "Error setting pin edge trigger" << endl; return 1; } auto echo_filename = gpio::pin_gpio_dir(echo_pin) + "/value"; gpio::FileDescriptor echo_value_file = gpio::open_read_only(echo_filename); if (!echo_value_file.ok()) { std::perror(("Error opening echo pin value file " + echo_filename).c_str()); return 1; } char c; // verify echo pin is already 0. auto rc = ::read(echo_value_file.fd(), &c, 1); if (rc == -1) { std::perror("Error reading echo value to see if it's already 0"); return 1; } if (c != '0') { cerr << "Expected echo to initially be set to 0 but it is " << c << endl; return 1; } auto trigger_filename = gpio::pin_gpio_dir(trigger_pin) + "/value"; gpio::FileDescriptor trigger_value_file = gpio::open_write_only(trigger_filename); if (!trigger_value_file.ok()) { std::perror(("Error opening trigger pin value file " + trigger_filename).c_str()); return 1; } // One document on a similar breakout board, the SRF05, said the trigger pulse should // be 10uS minimum. So, drive the pin low for 15uS, then pulse high for 15uS, then low again. auto srf05_min_pulse = 15us; rc = ::write(trigger_value_file.fd(), "0", 1); if (rc == -1) { std::perror("Error initially setting trigger to 0"); return 1; } std::this_thread::sleep_for(srf05_min_pulse); rc = ::write(trigger_value_file.fd(), "1", 1); if (rc == -1) { std::perror("Error setting trigger pulse to 1"); return 1; } std::this_thread::sleep_for(srf05_min_pulse); rc = ::write(trigger_value_file.fd(), "0", 1); if (rc == -1) { std::perror("Error setting trigger pulse back to 0"); return 1; } struct pollfd pfd; pfd.fd = echo_value_file.fd(); pfd.events = POLLPRI; // SRF05 (which I'm basing this code off) doc says it will lower echo after // 30ms, even if nothing detected, so timeout some time after that. int constexpr timeout_ms = 100; std::chrono::high_resolution_clock::time_point echo_pulse_start; std::chrono::high_resolution_clock::time_point echo_pulse_end; while(true) { auto rc = ::poll(&pfd, 1, timeout_ms); if (rc > 0) { // lseek back to beginning, per gpio sysfs spec auto off = ::lseek(pfd.fd, 0, SEEK_SET); if (off == -1) { std::perror("Error seeking to beginning of file."); break; } if (pfd.revents & POLLPRI) { char buf; auto rc = ::read(pfd.fd, &buf, sizeof(buf)); if (rc == -1) { std::perror("Error reading value after poll signalled it was available."); break; } if (buf == '1') { // pulse went high echo_pulse_start = std::chrono::high_resolution_clock::now(); } else if (buf == '0') { echo_pulse_end = std::chrono::high_resolution_clock::now(); break; } else { cerr << "Unexpected value " << buf << endl; return 1; } } // Ignore POLLERR. sysfs files always return POLLERR on poll (see fs/sysfs/file.c). } else if (rc == 0) { // timeout occurred. Don't expect this since SRF05 should go low after 30ms // regardless if anything was detected. cerr << "Timeout occurred" << endl; return 1; } else if (rc == -1) { // other error std::perror("poll failed"); return 1; } } constexpr auto zero = std::chrono::high_resolution_clock::duration::zero(); if (echo_pulse_start.time_since_epoch() == zero) { cerr << "echo pulse started was not set" << endl; return 1; } if (echo_pulse_end.time_since_epoch() == zero) { cerr << "echo pulse end was not set" << endl; return 1; } std::chrono::duration<double> pulse_duration_sec = echo_pulse_end - echo_pulse_start; // distance = velocity * time auto velocity = velocity_of_sound_in_dry_air(temperature_c); auto distance = velocity * pulse_duration_sec.count(); // in meters // since the sound had to travel to the object and back, divide by 2. auto distance_to_object_m = distance / 2.0; auto distance_to_object_cm = distance_to_object_m * 100.0; cout << "distance: " << distance_to_object_cm << "cm" << endl; return 0; }
37.12
99
0.613027
[ "object" ]