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
1ce473f2d09b354e8d7c6fb85bb38329446de4f6
3,554
cpp
C++
src/Modules/Graphics/Geometry/Prop/PropSync_System.cpp
Yattabyte/reVision
014cb450d1c30b8f64abbacf00425b4f814b05a0
[ "MIT" ]
5
2018-10-12T17:40:17.000Z
2020-11-20T10:49:34.000Z
src/Modules/Graphics/Geometry/Prop/PropSync_System.cpp
Yattabyte/reVision
014cb450d1c30b8f64abbacf00425b4f814b05a0
[ "MIT" ]
71
2018-07-19T01:59:38.000Z
2020-03-29T18:03:13.000Z
src/Modules/Graphics/Geometry/Prop/PropSync_System.cpp
Yattabyte/reVision
014cb450d1c30b8f64abbacf00425b4f814b05a0
[ "MIT" ]
1
2022-03-24T13:21:25.000Z
2022-03-24T13:21:25.000Z
#include "Modules/Graphics/Geometry/Prop/PropSync_System.h" #include "Modules/Graphics/Geometry/Prop/PropData.h" #include "Modules/ECS/component_types.h" PropSync_System::PropSync_System(PropData& frameData) : m_frameData(frameData) { addComponentType(Prop_Component::Runtime_ID, RequirementsFlag::FLAG_REQUIRED); addComponentType(Skeleton_Component::Runtime_ID, RequirementsFlag::FLAG_OPTIONAL); addComponentType(Transform_Component::Runtime_ID, RequirementsFlag::FLAG_OPTIONAL); addComponentType(BoundingBox_Component::Runtime_ID, RequirementsFlag::FLAG_OPTIONAL); } void PropSync_System::updateComponents(const float& /*deltaTime*/, const std::vector<std::vector<ecsBaseComponent*>>& components) { // Resize BOTH buffers to match number of entities this frame, even though not all models have skeletons m_frameData.modelBuffer.resize(components.size()); m_frameData.skeletonBuffer.resize(components.size()); m_frameData.modelBuffer.beginWriting(); m_frameData.skeletonBuffer.beginWriting(); int index = 0; for (const auto& componentParam : components) { const auto* propComponent = static_cast<Prop_Component*>(componentParam[0]); auto* skeletonComponent = dynamic_cast<Skeleton_Component*>(componentParam[1]); const auto* transformComponent = dynamic_cast<Transform_Component*>(componentParam[2]); auto* bboxComponent = dynamic_cast<BoundingBox_Component*>(componentParam[3]); // Synchronize the component if it is visible if (propComponent->m_model->ready()) { // Sync Transform Attributes if (transformComponent != nullptr) { const auto& position = transformComponent->m_worldTransform.m_position; const auto& orientation = transformComponent->m_worldTransform.m_orientation; const auto& scale = transformComponent->m_worldTransform.m_scale; const auto matRot = glm::mat4_cast(orientation); m_frameData.modelBuffer[index].mMatrix = transformComponent->m_worldTransform.m_modelMatrix; // Update bounding sphere const glm::vec3 bboxMax_World = (propComponent->m_model->m_bboxMax * scale) + position; const glm::vec3 bboxMin_World = (propComponent->m_model->m_bboxMin * scale) + position; const glm::vec3 bboxCenter = (bboxMax_World + bboxMin_World) / 2.0F; const glm::vec3 bboxScale = (bboxMax_World - bboxMin_World) / 2.0F; const glm::mat4 matTrans = glm::translate(glm::mat4(1.0F), bboxCenter); const glm::mat4 matScale = glm::scale(glm::mat4(1.0F), bboxScale); const glm::mat4 matFinal = (matTrans * matRot * matScale); m_frameData.modelBuffer[index].bBoxMatrix = matFinal; } if (bboxComponent != nullptr) { bboxComponent->m_extent = propComponent->m_model->m_bboxScale; bboxComponent->m_min = propComponent->m_model->m_bboxMin; bboxComponent->m_max = propComponent->m_model->m_bboxMax; bboxComponent->m_positionOffset = propComponent->m_model->m_bboxCenter; } // Sync Animation Attributes if (skeletonComponent != nullptr) { skeletonComponent->m_mesh = propComponent->m_model->m_mesh; auto& bones = m_frameData.skeletonBuffer[index].bones; const auto total = std::min(skeletonComponent->m_transforms.size(), static_cast<size_t>(NUM_MAX_BONES)); for (size_t i = 0; i < total; ++i) bones[i] = skeletonComponent->m_transforms[i]; } // Sync Prop Attributes m_frameData.modelBuffer[index].materialID = propComponent->m_materialID; m_frameData.modelBuffer[index].skinID = propComponent->m_skin; } index++; } m_frameData.modelBuffer.endWriting(); m_frameData.skeletonBuffer.endWriting(); }
48.684932
129
0.76224
[ "geometry", "vector", "transform" ]
1ce6dff8203bbb47d77b6b5d6cc36bacb694fcc3
3,807
cpp
C++
lib/Andersen.cpp
efeslab/andersen
e6e3f6ae3bf20c1a873be21759025cb413a9a206
[ "MIT" ]
154
2015-01-28T17:45:21.000Z
2022-03-27T13:48:37.000Z
lib/Andersen.cpp
csabahruska/andersen
bd5326269401568bf784c42f8fbf0d74d74b0532
[ "MIT" ]
5
2016-04-23T06:55:47.000Z
2019-06-19T21:57:42.000Z
lib/Andersen.cpp
csabahruska/andersen
bd5326269401568bf784c42f8fbf0d74d74b0532
[ "MIT" ]
47
2015-01-05T09:55:34.000Z
2022-02-24T15:04:56.000Z
#include "Andersen.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; cl::opt<bool> DumpDebugInfo("dump-debug", cl::desc("Dump debug info into stderr"), cl::init(false), cl::Hidden); cl::opt<bool> DumpResultInfo("dump-result", cl::desc("Dump result info into stderr"), cl::init(false), cl::Hidden); cl::opt<bool> DumpConstraintInfo("dump-cons", cl::desc("Dump constraint info into stderr"), cl::init(false), cl::Hidden); Andersen::Andersen(const Module &module) { runOnModule(module); } void Andersen::getAllAllocationSites( std::vector<const llvm::Value *> &allocSites) const { nodeFactory.getAllocSites(allocSites); } bool Andersen::getPointsToSet(const llvm::Value *v, std::vector<const llvm::Value *> &ptsSet) const { NodeIndex ptrIndex = nodeFactory.getValueNodeFor(v); // We have no idea what v is... if (ptrIndex == AndersNodeFactory::InvalidIndex || ptrIndex == nodeFactory.getUniversalPtrNode()) return false; NodeIndex ptrTgt = nodeFactory.getMergeTarget(ptrIndex); ptsSet.clear(); auto ptsItr = ptsGraph.find(ptrTgt); if (ptsItr == ptsGraph.end()) { // Can't find ptrTgt. The reason might be that ptrTgt is an undefined // pointer. Dereferencing it is undefined behavior anyway, so we might just // want to treat it as a nullptr pointer return true; } for (auto v : ptsItr->second) { if (v == nodeFactory.getNullObjectNode()) continue; const llvm::Value *val = nodeFactory.getValueForNode(v); if (val != nullptr) ptsSet.push_back(val); } return true; } bool Andersen::runOnModule(const Module &M) { collectConstraints(M); if (DumpDebugInfo) dumpConstraintsPlainVanilla(); optimizeConstraints(); if (DumpConstraintInfo) dumpConstraints(); solveConstraints(); if (DumpDebugInfo) { errs() << "\n"; dumpPtsGraphPlainVanilla(); } if (DumpResultInfo) { nodeFactory.dumpNodeInfo(); errs() << "\n"; dumpPtsGraphPlainVanilla(); } return false; } void Andersen::dumpConstraint(const AndersConstraint &item) const { NodeIndex dest = item.getDest(); NodeIndex src = item.getSrc(); switch (item.getType()) { case AndersConstraint::COPY: { nodeFactory.dumpNode(dest); errs() << " = "; nodeFactory.dumpNode(src); break; } case AndersConstraint::LOAD: { nodeFactory.dumpNode(dest); errs() << " = *"; nodeFactory.dumpNode(src); break; } case AndersConstraint::STORE: { errs() << "*"; nodeFactory.dumpNode(dest); errs() << " = "; nodeFactory.dumpNode(src); break; } case AndersConstraint::ADDR_OF: { nodeFactory.dumpNode(dest); errs() << " = &"; nodeFactory.dumpNode(src); } } errs() << "\n"; } void Andersen::dumpConstraints() const { errs() << "\n----- Constraints -----\n"; for (auto const &item : constraints) dumpConstraint(item); errs() << "----- End of Print -----\n"; } void Andersen::dumpConstraintsPlainVanilla() const { for (auto const &item : constraints) { errs() << item.getType() << " " << item.getDest() << " " << item.getSrc() << " 0\n"; } } void Andersen::dumpPtsGraphPlainVanilla() const { for (unsigned i = 0, e = nodeFactory.getNumNodes(); i < e; ++i) { NodeIndex rep = nodeFactory.getMergeTarget(i); auto ptsItr = ptsGraph.find(rep); if (ptsItr != ptsGraph.end()) { errs() << i << " "; for (auto v : ptsItr->second) errs() << v << " "; errs() << "\n"; } } }
26.622378
79
0.607565
[ "vector" ]
1ceabe509d03d0a86efff240674f66150858cd51
2,002
cpp
C++
src/C++ STL Examples/algorithms/find_end_example.cpp
Fennec2000GH/Software-Engineering-Interview
c7a182d7f8c44f7cabaf77982099594ce297a48b
[ "MIT" ]
1
2020-03-15T04:09:11.000Z
2020-03-15T04:09:11.000Z
src/C++ STL Examples/algorithms/find_end_example.cpp
Fennec2000GH/Software-Engineering-Interview
c7a182d7f8c44f7cabaf77982099594ce297a48b
[ "MIT" ]
null
null
null
src/C++ STL Examples/algorithms/find_end_example.cpp
Fennec2000GH/Software-Engineering-Interview
c7a182d7f8c44f7cabaf77982099594ce297a48b
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <iterator> #include <vector> using namespace std; //std::find_end /* equality (1) * template <class ForwardIterator1, class ForwardIterator2> * ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1,ForwardIterator2 first2, ForwardIterator2 last2); */ /* predicate (2) * template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> * ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); */ //predicate function confirms equality if second integer is a multiple of first integer bool multiple(int a, int b) { return b % a == 0; } int main() { //main vector vector<int> v = {-2, 1, 4, 2, 4, 0, -3, -4, 4, 2}; cout << "v: { "; copy(v.cbegin(), v.cend(), ostream_iterator<int>(cout, ", ")); cout << "} " << endl; //finding first occurrence of {4, 2} vector<int> test = {4, 2}; cout << "test: { "; copy(test.cbegin(), test.cend(), ostream_iterator<int>(cout, ", ")); cout << "} " << endl; vector<int>::const_iterator it1 = search(v.cbegin(), v.cend(), test.cbegin(), test.cend()); cout << "first occurrence index: " << it1 - v.cbegin() << endl; //finding last occurrence of {4, 2} vector<int>::const_iterator it2 = find_end(v.cbegin(), v.cend(), test.cbegin(), test.cend()); cout << "last occurrence index: " << it2 - v.cbegin() << endl; //finding first occurrence of {4, 2} with predicate function vector<int>::const_iterator it3 = search(v.cbegin(), v.cend(), test.cbegin(), test.cend(), multiple); cout << "first occurrence pred index: " << it3 - v.cbegin() << endl; //finding last occurrence of {4, 2} with predicate function vector<int>::const_iterator it4 = find_end(v.cbegin(), v.cend(), test.cbegin(), test.cend(), multiple); cout << "last occurrence pred index: " << it4 - v.cbegin() << endl; return 0; }
40.04
151
0.653846
[ "vector" ]
1cecfdf5e53d508c3c5003a250b37568beb662d9
11,643
cc
C++
examples/collection/jacobi1d_vt.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
26
2019-11-26T08:36:15.000Z
2022-02-15T17:13:21.000Z
examples/collection/jacobi1d_vt.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
1,215
2019-09-09T14:31:33.000Z
2022-03-30T20:20:14.000Z
examples/collection/jacobi1d_vt.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
12
2019-09-08T00:03:05.000Z
2022-02-23T21:28:35.000Z
/* //@HEADER // ***************************************************************************** // // jacobi1d_vt.cc // DARMA/vt => Virtual Transport // // Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ /// [Jacobi1D example] // // This code applies a few steps of the Jacobi iteration to // the linear system A x = 0 // where is the tridiagonal matrix with pattern [-1 2 -1] // The initial guess for x is a made-up non-zero vector. // The exact solution is the vector 0. // // The matrix A is square and invertible. // The number of rows is ((number of objects) * (number of rows per object)) // // Such a matrix A is obtained when using 2nd-order finite difference // for discretizing (-d^2 u /dx^2 = f) on [0, 1] with homogeneous // Dirichlet condition (u(0) = u(1) = 0) using a uniform grid // with grid size 1 / ((number of objects) * (number of rows per object) + 1) // #include <vt/transport.h> #include <vt/runnable/invoke.h> #include <cstdlib> #include <cassert> #include <iostream> static constexpr std::size_t const default_nrow_object = 8; static constexpr std::size_t const default_num_objs = 4; static constexpr double const default_tol = 1.0e-02; struct NodeObj { bool is_finished_ = false; struct WorkFinishedMsg : vt::Message {}; void workFinishedHandler(WorkFinishedMsg*) { is_finished_ = true; } bool isWorkFinished() { return is_finished_; } }; using NodeObjProxy = vt::objgroup::proxy::Proxy<NodeObj>; struct LinearPb1DJacobi : vt::Collection<LinearPb1DJacobi,vt::Index1D> { private: std::vector<double> tcur_, told_; std::vector<double> rhs_; size_t iter_ = 0; size_t msgReceived_ = 0, totalReceive_ = 0; size_t numObjs_ = 1; size_t numRowsPerObject_ = 1; size_t maxIter_ = 8; NodeObjProxy objProxy_; public: explicit LinearPb1DJacobi() : tcur_(), told_(), rhs_(), iter_(0), msgReceived_(0), totalReceive_(0), numObjs_(1), numRowsPerObject_(1), maxIter_(8) { } using BlankMsg = vt::CollectionMessage<LinearPb1DJacobi>; struct LPMsg : vt::CollectionMessage<LinearPb1DJacobi> { size_t numObjects = 0; size_t nRowPerObject = 0; size_t iterMax = 0; NodeObjProxy objProxy; LPMsg() = default; LPMsg(const size_t nobjs, const size_t nrow, const size_t itMax, NodeObjProxy proxy) : numObjects(nobjs), nRowPerObject(nrow), iterMax(itMax), objProxy(proxy) { } }; struct ReduxMsg : vt::collective::ReduceTMsg<double> { ReduxMsg() = default; explicit ReduxMsg(double in_val) : ReduceTMsg<double>(in_val) { } }; void checkCompleteCB(ReduxMsg* msg) { // // Only one object for the reduction will visit // this function // double normRes = msg->getConstVal(); auto const iter_max_reached = iter_ > maxIter_; auto const norm_res_done = normRes < default_tol; if (iter_max_reached or norm_res_done) { auto const to_print = iter_max_reached ? "\n Maximum Number of Iterations Reached. \n\n" : fmt::format("\n Max-Norm Residual Reduced by {} \n\n", default_tol); fmt::print(to_print); // Notify all nodes that computation is finished objProxy_.broadcast<NodeObj::WorkFinishedMsg, &NodeObj::workFinishedHandler>(); } else { fmt::print(" ## ITER {} >> Residual Norm = {} \n", iter_, normRes); } } void doIteration() { iter_ += 1; // //--- Copy extremal values // tcur_[0] = told_[0]; tcur_[numRowsPerObject_+1] = told_[numRowsPerObject_+1]; // //---- Jacobi iteration step //---- A tridiagonal matrix = "tridiag" ( [-1.0 2.0 -1.0] ) //---- rhs_ right hand side vector // for (size_t ii = 1; ii <= numRowsPerObject_; ++ii) { tcur_[ii] = 0.5*(rhs_[ii] + told_[ii-1] + told_[ii+1]); } std::copy(tcur_.begin(), tcur_.end(), told_.begin()); // // Compute the maximum entries among the rows on this object // We do not take into account the "ghost" entries // as they may be "out of date". // double maxNorm = 0.0; for (size_t ii = 1; ii < tcur_.size()-1; ++ii) { double val = tcur_[ii]; maxNorm = (maxNorm > std::fabs(val)) ? maxNorm : std::fabs(val); } auto proxy = this->getCollectionProxy(); auto cb = vt::theCB()->makeSend< LinearPb1DJacobi,ReduxMsg,&LinearPb1DJacobi::checkCompleteCB >(proxy[0]); auto msg2 = vt::makeMessage<ReduxMsg>(maxNorm); proxy.reduce<vt::collective::MaxOp<double>>(msg2.get(),cb); } struct VecMsg : vt::CollectionMessage<LinearPb1DJacobi> { using MessageParentType = vt::CollectionMessage<LinearPb1DJacobi>; vt_msg_serialize_if_needed_by_parent_or_type1(vt::IdxBase); VecMsg() = default; VecMsg(vt::IdxBase const& in_index, double const& ref) : vt::CollectionMessage<LinearPb1DJacobi>(), from_index(in_index), val(ref) { } template <typename Serializer> void serialize(Serializer& s) { MessageParentType::serialize(s); s | from_index; s | val; } vt::IdxBase from_index = 0; double val = 0.0; }; void exchange(VecMsg *msg) { // Receive and treat the message from a neighboring object. const vt::IdxBase myIdx = getIndex().x(); if (myIdx > msg->from_index) { this->told_[0] = msg->val; msgReceived_ += 1; } if (myIdx < msg->from_index) { this->told_[numRowsPerObject_ + 1] = msg->val; msgReceived_ += 1; } // Check whether this 'object' has received all the expected messages. if (msgReceived_ == totalReceive_) { msgReceived_ = 0; doIteration(); } } void doIter(BlankMsg *msg) { // // Treat the particular case of 1 object // where no communication is needed. // Without this treatment, the code would not iterate. // if (numObjs_ == 1) { doIteration(); return; } //--------------------------------------- // // Routine to send information to a different object // vt::IdxBase const myIdx = getIndex().x(); //--- Send the values to the left auto proxy = this->getCollectionProxy(); if (myIdx > 0) { proxy[myIdx - 1].send<VecMsg, &LinearPb1DJacobi::exchange>( myIdx, told_[1] ); } //--- Send values to the right if (size_t(myIdx) < numObjs_ - 1) { proxy[myIdx + 1].send<VecMsg, &LinearPb1DJacobi::exchange>( myIdx, told_[numRowsPerObject_] ); } } void init() { tcur_.assign(numRowsPerObject_ + 2, 0.0); told_.assign(numRowsPerObject_ + 2, 0.0); rhs_.assign(numRowsPerObject_ + 2, 0.0); double h = 1.0 / (numRowsPerObject_ * numObjs_ + 1.0); int nf = 3 * int(numRowsPerObject_ * numObjs_ + 1) / 4; size_t const myIdx = getIndex().x(); for (size_t ii = 0; ii < tcur_.size(); ++ii) { double x0 = ( numRowsPerObject_ * myIdx + ii) * h; tcur_[ii] = sin(nf * M_PI * x0 * x0); } totalReceive_ = 2; if (myIdx == 0) { tcur_[0] = 0.0; totalReceive_ -= 1; } if (myIdx == numObjs_ - 1) { tcur_[numRowsPerObject_+1] = 0.0; totalReceive_ -= 1; } std::copy(tcur_.begin(), tcur_.end(), told_.begin()); } void init(LPMsg* msg) { numObjs_ = msg->numObjects; numRowsPerObject_ = msg->nRowPerObject; maxIter_ = msg->iterMax; objProxy_ = msg->objProxy; // Initialize the starting vector init(); } }; bool isWorkDone( vt::objgroup::proxy::Proxy<NodeObj> const& proxy){ auto const this_node = vt::theContext()->getNode(); return proxy[this_node].invoke<decltype(&NodeObj::isWorkFinished), &NodeObj::isWorkFinished>(); } int main(int argc, char** argv) { size_t num_objs = default_num_objs; size_t numRowsPerObject = default_nrow_object; size_t maxIter = 8; std::string name(argv[0]); vt::initialize(argc, argv); vt::NodeType this_node = vt::theContext()->getNode(); vt::NodeType num_nodes = vt::theContext()->getNumNodes(); if (argc == 1) { if (this_node == 0) { fmt::print( stderr, "{}: using default arguments since none provided\n", name ); } num_objs = default_num_objs * num_nodes; } else if (argc == 2) { num_objs = static_cast<size_t>(strtol(argv[1], nullptr, 10)); } else if (argc == 3) { num_objs = static_cast<size_t>(strtol(argv[1], nullptr, 10)); numRowsPerObject = static_cast<size_t>(strtol(argv[2], nullptr, 10)); } else if (argc == 4) { num_objs = static_cast<size_t>(strtol(argv[1], nullptr, 10)); numRowsPerObject = static_cast<size_t>(strtol(argv[2], nullptr, 10)); maxIter = static_cast<size_t>(strtol(argv[3], nullptr, 10)); } else { fmt::print( stderr, "usage: {} <num-objects> <num-rows-per-object> <maxiter>\n", name ); return 1; } // Object group of all nodes that take part in computation // Used to determine whether the computation is finished auto grp_proxy = vt::theObjGroup()->makeCollective<NodeObj>(); // Create the decomposition into objects using BaseIndexType = typename vt::Index1D::DenseIndexType; auto range = vt::Index1D(static_cast<BaseIndexType>(num_objs)); auto col_proxy = vt::makeCollection<LinearPb1DJacobi>() .bounds(range) .bulkInsert() .wait(); vt::runInEpochCollective([col_proxy, grp_proxy, num_objs, numRowsPerObject, maxIter]{ col_proxy.broadcastCollective<LinearPb1DJacobi::LPMsg, &LinearPb1DJacobi::init>( num_objs, numRowsPerObject, maxIter, grp_proxy ); }); while(!isWorkDone(grp_proxy)){ vt::runInEpochCollective([col_proxy]{ col_proxy.broadcastCollective< LinearPb1DJacobi::BlankMsg, &LinearPb1DJacobi::doIter >(); }); vt::thePhase()->nextPhaseCollective(); } vt::finalize(); return 0; } /// [Jacobi1D example]
28.890819
97
0.644507
[ "object", "vector" ]
1cef7ffe508ec04e4d6b9613071081f981fbcda4
3,152
cpp
C++
frameworks/core/gestures/click_recognizer.cpp
chaoyangcui/ace_ace_engine
05ebe2d6d2674777f5dc64fd735088dcf1a42cd9
[ "Apache-2.0" ]
null
null
null
frameworks/core/gestures/click_recognizer.cpp
chaoyangcui/ace_ace_engine
05ebe2d6d2674777f5dc64fd735088dcf1a42cd9
[ "Apache-2.0" ]
null
null
null
frameworks/core/gestures/click_recognizer.cpp
chaoyangcui/ace_ace_engine
05ebe2d6d2674777f5dc64fd735088dcf1a42cd9
[ "Apache-2.0" ]
1
2021-09-13T12:07:42.000Z
2021-09-13T12:07:42.000Z
/* * Copyright (c) 2021 Huawei Device 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. */ #include "core/gestures/click_recognizer.h" #include "base/geometry/offset.h" #include "base/log/log.h" #include "core/gestures/gesture_referee.h" namespace OHOS::Ace { namespace { constexpr double MAX_THRESHOLD = 20.0; } // namespace void ClickRecognizer::OnAccepted(size_t touchId) { LOGD("click gesture has been accepted! the touch id is %{public}zu", touchId); state_ = DetectState::DETECTED; if (onClick_) { ClickInfo info(touchId); info.SetTimeStamp(touchPoint_.time); info.SetGlobalLocation(touchPoint_.GetOffset()).SetLocalLocation(touchPoint_.GetOffset() - coordinateOffset_); onClick_(info); } } void ClickRecognizer::OnRejected(size_t touchId) { LOGD("click gesture has been rejected! the touch id is %{public}zu", touchId); state_ = DetectState::READY; } void ClickRecognizer::HandleTouchDownEvent(const TouchPoint& event) { LOGD("click recognizer receives touch down event, begin to detect click event"); if (state_ == DetectState::READY) { GestureReferee::GetInstance().AddGestureRecognizer(event.id, AceType::Claim(this)); touchPoint_ = event; state_ = DetectState::DETECTING; } else { LOGW("the state is not ready for detecting click event"); } } void ClickRecognizer::HandleTouchUpEvent(const TouchPoint& event) { LOGD("click recognizer receives touch up event"); if (state_ == DetectState::DETECTING) { LOGD("this gesture is click, try to accept it"); GestureReferee::GetInstance().Adjudicate(event.id, AceType::Claim(this), GestureDisposal::ACCEPT); } state_ = DetectState::READY; } void ClickRecognizer::HandleTouchMoveEvent(const TouchPoint& event) { LOGD("click recognizer receives touch move event"); if (state_ == DetectState::DETECTING) { Offset offset = event.GetOffset() - touchPoint_.GetOffset(); if (offset.GetDistance() > MAX_THRESHOLD) { LOGD("this gesture is not click, try to reject it"); GestureReferee::GetInstance().Adjudicate(event.id, AceType::Claim(this), GestureDisposal::REJECT); } } } void ClickRecognizer::HandleTouchCancelEvent(const TouchPoint& event) { LOGD("click recognizer receives touch cancel event"); if (state_ == DetectState::DETECTING) { LOGD("cancel click gesture detect, try to reject it"); GestureReferee::GetInstance().Adjudicate(event.id, AceType::Claim(this), GestureDisposal::REJECT); } state_ = DetectState::READY; } } // namespace OHOS::Ace
34.637363
118
0.703997
[ "geometry" ]
7f2f947ec0a42eb4ffc28f6f51e351f5d17a4043
2,104
cpp
C++
src/gusanos/parser.cpp
JiPRA/openlierox
1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc
[ "CECILL-B" ]
192
2015-02-13T14:53:59.000Z
2022-03-29T11:18:58.000Z
src/gusanos/parser.cpp
JiPRA/openlierox
1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc
[ "CECILL-B" ]
48
2015-01-06T22:00:53.000Z
2022-01-15T18:22:46.000Z
src/gusanos/parser.cpp
JiPRA/openlierox
1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc
[ "CECILL-B" ]
51
2015-01-16T00:55:16.000Z
2022-02-05T03:09:30.000Z
#include "parser.h" #include <vector> #include <string> using namespace std; namespace Parser { const vector<string> tokenize(const string &text) { size_t left = 0; size_t right = 0; string lastChar = " "; vector<string> stringList; while (right != string::npos) { left = text.find_first_not_of(lastChar, right); if (left != string::npos) { right = text.find_first_of(", =()",left); if (right != string::npos) { lastChar = text[right]; if (right > left) stringList.push_back( text.substr(left, right - left) ); if ( lastChar != " " ) { stringList.push_back( lastChar ); } }else stringList.push_back( text.substr(left) ); } else right = string::npos; } return stringList; } // May the god of inderdaad forgive me for this sin :( int identifyLine( const vector<string> & tokens ) { int id = INVALID; if ( tokens.size() > 1 ) { vector<string>::const_iterator token = tokens.begin(); if( (*token)[0] == '#' ) // Is it a comment? return INVALID; if ( *token == "on" ) //First token is 'on'? Then its the start of an event { id = EVENT_START; } else { token++; if ( *token == "=" ) // Second token is '='? Then its a property assignment { token++; if ( token != tokens.end() ) { id = PROP_ASSIGMENT; } } if ( *token == "(" ) // Second token is '('? Then its an action { // I check for the closing brackets of the action for(; token != tokens.end() ; token++) { if ( *token == ")" ) id = ACTION; } } } } return id; } vector<string> getActionParams( const vector<string> & tokens ) { vector<string>::const_iterator token = tokens.begin(); vector<string> params; if( tokens.size() > 3 ) { token++; token++; while( token != tokens.end()) { if ( *token == ")" ) break; if ( *token != "," ) { params.push_back(*token); } token++; } } return params; } }
16.566929
79
0.53327
[ "vector" ]
7f326b8732c4d4fc1f2f0568c068fe7d3c2bb768
886
cpp
C++
test/resources/solver/solvertool.cpp
Manu343726/biicode-common
91b32c6fd1e4a72ce5451183f1766d313cd0e420
[ "MIT" ]
17
2015-04-15T09:40:23.000Z
2017-05-17T20:34:49.000Z
test/resources/solver/solvertool.cpp
Manu343726/biicode-common
91b32c6fd1e4a72ce5451183f1766d313cd0e420
[ "MIT" ]
2
2015-04-22T11:29:36.000Z
2018-09-25T09:31:09.000Z
test/resources/solver/solvertool.cpp
bowlofstew/common
45e9ca902be7bbbdd73dafe3ab8957bc4a006020
[ "MIT" ]
22
2015-04-15T09:46:00.000Z
2020-09-29T17:03:31.000Z
#include "systemsolver.h" int main(int arg, char** argv) { /* MatrixXd m(2,2); m(0,0) = 3; m(1,0) = 2.5; m(0,1) = -1; m(1,1) = m(1,0) + m(0,1); std::cout << m << std::endl; MatrixXf m2 = MatrixXf::Random(3,3); m2 = (m2 + MatrixXf::Constant(3,3,1.2)) * 50; cout << "m2 =" << endl << m2 << endl; VectorXf v(3); v << 1, 2, 3; cout << "m * v =" << endl << m2 * v << endl;*/ SystemSolver solver; vector<double> b; int size=10; for(int i=0;i<size;i++) { solver(i,i)=i+1; b.push_back(1); } vector<double> sol=solver.SolveSparse(b); cout<<"*************** SPARSE *************** "<<endl; for(int i=0;i<size;i++) cout<<i<<": "<<sol[i]<<endl; vector<double> sol2=solver.SolveDense(b); cout<<"*************** DENSE *************** "<<endl; for(int i=0;i<size;i++) cout<<i<<": "<<sol2[i]<<endl; }
24.611111
57
0.463883
[ "vector" ]
7f4d34846553d3ae6c8f5fc68efb7500d50289e4
21,271
cpp
C++
sources/SceneGraph/spSceneGraph.cpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/SceneGraph/spSceneGraph.cpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/SceneGraph/spSceneGraph.cpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2016-10-31T06:08:44.000Z
2019-08-02T16:12:33.000Z
/* * Scene graph file * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #include "SceneGraph/spSceneGraph.hpp" #include "SceneGraph/spSceneManager.hpp" #include "Platform/spSoftPixelDeviceOS.hpp" #include "Base/spInternalDeclarations.hpp" #include "Base/spSharedObjects.hpp" #include <boost/foreach.hpp> namespace sp { extern SoftPixelDevice* GlbEngineDev; extern io::InputControl* GlbInputCtrl; extern video::RenderSystem* GlbRenderSys; extern scene::SceneGraph* GlbSceneGraph; namespace scene { /* * Internal functions */ bool cmpObjectLights(Light* ObjA, Light* ObjB) { /* Compare visiblity */ //if (ObjA->getVisible() != ObjB->getVisible()) // return static_cast<s32>(ObjA->getVisible()) > static_cast<s32>(ObjB->getVisible()); /* Compare light model */ /*if (ObjA->getLightModel() == LIGHT_DIRECTIONAL && ObjB->getLightModel() != LIGHT_DIRECTIONAL) return true; if (ObjA->getLightModel() != LIGHT_DIRECTIONAL && ObjB->getLightModel() == LIGHT_DIRECTIONAL) return false;*/ /* Compare distance to camera */ const dim::vector3df CamPos( GlbSceneGraph->getActiveCamera() ? GlbSceneGraph->getActiveCamera()->getPosition(true) : 0.0f ); return math::getDistanceSq(ObjA->getPosition(true), CamPos) < math::getDistanceSq(ObjB->getPosition(true), CamPos); } bool compareSceneNodes(SceneNode* ObjA, SceneNode* ObjB) { /* Compare visiblity */ if (ObjA->getVisible() != ObjB->getVisible()) return ObjA->getVisible(); /* Compare material nodes */ if (ObjA->getType() >= NODE_MESH && ObjB->getType() >= NODE_MESH) return static_cast<MaterialNode*>(ObjA)->compare(static_cast<MaterialNode*>(ObjB)); /* Compare types */ return ObjA->getType() > ObjB->getType(); } static bool compareRenderNodesDepthDistance(RenderNode* ObjA, RenderNode* ObjB) { /* Compare visiblity */ if (ObjA->getVisible() != ObjB->getVisible()) return ObjA->getVisible(); /* Compare material nodes */ if (ObjA->getType() >= NODE_MESH && ObjB->getType() >= NODE_MESH) return static_cast<MaterialNode*>(ObjA)->compare(static_cast<MaterialNode*>(ObjB)); /* Compare types */ return ObjA->getType() > ObjB->getType(); } static bool compareRenderNodesMeshBuffer(RenderNode* ObjA, RenderNode* ObjB) { /* Compare visiblity */ if (ObjA->getVisible() != ObjB->getVisible()) return ObjA->getVisible(); /* Compare mesh nodes */ if (ObjA->getType() == NODE_MESH && ObjB->getType() == NODE_MESH) return static_cast<Mesh*>(ObjA)->compareMeshBuffers(static_cast<Mesh*>(ObjB)); /* Compare types */ return ObjA->getType() > ObjB->getType(); } /* * SceneGraph class */ bool SceneGraph::ReverseDepthSorting_ = false; SceneGraph::SceneGraph(const ESceneGraphs Type) : RenderNode (NODE_SCENEGRAPH ), GraphType_ (Type ), hasChildTree_ (false ), ActiveCamera_ (0 ), ActiveMesh_ (0 ), WireframeFront_ (video::WIREFRAME_SOLID ), WireframeBack_ (video::WIREFRAME_SOLID ), DepthSorting_ (true ), LightSorting_ (true ) { } SceneGraph::~SceneGraph() { } void SceneGraph::addSceneNode(SceneNode* Object) { if (Object) NodeList_.push_back(Object); } void SceneGraph::removeSceneNode(SceneNode* Object) { MemoryManager::removeElement(NodeList_, Object); } void SceneGraph::addSceneNode(Camera* Object) { if (Object) CameraList_.push_back(Object); } void SceneGraph::removeSceneNode(Camera* Object) { MemoryManager::removeElement(CameraList_, Object); } void SceneGraph::addSceneNode(Light* Object) { if (Object) LightList_.push_back(Object); } void SceneGraph::removeSceneNode(Light* Object) { MemoryManager::removeElement(LightList_, Object); } void SceneGraph::addSceneNode(RenderNode* Object) { if (Object) RenderList_.push_back(Object); } void SceneGraph::removeSceneNode(RenderNode* Object) { MemoryManager::removeElement(RenderList_, Object); } void SceneGraph::addRootNode(SceneNode* Object) { // do nothing } void SceneGraph::removeRootNode(SceneNode* Object) { // do nothing } SceneNode* SceneGraph::createNode() { SceneNode* NewSceneNode = gSharedObjects.SceneMngr->createNode(); addSceneNode(NewSceneNode); return NewSceneNode; } Mesh* SceneGraph::createMesh() { return integrateNewMesh(gSharedObjects.SceneMngr->createMesh()); } Mesh* SceneGraph::createMesh(const EBasicMeshes Model, const SMeshConstruct &BuildConstruct) { return integrateNewMesh(gSharedObjects.SceneMngr->createMesh(Model, BuildConstruct)); } Mesh* SceneGraph::createSuperShape(const f32 (&ValueList)[12], s32 Detail) { return integrateNewMesh(gSharedObjects.SceneMngr->createSuperShape(ValueList, Detail)); } Mesh* SceneGraph::createSkyBox(video::Texture* (&TextureList)[6], f32 Radius) { return integrateNewMesh(gSharedObjects.SceneMngr->createSkyBox(TextureList, Radius)); } Mesh* SceneGraph::createHeightField(const video::Texture* TexHeightMap, const s32 Segments) { return integrateNewMesh(gSharedObjects.SceneMngr->createHeightField(TexHeightMap, Segments)); } Mesh* SceneGraph::createMeshList(std::list<Mesh*> MergeList, bool isOldDelete) { return integrateNewMesh(gSharedObjects.SceneMngr->createMeshList(MergeList, isOldDelete)); } Mesh* SceneGraph::createMeshSurface(Mesh* Model, u32 Surface) { return integrateNewMesh(gSharedObjects.SceneMngr->createMeshSurface(Model, Surface)); } Mesh* SceneGraph::loadMesh(const io::stringc &Filename, const io::stringc &TexturePath, const EMeshFileFormats Format, const s32 Flags) { return integrateNewMesh(gSharedObjects.SceneMngr->loadMesh(Filename, TexturePath, Format, Flags)); } bool SceneGraph::saveMesh(Mesh* Model, const io::stringc &Filename, const EMeshFileFormats Format) { return gSharedObjects.SceneMngr->saveMesh(Model, Filename, Format); } Mesh* SceneGraph::loadScene( const io::stringc &Filename, const io::stringc &TexturePath, const ESceneFileFormats Format, const s32 Flags) { return integrateNewMesh(gSharedObjects.SceneMngr->loadScene(Filename, TexturePath, Format, Flags)); } Mesh* SceneGraph::getMesh(const io::stringc &Filename, const io::stringc &TexturePath, const EMeshFileFormats Format) { return integrateNewMesh(gSharedObjects.SceneMngr->getMesh(Filename, TexturePath, Format)); } Light* SceneGraph::createLight(const ELightModels Type) { Light* NewLight = gSharedObjects.SceneMngr->createLight(Type); addSceneNode(NewLight); return NewLight; } Billboard* SceneGraph::createBillboard(video::Texture* BaseTexture) { Billboard* NewBillboard = gSharedObjects.SceneMngr->createBillboard(BaseTexture); addSceneNode(NewBillboard); return NewBillboard; } Camera* SceneGraph::createCamera() { Camera* NewCamera = gSharedObjects.SceneMngr->createCamera(); addSceneNode(NewCamera); return NewCamera; } Terrain* SceneGraph::createTerrain( const video::SHeightMapTexture &TextureHeightMap, const dim::size2di &Resolution, s32 GeoMIPLevels) { Terrain* NewTerrain = gSharedObjects.SceneMngr->createTerrain(TextureHeightMap, Resolution, GeoMIPLevels); addSceneNode(NewTerrain); return NewTerrain; } void SceneGraph::renderScene() { foreach (Camera* Cam, CameraList_) { if (Cam->getVisible()) renderScene(Cam); } } void SceneGraph::renderScene(Camera* ActiveCamera) { /* Configure view to the current active camera */ setActiveCamera(ActiveCamera); if (ActiveCamera) ActiveCamera->setupRenderView(); spWorldMatrix.reset(); /* Render the scene graph */ GlbRenderSys->setRenderMode(video::RENDERMODE_SCENE); { render(); } GlbRenderSys->setRenderMode(video::RENDERMODE_NONE); } void SceneGraph::renderScenePlain(Camera* ActiveCamera) { if (ActiveCamera) renderScene(ActiveCamera); else renderScene(); } /* Renders the whole scene as a stereo image You can use '3d glaces' because this scene will renderd two times in a red and a green color mask */ void SceneGraph::renderSceneStereoImage(Camera* ActiveCamera, f32 CamDegree, f32 CamDist) { if (!ActiveCamera) return; /* Temporary variables and static members */ static video::Texture* StereoImageA, * StereoImageB; const dim::size2di ScrSize(gSharedObjects.ScreenWidth, gSharedObjects.ScreenHeight); video::Texture* CurRenderTarget = GlbRenderSys->getRenderTarget(); if (!StereoImageA) { StereoImageA = GlbRenderSys->createTexture(ScrSize); StereoImageA->setMipMapping(false); StereoImageA->setMinMagFilter(video::FILTER_LINEAR); StereoImageA->setRenderTarget(true); StereoImageB = GlbRenderSys->createTexture(ScrSize); StereoImageB->setMipMapping(false); StereoImageB->setMinMagFilter(video::FILTER_LINEAR); StereoImageB->setRenderTarget(true); } /* Red color scene */ GlbRenderSys->setRenderTarget(StereoImageA); GlbRenderSys->setColorMask(true, true, true, true); GlbRenderSys->clearBuffers(); GlbRenderSys->setColorMask(false, true, false, true); { ActiveCamera->move(dim::vector3df(CamDist, 0, 0)); ActiveCamera->turn(dim::vector3df(0, CamDegree, 0)); } renderScene(ActiveCamera); /* Green color scene */ GlbRenderSys->setRenderTarget(StereoImageB); GlbRenderSys->setColorMask(true, true, true, true); GlbRenderSys->clearBuffers(); GlbRenderSys->setColorMask(true, false, false, true); { ActiveCamera->turn(dim::vector3df(0, -CamDegree, 0)); ActiveCamera->move(dim::vector3df(-CamDist*2, 0, 0)); ActiveCamera->turn(dim::vector3df(0, -CamDegree, 0)); } renderScene(ActiveCamera); GlbRenderSys->setRenderTarget(CurRenderTarget); GlbRenderSys->setColorMask(true, true, true, true); GlbRenderSys->clearBuffers(); { ActiveCamera->turn(dim::vector3df(0, CamDegree, 0)); ActiveCamera->move(dim::vector3df(CamDist, 0, 0)); } /* Drawing */ const dim::rect2df Clipping(0, 0, 1, 1); GlbRenderSys->draw2DImage( StereoImageA, dim::rect2di(0, 0, ScrSize.Width, ScrSize.Height), Clipping ); GlbRenderSys->draw2DImage( StereoImageB, dim::rect2di(0, 0, ScrSize.Width, ScrSize.Height), Clipping, video::color(255, 255, 255, 128) ); } void SceneGraph::clearScene( bool isRemoveNodes, bool isRemoveMeshes, bool isRemoveCameras, bool isRemoveLights, bool isRemoveBillboards, bool isRemoveTerrains) { if (isRemoveNodes) NodeList_.clear(); if (isRemoveCameras) CameraList_.clear(); if (isRemoveLights) LightList_.clear(); if (isRemoveMeshes && isRemoveBillboards && isRemoveTerrains) RenderList_.clear(); else { //todo RenderList_.clear(); #ifdef SP_DEBUGMODE io::Log::debug("SceneGraph::clearScene", "TODO (isRemoveMeshes || isRemoveBillboards || isRemoveTerrains)"); #endif } } SceneNode* SceneGraph::copyNode(const SceneNode* Object) { SceneNode* NewObject = gSharedObjects.SceneMngr->copyNode(Object); addSceneNode(NewObject); return NewObject; } Mesh* SceneGraph::copyNode(const Mesh* Object) { Mesh* NewObject = gSharedObjects.SceneMngr->copyNode(Object); addSceneNode(NewObject); return NewObject; } Light* SceneGraph::copyNode(const Light* Object) { Light* NewObject = gSharedObjects.SceneMngr->copyNode(Object); addSceneNode(NewObject); return NewObject; } Billboard* SceneGraph::copyNode(const Billboard* Object) { Billboard* NewObject = gSharedObjects.SceneMngr->copyNode(Object); addSceneNode(NewObject); return NewObject; } Camera* SceneGraph::copyNode(const Camera* Object) { Camera* NewObject = gSharedObjects.SceneMngr->copyNode(Object); addSceneNode(NewObject); return NewObject; } Terrain* SceneGraph::copyNode(const Terrain* Object) { /*Terrain* NewObject = gSharedObjects.SceneMngr->copyNode(Object); addSceneNode(NewObject); return NewObject;*/ return 0; } bool SceneGraph::deleteNode(SceneNode* Object) { if (Object) { switch (Object->getType()) { case NODE_CAMERA: removeSceneNode(static_cast<Camera*>(Object)); break; case NODE_LIGHT: removeSceneNode(static_cast<Light*>(Object)); break; case NODE_MESH: case NODE_BILLBOARD: case NODE_TERRAIN: case NODE_SCENEGRAPH: removeSceneNode(static_cast<RenderNode*>(Object)); break; default: removeSceneNode(Object); break; } gSharedObjects.SceneMngr->deleteNode(Object); } return false; } std::list<SceneNode*> SceneGraph::findNodes(const io::stringc &Name) const { std::list<SceneNode*> NodeList; addNodeToList<SceneNode ,SceneNode> (Name, NodeList, NodeList_ ); addNodeToList<Camera, Camera> (Name, NodeList, CameraList_); addNodeToList<Light, Light> (Name, NodeList, LightList_ ); addNodeToList<Mesh, RenderNode> (Name, NodeList, RenderList_); addNodeToList<Billboard, RenderNode>(Name, NodeList, RenderList_); addNodeToList<Terrain, RenderNode> (Name, NodeList, RenderList_); return NodeList; } SceneNode* SceneGraph::findNode(const io::stringc &Name) const { SceneNode* Object = 0; if ( ( Object = findNodeInList<SceneNode> (Name, NodeList_ ) ) != 0 ) return Object; if ( ( Object = findNodeInList<Camera> (Name, CameraList_ ) ) != 0 ) return Object; if ( ( Object = findNodeInList<Light> (Name, LightList_ ) ) != 0 ) return Object; if ( ( Object = findNodeInList<RenderNode> (Name, RenderList_ ) ) != 0 ) return Object; if ( ( Object = findNodeInList<RenderNode> (Name, RenderList_ ) ) != 0 ) return Object; if ( ( Object = findNodeInList<RenderNode> (Name, RenderList_ ) ) != 0 ) return Object; return 0; } std::vector<SceneNode*> SceneGraph::findChildren(const SceneNode* ParentNode) const { std::vector<SceneNode*> NodeList; addChildToList<SceneNode> (ParentNode, NodeList, NodeList_ ); addChildToList<Camera> (ParentNode, NodeList, CameraList_ ); addChildToList<Light> (ParentNode, NodeList, LightList_ ); addChildToList<RenderNode> (ParentNode, NodeList, RenderList_ ); return NodeList; } SceneNode* SceneGraph::findChild(const SceneNode* ParentNode, const io::stringc &Name) const { SceneNode* Child = 0; if ( ( Child = findChildInList<SceneNode> (ParentNode, NodeList_, Name) ) != 0 ) return Child; if ( ( Child = findChildInList<Camera> (ParentNode, CameraList_, Name) ) != 0 ) return Child; if ( ( Child = findChildInList<Light> (ParentNode, LightList_, Name) ) != 0 ) return Child; if ( ( Child = findChildInList<RenderNode> (ParentNode, RenderList_, Name) ) != 0 ) return Child; if ( ( Child = findChildInList<RenderNode> (ParentNode, RenderList_, Name) ) != 0 ) return Child; if ( ( Child = findChildInList<RenderNode> (ParentNode, RenderList_, Name) ) != 0 ) return Child; return 0; } std::list<Mesh*> SceneGraph::getMeshList() const { return filterRenderNodeList<Mesh>(scene::NODE_MESH); } std::list<Billboard*> SceneGraph::getBillboardList() const { return filterRenderNodeList<Billboard>(scene::NODE_BILLBOARD); } std::list<Terrain*> SceneGraph::getTerrainList() const { return filterRenderNodeList<Terrain>(scene::NODE_TERRAIN); } void SceneGraph::setWireframe(const video::EWireframeTypes Type) { WireframeFront_ = WireframeBack_ = Type; foreach (RenderNode* Obj, RenderList_) { if (Obj->getType() == NODE_MESH || Obj->getType() == NODE_BILLBOARD || Obj->getType() == NODE_TERRAIN) static_cast<MaterialNode*>(Obj)->getMaterial()->setWireframe(Type); } } void SceneGraph::setWireframe(const video::EWireframeTypes TypeFront, const video::EWireframeTypes TypeBack) { WireframeFront_ = TypeFront; WireframeBack_ = TypeBack; foreach (Mesh* Obj, getMeshList()) Obj->getMaterial()->setWireframe(WireframeFront_, WireframeBack_); } void SceneGraph::setRenderFace(const video::EFaceTypes Face) { foreach (Mesh* Obj, getMeshList()) Obj->getMaterial()->setRenderFace(Face); } void SceneGraph::setLighting(bool isLighting) { //!TODO! -> make this a member variable and not a global state __isLighting = isLighting; } bool SceneGraph::getLighting() const { return __isLighting; } /* === Static functions: === */ void SceneGraph::setReverseDepthSorting(bool Enable) { ReverseDepthSorting_ = Enable; } bool SceneGraph::getReverseDepthSorting() { return ReverseDepthSorting_; } u32 SceneGraph::getSceneMeshBufferCount() const { u32 SurfaceCount = 0; foreach (Mesh* Obj, getMeshList()) SurfaceCount += Obj->getMeshBufferCount(); return SurfaceCount; } u32 SceneGraph::getSceneVertexCount() const { u32 VertexCount = 0; foreach (Mesh* Obj, getMeshList()) VertexCount += Obj->getVertexCount(); return VertexCount; } u32 SceneGraph::getSceneTriangleCount() const { u32 TriangleCount = 0; foreach (Mesh* Obj, getMeshList()) TriangleCount += Obj->getTriangleCount(); return TriangleCount; } u32 SceneGraph::getSceneObjectsCount() const { return NodeList_.size() + CameraList_.size() + LightList_.size() + RenderList_.size(); } void SceneGraph::sortRenderList(const ERenderListSortMethods Method, std::vector<RenderNode*> &ObjectList) { switch (Method) { case RENDERLIST_SORT_DEPTHDISTANCE: std::sort(ObjectList.begin(), ObjectList.end(), compareRenderNodesDepthDistance); break; case RENDERLIST_SORT_MESHBUFFER: std::sort(ObjectList.begin(), ObjectList.end(), compareRenderNodesMeshBuffer); break; default: break; } } void SceneGraph::sortRenderList(const ERenderListSortMethods Method) { sortRenderList(Method, RenderList_); } /* * ======= Protected: ======= */ Mesh* SceneGraph::integrateNewMesh(Mesh* NewMesh) { if (NewMesh) { NewMesh->getMaterial()->setWireframe(WireframeFront_, WireframeBack_); addSceneNode(dynamic_cast<RenderNode*>(NewMesh)); } return NewMesh; } void SceneGraph::arrangeRenderList(std::vector<RenderNode*> &ObjectList, const dim::matrix4f &BaseMatrix) { if (ActiveCamera_) ActiveCamera_->updateTransformation(); foreach (RenderNode* Obj, ObjectList) { if (Obj->getVisible()) Obj->updateTransformationBase(BaseMatrix); } if (DepthSorting_) sortRenderList(RENDERLIST_SORT_DEPTHDISTANCE, ObjectList); } void SceneGraph::arrangeLightList(std::vector<Light*> &ObjectList) { const u32 MaxLightCount = static_cast<u32>(GlbRenderSys->getMaxLightCount()); if (ObjectList.size() <= MaxLightCount) return; /* Sort light list */ std::sort(ObjectList.begin(), ObjectList.end(), cmpObjectLights); /* Update renderer lights for the first [MaxLightCount] objects */ //if (!RenderFixedFunctionOnly || !GlbRenderSys->getGlobalShaderClass()) if (!GlbRenderSys->getGlobalShaderClass()) { u32 LightID = 0; video::color Diffuse, Ambient, Specular; foreach (Light* Obj, ObjectList) { Obj->LightID_ = LightID; /* Update light colors */ Obj->getLightingColor(Diffuse, Ambient, Specular); GlbRenderSys->setLightColor(LightID, Diffuse, Ambient, Specular); /* Update light status */ GlbRenderSys->setLightStatus(LightID, Obj->getVisible()); if (++LightID >= MaxLightCount) break; } } } void SceneGraph::renderLightsDefault(const dim::matrix4f &BaseMatrix, bool RenderFixedFunctionOnly) { if (LightSorting_) arrangeLightList(LightList_); if (!RenderFixedFunctionOnly || !GlbRenderSys->getGlobalShaderClass()) { s32 LightIndex = 0; foreach (Light* Node, LightList_) { if (!Node->getVisible()) continue; if (++LightIndex > MAX_COUNT_OF_LIGHTS) break; spWorldMatrix = BaseMatrix; Node->render(); } } } void SceneGraph::finishRenderScene() { GlbRenderSys->endSceneRendering(); } } // /namespace scene } // /namespace sp // ================================================================================
29.461219
135
0.668939
[ "mesh", "render", "object", "vector", "model", "3d" ]
7f52a75b99ed833411237525bcf0ad9bc6288d40
4,761
hpp
C++
src/utils/string.hpp
Youka/SSBRenderer_rework
a42aa7f90819f8dddd2073d5c971f74b36c97380
[ "Zlib" ]
7
2015-06-21T14:35:16.000Z
2021-08-30T12:00:52.000Z
src/utils/string.hpp
Youka/SSBRenderer_rework
a42aa7f90819f8dddd2073d5c971f74b36c97380
[ "Zlib" ]
1
2017-02-28T14:09:43.000Z
2017-03-02T06:55:19.000Z
src/utils/string.hpp
Youka/SSBRenderer_rework
a42aa7f90819f8dddd2073d5c971f74b36c97380
[ "Zlib" ]
1
2015-12-09T18:22:09.000Z
2015-12-09T18:22:09.000Z
/* Project: SSBRenderer File: string.hpp Copyright (c) 2015, Christoph "Youka" Spanknebel 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. */ #pragma once #include <sstream> #include <vector> namespace stdex{ // Converts string to number template<typename T> static inline bool string_to_number(const std::string& src, T& dst){ std::istringstream s(src); return s >> std::noskipws >> dst && s.eof(); } // Converts string to number pair template<typename T> static inline bool string_to_number(const std::string& src, T& dst1, T& dst2){ std::string::size_type pos; return (pos = src.find(',')) != std::string::npos && string_to_number(src.substr(0, pos), dst1) && string_to_number(src.substr(pos+1), dst2); } // Converts hex string to number template<typename T> static inline bool hex_string_to_number(const std::string& src, T& dst){ std::istringstream s(src); return s >> std::noskipws >> std::hex >> dst && s.eof(); } // Converts hex string to number pair template<typename T> static inline bool hex_string_to_number(const std::string& src, T& dst1, T& dst2){ std::string::size_type pos; return (pos = src.find(',')) != std::string::npos && hex_string_to_number(src.substr(0, pos), dst1) && hex_string_to_number(src.substr(pos+1), dst2); } // Converts hex string to four numbers template<typename T> static inline bool hex_string_to_number(const std::string& src, T& dst1, T& dst2, T& dst3, T& dst4){ std::string::size_type pos1, pos2; return (pos1 = src.find(',')) != std::string::npos && hex_string_to_number(src.substr(0, pos1), dst1) && (pos2 = src.find(',', pos1+1)) != std::string::npos && hex_string_to_number(src.substr(pos1+1, pos2-(pos1+1)), dst2) && (pos1 = src.find(',', pos2+1)) != std::string::npos && hex_string_to_number(src.substr(pos2+1, pos1-(pos2+1)), dst3) && hex_string_to_number(src.substr(pos1+1), dst4); } // Find character in string which isn't escaped by character '\' static inline std::string::size_type find_non_escaped_character(const std::string& s, const char c, const std::string::size_type pos_start = 0){ std::string::size_type pos_end; for(auto search_pos_start = pos_start; (pos_end = s.find(c, search_pos_start)) != std::string::npos && pos_end > 0 && s[pos_end-1] == '\\'; search_pos_start = pos_end + 1); return pos_end; } // Replaces subtext static inline std::string& string_replace(std::string& s, std::string find, std::string repl){ for(std::string::size_type pos = 0; (pos = s.find(find, pos)) != std::string::npos; pos+=repl.length()) s.replace(pos, find.length(), repl); return s; } // Splits text to words struct WordData{ size_t prespace; std::string text; }; static inline std::vector<WordData> get_words(const std::string& s){ std::vector<WordData> words; if(!s.empty()){ std::string::size_type pos_begin = 0, pos_end; bool search_prespace = true; do{ if(search_prespace) pos_end = s.find_first_not_of(" \t\n\r", pos_begin), words.push_back({pos_end == std::string::npos ? s.length() - pos_begin : pos_end - pos_begin, ""}); else pos_end = s.find_first_of(" \t\n\r", pos_end), words.back().text = s.substr(pos_begin, pos_end == std::string::npos ? std::string::npos : pos_end - pos_begin); search_prespace = !search_prespace, pos_begin = pos_end; }while(pos_end != std::string::npos); } return words; } // Checks stream for the last line after delimiter being empty static inline bool has_empty_last_line(std::istream& str, const char delimiter){ if(!str.bad()){ if(str.eof()){ str.clear(); if(str.unget() && str.get() == delimiter) return true; }else{ auto pos = str.tellg(); str.seekg(0, std::istream::end); bool result = str.unget() && str.get() == delimiter; str.clear(), str.seekg(pos); return result; } } return false; } } #define STR_LIT_EQU_FIRST(s, s2) (s.compare(0, sizeof(s2)-1, s2) == 0)
38.088
247
0.6862
[ "vector" ]
7f53dc28d280ac7bafa3119353ea4178bd9c0431
780
cpp
C++
STL/vectors.cpp
Radix1/tcs-digital-prep
0c1728363f328a1eca1189f20e27c2b173e6ba57
[ "MIT" ]
112
2019-03-15T20:50:22.000Z
2022-03-29T07:25:31.000Z
STL/vectors.cpp
Radix1/tcs-digital-prep
0c1728363f328a1eca1189f20e27c2b173e6ba57
[ "MIT" ]
2
2019-10-20T17:01:27.000Z
2020-10-02T09:30:12.000Z
STL/vectors.cpp
Radix1/tcs-digital-prep
0c1728363f328a1eca1189f20e27c2b173e6ba57
[ "MIT" ]
42
2019-05-16T15:43:21.000Z
2022-03-10T08:11:49.000Z
/** Playing with vectors */ #include <iostream> #include <vector> using namespace std; int main(void) { // Create a vector with containing 0, 10, 20, ..., 90 vector<int> v1(10); for (int i = 0; i < v1.size(); i++) v1[i] = i*10; // Print the elements cout << "Elements of vector v1:" << endl; for (int i = 0; i < v1.size(); i++) cout << v1[i] << " "; cout << endl; // Add a new element at its end, and print it v1.push_back(55); cout << "New element added: " << v1[v1.size()-1] << endl; // Resize so v1 could contain 15 elements v1.resize(15); // Copy this resized vector into another vector v2 vector <int> v2(v1); cout << "\nElements of new vector v2:" << endl; for (int i = 0; i < v2.size(); i++) cout << v2[i] << " "; cout << endl; return 0; }
21.081081
58
0.584615
[ "vector" ]
7f62da0fd546870cc924af6aa86a3b778dd3d078
1,258
cpp
C++
Data-Structures/week1_basic_data_structures/3_network_simulation/process_packages.cpp
ChristineHu1207/Coursera-Data-Structures-and-Algorithms-Specialization
27f543ca0778d00ffd624ffcd18bf555660e0168
[ "MIT" ]
1
2018-10-22T09:29:16.000Z
2018-10-22T09:29:16.000Z
Data-Structures/week1_basic_data_structures/3_network_simulation/process_packages.cpp
ChristineHu1207/Coursera-Data-Structures-and-Algorithms-Specialization
27f543ca0778d00ffd624ffcd18bf555660e0168
[ "MIT" ]
null
null
null
Data-Structures/week1_basic_data_structures/3_network_simulation/process_packages.cpp
ChristineHu1207/Coursera-Data-Structures-and-Algorithms-Specialization
27f543ca0778d00ffd624ffcd18bf555660e0168
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <vector> #include <string> #include <algorithm> #include <queue> #define MAX(x,y) ((x)>(y)?(x):(y)) #define MIN(x,y) ((x)<(y)?(x):(y)) #define pb push_back #define mp make_pair #define rep(i,n) for(i=0;i<n;i++) #define repr(i,j,n) for(i=j;i<=n;i++) #define endl '\n' using namespace std; typedef long long ll; typedef vector<ll> vll; typedef vector<vector<int> > graph; const ll maxn = (ll) 1e5+9; const ll mod = (ll) 1e9+7; //ll a[maxn]; //ll dp[1024][1024]; int main() { std::ios::sync_with_stdio(0); int i,j,k,t,m,l,r,n; int S; cin>>S>>n; queue<pair<int, pair<int, int> > > q; vector<pair<int, pair<int, int> > > v(n); rep(i, n){ cin>>j>>k; v[i]=mp(i, mp(j,k)); } vector<int> res(n); j=0; while(j<n && j<S){ q.push(v[j]); j++; } t=0; while(!q.empty()){ int st=MAX(t, q.front().second.first); t = st+q.front().second.second; res[q.front().first]=st; q.pop(); while(q.size()<S && j<n){ if(v[j].second.first<t){ res[j++]=-1; }else{ q.push(v[j++]); } } } rep(i, n){ cout<<res[i]<<endl; } }
20.290323
46
0.491256
[ "vector" ]
7f639ffc23c74415659cdf1d50f8a6237bf40593
10,570
cpp
C++
global_body_planner/src/gbpl.cpp
robomechanics/quad-software
89154df18e98162249f38301b669df27ee595220
[ "MIT" ]
20
2021-12-05T03:40:28.000Z
2022-03-30T02:53:56.000Z
global_body_planner/src/gbpl.cpp
robomechanics/rml-spirit-firmware
89154df18e98162249f38301b669df27ee595220
[ "MIT" ]
45
2021-12-06T12:45:05.000Z
2022-03-31T22:15:47.000Z
global_body_planner/src/gbpl.cpp
robomechanics/rml-spirit-firmware
89154df18e98162249f38301b669df27ee595220
[ "MIT" ]
2
2021-12-06T03:20:15.000Z
2022-02-20T04:19:41.000Z
#include "global_body_planner/gbpl.h" using namespace planning_utils; GBPL::GBPL() {} int GBPL::connect(PlannerClass &T, State s, const PlannerConfig &planner_config, int direction, ros::Publisher &tree_pub) { // Find nearest neighbor flipDirection(s); int s_near_index = T.getNearestNeighbor(s); State s_near = T.getVertex(s_near_index); StateActionResult result; // Try to connect to nearest neighbor, add to graph if REACHED or ADVANCED int connect_result = attemptConnect(s_near, s, result, planner_config, direction); if (connect_result != TRAPPED) { int s_new_index = T.getNumVertices(); T.addVertex(s_new_index, result.s_new); T.addEdge(s_near_index, s_new_index, result.length); T.addAction(s_new_index, result.a_new); #ifdef VISUALIZE_TREE publishStateActionPair(s_near, result.a_new, s, planner_config, tree_viz_msg_, tree_pub); #endif } return connect_result; } std::vector<Action> GBPL::getActionSequenceReverse(PlannerClass &T, std::vector<int> path) { // Assumes that actions are synched with the states at which they are executed // (opposite of the definition in RRT) std::vector<Action> action_sequence; for (int i = 0; i < path.size() - 1; ++i) { action_sequence.push_back(T.getAction(path.at(i))); } return action_sequence; } void GBPL::postProcessPath(std::vector<State> &state_sequence, std::vector<Action> &action_sequence, const PlannerConfig &planner_config) { auto t_start = std::chrono::steady_clock::now(); // Initialize first and last states State s_goal = state_sequence.back(); State s = state_sequence.front(); State s_next; State dummy; Action a_new; Action a_next; // Initialize state and action sequences std::vector<State> new_state_sequence; new_state_sequence.push_back(s); std::vector<Action> new_action_sequence; path_length_ = 0; // Iterate until the goal has been added to the state sequence while (s != s_goal) { // Make a copy of the original state and action sequences std::vector<State> state_sequence_copy = state_sequence; std::vector<Action> action_sequence_copy = action_sequence; // Start at the back of the sequence s_next = state_sequence_copy.back(); a_next = action_sequence_copy.back(); State old_state; Action old_action; StateActionResult result; // Try to connect to the last state in the sequence // if unsuccesful remove the back and try again until successful or no // states left while ((attemptConnect(s, s_next, result, planner_config, FORWARD) != REACHED) && (s != s_next)) { old_state = s_next; old_action = a_next; state_sequence_copy.pop_back(); action_sequence_copy.pop_back(); s_next = state_sequence_copy.back(); a_next = action_sequence_copy.back(); } // If a new state was found add it to the sequence, otherwise add the next // state in the original sequence if (s != s_next) { new_state_sequence.push_back(s_next); new_action_sequence.push_back(result.a_new); path_length_ += result.length; s = s_next; } else { new_state_sequence.push_back(old_state); new_action_sequence.push_back(old_action); // Recompute path length isValidStateActionPair(old_state, old_action, result, planner_config); path_length_ += result.length; s = old_state; } } // Replace the old state and action sequences with the new ones state_sequence = new_state_sequence; action_sequence = new_action_sequence; auto t_end = std::chrono::steady_clock::now(); std::chrono::duration<double> processing_time = t_end - t_start; } void GBPL::extractPath(PlannerClass &Ta, PlannerClass &Tb, std::vector<State> &state_sequence, std::vector<Action> &action_sequence, const PlannerConfig &planner_config) { // Get both paths, remove the back of path_b and reverse it to align with path // a std::vector<int> path_a = pathFromStart(Ta, Ta.getNumVertices() - 1); std::vector<int> path_b = pathFromStart(Tb, Tb.getNumVertices() - 1); std::reverse(path_b.begin(), path_b.end()); std::vector<Action> action_sequence_b = getActionSequenceReverse(Tb, path_b); for (int i = 0; i < action_sequence_b.size(); i++) { flipDirection(action_sequence_b[i]); } path_b.erase(path_b.begin()); state_sequence = getStateSequence(Ta, path_a); std::vector<State> state_sequence_b = getStateSequence(Tb, path_b); for (int i = 0; i < state_sequence_b.size(); i++) { flipDirection(state_sequence_b[i]); } state_sequence.insert(state_sequence.end(), state_sequence_b.begin(), state_sequence_b.end()); action_sequence = getActionSequence(Ta, path_a); action_sequence.insert(action_sequence.end(), action_sequence_b.begin(), action_sequence_b.end()); // Post process to reduce the path length postProcessPath(state_sequence, action_sequence, planner_config); } void GBPL::extractClosestPath(PlannerClass &Ta, const State &s_goal, std::vector<State> &state_sequence, std::vector<Action> &action_sequence, const PlannerConfig &planner_config) { std::vector<int> path_a = pathFromStart(Ta, Ta.getNearestNeighbor(s_goal)); state_sequence = getStateSequence(Ta, path_a); action_sequence = getActionSequence(Ta, path_a); postProcessPath(state_sequence, action_sequence, planner_config); } int GBPL::findPlan(const PlannerConfig &planner_config, State s_start, State s_goal, std::vector<State> &state_sequence, std::vector<Action> &action_sequence, ros::Publisher &tree_pub) { // Perform validity checking on start and goal states if (!isValidState(s_start, planner_config, LEAP_STANCE)) { return INVALID_START_STATE; } // Set goal height to nominal distance above terrain s_goal.pos[2] = getTerrainZFromState(s_goal, planner_config) + planner_config.h_nom; if (!isValidState(s_goal, planner_config, LEAP_STANCE)) { return INVALID_GOAL_STATE; } if (poseDistance(s_start, s_goal) <= 1e-1) { return INVALID_START_GOAL_EQUAL; } // Initialize timing information auto t_start_total_solve = std::chrono::steady_clock::now(); auto t_start_current_solve = std::chrono::steady_clock::now(); int result; PlannerClass Ta(FORWARD, planner_config); PlannerClass Tb(REVERSE, planner_config); Ta.init(s_start); flipDirection(s_goal); Tb.init(s_goal); #ifdef VISUALIZE_TREE tree_viz_msg_.markers.clear(); tree_viz_msg_.markers.resize(1); #endif anytime_horizon_init = 0.01; anytime_horizon = std::max(poseDistance(s_start, s_goal) / planning_rate_estimate, anytime_horizon_init); while (ros::ok()) { auto t_current = std::chrono::steady_clock::now(); std::chrono::duration<double> total_elapsed = t_current - t_start_total_solve; std::chrono::duration<double> current_elapsed = t_current - t_start_current_solve; #ifndef VISUALIZE_TREE if (total_elapsed.count() >= planner_config.max_planning_time) { elapsed_to_first_ = total_elapsed; num_vertices_ = (Ta.getNumVertices() + Tb.getNumVertices()); break; } if (current_elapsed.count() >= anytime_horizon) { auto t_start_current_solve = std::chrono::steady_clock::now(); anytime_horizon = anytime_horizon * horizon_expansion_factor; Ta = PlannerClass(FORWARD, planner_config); Tb = PlannerClass(REVERSE, planner_config); tree_viz_msg_.markers.clear(); Ta.init(s_start); Tb.init(s_goal); continue; } #endif // Generate random s State s_rand = Ta.randomState(planner_config); if (isValidState(s_rand, planner_config, LEAP_STANCE)) { if (extend(Ta, s_rand, planner_config, FORWARD, tree_pub) != TRAPPED) { State s_new = Ta.getVertex(Ta.getNumVertices() - 1); #ifdef VISUALIZE_TREE Action a_new = Ta.getAction(Ta.getNumVertices() - 1); State s_parent = Ta.getVertex(Ta.getPredecessor(Ta.getNumVertices() - 1)); publishStateActionPair(s_parent, a_new, s_rand, planner_config, tree_viz_msg_, tree_pub); #endif if (connect(Tb, s_new, planner_config, FORWARD, tree_pub) == REACHED) { goal_found = true; auto t_end = std::chrono::steady_clock::now(); elapsed_to_first_ = t_end - t_start_total_solve; path_length_ = Ta.getGValue(Ta.getNumVertices() - 1) + Tb.getGValue(Tb.getNumVertices() - 1); break; } } } s_rand = Tb.randomState(planner_config); if (isValidState(s_rand, planner_config, LEAP_STANCE)) { if (extend(Tb, s_rand, planner_config, FORWARD, tree_pub) != TRAPPED) { State s_new = Tb.getVertex(Tb.getNumVertices() - 1); #ifdef VISUALIZE_TREE Action a_new = Tb.getAction(Tb.getNumVertices() - 1); State s_parent = Tb.getVertex(Tb.getPredecessor(Tb.getNumVertices() - 1)); publishStateActionPair(s_parent, a_new, s_rand, planner_config, tree_viz_msg_, tree_pub); #endif if (connect(Ta, s_new, planner_config, FORWARD, tree_pub) == REACHED) { goal_found = true; auto t_end = std::chrono::steady_clock::now(); elapsed_to_first_ = t_end - t_start_total_solve; path_length_ = Ta.getGValue(Ta.getNumVertices() - 1) + Tb.getGValue(Tb.getNumVertices() - 1); break; } } } } num_vertices_ = (Ta.getNumVertices() + Tb.getNumVertices()); if (goal_found == true) { extractPath(Ta, Tb, state_sequence, action_sequence, planner_config); result = VALID; } else { extractClosestPath(Ta, s_goal, state_sequence, action_sequence, planner_config); result = (state_sequence.size() > 1) ? VALID_PARTIAL : UNSOLVED; } auto t_end = std::chrono::steady_clock::now(); elapsed_total_ = t_end - t_start_total_solve; path_duration_ = 0.0; for (Action a : action_sequence) { path_duration_ += (a.t_s_leap + a.t_f + a.t_s_land); } dist_to_goal_ = poseDistance(s_goal, state_sequence.back()); return result; }
35.233333
80
0.666982
[ "vector" ]
7f662748468a437810893f812574213323e39217
1,785
cpp
C++
amr-wind/physics/multiphase/RainDrop.cpp
mchurchf/amr-wind
4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f
[ "BSD-3-Clause" ]
40
2019-11-27T15:38:45.000Z
2022-03-07T10:56:35.000Z
amr-wind/physics/multiphase/RainDrop.cpp
mchurchf/amr-wind
4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f
[ "BSD-3-Clause" ]
207
2019-11-07T22:53:02.000Z
2022-03-30T21:41:57.000Z
amr-wind/physics/multiphase/RainDrop.cpp
mchurchf/amr-wind
4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f
[ "BSD-3-Clause" ]
55
2019-11-08T19:25:08.000Z
2022-03-15T20:36:25.000Z
#include "amr-wind/physics/multiphase/RainDrop.H" #include "amr-wind/CFDSim.H" #include "AMReX_ParmParse.H" namespace amr_wind { RainDrop::RainDrop(CFDSim& sim) : m_velocity(sim.repo().get_field("velocity")) , m_levelset(sim.repo().get_field("levelset")) { amrex::ParmParse pp(identifier()); pp.queryarr("location", m_loc, 0, AMREX_SPACEDIM); pp.query("radius", m_radius); } /** Initialize the velocity and levelset fields at the beginning of the * simulation. * * \sa amr_wind::RainDropFieldInit */ void RainDrop::initialize_fields(int level, const amrex::Geometry& geom) { auto& velocity = m_velocity(level); auto& levelset = m_levelset(level); const auto& dx = geom.CellSizeArray(); const auto& problo = geom.ProbLoArray(); const amrex::Real xc = m_loc[0]; const amrex::Real yc = m_loc[1]; const amrex::Real zc = m_loc[2]; const amrex::Real radius = m_radius; for (amrex::MFIter mfi(velocity); mfi.isValid(); ++mfi) { const auto& vbx = mfi.validbox(); auto vel = velocity.array(mfi); auto phi = levelset.array(mfi); amrex::ParallelFor( vbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept { const amrex::Real x = problo[0] + (i + 0.5) * dx[0]; const amrex::Real y = problo[1] + (j + 0.5) * dx[1]; const amrex::Real z = problo[2] + (k + 0.5) * dx[2]; vel(i, j, k, 0) = 0.0; vel(i, j, k, 1) = 0.0; vel(i, j, k, 2) = 0.0; phi(i, j, k) = radius - std::sqrt( (x - xc) * (x - xc) + (y - yc) * (y - yc) + (z - zc) * (z - zc)); }); } } } // namespace amr_wind
32.454545
76
0.540616
[ "geometry" ]
7f6b4bb010f91b2f2ddda607e0400c253517db43
885
cpp
C++
SandBox/src/New/New.cpp
AmirrezaPayandeh/CPP
a24623339423333e61cd175558e8ecc122e7094b
[ "Apache-2.0" ]
null
null
null
SandBox/src/New/New.cpp
AmirrezaPayandeh/CPP
a24623339423333e61cd175558e8ecc122e7094b
[ "Apache-2.0" ]
null
null
null
SandBox/src/New/New.cpp
AmirrezaPayandeh/CPP
a24623339423333e61cd175558e8ecc122e7094b
[ "Apache-2.0" ]
null
null
null
// New #include <iostream> class NewEntity { private: int m_X; public: NewEntity(int var) :m_X(var) { std::cout << "Created NewEntity!\n"; } ~NewEntity() { std::cout << "Destroyed NewEntity!\n"; } void PrintX() const { std::cout << "X = " << m_X << std::endl; } }; void NewPrint() { // 'new' will allocate memory on heap when we create a new instance of a class. it will also automatically // call constructor for us. NewEntity* ne1 = new NewEntity(6); // always remember to delete your object. delete ne1; std::cout << "========================================" << std::endl; // if you already have a memory and just want to give it to your instance and call constructor for your // istance you can do this int* size = new int; std::cout << size << std::endl; NewEntity* ne2 = new(size) NewEntity(5); std::cout << ne2 << std::endl; ne2->PrintX(); delete ne2; }
26.818182
107
0.624859
[ "object" ]
7f7829fb28c9eb126d5890c1f2fdf86f88ab0247
968
hpp
C++
owl/scene/look_at_constraint.hpp
soerenkoenig/owl
ab10054514a7a5b12a6b81665b3b264cfe37b0f3
[ "MIT" ]
null
null
null
owl/scene/look_at_constraint.hpp
soerenkoenig/owl
ab10054514a7a5b12a6b81665b3b264cfe37b0f3
[ "MIT" ]
null
null
null
owl/scene/look_at_constraint.hpp
soerenkoenig/owl
ab10054514a7a5b12a6b81665b3b264cfe37b0f3
[ "MIT" ]
null
null
null
// // .___. // {o,o} // ./)_) // owl --"-"--- // // Copyright © 2017 Sören König. All rights reserved. // #pragma once #include "owl/scene/node.hpp" #include "owl/math/trafos.hpp" namespace owl { namespace scene { template<typename Scalar, typename Color> class look_at_constraint { public: look_at_constraint(node<Scalar, Color>& target) : target_(&target) { } void operator()(node<Scalar, Color>& n) { math::vector3<Scalar> center = target_->convert_position(math::vector<Scalar,3>::zero(),n.parent()); math::vector3<Scalar> eye = n.convert_position(math::vector<Scalar,3>::zero(),n.parent()); math::vector3<Scalar> up = n.convert_direction(math::vector<Scalar,3>::identity_y(), n.parent()); n.orientation = math::lookat<Scalar>(eye, center, up); } private: node<Scalar, Color>* target_; }; } }
22.511628
108
0.570248
[ "vector" ]
7f7cf54dfc322f4ab8b2ca644326c3c09ee93bb7
1,991
cpp
C++
class/native/internal_field_wrang/internal.cpp
Txiaozhe/js-modules
8ab65a0fce30430358b33d9e35c94a6c14843513
[ "MIT" ]
1
2018-09-14T13:51:56.000Z
2018-09-14T13:51:56.000Z
class/native/internal_field_wrang/internal.cpp
Txiaozhe/js-modules
8ab65a0fce30430358b33d9e35c94a6c14843513
[ "MIT" ]
7
2020-05-07T07:40:47.000Z
2020-05-07T07:40:57.000Z
class/native/internal_field_wrang/internal.cpp
Txiaozhe/js-modules
8ab65a0fce30430358b33d9e35c94a6c14843513
[ "MIT" ]
null
null
null
#include <node.h> namespace __internal{ using v8::FunctionCallbackInfo; using v8::HandleScope; using v8::FunctionTemplate; using v8::ObjectTemplate; using v8::Function; using v8::Isolate; using v8::Local; using v8::External; using v8::Object; using v8::String; using v8::Value; using v8::Number; using v8::Array; using v8::MaybeLocal; enum Gender { MALE, FEMALE }; struct Person { char name[256]; int age; Gender gender; }; void GetSummary(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Object> self = args.Holder(); Local<External> wrap = Local<External>::Cast(self->GetInternalField(0)); Person* person = static_cast<Person*>(wrap->Value()); char ret[512]; sprintf(ret, "%s, %s, %d, 岁", person->name, person->gender == MALE ? "男" : "女", person->age); MaybeLocal<String> summary = String::NewFromUtf8(isolate, ret); args.GetReturnValue().Set(summary.ToLocalChecked()); } void Init(Local<Object> exports, Local<Object> module) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); Local<ObjectTemplate> templ = ObjectTemplate::New(isolate); templ->SetInternalFieldCount(1); Person* person = new Person(); strcpy(person->name, "txj"); person->gender = Gender::MALE; person->age = 25; MaybeLocal<Object> dummy_obj = templ->NewInstance(); Local<Object> obj = dummy_obj.ToLocalChecked(); // 假设obj肯定不为空 obj->SetInternalField(0, External::New(isolate, person)); obj->Set((MaybeLocal<String>(String::NewFromUtf8(isolate, "getSummary"))).ToLocalChecked(), FunctionTemplate::New(isolate, GetSummary)->GetFunction()); module->Set(String::NewFromUtf8(isolate, "exports"), obj); } NODE_MODULE(_template, Init); }
29.279412
101
0.615269
[ "object" ]
7f8995b2033fe856c0c6ec21bd93f0e89c8421fd
105,160
cpp
C++
semargl3/n_mag_class.cpp
godsic/semargl3
09274ebd56a5ff7020d36c4943e51512d31458ac
[ "MIT" ]
2
2017-04-22T18:00:47.000Z
2019-04-17T22:41:30.000Z
semargl3/n_mag_class.cpp
godsic/semargl3
09274ebd56a5ff7020d36c4943e51512d31458ac
[ "MIT" ]
null
null
null
semargl3/n_mag_class.cpp
godsic/semargl3
09274ebd56a5ff7020d36c4943e51512d31458ac
[ "MIT" ]
2
2019-01-21T04:48:48.000Z
2019-08-14T09:44:00.000Z
#pragma unmanaged #include "n_probe.h" #include "n_mag_class.h" #include "n_common_func.h" #include "n_vfft.h" #include <stdio.h> #include <stdlib.h> #include <memory.h> #include <string.h> #include <omp.h> //#include <ppl.h> #include <memory.h> //using namespace Concurrency; cMagnetization::cMagnetization(SIMPARAMS* params) { // copy the simulations parameters SetSimulationParameters(params); // allocate the storage for the buffers long long size_xyzt_v1 = s_params.m_SizeX * s_params.m_SizeY * s_params.m_SizeZ * s_params.m_NumberOfTimeSteps; long long size_xyz_v3 = 3 * s_params.m_SizeX * s_params.m_SizeY * s_params.m_SizeZ; // 3 components vector of spatial distribution of M m_SizeOfDataBytes = sizeof(COMPLEX) * size_xyzt_v1; m_SizeOfDataElements = 2 * size_xyzt_v1; data = (COMPLEX*)new float[m_SizeOfDataElements]; static_data = new float[size_xyz_v3]; // initialize flags m_IsParametersLoaded = 1; m_IsKDomain = 0; m_IsFreqDomain = 0; m_IsAmpAndPhase = 0; m_IsLoaded = 0; } cMagnetization::cMagnetization() { m_SizeOfDataBytes = 0; m_IsParametersLoaded = 0; m_SizeOfDataElements = 0; m_IsKDomain = 0; m_IsFreqDomain = 0; m_IsAmpAndPhase = 0; m_IsLoaded = 0; } cMagnetization::~cMagnetization() { delete(data); delete(static_data); m_SizeOfDataBytes = 0; m_SizeOfDataElements = 0; m_IsKDomain = 0; m_IsFreqDomain = 0; m_IsAmpAndPhase = 0; m_IsLoaded = 0; } void cMagnetization::CleanBuffers() { delete(this->data); delete(this->static_data); delete(this->avgdata); delete(this->avgdata_fft); delete(this->layer_buff_2d); delete(this->layer_buff_3d); this->m_SizeOfDataBytes = 0; this->m_SizeOfDataElements = 0; this->m_IsKDomain = 0; this->m_IsFreqDomain = 0; this->m_IsAmpAndPhase = 0; this->m_IsLoaded = 0; } long long cMagnetization::ValidateRealData() { long long size_xyzt_v1 = (long long)s_params.m_SizeX * (long long)s_params.m_SizeY * (long long)s_params.m_SizeZ * (long long)s_params.m_NumberOfTimeSteps; for (long long i = 0; i < size_xyzt_v1;i++) { float Re = data[i].Re; float Img = data[i].Img; if(Re != Re) return 1; if(Img != Img) return 1; if(Img != 0.0f) return 1; } return 0; } long long cMagnetization::ValidateCMPXData() { long long size_xyzt_v1 = (long long)s_params.m_SizeX * (long long)s_params.m_SizeY * (long long)s_params.m_SizeZ * (long long)s_params.m_NumberOfTimeSteps; for (long long i = 0; i < size_xyzt_v1;i++) { float Re = data[i].Re; float Img = data[i].Img; if(Re != Re) return 1; if(Img != Img) return 1; } return 0; } void cMagnetization::AllocateBuffers() { long long size_xyzt_v1 = (long long)s_params.m_SizeX * (long long)s_params.m_SizeY * (long long)s_params.m_SizeZ * (long long)s_params.m_NumberOfTimeSteps; long long size_xyz_v3 = (long long)3 * (long long)s_params.m_SizeX * (long long)s_params.m_SizeY * (long long)s_params.m_SizeZ; // 3 components vector of spatial distribution of M m_SizeOfDataBytes = (long long)sizeof(COMPLEX) * size_xyzt_v1; m_SizeOfDataElements = (long long)2 * size_xyzt_v1; data = (COMPLEX*)new float[m_SizeOfDataElements]; static_data = new float[size_xyz_v3]; } void cMagnetization::AllocateAvgBuffer(long long sizex, long long sizey, long long sizez, long long sizet) { long long size = (long long)2 * (long long)sizex * (long long)sizey * (long long)sizez * (long long)sizet; avgdata = (COMPLEX*) new float[size]; m_asizeX = sizex; m_asizeY = sizey; m_asizeZ = sizez; m_asizeT = sizet; } void cMagnetization::AllocateAvgFFTBuffer(long long sizex, long long sizey, long long sizez, long long sizet) { long long size = (long long)2 * (long long)sizex * (long long)sizey * (long long)sizez * (long long)sizet; avgdata_fft = (COMPLEX*) new float[size]; m_asizeX = sizex; m_asizeY = sizey; m_asizeZ = sizez; m_asizeT = sizet; } void cMagnetization::Allocate2DLayerBuffer(long long sizex, long long sizey) { m_lsizeX = sizex; m_lsizeY = sizey; long long size = (long long)2 * (long long)sizex * (long long)sizey; layer_buff_2d = (COMPLEX*)new float[size]; } void cMagnetization::Allocate3DLayerBuffer(long long sizex, long long sizey, long long sizez) { m_lsizeX = sizex; m_lsizeY = sizey; m_lsizeZ = sizez; long long size = (long long)2 * (long long)sizex * (long long)sizey * (long long)sizez; layer_buff_3d = (COMPLEX*)new float[size]; } void cMagnetization::Destroy3DLayerBuffer() { delete[] layer_buff_3d; //m_lsizeX = 0; //m_lsizeY = 0; m_lsizeZ = 0; } void cMagnetization::SetSimulationParameters(SIMPARAMS *sim_params) { s_params.m_CellSizeX = sim_params->m_CellSizeX; s_params.m_CellSizeY = sim_params->m_CellSizeY; s_params.m_CellSizeZ = sim_params->m_CellSizeZ; s_params.m_MaxFrequency= sim_params->m_MaxFrequency; s_params.m_MaxInverseWavelengthX = sim_params->m_MaxInverseWavelengthX; s_params.m_MaxInverseWavelengthY = sim_params->m_MaxInverseWavelengthY; s_params.m_MaxInverseWavelengthZ = sim_params->m_MaxInverseWavelengthZ; s_params.m_MsCount = sim_params->m_MsCount; s_params.m_MsMax = sim_params->m_MsMax; s_params.m_NumberOfTimeSteps = sim_params->m_NumberOfTimeSteps; if (sim_params->m_pFolderWithTheData != NULL) { long long len = strlen(sim_params->m_pFolderWithTheData); //s_params.m_pFolderWithTheData = new char[len]; strcpy(s_params.m_pFolderWithTheData, sim_params->m_pFolderWithTheData); } if (sim_params->m_pMIFFileName != NULL) { long long len = strlen(sim_params->m_pMIFFileName); //s_params.m_pMIFFileName = new char[len]; strcpy(s_params.m_pMIFFileName, sim_params->m_pMIFFileName); } //s_params.m_pMs = new double[sim_params->m_MsCount]; for (long long i=0;i<sim_params->m_MsCount;i++) { s_params.m_pMs[i] = sim_params->m_pMs[i]; } if (sim_params->m_pStaticFileName != NULL) { long long len = strlen(sim_params->m_pStaticFileName); //s_params.m_pStaticFileName = new char[len]; strcpy(s_params.m_pStaticFileName, sim_params->m_pStaticFileName); } s_params.m_ResFrequency = sim_params->m_ResFrequency; s_params.m_ResInverseWavelengthX = sim_params->m_ResInverseWavelengthX; s_params.m_ResInverseWavelengthY = sim_params->m_ResInverseWavelengthY; s_params.m_ResInverseWavelengthZ = sim_params->m_ResInverseWavelengthZ; s_params.m_SimulationsTotalTime = sim_params->m_SimulationsTotalTime; s_params.m_SizeX = sim_params->m_SizeX; s_params.m_SizeY = sim_params->m_SizeY; s_params.m_SizeZ = sim_params->m_SizeZ; s_params.m_StageTime = sim_params->m_StageTime; } void cMagnetization::dbgDoDataAveraging() { if (data==NULL) return; long long xyz_size = s_params.m_SizeX * s_params.m_SizeY * s_params.m_SizeZ; avgdata = (COMPLEX*)new float[s_params.m_NumberOfTimeSteps]; float norm = 1.0 / xyz_size; for (long long k=0;k<s_params.m_NumberOfTimeSteps;k++) { long long addr = k * xyz_size; double avg = 0.0; for (long long i=0;i<xyz_size;i++) { avg += data[addr+i].Re; } avgdata[k].Re = (float)norm * (float)avg; } } void cMagnetization::SetParametersFlag() { m_IsParametersLoaded = 1; } void cMagnetization::ResetParametersFlag() { m_IsParametersLoaded = 0; } long long cMagnetization::GetParametersFlag() { return m_IsParametersLoaded; } void cMagnetization::Do1DAveraging(long long axis) { const long long sx = cProbe::sizeX; const long long sy = cProbe::sizeY; const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; long long size = 0; double norm = 0; switch(axis) { case 0: // averaging along the X direction; size = sy * sz * s_params.m_NumberOfTimeSteps; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! norm = 1.0 / sx; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long j = 0; j < sy; j++) { long long j1 = by + j; double avg_re = 0.0; double avg_img = 0.0; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); avg_re += cProbe::probe[paddr] * data[daddr].Re; avg_img += cProbe::probe[paddr] * data[daddr].Img; } avg_re *= norm; avg_img *= norm; long long aaddr = p_addr_xyz_v1(sy, sz, j, k, t); avgdata[aaddr].Re = avg_re; avgdata[aaddr].Img = avg_img; } } } m_asizeX = sy; m_asizeY = sz; m_asizeZ = st; break; case 1: // averaging along the Y direction; size = sx * sz * s_params.m_NumberOfTimeSteps; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! norm = 1.0 / sy; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; double avg_re = 0.0; double avg_img = 0.0; for (long long j = 0; j < sy; j++) { long long j1 = by + j; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); avg_re += cProbe::probe[paddr] * data[daddr].Re; avg_img += cProbe::probe[paddr] * data[daddr].Img; } long long aaddr = p_addr_xyz_v1(sx, sz, i, k, t); avg_re *= norm; avg_img *= norm; avgdata[aaddr].Re = (float)avg_re; avgdata[aaddr].Img = (float)avg_img; } } } m_asizeX = sx; m_asizeY = sz; m_asizeZ = st; break; case 2: // averaging along the Z direction; size = sx * sy * s_params.m_NumberOfTimeSteps; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! norm = 1.0 / sz; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long j = 0; j < sy; j++) { long long j1 = by + j; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < sz; k++) { long long k1 = bz + k; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); avg_re += cProbe::probe[paddr] * data[daddr].Re; avg_img += cProbe::probe[paddr] * data[daddr].Img; } long long aaddr = p_addr_xyz_v1(sx, sy, i, j, t); avg_re *= norm; avg_img *= norm; avgdata[aaddr].Re = (float)avg_re; avgdata[aaddr].Img = (float)avg_img; } } } m_asizeX = sx; m_asizeY = sy; m_asizeZ = st; break; } } void cMagnetization::Do1DAveragingInplace(long long axis) { // will write to bx, j, k; i, by, k; i, j, bz depends on the value of axis long long sx, sy, sz; if (m_isXavg == 1) sx = 1; else sx = cProbe::sizeX; if (m_isYavg == 1) sy = 1; else sy = cProbe::sizeY; if (m_isZavg == 1) sz = 1; else sz = cProbe::sizeZ; //const long long sx = cProbe::sizeX; //const long long sy = cProbe::sizeY; //const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; long long size = 0; double norm = 0.0; switch(axis) { case 0: // averaging along the X direction; norm = 1.0 / sx; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long j = 0; j < sy; j++) { long long j1 = by + j; double avg_re = 0.0; //FLOAT? double avg_img = 0.0; //FLOAT? for (long long i = 0; i <sx; i++) { long long i1 = bx + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); avg_re += data[daddr].Re; avg_img += data[daddr].Img; } avg_re *= norm; avg_img *= norm; long long naddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, bx, j1, k1, t); data[naddr].Re = avg_re; data[naddr].Img = avg_img; } } } m_isXavg = 1; break; case 1: // averaging along the Y direction; norm = 1.0 / sy; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; double avg_re = 0.0; double avg_img = 0.0; for (long long j = 0; j < sy; j++) { long long j1 = by + j; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); avg_re += data[daddr].Re; avg_img += data[daddr].Img; } long long naddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, by, k1, t); avg_re *= norm; avg_img *= norm; data[naddr].Re = (float)avg_re; data[naddr].Img = (float)avg_img; } } } m_isYavg = 1; break; case 2: // averaging along the Z direction; norm = 1.0 / sz; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long j = 0; j < sy; j++) { long long j1 = by + j; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < sz; k++) { long long k1 = bz + k; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); avg_re += data[daddr].Re; avg_img += data[daddr].Img; } long long naddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, bz, t); avg_re *= norm; avg_img *= norm; data[naddr].Re = (float)avg_re; data[naddr].Img = (float)avg_img; } } } m_isZavg = 1; break; } } void cMagnetization::Do1DAveragingInplaceParallel(long long axis) { // will write to bx, j, k; i, by, k; i, j, bz depends on the value of axis long long sx, sy, sz; if (m_isXavg == 1) sx = 1; else sx = cProbe::sizeX; if (m_isYavg == 1) sy = 1; else sy = cProbe::sizeY; if (m_isZavg == 1) sz = 1; else sz = cProbe::sizeZ; //const long long sx = cProbe::sizeX; //const long long sy = cProbe::sizeY; //const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; long long size = 0; double norm = 0.0; switch(axis) { case 0: // averaging along the X direction; norm = 1.0 / sx; //parallel_for(long long(0), sy, [&](long long j) #pragma omp parallel for for (long long j = 0; j < sy; j++) { long long j1 = by + j; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long k = 0; k < sz; k++) { long long k1 = bz + k; double avg_re = 0.0; //FLOAT? double avg_img = 0.0; //FLOAT? for (long long i = 0; i <sx; i++) { long long i1 = bx + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); avg_re += data[daddr].Re; avg_img += data[daddr].Img; } avg_re *= norm; avg_img *= norm; long long naddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, bx, j1, k1, t); data[naddr].Re = avg_re; data[naddr].Img = avg_img; } } }//); m_isXavg = 1; break; case 1: // averaging along the Y direction; norm = 1.0 / sy; //parallel_for(long long (0), sz, [&](long long k) #pragma omp parallel for for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long i = 0; i <sx; i++) { long long i1 = bx + i; double avg_re = 0.0; double avg_img = 0.0; for (long long j = 0; j < sy; j++) { long long j1 = by + j; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); avg_re += data[daddr].Re; avg_img += data[daddr].Img; } long long naddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, by, k1, t); avg_re *= norm; avg_img *= norm; data[naddr].Re = (float)avg_re; data[naddr].Img = (float)avg_img; } } }//); m_isYavg = 1; break; case 2: // averaging along the Z direction; norm = 1.0 / sz; //parallel_for(long long(0), sy, [&](long long j) #pragma omp parallel for for (long long j = 0; j < sy; j++) { long long j1 = by + j; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long i = 0; i <sx; i++) { long long i1 = bx + i; double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < sz; k++) { long long k1 = bz + k; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); avg_re += data[daddr].Re; avg_img += data[daddr].Img; } long long naddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, bz, t); avg_re *= norm; avg_img *= norm; data[naddr].Re = (float)avg_re; data[naddr].Img = (float)avg_img; } } }//); m_isZavg = 1; break; } } void cMagnetization::Do1DAveragingAmpInplace(long long axis) { // will write to bx, j, k; i, by, k; i, j, bz depends on the value of axis /*const long long sx = cProbe::sizeX; const long long sy = cProbe::sizeY; const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps;*/ long long sx, sy, sz; if (m_isXavg == 1) sx = 1; else sx = cProbe::sizeX; if (m_isYavg == 1) sy = 1; else sy = cProbe::sizeY; if (m_isZavg == 1) sz = 1; else sz = cProbe::sizeZ; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; long long size = 0; double norm = 0.0; switch(axis) { case 0: // averaging along the X direction; norm = 1.0 / sx; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long j = 0; j < sy; j++) { long long j1 = by + j; double avg_re = 0.0; //FLOAT? double avg_img = 0.0; //FLOAT? for (long long i = 0; i <sx; i++) { long long i1 = bx + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); float Re = data[daddr].Re; float Img = data[daddr].Img; float Amp = sqrtf(Re * Re + Img * Img); float Phz = atan2f(Img, Re); avg_re += Amp; avg_img += Phz; } avg_re *= norm; avg_img *= norm; long long naddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, bx, j1, k1, t); data[naddr].Re = avg_re; data[naddr].Img = avg_img; } } } m_isXavg = 1; break; case 1: // averaging along the Y direction; norm = 1.0 / sy; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; double avg_re = 0.0; double avg_img = 0.0; for (long long j = 0; j < sy; j++) { long long j1 = by + j; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); float Re = data[daddr].Re; float Img = data[daddr].Img; float Amp = sqrtf(Re * Re + Img * Img); float Phz = atan2f(Img, Re); avg_re += Amp; avg_img += Phz; } long long naddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, by, k1, t); avg_re *= norm; avg_img *= norm; data[naddr].Re = (float)avg_re; data[naddr].Img = (float)avg_img; } } } m_isYavg = 1; break; case 2: // averaging along the Z direction; norm = 1.0 / sz; for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long j = 0; j < sy; j++) { long long j1 = by + j; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < sz; k++) { long long k1 = bz + k; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); float Re = data[daddr].Re; float Img = data[daddr].Img; float Amp = sqrtf(Re * Re + Img * Img); float Phz = atan2f(Img, Re); avg_re += Amp; avg_img += Phz; } long long naddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, bz, t); avg_re *= norm; avg_img *= norm; data[naddr].Re = (float)avg_re; data[naddr].Img = (float)avg_img; } } } m_isZavg = 1; break; } } void cMagnetization::Do2DAveraging(long long axis) { const long long sx = cProbe::sizeX; const long long sy = cProbe::sizeY; const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; long long size = 0; double norm = 0.0; switch(axis) { case 0: // averaging of the YZ plane; size = sx * s_params.m_NumberOfTimeSteps; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! norm = 1.0 / (sy*sz); for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long i = 0; i <sx; i++) { long long i1 = bx + i; double avg_re = 0.0; double avg_img = 0.0; for (long long j = 0; j < sy; j++) { long long j1 = by + j; for (long long k = 0; k < sz; k++) { long long k1 = bz + k; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); avg_re += cProbe::probe[paddr] * data[daddr].Re; avg_img += cProbe::probe[paddr] * data[daddr].Img; } } long long aaddr = p_addr_xy_v1(sx,i,t); avg_re *= norm; avg_img *= norm; avgdata[aaddr].Re = (float)avg_re; avgdata[aaddr].Img = (float)avg_img; } } m_asizeX = sx; m_asizeY = 1; m_asizeZ = 1; m_asizeT = st; break; case 1: // averaging of the XZ plane; size = sy * s_params.m_NumberOfTimeSteps; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! norm = 1.0 / (sx*sz); for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long j = 0; j < sy; j++) { long long j1 = by + j; double avg_re = 0.0; double avg_img = 0.0; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; for (long long k = 0; k < sz; k++) { long long k1 = bz + k; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); avg_re += cProbe::probe[paddr] * data[daddr].Re; avg_img += cProbe::probe[paddr] * data[daddr].Img; } } long long aaddr = p_addr_xy_v1(sy,j,t); avg_re *= norm; avg_img *= norm; avgdata[aaddr].Re = (float)avg_re; avgdata[aaddr].Img = (float)avg_img; } } m_asizeX = sy; m_asizeY = 1; m_asizeZ = 1; m_asizeT = st; break; case 2: // averaging of the XY plane; size = sz * s_params.m_NumberOfTimeSteps; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! norm = 1.0 / (sx*sy); for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { for (long long k = 0; k < sz; k++) { long long k1 = bz + k; double avg_re = 0.0; double avg_img = 0.0; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; for (long long j = 0; j < sy; j++) { long long j1 = by + j; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); avg_re += cProbe::probe[paddr] * data[daddr].Re; avg_img += cProbe::probe[paddr] * data[daddr].Img; } } long long aaddr = p_addr_xy_v1(sz,k,t); avg_re *= norm; avg_img *= norm; avgdata[aaddr].Re = (float)avg_re; avgdata[aaddr].Img = (float)avg_img; } } m_asizeX = sz; m_asizeY = 1; m_asizeT = st; m_asizeZ = 1; break; } } void cMagnetization::Do3DAveraging() { const long long sx = cProbe::sizeX; const long long sy = cProbe::sizeY; const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; // averaging of the XY plane; const long long size = s_params.m_NumberOfTimeSteps; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! const double norm = 1.0 / (sx*sy*sz); for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long j = 0; j < sy; j++) { long long j1 = by + j; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); avg_re += cProbe::probe[paddr] * data[daddr].Re; avg_img += cProbe::probe[paddr] * data[daddr].Img; } } } avg_re *= norm; avg_img *= norm; avgdata[t].Re = (float)avg_re; avgdata[t].Img = (float)avg_img; } m_asizeX = 1; m_asizeY = 1; m_asizeZ = st; } void cMagnetization::Do3DAveragingBW(float kxa, float kxb, float kya, float kyb, float kza, float kzb) { const long long sx = cProbe::sizeX; const long long sy = cProbe::sizeY; const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; long long hsx = sx / 2; long long hsy = sy / 2; long long hsz = sz / 2; long long bwxa = (long long)(kxa * hsx); long long bwxb = (long long)(kxb * hsx); long long bwya = (long long)(kya * hsy); long long bwyb = (long long)(kyb * hsy); long long bwza = (long long)(kza * hsz); long long bwzb = (long long)(kzb * hsz); long long bwx = bwxa + bwxb; long long bwy = bwya + bwyb; long long bwz = bwza + bwzb; long long sxa = bx + (hsx - bwxa); long long sxb = bx + (hsx + bwxb); long long sya = by + (hsy - bwya); long long syb = by + (hsy + bwyb); long long sza = bz + (hsz - bwza); long long szb = bz + (hsz + bwzb); bwx = (bwx==0) ? 1 : bwx; bwy = (bwy==0) ? 1 : bwy; bwz = (bwz==0) ? 1 : bwz; // averaging of the XY plane; const long long size = st; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! const double norm = 1.0 / (bwx*bwy*bwz); for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < bwz; k++) { long long k1 = sza + k; for (long long j = 0; j < bwy; j++) { long long j1 = sya + j; for (long long i = 0; i < bwx; i++) { long long i1 = sxa + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); avg_re += cProbe::probe[paddr] * data[daddr].Re; avg_img += cProbe::probe[paddr] * data[daddr].Img; } } } avg_re *= norm; avg_img *= norm; avgdata[t].Re = (float)avg_re; avgdata[t].Img = (float)avg_img; } m_asizeX = 1; m_asizeY = 1; m_asizeZ = st; } void cMagnetization::Do3DAveragingBWCMPX(float kxa, float kxb, float kya, float kyb, float kza, float kzb) { const long long sx = cProbe::sizeX; const long long sy = cProbe::sizeY; const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; long long hsx = sx / 2; long long hsy = sy / 2; long long hsz = sz / 2; long long bwxa = (long long)(kxa * hsx); long long bwxb = (long long)(kxb * hsx); long long bwya = (long long)(kya * hsy); long long bwyb = (long long)(kyb * hsy); long long bwza = (long long)(kza * hsz); long long bwzb = (long long)(kzb * hsz); long long bwx = bwxa + bwxb; long long bwy = bwya + bwyb; long long bwz = bwza + bwzb; long long sxa = bx + (hsx - bwxa); long long sxb = bx + (hsx + bwxb); long long sya = by + (hsy - bwya); long long syb = by + (hsy + bwyb); long long sza = bz + (hsz - bwza); long long szb = bz + (hsz + bwzb); bwx = (bwx==0) ? 1 : bwx; bwy = (bwy==0) ? 1 : bwy; bwz = (bwz==0) ? 1 : bwz; // averaging of the XY plane; const long long size = st; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! const double norm = 1.0 / (bwx*bwy*bwz); for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < bwz; k++) { long long k1 = sza + k; for (long long j = 0; j < bwy; j++) { long long j1 = sya + j; for (long long i = 0; i < bwx; i++) { long long i1 = sxa + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); float Re = cProbe::probe[paddr] * data[daddr].Re; float Img = cProbe::probe[paddr] * data[daddr].Img; float Amp = sqrtf(Re*Re + Img*Img); float Phz = atan2f(Img, Re); avg_re += Amp; avg_img += Phz; } } } avg_re *= norm; avg_img *= norm; avgdata[t].Re = (float)avg_re; avgdata[t].Img = (float)avg_img; } m_asizeX = 1; m_asizeY = 1; m_asizeZ = st; } void cMagnetization::Do3DAveragingBWCMPXParallel(float kxa, float kxb, float kya, float kyb, float kza, float kzb) { const long long sx = cProbe::sizeX; const long long sy = cProbe::sizeY; const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; long long hsx = sx / 2; long long hsy = sy / 2; long long hsz = sz / 2; long long bwxa = (long long)(kxa * hsx); long long bwxb = (long long)(kxb * hsx); long long bwya = (long long)(kya * hsy); long long bwyb = (long long)(kyb * hsy); long long bwza = (long long)(kza * hsz); long long bwzb = (long long)(kzb * hsz); long long bwx = bwxa + bwxb; long long bwy = bwya + bwyb; long long bwz = bwza + bwzb; long long sxa = bx + (hsx - bwxa); long long sxb = bx + (hsx + bwxb); long long sya = by + (hsy - bwya); long long syb = by + (hsy + bwyb); long long sza = bz + (hsz - bwza); long long szb = bz + (hsz + bwzb); bwx = (bwx==0) ? 1 : bwx; bwy = (bwy==0) ? 1 : bwy; bwz = (bwz==0) ? 1 : bwz; // averaging of the XY plane; const long long size = st; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! const double norm = 1.0 / (bwx*bwy*bwz); #pragma omp parallel for for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < bwz; k++) { long long k1 = sza + k; for (long long j = 0; j < bwy; j++) { long long j1 = sya + j; for (long long i = 0; i < bwx; i++) { long long i1 = sxa + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); float Re = cProbe::probe[paddr] * data[daddr].Re; float Img = cProbe::probe[paddr] * data[daddr].Img; float Amp = sqrtf(Re*Re + Img*Img); float Phz = atan2f(Img, Re); avg_re += Amp; avg_img += Phz; } } } avg_re *= norm; avg_img *= norm; avgdata[t].Re = (float)avg_re; avgdata[t].Img = (float)avg_img; } m_asizeX = 1; m_asizeY = 1; m_asizeZ = st; } void cMagnetization::Do3DAveragingAmp() { const long long sx = cProbe::sizeX; const long long sy = cProbe::sizeY; const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; // averaging of the XY plane; const long long size = s_params.m_NumberOfTimeSteps; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! const double norm = 1.0 / (sx*sy*sz); for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long j = 0; j < sy; j++) { long long j1 = by + j; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); float Re = cProbe::probe[paddr] * data[daddr].Re; float Img = cProbe::probe[paddr] * data[daddr].Img; float amp = sqrtf(Re * Re + Img * Img); float phase = atan2f(Img, Re); avg_re += amp; avg_img += phase; } } } avg_re *= norm; avg_img *= norm; avgdata[t].Re = (float)avg_re; avgdata[t].Img = (float)avg_img; } m_asizeX = 1; m_asizeY = 1; m_asizeZ = st; } void cMagnetization::Do3DAveragingAmpParallel() { const long long sx = cProbe::sizeX; const long long sy = cProbe::sizeY; const long long sz = cProbe::sizeZ; const long long st = s_params.m_NumberOfTimeSteps; const long long bx = cProbe::X0; const long long by = cProbe::Y0; const long long bz = cProbe::Z0; // averaging of the XY plane; const long long size = s_params.m_NumberOfTimeSteps; avgdata = (COMPLEX*)new float[2 * size]; // 2 for complex! const double norm = 1.0 / (sx*sy*sz); #pragma omp parallel for for (long long t = 0; t < s_params.m_NumberOfTimeSteps; t++) { double avg_re = 0.0; double avg_img = 0.0; for (long long k = 0; k < sz; k++) { long long k1 = bz + k; for (long long j = 0; j < sy; j++) { long long j1 = by + j; for (long long i = 0; i <sx; i++) { long long i1 = bx + i; long long daddr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, t); long long paddr = p_addr_xyz_v1(sx,sy,i,j,k); float Re = cProbe::probe[paddr] * data[daddr].Re; float Img = cProbe::probe[paddr] * data[daddr].Img; float amp = sqrtf(Re * Re + Img * Img); float phase = atan2f(Img, Re); avg_re += amp; avg_img += phase; } } } avg_re *= norm; avg_img *= norm; avgdata[t].Re = (float)avg_re; avgdata[t].Img = (float)avg_img; } m_asizeX = 1; m_asizeY = 1; m_asizeZ = st; } void cMagnetization::Get2DFFTFromAveragedData() { double scale = 1.0; long long sizex = m_asizeX; long long sizey = m_asizeT; long long size = sizex * sizey; long long size_cmpx = 2 * size; long long size_byte = sizeof(float) * size_cmpx; AllocateAvgFFTBuffer(sizex, 1, 1, sizey); //memcpy(avgdata_fft, avgdata, size_byte); int error = 0; long long commsize = 5 * sizey + 200; if (cFFT::m_IsRectWindow != 1) cFFT::ApplyWindow2D((COMPLEX*)&avgdata[0].Re, m_asizeX); long long size_tbuf = 2 * sizey; COMPLEX* comm = (COMPLEX*)new float[2 * commsize]; COMPLEX* tbuf = (COMPLEX*)new float[size_tbuf]; cFFT::InitZFFT1D(sizey, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long i = 0; i < sizex; i++) { for (long long t = 0 ; t < sizey; t++) { long long addr = p_addr_xy_v1(sizex, i, t); tbuf[t].Re = avgdata[addr].Re; tbuf[t].Img = avgdata[addr].Img; } cFFT::ZFFT1D(sizey, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long t = 0 ; t < sizey; t++) { long long addr = p_addr_xy_v1(sizex, i, t); avgdata_fft[addr].Re = tbuf[t].Re ; avgdata_fft[addr].Img = tbuf[t].Img; } } } void cMagnetization::Get2DSpatialLayer(long long plane, long long timestep, long long depth) { long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; switch(plane) { case 0: // XY Allocate2DLayerBuffer(sizex, sizey); for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; long long addr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, depth, timestep); long long laddr = i + j * sizex; layer_buff_2d[laddr].Re = data[addr].Re; layer_buff_2d[laddr].Img = data[addr].Img; } } break; case 1: // XZ Allocate2DLayerBuffer(sizex, sizez); for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; long long addr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, depth, k1, timestep); long long laddr = i + k * sizex; layer_buff_2d[laddr].Re = data[addr].Re; layer_buff_2d[laddr].Img = data[addr].Img; } } break; case 2: // XZ Allocate2DLayerBuffer(sizey, sizez); for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long j = 0; j < sizey; j++) { long long j1 = by + j; long long addr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, depth, j1, k1, timestep); long long laddr = j + k * sizey; layer_buff_2d[laddr].Re = data[addr].Re; layer_buff_2d[laddr].Img = data[addr].Img; } } break; } } void cMagnetization::Get3DSpatialLayer(long long timestep) { long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; Allocate3DLayerBuffer(sizex, sizey, sizez); for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; long long addr = p_addr_xyzt_v1(s_params.m_SizeX, s_params.m_SizeY, s_params.m_SizeZ, i1, j1, k1, timestep); long long laddr = p_addr_xyz_v1(sizex, sizey, i, j, k); layer_buff_3d[laddr].Re = data[addr].Re; layer_buff_3d[laddr].Img = data[addr].Img; } } } } void cMagnetization::DoF2A(long long avgmethod) { // FFT Along the T DoFFTTParallel(); //DoFFTT(); // Averaging XYZT->T switch(avgmethod) { case 0: Do3DAveraging(); break; case 1: Do3DAveragingAmpParallel(); //Do3DAveragingAmp(); break; } m_IsFreqDomain = 1; }; void cMagnetization::DoA2F() { Do3DAveraging(); long long sizet = s_params.m_NumberOfTimeSteps; int error = 0; long long commsize = 5 * sizet + 200; if (cFFT::m_IsRectWindow != 1) cFFT::ApplyWindow1D((COMPLEX*)&avgdata[0].Re); COMPLEX* comm = (COMPLEX*)new float[2 * commsize]; long long size_tbuf = 2 * sizet; COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; cFFT::InitZFFT1D(sizet, (COMPLEX*)&avgdata[0].Re, (COMPLEX*)&comm[0].Re, &error); cFFT::ZFFT1D(sizet, (COMPLEX*)&avgdata[0].Re, (COMPLEX*)&comm[0].Re, &error); } // FFT-n void cMagnetization::Do3DFFT() { // 3D spatial FFT at each point of time long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; //long long sizex = cProbe::sizeX; //long long sizey = cProbe::sizeY; //long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * (sizex + sizey + sizez) + 150; //long long size_tbuf = 2 * sizet; COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; //COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; long long addr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, bx, by, bz, 0); cFFT::InitZFFT3Df(sizex, sizey, sizez, dsizex, dsizey, dsizez, commsize, 1.0, (COMPLEX*)&data[addr].Re, comm, NULL, &error); for (int p = 0; p < sizet; p++) { long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, bx, by, bz, p); cFFT::ZFFT3Df(sizex, sizey, sizez, dsizex, dsizey, dsizez, commsize, 1.0, (COMPLEX*)&data[daddr].Re, comm, NULL, &error); } delete[] (float*)comm; } void cMagnetization::Do3DFFTParallel() { // 3D spatial FFT at each point of time long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; //long long sizex = cProbe::sizeX; //long long sizey = cProbe::sizeY; //long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; long long commsize = sizex * sizey * sizez + 4 * (sizex + sizey + sizez) + 300;//L*M*N + 4*(L+M+N) + 300//5 * (sizex + sizey + sizez) + 150; // allocate one huge buffer for communication int nt = omp_get_max_threads(); int init = 0; int err = 0; COMPLEX* comm = (COMPLEX*)new float[2 * commsize * nt]; long long addr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, bx, by, bz, 0); //Performance penalty on NUMA! for (int i = 0; i < nt; i++) { cFFT::InitZFFT3Df(sizex, sizey, sizez, dsizex, dsizey, dsizez, commsize, 1.0, (COMPLEX*)&data[addr].Re, (COMPLEX*)&comm[i * commsize].Re, NULL, &err); } #pragma omp parallel for default(shared) firstprivate(err) for (long long p = 0; p < sizet; p++) { int ii = omp_get_thread_num(); long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, bx, by, bz, p); cFFT::ZFFT3Df(sizex, sizey, sizez, dsizex, dsizey, dsizez, commsize, 1.0, (COMPLEX*)&data[daddr].Re, (COMPLEX*)&comm[ii * commsize].Re, NULL, &err); } delete[] (float*)comm; } void cMagnetization::DoFFTT() { // temporal FFT and each particular X,Y,Z long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; //long long sizex = cProbe::sizeX; //long long sizey = cProbe::sizeY; //long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * sizet + 200; if (cFFT::m_IsRectWindow != 1) cFFT::ApplyWindow4D((COMPLEX*)&data[0].Re, bx, by, bz, sizex, sizey, sizez, dsizex, dsizey, dsizez); long long size_tbuf = 2 * sizet; COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; cFFT::InitZFFT1D(sizet, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; long long paddr = p_addr_xyz_v1(sizex, sizey, i, j, k); float probe = cProbe::probe[paddr]; for (long long p = 0; p < sizet; p++) { long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); tbuf[p].Re = data[daddr].Re * probe; tbuf[p].Img = data[daddr].Img * probe; } cFFT::ZFFT1D(sizet, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long p = 0; p < sizet;p++) { long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); data[daddr].Re = tbuf[p].Re; data[daddr].Img = tbuf[p].Img; } } } } } void cMagnetization::DoFFTTParallel() { // temporal FFT and each particular X,Y,Z long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; //long long sizex = cProbe::sizeX; //long long sizey = cProbe::sizeY; //long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; long long commsize = 5 * sizet + 200; if (cFFT::m_IsRectWindow != 1) cFFT::ApplyWindow4D((COMPLEX*)&data[0].Re, bx, by, bz, sizex, sizey, sizez, dsizex, dsizey, dsizez); long long size_tbuf = 2 * sizet; //COMPLEX *comma = (COMPLEX*)new float[2 * commsize]; //COMPLEX *tbufa = (COMPLEX*)new float[size_tbuf]; int err = 0; //cFFT::InitZFFT1D(sizet, (COMPLEX*)&tbufa[0].Re, (COMPLEX*)&comma[0].Re, &errora); // //parallel_for(long long(0), sizey,[&](long long j) int nt = omp_get_max_threads(); COMPLEX *comm = (COMPLEX*)new float[2 * commsize * nt]; COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf * nt]; for (int i = 0; i < nt; i++) { cFFT::InitZFFT1D(sizet, (COMPLEX*)&tbuf[i * sizet].Re, (COMPLEX*)&comm[i * commsize].Re, &err); } #pragma omp parallel for default(shared) firstprivate(err) for (long long j = 0; j < sizey; j++) { long long j1 = by + j; long long ii = (long long)omp_get_thread_num(); long long tbc = sizet * ii; long long cbc = commsize * ii; for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; long long paddr = p_addr_xyz_v1(sizex, sizey, i, j, k); float probe = cProbe::probe[paddr]; for (long long p = 0; p < sizet; p++) { long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); tbuf[p + tbc].Re = data[daddr].Re * probe; tbuf[p + tbc].Img = data[daddr].Img * probe; } cFFT::ZFFT1D(sizet, (COMPLEX*)&tbuf[tbc].Re, (COMPLEX*)&comm[cbc].Re, &err); for (long long p = 0; p < sizet;p++) { long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); data[daddr].Re = tbuf[p + tbc].Re; data[daddr].Img = tbuf[p + tbc].Img; } } } } delete[] (float*)comm; delete[] (float*)tbuf; } void cMagnetization::DoFFTTMParallel() { // temporal FFT and each particular X,Y,Z long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; //long long sizex = cProbe::sizeX; //long long sizey = cProbe::sizeY; //long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; long long commsize = 5 * sizet + 200; if (cFFT::m_IsRectWindow != 1) cFFT::ApplyWindow4D((COMPLEX*)&data[0].Re, bx, by, bz, sizex, sizey, sizez, dsizex, dsizey, dsizez); long long size_tbuf = 2 * sizet; int err = 0; int sxyz = dsizex * dsizey * dsizez; COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; cFFT::InitZFFT1DM(sizet, sxyz, sxyz, 1, data, comm, &err); cFFT::ZFFT1DM(sizet, sxyz, sxyz, 1, data, comm, &err); } void cMagnetization::DoFFTX() { // FFT along X axis and each particular X,Y,T long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long size = sizex; // CRUCIAL POINT long long commsize = 5 * size+ 200; long long size_tbuf = 2 * size; COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; cFFT::InitZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; long long paddr = p_addr_xyz_v1(sizex, sizey, i, j, k); float probe = cProbe::probe[paddr]; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); tbuf[i].Re = data[daddr].Re * probe; tbuf[i].Img = data[daddr].Img * probe; } cFFT::ZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); data[daddr].Re = tbuf[i].Re; data[daddr].Img = tbuf[i].Img; } } } } } void cMagnetization::DoFFTXParallel() { // FFT along X axis and each particular X,Y,T long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; //int error = 0; long long size = sizex; // CRUCIAL POINT long long commsize = 5 * size+ 200; long long size_tbuf = 2 * size; //COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; //COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; //cFFT::InitZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); //parallel_for(long long(0), sizey,[&](long long j) #pragma omp parallel for//#pragma omp parallel for for (long long j = 0; j < sizey; j++) { long long j1 = by + j; int error = 0; COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; cFFT::InitZFFT1DSimple(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; long long paddr = p_addr_xyz_v1(sizex, sizey, i, j, k); float probe = cProbe::probe[paddr]; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); tbuf[i].Re = data[daddr].Re * probe; tbuf[i].Img = data[daddr].Img * probe; } cFFT::ZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); data[daddr].Re = tbuf[i].Re; data[daddr].Img = tbuf[i].Img; } } } delete[] (float*)comm; delete[] (float*)tbuf; }//); } void cMagnetization::DoFFTY() { // FFT along Y axis and each particular X,Z,T long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long size = sizey; // CRUCIAL POINT long long commsize = 5 * size+ 200; long long size_tbuf = 2 * size; COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; cFFT::InitZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long j = 0; j < sizey; j++) { long long j1 = by + j; long long paddr = p_addr_xyz_v1(sizex, sizey, i, j, k); float probe = cProbe::probe[paddr]; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); tbuf[j].Re = data[daddr].Re * probe; tbuf[j].Img = data[daddr].Img * probe; } cFFT::ZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long j = 0; j < sizey; j++) { long long j1 = by + j; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); data[daddr].Re = tbuf[j].Re; data[daddr].Img = tbuf[j].Img; } } } } } void cMagnetization::DoFFTYParallel() { // FFT along Y axis and each particular X,Z,T long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; long long size = sizey; // CRUCIAL POINT long long commsize = 5 * size+ 200; long long size_tbuf = 2 * size; //parallel_for(long long(0), sizez,[&](long long k) #pragma omp parallel for for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; int error = 0; COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; cFFT::InitZFFT1DSimple(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long p = 0; p < sizet; p++) { for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long j = 0; j < sizey; j++) { long long j1 = by + j; long long paddr = p_addr_xyz_v1(sizex, sizey, i, j, k); float probe = cProbe::probe[paddr]; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); tbuf[j].Re = data[daddr].Re * probe; tbuf[j].Img = data[daddr].Img * probe; } cFFT::ZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long j = 0; j < sizey; j++) { long long j1 = by + j; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); data[daddr].Re = tbuf[j].Re; data[daddr].Img = tbuf[j].Img; } } } delete[] (float*)comm; delete[] (float*)tbuf; }//); } void cMagnetization::DoFFTZ() { // FFT along Z axis and each particular X, Y, T long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long size = sizez; // CRUCIAL POINT long long commsize = 5 * size+ 200; long long size_tbuf = 2 * size; COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; cFFT::InitZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long p = 0; p < sizet; p++) { for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; long long paddr = p_addr_xyz_v1(sizex, sizey, i, j, k); float probe = cProbe::probe[paddr]; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); tbuf[k].Re = data[daddr].Re * probe; tbuf[k].Img = data[daddr].Img * probe; } cFFT::ZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); data[daddr].Re = tbuf[k].Re; data[daddr].Img = tbuf[k].Img; } } } } } void cMagnetization::DoFFTZParallel() { // FFT along Z axis and each particular X, Y, T long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; long long size = sizez; // CRUCIAL POINT long long commsize = 5 * size+ 200; long long size_tbuf = 2 * size; //#pragma omp parallel for //parallel_for(long long(0), sizey,[&](long long j) #pragma omp parallel for for (long long j = 0; j < sizey; j++) { long long j1 = by + j; int error = 0; COMPLEX *comm = (COMPLEX*)new float[2 * commsize]; COMPLEX *tbuf = (COMPLEX*)new float[size_tbuf]; cFFT::InitZFFT1DSimple(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long p = 0; p < sizet; p++) { for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; long long paddr = p_addr_xyz_v1(sizex, sizey, i, j, k); float probe = cProbe::probe[paddr]; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); tbuf[k].Re = data[daddr].Re * probe; tbuf[k].Img = data[daddr].Img * probe; } cFFT::ZFFT1D(size, (COMPLEX*)&tbuf[0].Re, (COMPLEX*)&comm[0].Re, &error); for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); data[daddr].Re = tbuf[k].Re; data[daddr].Img = tbuf[k].Img; } } } delete[] (float*)comm; delete[] (float*)tbuf; }//); } void cMagnetization::DoShiftedFormT() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * sizet + 200; long long size = sizet; long long hsize = size/2; for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long p = 0; p < hsize; p++) { long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, hsize + p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } } } void cMagnetization::DoShiftedFormTParallel() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * sizet + 200; long long size = sizet; long long hsize = size/2; if (sizez > 1) { //parallel_for(long long(0), sizez, [&](long long k) #pragma omp parallel for for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long p = 0; p < hsize; p++) { long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, hsize + p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } }//); } else { //parallel_for(long long(0), sizey, [&](long long j) #pragma omp parallel for for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long p = 0; p < hsize; p++) { long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, hsize + p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } }//); } } void cMagnetization::DoShiftedFormX() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * sizet + 200; long long size = sizex; long long hsize = size/2; for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < hsize; i++) { long long i1 = bx + i; long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, hsize + i1, j1, k1, p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } } } void cMagnetization::DoShiftedFormXParallel() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * sizet + 200; long long size = sizex; long long hsize = size/2; if (sizez > 1) { //parallel_for(long long(0), sizez, [&](long long k) #pragma omp parallel for for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long p = 0; p < sizet; p++) { for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < hsize; i++) { long long i1 = bx + i; long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, hsize + i1, j1, k1, p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } }//); } else { //parallel_for(long long(0), sizey, [&](long long j) #pragma omp parallel for for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long i = 0; i < hsize; i++) { long long i1 = bx + i; long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, hsize + i1, j1, k1, p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } }//); } } void cMagnetization::DoShiftedFormY() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * sizet + 200; long long size = sizey; long long hsize = size/2; for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long j = 0; j < hsize; j++) { long long j1 = by + j; long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, hsize + j1, k1, p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } } } void cMagnetization::DoShiftedFormYParallel() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * sizet + 200; long long size = sizey; long long hsize = size/2; if (sizez > 1) { //parallel_for(long long(0), sizez, [&](long long k) #pragma omp parallel for for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long p = 0; p < sizet; p++) { for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long j = 0; j < hsize; j++) { long long j1 = by + j; long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, hsize + j1, k1, p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } }//); } else { //parallel_for(long long(0), sizet, [&](long long p) #pragma omp parallel for for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { long long k1 = bz + k; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long j = 0; j < hsize; j++) { long long j1 = by + j; long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, hsize + j1, k1, p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } }//); } } void cMagnetization::DoShiftedFormZ() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * sizet + 200; long long size = sizez; long long hsize = size/2; for (long long p = 0; p < sizet; p++) { for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long k = 0; k < hsize; k++) { long long k1 = bz + k; long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, hsize + k1, p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } } } void cMagnetization::DoShiftedFormZParallel() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; int error = 0; long long commsize = 5 * sizet + 200; long long size = sizez; long long hsize = size/2; //parallel_for(long long(0), sizey, [&](long long j) #pragma omp parallel for for (long long j = 0; j < sizey; j++) { long long j1 = by + j; for (long long p = 0; p < sizet; p++) { for (long long i = 0; i < sizex; i++) { long long i1 = bx + i; for (long long k = 0; k < hsize; k++) { long long k1 = bz + k; long long daddr_l = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long daddr_r = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, hsize + k1, p); float Re = data[daddr_l].Re; float Img = data[daddr_l].Img; data[daddr_l].Re = data[daddr_r].Re; data[daddr_l].Img = data[daddr_r].Img; data[daddr_r].Re = Re; data[daddr_r].Img = Img; } } } }//); } void cMagnetization::Get4DFFT() { long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ; /*DoFFTTParallel(); if (sizex != 1) DoFFTXParallel(); if (sizey != 1) DoFFTYParallel(); if (sizez != 1) DoFFTZParallel();*/ DoFFTTParallel(); if (sizex != 1) DoFFTX();//Parallel(); if (sizey != 1) DoFFTY();//Parallel(); if (sizez != 1) DoFFTZ();//Parallel(); DoShiftedFormT(); if (sizex != 1) DoShiftedFormX(); if (sizey != 1) DoShiftedFormY(); if (sizez != 1) DoShiftedFormZ(); } void cMagnetization::Get4DFFTVolumeSlice(long long isAvgX, long long isAvgY, long long isAvgZ, long long AvgMX, long long AvgMY, long long AvgMZ, long long coordx, long long coordy, long long coordz) { long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; m_isXavg = 0; m_isYavg = 0; m_isZavg = 0; //**********Averaging in real space if required***************** if (AvgMX == 0 && isAvgX == 1) Do1DAveragingInplaceParallel(0); if (AvgMY == 0 && isAvgY == 1) Do1DAveragingInplaceParallel(1); if (AvgMZ == 0 && isAvgZ == 1) Do1DAveragingInplaceParallel(2); //************************************************************** //***********************4D FFT********************************* if (m_IsKDomain == 0 && m_IsFreqDomain == 0)// && (isAvgX != 0 || isAvgY !=0 || isAvgZ !=0)) { DoFFTTParallel(); printf("FFTT Done."); Do3DFFTParallel(); DoShiftedFormTParallel(); if (sizex != 1) DoShiftedFormXParallel(); if (sizey != 1) DoShiftedFormYParallel(); if (sizez != 1) DoShiftedFormZParallel(); m_IsFreqDomain = 1; m_IsKDomain = 1; // X //*************************************************************** if (AvgMX == 1 || AvgMY == 1 || AvgMZ == 1) DoAmpPhsFromParallel(); //**********Averaging in reciprocal space if required************ if (AvgMX == 1 && isAvgX == 1) Do1DAveragingInplaceParallel(0); if (AvgMY == 1 && isAvgY == 1) Do1DAveragingInplaceParallel(1); if (AvgMZ == 1 && isAvgZ == 1) Do1DAveragingInplaceParallel(2); //*************************************************************** } Get2Dfrom4DVolume(isAvgX, isAvgY, isAvgZ, coordx, coordy, coordz); } void cMagnetization::Get2Dfrom4DVolume(long long isavgx, long long isavgy, long long isavgz, long long coordx, long long coordy, long long coordz) { long long adeg = isavgx + isavgy + isavgz; long long faxis = 0; long long aaxis = 0; long long coordA = 0; long long coordB = 0; long long guess = 0; switch(adeg) { case 0: // DATA ARE NOT AVERAGED AT ANY POINT // Guess the fixed axis if (coordx == -1) { // X faxis = 0; coordA = coordy; coordB = coordz; } if (coordy == -1) { // Y faxis = 1; coordA = coordx; coordB = coordz; } if (coordz == -1) { // Z faxis = 2; coordA = coordx; coordB = coordy; } Get2Dfrom4DNAvg(faxis, coordA, coordB); break; case 1: // ONLY ONE DIRECTION IS AVERAGED // GUESS DIRECTION if (coordx == -1) { // X faxis = 0; } if (coordy == -1) { // Y faxis = 1; } if (coordz == -1) { // Z faxis = 2; } if (isavgx == 1) { // X aaxis = 0; switch(faxis) { case 0: // X - averaged, X - fixed causing error!!!!!!! coordA = coordx; break; case 1: // X - averaged, Y - fixed: Z slice coordA = coordz; break; case 2: // X - averaged, Z - fixed: Y slice coordA = coordy; break; } } if (isavgy == 1) { // Y aaxis = 1; switch(faxis) { case 0: // Y - averaged, X fixed: Z slice coordA = coordz; break; case 1: // Y - averaged, Y fixed: ERROR coordA = coordy; break; case 2: // Y - averaged, Z fixed: X slice coordA = coordx; break; } } if (isavgz == 1) { // Z aaxis = 2; switch(faxis) { case 0: // Z - averaged, X fixed: Y slice coordA = coordy; break; case 1: // Z - averaged, Y fixed: X slice coordA = coordx; break; case 2: // Z - averaged, Z fixed: ERROR coordA = coordz; break; } } Get2Dfrom4DSAvg(faxis, aaxis, coordA); break; case 2: // TWO DIRECTIONS ARE AVERAGED // GUESSING fixed axis! faxis = 0; guess = isavgx + 2 * isavgy + 4 * isavgz; switch (guess) { case 6: // X faxis = 0; break; case 5: // Y faxis = 1; break; case 3: // Z faxis = 2; break; } Get2Dfrom4DDAvg(faxis); break; case 3: // ALL THREE DIRECTIONS ARE AVERAGED Get2Dfrom4DTAvg(); break; } } void cMagnetization::Get2Dfrom4DNAvg(long long fixedaxis, long long coordA, long long coordB) { long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; long long j1 = 0; long long i1 = 0; long long k1 = 0; switch(fixedaxis) { case 0: // X is fixed AllocateAvgFFTBuffer(sizex, 1, 1, sizet); j1 = coordA + by; k1 = coordB + bz; for (long long p = 0; p < sizet; p++) { for (long long i = 0; i < sizex; i++) { i1 = bx + i; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long naddr = p_addr_xy_v1(sizex, i, p); avgdata_fft[naddr].Re = data[daddr].Re; avgdata_fft[naddr].Img = data[daddr].Img; } } break; case 1: // Y is fixed AllocateAvgFFTBuffer(sizey, 1, 1, sizet); i1 = coordA + bx; k1 = coordB + bz; for (long long p = 0; p < sizet; p++) { for (long long j = 0; j < sizey; j++) { j1 = by + j; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long naddr = p_addr_xy_v1(sizey, j, p); avgdata_fft[naddr].Re = data[daddr].Re; avgdata_fft[naddr].Img = data[daddr].Img; } } break; case 2: // Y is fixed AllocateAvgFFTBuffer(sizez, 1, 1, sizet); i1 = coordA + bx; j1 = coordB + by; for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { k1 = bz + k; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long naddr = p_addr_xy_v1(sizez, k, p); avgdata_fft[naddr].Re = data[daddr].Re; avgdata_fft[naddr].Img = data[daddr].Img; } } break; } } void cMagnetization::Get2Dfrom4DSAvg(long long fixedaxis, long long avg, long long coordA) { long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; long long i1 = 0; long long j1 = 0; long long k1 = 0; switch(avg) { case 0: // X is averaged so free is Y and Z; i1 = bx; k1 = coordA + bz; j1 = coordA + by; break; case 1: // Y is averaged so free is X and Z; j1 = by; k1 = coordA + bz; i1 = coordA + bx; break; case 2: // Z is averaged so free is X and Y k1 = bz; j1 = coordA + by; i1 = coordA + bx; break; } switch(fixedaxis) { case 0: // X is fixed AllocateAvgFFTBuffer(sizex, 1, 1, sizet); for (long long p = 0; p < sizet; p++) { for (long long i = 0; i < sizex; i++) { i1 = bx + i; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long naddr = p_addr_xy_v1(sizex, i, p); avgdata_fft[naddr].Re = data[daddr].Re; avgdata_fft[naddr].Img = data[daddr].Img; } } break; case 1: // Y is fixed AllocateAvgFFTBuffer(sizey, 1, 1, sizet); for (long long p = 0; p < sizet; p++) { for (long long j = 0; j < sizey; j++) { j1 = by + j; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long naddr = p_addr_xy_v1(sizey, j, p); avgdata_fft[naddr].Re = data[daddr].Re; avgdata_fft[naddr].Img = data[daddr].Img; } } break; case 2: // Y is fixed AllocateAvgFFTBuffer(sizez, 1, 1, sizet); for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { k1 = bz + k; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long naddr = p_addr_xy_v1(sizez, k, p); avgdata_fft[naddr].Re = data[daddr].Re; avgdata_fft[naddr].Img = data[daddr].Img; } } break; } } void cMagnetization::Get2Dfrom4DDAvg(long long fixedaxis) { long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; long long i1 = bx; long long j1 = by; long long k1 = bz; switch(fixedaxis) { case 0: // X is fixed AllocateAvgFFTBuffer(sizex, 1, 1, sizet); for (long long p = 0; p < sizet; p++) { for (long long i = 0; i < sizex; i++) { i1 = bx + i; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long naddr = p_addr_xy_v1(sizex, i, p); avgdata_fft[naddr].Re = data[daddr].Re; avgdata_fft[naddr].Img = data[daddr].Img; } } break; case 1: // Y is fixed AllocateAvgFFTBuffer(sizey, 1, 1, sizet); for (long long p = 0; p < sizet; p++) { for (long long j = 0; j < sizey; j++) { j1 = by + j; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long naddr = p_addr_xy_v1(sizey, j, p); avgdata_fft[naddr].Re = data[daddr].Re; avgdata_fft[naddr].Img = data[daddr].Img; } } break; case 2: // Y is fixed AllocateAvgFFTBuffer(sizez, 1, 1, sizet); for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { k1 = bz + k; long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); long long naddr = p_addr_xy_v1(sizez, k, p); avgdata_fft[naddr].Re = data[daddr].Re; avgdata_fft[naddr].Img = data[daddr].Img; } } break; } } void cMagnetization::Get2Dfrom4DTAvg() { long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; long long i1 = bx; long long j1 = by; long long k1 = bz; AllocateAvgFFTBuffer(1, 1, 1, sizet); for (long long p = 0; p < sizet; p++) { long long daddr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); avgdata_fft[p].Re = data[daddr].Re; avgdata_fft[p].Img = data[daddr].Img; } } void cMagnetization::DoAmpPhsFrom() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { long long k1 = k + bz; for (long long j = 0; j < sizey; j++) { long long j1 = j + by; for (long long i = 0; i < sizex; i++) { long long i1 = i + bx; long long addr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); float Re = data[addr].Re; float Img = data[addr].Img; float Amp = sqrtf(Re * Re + Img * Img); float Phz = atan2f(Img, Re); data[addr].Re = Amp; data[addr].Img = Phz; } } } } } void cMagnetization::DoAmpPhsFromParallel() { long long sizex, sizey, sizez; if (m_isXavg == 1) sizex = 1; else sizex = cProbe::sizeX; if (m_isYavg == 1) sizey = 1; else sizey = cProbe::sizeY; if (m_isZavg == 1) sizez = 1; else sizez = cProbe::sizeZ; /*long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ;*/ long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; //parallel_for(long long(0), sizey, [&](long long j) #pragma omp parallel for for (long long j = 0; j < sizey; j++) { long long j1 = j + by; for (long long p = 0; p < sizet; p++) { for (long long k = 0; k < sizez; k++) { long long k1 = k + bz; for (long long i = 0; i < sizex; i++) { long long i1 = i + bx; long long addr = p_addr_xyzt_v1(dsizex, dsizey, dsizez, i1, j1, k1, p); float Re = data[addr].Re; float Img = data[addr].Img; float Amp = sqrtf(Re * Re + Img * Img); float Phz = atan2f(Img, Re); data[addr].Re = Amp; data[addr].Img = Phz; } } } }//); } void cMagnetization::DoFF2A() { //Apply 4D FFT first long long sizex = cProbe::sizeX; long long sizey = cProbe::sizeY; long long sizez = cProbe::sizeZ; long long sizet = s_params.m_NumberOfTimeSteps; long long bx = cProbe::X0; long long by = cProbe::Y0; long long bz = cProbe::Z0; long long dsizex = s_params.m_SizeX; long long dsizey = s_params.m_SizeY; long long dsizez = s_params.m_SizeZ; m_isXavg = 0; m_isYavg = 0; m_isZavg = 0; //***********************4D FFT********************************* if (m_IsKDomain == 0 && m_IsFreqDomain == 0)// && (isAvgX != 0 || isAvgY !=0 || isAvgZ !=0)) { DoFFTTParallel(); printf("FFTT Done."); Do3DFFTParallel(); DoShiftedFormTParallel(); if (sizex != 1) DoShiftedFormXParallel(); if (sizey != 1) DoShiftedFormYParallel(); if (sizez != 1) DoShiftedFormZParallel(); m_IsFreqDomain = 1; m_IsKDomain = 1; //DoAmpPhsFromParallel(); } Do3DAveragingBWCMPXParallel(0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f); DoShiftedFormSpectrumParallel(); } void cMagnetization::DoShiftedFormSpectrumParallel() { long long sx = m_asizeX; long long sy = m_asizeY; long long sz = m_asizeZ; long long hx = sx / 2; long long hy = sy / 2; long long hz = sz / 2; for (int i = 0; i < sx; i++) { for (int j=0; j < sy; j++) { for (int k=0; k < hz; k++) { long long addr_l = p_addr_xyz_v1(sx, sy, i, j, k); long long addr_r = p_addr_xyz_v1(sx, sy, i, j, k + hz); float tRe = avgdata[addr_l].Re; float tImg = avgdata[addr_l].Img; avgdata[addr_l].Re = avgdata[addr_r].Re; avgdata[addr_l].Img = avgdata[addr_r].Img; avgdata[addr_r].Re = tRe; avgdata[addr_r].Img = tImg; } } } } void cMagnetization::GetMultipoleCoeff(long long t, long long order, double** Q, long long** size) { long long tenssize = (long long)pow(3.0, (double)order); *Q = (double*)malloc(tenssize*sizeof(double)); for (int i = 0; i < tenssize; i++) { *(*Q + i) = 0.0; } double PI = 4.0F * atanf(1.0F); double PIo2 = PI / 2.0; long long sx = s_params.m_SizeX; long long sy = s_params.m_SizeY; long long sz = s_params.m_SizeZ; long long i0 = cProbe::X0; long long j0 = cProbe::Y0; long long k0 = cProbe::Z0; long long psx = cProbe::sizeX; long long psy = cProbe::sizeY; long long psz = cProbe::sizeZ; double q = 0.0; // have to guess the relative phase prior the the coefficients calculation double mamp = 0.0; double mphz = 0.0; double value; /*for (long long k = k0; k < psz; k++) { for (long long j = j0; j < psy; j++) { for (long long i = i0; i < psx; i++) { double x = i * s_params.m_CellSizeX; double y = j * s_params.m_CellSizeY; double z = k * s_params.m_CellSizeZ; long long addr = p_addr_xyzt_v1(sx, sy, sz, i, j, k, t); float Re = data[addr].Re; float Img = data[addr].Img; double Amp = sqrt(Re * Re + Img * Img); double Phz = atan2(Img, Re); if (Amp > mamp) { mamp = Amp; mphz = Phz; } } } }*/ double pshift = 0.0; //PIo2 - mphz; switch (order) { case 0LL: // monopole for (long long k = k0; k < psz; k++) { for (long long j = j0; j < psy; j++) { for (long long i = i0; i < psx; i++) { double x = i * s_params.m_CellSizeX; double y = j * s_params.m_CellSizeY; double z = k * s_params.m_CellSizeZ; long long addr = p_addr_xyzt_v1(sx, sy, sz, i, j, k, t); float Re = data[addr].Re; float Img = data[addr].Img; double Amp = sqrt(Re * Re + Img * Img); double Phz = atan2(Img, Re); double chg = Amp * sin(pshift + Phz); *(*Q + 0) += chg; } } } break; case 1LL: // dipole for (long long k = k0; k < psz; k++) { for (long long j = j0; j < psy; j++) { for (long long i = i0; i < psx; i++) { double x = i * s_params.m_CellSizeX; double y = j * s_params.m_CellSizeY; double z = k * s_params.m_CellSizeZ; long long addr = p_addr_xyzt_v1(sx, sy, sz, i, j, k, t); float Re = data[addr].Re; float Img = data[addr].Img; double Amp = sqrt(Re * Re + Img * Img); double Phz = atan2(Img, Re); double chg = Amp * sin(pshift + Phz); *(*Q + 0) += chg * x; *(*Q + 1) += chg * y; *(*Q + 2) += chg * z; } } } break; case 2LL: // quadrupole for (long long k = k0; k < psz; k++) { for (long long j = j0; j < psy; j++) { for (long long i = i0; i < psx; i++) { double x = i * s_params.m_CellSizeX; double y = j * s_params.m_CellSizeY; double z = k * s_params.m_CellSizeZ; double r2 = (x * x + y * y + z * z); long long addr = p_addr_xyzt_v1(sx, sy, sz, i, j, k, t); float Re = data[addr].Re; float Img = data[addr].Img; double Amp = sqrt(Re * Re + Img * Img); double Phz = atan2(Img, Re); double chg = Amp * sin(pshift + Phz); //xx *(*Q + 0) += chg * (3.0 * x * x - r2); //xy *(*Q + 1) += chg * (3.0 * x * y); //xz *(*Q + 2) += chg * (3.0 * x * z); //yx *(*Q + 3) += chg * (3.0 * y * x); //yy *(*Q + 4) += chg * (3.0 * y * y - r2); //yz *(*Q + 5) += chg * (3.0 * y * z); //zx *(*Q + 6) += chg * (3.0 * z * x); //yy *(*Q + 7) += chg * (3.0 * z * y); //yz *(*Q + 8) += chg * (3.0 * z * z - r2); } } } break; } (*size[0]) = tenssize; } void cMagnetization::GetOrigin(long long t, double** r) { long long sx = s_params.m_SizeX; long long sy = s_params.m_SizeY; long long sz = s_params.m_SizeZ; long long i0 = cProbe::X0; long long j0 = cProbe::Y0; long long k0 = cProbe::Z0; long long psx = cProbe::sizeX; long long psy = cProbe::sizeY; long long psz = cProbe::sizeZ; double q = 0.0; double qx = 0.0; double qy = 0.0; double qz = 0.0; for (long long k = k0; k < psz; k++) { for (long long j = 0; j < psy; j++) { for (long long i = 0; i < psx; i++) { double x = i * s_params.m_CellSizeX; double y = j * s_params.m_CellSizeY; double z = k * s_params.m_CellSizeZ; long long addr = p_addr_xyzt_v1(sx, sy, sz, i, j, k, t); float Re = data[addr].Re; float Img = data[addr].Img; double chg = sqrt(Re * Re + Img * Img) * sin(atan2(Img, Re)); } } } } void cMagnetization::Get3DModeWaveNumber() { // Calculate 3D DFT of the mode long long sizex = m_lsizeX; long long sizey = m_lsizeY; long long sizez = m_lsizeZ; double* dax = (double*)new double[sizex]; double* day = (double*)new double[sizey]; double* daz = (double*)new double[sizez]; long long commsize = sizex * sizey * sizez + 4 * (sizex + sizey + sizez) + 300;//L*M*N + 4*(L+M+N) + 300//5 * (sizex + sizey + sizez) + 150; // allocate one huge buffer for communication COMPLEX* comm = (COMPLEX*)new float[2 * commsize]; int err = 0; cFFT::InitZFFT3Df(sizex, sizey, sizez, sizex, sizey, sizez, commsize, 1.0, (COMPLEX*)&layer_buff_3d[0].Re, (COMPLEX*)&comm[0].Re, NULL, &err); cFFT::ZFFT3Df(sizex, sizey, sizez, sizex, sizey, sizez, commsize, 1.0, (COMPLEX*)&layer_buff_3d[0].Re, (COMPLEX*)&comm[0].Re, NULL, &err); delete[] (float*)comm; // Brings to shifted form long long hsizex = sizex / 2; long long hsizey = sizey / 2; long long hsizez = sizez / 2; // X for (long long k = 0 ; k < sizez; k++) { for (long long j = 0; j < sizey; j++) { for (long long i = 0; i < hsizex; i++) { long long addr_l = p_addr_xyz_v1(sizex, sizey, i, j , k); long long addr_r = p_addr_xyz_v1(sizex, sizey, i + hsizex, j, k); float Re = layer_buff_3d[addr_l].Re; float Img = layer_buff_3d[addr_l].Img; layer_buff_3d[addr_l].Re = layer_buff_3d[addr_r].Re; layer_buff_3d[addr_l].Img = layer_buff_3d[addr_r].Img; layer_buff_3d[addr_r].Re = Re; layer_buff_3d[addr_r].Img = Img; } } } // Y for (long long k = 0 ; k < sizez; k++) { for (long long j = 0; j < hsizey; j++) { for (long long i = 0; i < sizex; i++) { long long addr_l = p_addr_xyz_v1(sizex, sizey, i, j , k); long long addr_r = p_addr_xyz_v1(sizex, sizey, i, j + hsizey, k); float Re = layer_buff_3d[addr_l].Re; float Img = layer_buff_3d[addr_l].Img; layer_buff_3d[addr_l].Re = layer_buff_3d[addr_r].Re; layer_buff_3d[addr_l].Img = layer_buff_3d[addr_r].Img; layer_buff_3d[addr_r].Re = Re; layer_buff_3d[addr_r].Img = Img; } } } // Z for (long long k = 0 ; k < hsizez; k++) { for (long long j = 0; j < sizey; j++) { for (long long i = 0; i < sizex; i++) { long long addr_l = p_addr_xyz_v1(sizex, sizey, i, j, k); long long addr_r = p_addr_xyz_v1(sizex, sizey, i, j, k + hsizez); float Re = layer_buff_3d[addr_l].Re; float Img = layer_buff_3d[addr_l].Img; layer_buff_3d[addr_l].Re = layer_buff_3d[addr_r].Re; layer_buff_3d[addr_l].Img = layer_buff_3d[addr_r].Img; layer_buff_3d[addr_r].Re = Re; layer_buff_3d[addr_r].Img = Img; } } } // Now do averaging of the data double imul = 0.0; // X imul = 1.0 / ((double)sizey * (double)sizez); for (long long i = 0; i < sizex; i++) { double aAmp = 0.0; for (long long k = 0 ; k < sizez; k++) { for (long long j = 0; j < sizey; j++) { long long addr = p_addr_xyz_v1(sizex, sizey, i, j, k); double Re = layer_buff_3d[addr].Re; double Img = layer_buff_3d[addr].Img; aAmp += sqrt(Re * Re + Img * Img); } } dax[i] = aAmp * imul; } // Y imul = 1.0 / ((double)sizex * (double)sizez); for (long long j = 0; j < sizey; j++) { double aAmp = 0.0; for (long long k = 0 ; k < sizez; k++) { for (long long i = 0; i < sizex; i++) { long long addr = p_addr_xyz_v1(sizex, sizey, i, j, k); double Re = layer_buff_3d[addr].Re; double Img = layer_buff_3d[addr].Img; aAmp += sqrt(Re * Re + Img * Img); } } day[j] = aAmp * imul; } // Z imul = 1.0 / ((double)sizex * (double)sizey); for (long long k = 0 ; k < sizez; k++) { double aAmp = 0.0; for (long long j = 0; j < sizey; j++) { for (long long i = 0; i < sizex; i++) { long long addr = p_addr_xyz_v1(sizex, sizey, i, j, k); double Re = layer_buff_3d[addr].Re; double Img = layer_buff_3d[addr].Img; aAmp += sqrt(Re * Re + Img * Img); } } daz[k] = aAmp * imul; } // Find the maxima // X long long coord; double max; // X coord = 0; max = dax[coord]; for (long long i = 1 ; i < sizex - 1; i++) { double maxt = dax[i]; if (maxt >= max) { // check if it is a real peak double maxp = dax[i - 1]; double maxn = dax[i + 1]; if (maxt > maxp && maxt > maxn) { if (i >= hsizex-1 && i <= hsizex + 1 && coord != 0) { double maxc = dax[i]; if (max < PEAKREJ * maxc) { max = maxt; coord = i; } } else { max = maxt; coord = i; } } } } coord = coord - hsizex; double kx = (double)coord * s_params.m_ResInverseWavelengthX; double nx = 2.0 * kx * s_params.m_SizeX * s_params.m_CellSizeX; k3d[0] = kx; n3d[0] = nx; // Y coord = 0; max = day[coord]; for (long long j = 1 ; j < sizey - 1; j++) { double maxt = day[j]; if (maxt >= max) { // check if it is a real peak double maxp = day[j - 1]; double maxn = day[j + 1]; if (maxt > maxp && maxt > maxn) { if (j >= hsizey - 1 && j <= hsizey + 1 && coord != 0) { double maxc = day[j]; if (max < PEAKREJ * maxc) { max = maxt; coord = j; } } else { max = maxt; coord = j; } } } } coord = coord - hsizey; double ky = (double)coord * s_params.m_ResInverseWavelengthY; double ny = 2.0 * ky * s_params.m_SizeY * s_params.m_CellSizeY; k3d[1] = ky; n3d[1] = ny; // Z coord = 0; max = daz[coord]; for (long long k = 1; k < sizez - 1; k++) { double maxt = daz[k]; if (maxt >= max) { // check if it is a real peak double maxp = daz[k - 1]; double maxn = daz[k + 1]; if (maxt > maxp && maxt > maxn) { if (k >= hsizez - 1 && k <= hsizez + 1 && coord != 0) { double maxc = daz[k]; if (max < PEAKREJ * maxc) { max = maxt; coord = k; } } else { max = maxt; coord = k; } } } } coord = coord - hsizez; double kz = (double)coord * s_params.m_ResInverseWavelengthZ; double nz = 2.0 * kz * s_params.m_SizeZ * s_params.m_CellSizeZ; k3d[2] = kz; n3d[2] = nz; delete[] dax; delete[] day; delete[] daz; } #pragma managed
26.191781
200
0.573906
[ "vector", "3d" ]
7f8999de4b3d3ebaea219cb922174734772bf9e2
635
cpp
C++
Sound/SoundProcessor/SoundProcessor.cpp
bigbn/libeXaDrums
4c89a9f4464ef00533610851c482abec489959e7
[ "BSD-3-Clause" ]
10
2017-06-18T19:59:44.000Z
2020-12-09T15:38:07.000Z
Sound/SoundProcessor/SoundProcessor.cpp
bigbn/libeXaDrums
4c89a9f4464ef00533610851c482abec489959e7
[ "BSD-3-Clause" ]
4
2019-11-25T22:49:01.000Z
2022-01-08T16:53:39.000Z
Sound/SoundProcessor/SoundProcessor.cpp
bigbn/libeXaDrums
4c89a9f4464ef00533610851c482abec489959e7
[ "BSD-3-Clause" ]
5
2019-06-16T16:09:46.000Z
2021-09-23T22:03:41.000Z
/* * SoundProcessor.cpp * * Created on: 14 Nov 2015 * Author: jeremy */ #include "SoundProcessor.h" #include <vector> #include <algorithm> #include <cmath> namespace Sound { Sound SoundProcessor::Muffle(const Sound& sound, float m) { //XXX Need to check m! const std::vector<short>& soundData = sound.GetInternalData(); std::vector<short> newSoundData(soundData.size()); const float gamma = -3.0f / (m * soundData.size()); for(std::size_t i = 0; i < newSoundData.size(); ++i) { newSoundData[i] = soundData[i] * std::exp(i * gamma); } return Sound(newSoundData); } } /* namespace Sound */
15.875
64
0.64252
[ "vector" ]
7f8c4c4d7f9fcb1852af5ec2487eb3fb7a256a87
703
cpp
C++
Leetcode/0630. Course Schedule III/0630.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0630. Course Schedule III/0630.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0630. Course Schedule III/0630.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: int scheduleCourse(vector<vector<int>>& courses) { int time = 0; sort(begin(courses), end(courses), [](const auto& a, const auto& b) { return a[1] < b[1]; }); priority_queue<int> maxHeap; for (const auto& c : courses) { const int duration = c[0]; const int lastDay = c[1]; maxHeap.push(duration); time += c[0]; // if current course could not be taken, check if it's able to swap with a // previously taken course with larger duration, to increase the time // available to take upcoming courses if (time > lastDay) time -= maxHeap.top(), maxHeap.pop(); } return maxHeap.size(); } };
29.291667
80
0.598862
[ "vector" ]
7f9135dca8825bf6193df37668a56f5ad81d420c
1,310
cpp
C++
Contests/USACO Solutions/2016-17/Jan 2017/Silver/17 Jan S1.cpp
nocrizwang/USACO
8a922f8d4b3bc905da97f53f9a447debe97d5e81
[ "CC0-1.0" ]
1,760
2017-05-21T21:07:06.000Z
2022-03-29T13:15:08.000Z
Contests/USACO Solutions/2016-17/Jan 2017/Silver/17 Jan S1.cpp
nocrizwang/USACO
8a922f8d4b3bc905da97f53f9a447debe97d5e81
[ "CC0-1.0" ]
12
2018-01-24T02:41:53.000Z
2022-03-17T13:09:26.000Z
Contests/USACO Solutions/2016-17/Jan 2017/Silver/17 Jan S1.cpp
nocrizwang/USACO
8a922f8d4b3bc905da97f53f9a447debe97d5e81
[ "CC0-1.0" ]
473
2017-07-06T04:53:41.000Z
2022-03-28T13:03:28.000Z
//#include <iostream> #include<fstream> #include<set> #include<map> #include<unordered_map> #include<cmath> #include<cstring> #include<string> #include<bitset> #include<algorithm> #include<vector> using namespace std; //using namespace __gnu_pbds; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pi; //typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set; #define FOR(i, a, b) for (int i=a; i<b; i++) #define F0R(i, a) for (int i=0; i<a; i++) #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound const int MOD = 1000000007; double PI = 4*atan(1); int N,T; vi dance; int ok (int k) { int cind = 0, ctime = 0; multiset<int> cur; F0R(i,N) { if (cur.size() == k) { ctime = *cur.begin(); cur.erase(cur.begin()); } cur.insert(dance[i]+ctime); } return *prev(cur.end()); } int main() { ifstream cin ("cowdance.in"); ofstream cout ("cowdance.out"); cin >> N >> T; dance.resize(N); F0R(i,N) cin >> dance[i]; int low = 1, high = N; while (low<high) { int mid = (low+high)/2; if (ok(mid) <= T) high = mid; else low = mid+1; } cout << low; }
19.848485
98
0.639695
[ "vector" ]
7fa6aea002996622ec4190a2cab39a0d305a8b06
3,848
hpp
C++
include/cminusf_builder.hpp
LuciferDarkStar/USTC_2020_Compiler_Lab_cminus-f
4ad49dac1b0c58c31ddbd0258e5674d91fc55ec5
[ "MIT" ]
2
2021-09-23T12:39:27.000Z
2021-11-23T11:31:12.000Z
labs/lab1/include/cminusf_builder.hpp
ltzheng/compiler-ustc
4856701207876e73480a5c431c03d19b7dcce7a3
[ "MIT" ]
null
null
null
labs/lab1/include/cminusf_builder.hpp
ltzheng/compiler-ustc
4856701207876e73480a5c431c03d19b7dcce7a3
[ "MIT" ]
1
2021-12-09T16:28:39.000Z
2021-12-09T16:28:39.000Z
#ifndef _CMINUSF_BUILDER_HPP_ #define _CMINUSF_BUILDER_HPP_ #include "BasicBlock.h" #include "Constant.h" #include "Function.h" #include "IRBuilder.h" #include "Module.h" #include "Type.h" #include "ast.hpp" #include <map> class Scope { public: // enter a new scope void enter() { inner.push_back({}); } // exit a scope void exit() { inner.pop_back(); } bool in_global() { return inner.size() == 1; } // push a name to scope // return true if successful // return false if this name already exits bool push(std::string name, Value *val) { auto result = inner[inner.size() - 1].insert({name, val}); return result.second; } Value* find(std::string name) { for (auto s = inner.rbegin(); s!= inner.rend();s++) { auto iter = s->find(name); if (iter != s->end()) { return iter->second; } } return nullptr; } private: std::vector<std::map<std::string, Value *>> inner; }; class CminusfBuilder: public ASTVisitor { public: CminusfBuilder() { module = std::unique_ptr<Module>(new Module("Cminus code")); builder = new IRBuilder(nullptr, module.get()); auto TyVoid = Type::get_void_type(module.get()); auto TyInt32 = Type::get_int32_type(module.get()); auto TyFloat = Type::get_float_type(module.get()); auto input_type = FunctionType::get(TyInt32, {}); auto input_fun = Function::create( input_type, "input", module.get()); std::vector<Type *> output_params; output_params.push_back(TyInt32); auto output_type = FunctionType::get(TyVoid, output_params); auto output_fun = Function::create( output_type, "output", module.get()); std::vector<Type *> output_float_params; output_float_params.push_back(TyFloat); auto output_float_type = FunctionType::get(TyVoid, output_float_params); auto output_float_fun = Function::create( output_float_type, "outputFloat", module.get()); auto neg_idx_except_type = FunctionType::get(TyVoid, {}); auto neg_idx_except_fun = Function::create( neg_idx_except_type, "neg_idx_except", module.get()); scope.enter(); scope.push("input", input_fun); scope.push("output", output_fun); scope.push("outputFloat", output_float_fun); scope.push("neg_idx_except", neg_idx_except_fun); } std::unique_ptr<Module> getModule() { return std::move(module); } private: virtual void visit(ASTProgram &) override final; virtual void visit(ASTNum &) override final; virtual void visit(ASTVarDeclaration &) override final; virtual void visit(ASTFunDeclaration &) override final; virtual void visit(ASTParam &) override final; virtual void visit(ASTCompoundStmt &) override final; virtual void visit(ASTExpressionStmt &) override final; virtual void visit(ASTSelectionStmt &) override final; virtual void visit(ASTIterationStmt &) override final; virtual void visit(ASTReturnStmt &) override final; virtual void visit(ASTAssignExpression &) override final; virtual void visit(ASTSimpleExpression &) override final; virtual void visit(ASTAdditiveExpression &) override final; virtual void visit(ASTVar &) override final; virtual void visit(ASTTerm &) override final; virtual void visit(ASTCall &) override final; IRBuilder *builder; Scope scope; std::unique_ptr<Module> module; }; #endif
30.0625
80
0.60369
[ "vector" ]
7fac183fa029dfb378a99aba30b818aafbb86e62
6,481
cpp
C++
source/AssetManager.cpp
dom380/IMAT3606-Coursework-2
36f50b25823cd3170a403a2e2ef50e3019fcd73b
[ "FTL", "Zlib", "Apache-2.0", "MIT" ]
null
null
null
source/AssetManager.cpp
dom380/IMAT3606-Coursework-2
36f50b25823cd3170a403a2e2ef50e3019fcd73b
[ "FTL", "Zlib", "Apache-2.0", "MIT" ]
null
null
null
source/AssetManager.cpp
dom380/IMAT3606-Coursework-2
36f50b25823cd3170a403a2e2ef50e3019fcd73b
[ "FTL", "Zlib", "Apache-2.0", "MIT" ]
null
null
null
#include "AssetManager.h" bool AssetManager::initialised = false; shared_ptr<AssetManager> AssetManager::instance; shared_ptr<AssetManager> AssetManager::getInstance() { if (initialised) { return instance; } instance = shared_ptr<AssetManager>(new AssetManager()); initialised = true; return instance; } shared_ptr<Texture> AssetManager::getTexture(const char * fileName) { string sFileName = string(fileName); auto it = textures.find(sFileName); if (it != textures.end()) { return it->second; } Bitmap bmp = Bitmap::bitmapFromFile(buildFilePath(ResourceType::TEXTURE, fileName)); bmp.flipVertically(); shared_ptr<Texture> ptr = std::make_shared<Texture>(bmp); textures.emplace(std::pair<string, shared_ptr<Texture>>(sFileName, ptr)); return ptr; } shared_ptr<Font> AssetManager::getFont(char * fontName, shared_ptr<Graphics>& graphics) { string sFontPath = string(fontName); auto it = fonts.find(sFontPath); if (it != fonts.end()) { return it->second; } FT_Library ft; FT_Error error = FT_Init_FreeType(&ft); string path = buildFilePath(ResourceType::FONT, fontName); shared_ptr<Font> fontPtr = std::make_shared<Font>(ft, path.c_str(), graphics); fontPtr->compile(); fonts.emplace(std::pair<string, shared_ptr<Font>>(string(fontName), fontPtr)); return fontPtr; } shared_ptr<Shader> AssetManager::getShader(std::pair<string, string> shaderName) { auto it = shaders.find(shaderName); if (it != shaders.end()) { return it->second; } shared_ptr<Shader> shader = std::make_shared<Shader>(); shader->compileShader(buildFilePath(ResourceType::SHADER, shaderName.first.c_str()).c_str(), GL_VERTEX_SHADER); shader->compileShader(buildFilePath(ResourceType::SHADER, shaderName.second.c_str()).c_str(), GL_FRAGMENT_SHADER); shader->link(); shader->bindShader(); shaders.emplace(std::pair<std::pair<string, string>, shared_ptr<Shader>>(shaderName, shader)); return shader; } shared_ptr<ModelData> AssetManager::getModelData(const char * fileName, shared_ptr<Graphics> graphics) { auto it = modelData.find(fileName); if (it != modelData.end()) { return it->second; } string fullPath = buildFilePath(ResourceType::MODEL, fileName); auto data = readModelFile(fullPath); graphics->bufferModelData(data); data->vertices.clear(); modelData.emplace(std::pair<string, shared_ptr<ModelData>>(fileName, data)); return data; } shared_ptr<std::vector<ConvexHull>> AssetManager::getCollisionData(const char * fileName) { auto it = collisionData.find(fileName); if (it != collisionData.end()) { return it->second; } shared_ptr<std::vector<ConvexHull>> data = std::make_shared<std::vector<ConvexHull>>(); string fullPath = buildFilePath(ResourceType::MODEL, fileName); readCollisionFile(fullPath, data); collisionData.emplace(std::pair <string, shared_ptr<std::vector<ConvexHull>>>(fileName, data)); return data; } string AssetManager::getScript(const char * fileName) { auto it = scripts.find(fileName); if (it != scripts.end()) { return it->second; } string fullPath = buildFilePath(ResourceType::SCRIPT, fileName); scripts.emplace(fileName, fullPath); return fullPath; } void AssetManager::setAssetFolder(string path, AssetManager::ResourceType resourceType) { switch (resourceType) { case ResourceType::LEVEL: levelFolder = path; break; case ResourceType::MODEL: modelFolder = path; break; case ResourceType::TEXTURE: textureFolder = path; break; case ResourceType::FONT: fontFolder = path; break; case ResourceType::SHADER: shaderFolder = path; break; case ResourceType::SCRIPT: scriptFolder = path; break; } } string AssetManager::getRootFolder(ResourceType resourceType) { switch (resourceType) { case ResourceType::LEVEL: return levelFolder; break; case ResourceType::MODEL: return modelFolder; break; case ResourceType::TEXTURE: return textureFolder; break; case ResourceType::FONT: return fontFolder; break; case ResourceType::SHADER: return shaderFolder; break; case ResourceType::SCRIPT: return scriptFolder; break; } } void AssetManager::exit() { textures.clear(); fonts.clear(); shaders.clear(); modelData.clear(); } string AssetManager::buildFilePath(ResourceType resourceType, const char * path) { switch (resourceType) { case ResourceType::LEVEL: return string(levelFolder+path); break; case ResourceType::MODEL: return string(modelFolder + path); break; case ResourceType::TEXTURE: return string(textureFolder + path); break; case ResourceType::FONT: return string(fontFolder + path); break; case ResourceType::SHADER: return string(shaderFolder + path); break; case ResourceType::SCRIPT: return string(scriptFolder + path); } } void AssetManager::readModelFile(string fullPath, vector<glm::vec4>& vertices, vector<glm::vec3>& normals, vector<glm::vec2>& textures, vector<unsigned short>& indices, shared_ptr<ModelData>& data, vector<glm::vec4>& points) { string fileExtension = getFileExt(fullPath); if (fileExtension == string("obj")) { //modelFileReader = std::make_shared<ObjReader>(); modelFileReader = std::make_shared<AssimpReader>(); modelFileReader->readFile(fullPath.c_str(), vertices, normals, textures, indices, data->material, points); } else if (fileExtension == string("dae")) { modelFileReader = std::make_shared<DaeReader>(); modelFileReader->readFile(fullPath.c_str(), vertices, normals, textures, indices, data->material, points); } else if (fileExtension == string("fbx")) { modelFileReader = std::make_shared<FbxReader>(); modelFileReader->readFile(fullPath.c_str(), vertices, normals, textures, indices, data->material, points); } else { std::cerr << "Unsupported file format" << fullPath << std::endl; } } shared_ptr<ModelData> AssetManager::readModelFile(string fullPath) { modelFileReader = std::make_shared<AssimpReader>(); return modelFileReader->readFile(fullPath.c_str()); } void AssetManager::readCollisionFile(string fullPath, shared_ptr<vector<ConvexHull>>& convexHulls) { string fileExtension = getFileExt(fullPath); if (fileExtension == string("obj")) { modelFileReader = std::make_shared<ObjReader>(); modelFileReader->readFile(fullPath.c_str(), convexHulls); } else { std::cerr << "Unsupported file format" << fullPath << std::endl; } } string AssetManager::getFileExt(const string& s) { size_t i = s.rfind('.', s.length()); if (i != string::npos) { return(s.substr(i + 1, s.length() - i)); } return(""); }
27.231092
224
0.731832
[ "vector", "model" ]
7fb10cffd44f9a0df971c3fa4af05aae6eefe47e
8,550
cpp
C++
tests/testPoseWithCovariance.cpp
AllMySlam1/Kimera-RPGO
8a020c26b1c4c5b5116396e4dd55c6647e382f00
[ "BSD-2-Clause" ]
null
null
null
tests/testPoseWithCovariance.cpp
AllMySlam1/Kimera-RPGO
8a020c26b1c4c5b5116396e4dd55c6647e382f00
[ "BSD-2-Clause" ]
null
null
null
tests/testPoseWithCovariance.cpp
AllMySlam1/Kimera-RPGO
8a020c26b1c4c5b5116396e4dd55c6647e382f00
[ "BSD-2-Clause" ]
null
null
null
/** * @file testPoseWithCovariance.cpp * @brief Unit test for PoseWithCovariance and calculations * @author Yun Chang */ #include <CppUnitLite/TestHarness.h> #include <random> #include "KimeraRPGO/utils/geometry_utils.h" using KimeraRPGO::PoseWithCovariance; struct normal_rv { explicit normal_rv(Eigen::MatrixXd const& covar) { Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigenSolver(covar); transform = eigenSolver.eigenvectors() * eigenSolver.eigenvalues().cwiseSqrt().asDiagonal(); } Eigen::MatrixXd transform; Eigen::VectorXd operator()() const { static std::mt19937 gen{std::random_device{}()}; static std::normal_distribution<> dist; return transform * Eigen::VectorXd{transform.rows()}.unaryExpr( [&](double x) { return dist(gen); }); } }; /* ************************************************************************* */ TEST(PoseWithCovariance, Inverse) { // Test the inverse operator for PoseWithCovariance struct PoseWithCovariance<gtsam::Pose3> A, B; // Create linearization points gtsam::Pose3 poseA(gtsam::Rot3(), gtsam::Point3(0, 0, 0)); A.pose = poseA; A.covariance_matrix = Eigen::MatrixXd::Identity(6, 6); B = A.inverse(); EXPECT(gtsam::assert_equal(B.pose, A.pose.inverse())); EXPECT(gtsam::assert_equal(B.covariance_matrix, A.covariance_matrix)); } /* ************************************************************************* */ TEST(PoseWithCovariance, Compose) { // Test the compose operator for PoseWithCovariance struct PoseWithCovariance<gtsam::Pose3> A, AB, B, BC, C, CD, D; A.pose = gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 1, 1)); // start A.covariance_matrix = 0.1 * Eigen::MatrixXd::Identity(6, 6); // First test a translation only gtsam::Pose3 poseAB(gtsam::Rot3(), gtsam::Point3(1, 1, 1)); AB.pose = poseAB; AB.covariance_matrix = 0.1 * Eigen::MatrixXd::Identity(6, 6); B = A.compose(AB); EXPECT(gtsam::assert_equal(A.pose.compose(AB.pose), B.pose)); // test first with calculation (so should be exact) Eigen::MatrixXd B_covar = Eigen::MatrixXd::Zero(6, 6); B_covar.row(0) << 2, 0, 0, 0, -1, 1; B_covar.row(1) << 0, 2, 0, 1, 0, -1; B_covar.row(2) << 0, 0, 2, -1, 1, 0; B_covar.row(3) << 0, 1, -1, 4, -1, -1; B_covar.row(4) << -1, 0, 1, -1, 4, -1; B_covar.row(5) << 1, -1, 0, -1, -1, 4; B_covar = 0.1 * B_covar; EXPECT(gtsam::assert_equal(B.covariance_matrix, B_covar)); // then test with monte carlo result (would take a while to compute) size_t sample_size = 1000; Eigen::MatrixXd cov = Eigen::MatrixXd::Zero(6, 6); for (size_t i = 0; i < sample_size; i++) { normal_rv noiseA(A.covariance_matrix); gtsam::Pose3 A_mc = A.pose.expmap(noiseA()); normal_rv noiseAB(AB.covariance_matrix); gtsam::Pose3 AB_mc = AB.pose.expmap(noiseAB()); gtsam::Pose3 B_mc = A_mc.compose(AB_mc); gtsam::Vector6 eps = gtsam::Pose3::Logmap(B.pose.inverse() * B_mc); cov = cov + eps * eps.transpose(); } cov = cov / sample_size; EXPECT(gtsam::assert_equal(cov, B.covariance_matrix, 0.1)); // 0.1 tolerance due to second order approximation // Then rotation only gtsam::Pose3 poseBC(gtsam::Rot3(0, 0, 0, 1), gtsam::Point3()); BC.pose = poseBC; BC.covariance_matrix = 0.1 * Eigen::MatrixXd::Identity(6, 6); BC.covariance_matrix.block(3, 3, 3, 3) = 0.01 * Eigen::MatrixXd::Identity(3, 3); C = B.compose(BC); EXPECT(gtsam::assert_equal(B.pose.compose(BC.pose), C.pose)); Eigen::MatrixXd C_covar = Eigen::MatrixXd::Zero(6, 6); C_covar.row(0) << 0.3, 0, 0, 0, -0.1, -0.1; C_covar.row(1) << 0, 0.3, 0, 0.1, 0, 0.1; C_covar.row(2) << 0, 0, 0.3, 0.1, -0.1, 0; C_covar.row(3) << 0, 0.1, 0.1, 0.41, -0.1, 0.1; C_covar.row(4) << -0.1, 0, -0.1, -0.1, 0.41, 0.1; C_covar.row(5) << -0.1, 0.1, 0, 0.1, 0.1, 0.41; EXPECT(gtsam::assert_equal(C.covariance_matrix, C_covar)); // then test with monte carlo result (would take a while to compute) cov = Eigen::MatrixXd::Zero(6, 6); for (size_t i = 0; i < sample_size; i++) { normal_rv noiseB(B.covariance_matrix); gtsam::Pose3 B_mc = B.pose.expmap(noiseB()); normal_rv noiseBC(BC.covariance_matrix); gtsam::Pose3 BC_mc = BC.pose.expmap(noiseBC()); gtsam::Pose3 C_mc = B_mc.compose(BC_mc); gtsam::Vector6 eps = gtsam::Pose3::Logmap(C.pose.inverse() * C_mc); cov = cov + eps * eps.transpose(); } cov = cov / sample_size; EXPECT(gtsam::assert_equal(cov, C.covariance_matrix, 0.1)); // rotation and translation gtsam::Pose3 poseCD(gtsam::Rot3(0, 0, 1, 0), gtsam::Point3(1, 0, 0)); CD.pose = poseCD; CD.covariance_matrix = 0.1 * Eigen::MatrixXd::Identity(6, 6); D = C.compose(CD); EXPECT(gtsam::assert_equal(C.pose.compose(CD.pose), D.pose)); Eigen::MatrixXd D_covar = Eigen::MatrixXd::Zero(6, 6); D_covar.row(0) << 0.4, 0, 0, 0, 0.1, -0.1; D_covar.row(1) << 0, 0.4, 0, -0.1, 0, 0.2; D_covar.row(2) << 0, 0, 0.4, 0.1, -0.2, 0; D_covar.row(3) << 0, -0.1, 0.1, 0.51, 0, 0; D_covar.row(4) << 0.1, 0, -0.2, 0, 0.61, -0.1; D_covar.row(5) << -0.1, 0.2, 0, 0, -0.1, 0.61; EXPECT(gtsam::assert_equal(D.covariance_matrix, D_covar)); // then test with monte carlo result (would take a while to compute) cov = Eigen::MatrixXd::Zero(6, 6); for (size_t i = 0; i < sample_size; i++) { normal_rv noiseC(C.covariance_matrix); gtsam::Pose3 C_mc = C.pose.expmap(noiseC()); normal_rv noiseCD(CD.covariance_matrix); gtsam::Pose3 CD_mc = CD.pose.expmap(noiseCD()); gtsam::Pose3 D_mc = C_mc.compose(CD_mc); gtsam::Vector6 eps = gtsam::Pose3::Logmap(D.pose.inverse() * D_mc); cov = cov + eps * eps.transpose(); } cov = cov / sample_size; EXPECT(gtsam::assert_equal(cov, D.covariance_matrix, 0.1)); } /* ************************************************************************* */ TEST(PoseWithCovariance, Between) { // Test the between operator for the PoseWithCovariance struct PoseWithCovariance<gtsam::Pose3> A, B, C; A.pose = gtsam::Pose3(); Eigen::MatrixXd A_covar = Eigen::MatrixXd::Zero(6, 6); A_covar.row(0) << 0.3, 0, 0, 0, -0.1, -0.1; A_covar.row(1) << 0, 0.3, 0, 0.1, 0, 0.1; A_covar.row(2) << 0, 0, 0.3, 0.1, -0.1, 0; A_covar.row(3) << 0, 0.1, 0.1, 0.41, -0.1, 0.1; A_covar.row(4) << -0.1, 0, -0.1, -0.1, 0.41, 0.1; A_covar.row(5) << -0.1, 0.1, 0, 0.1, 0.1, 0.41; A.covariance_matrix = A_covar; C.pose = gtsam::Pose3(gtsam::Rot3(0, 0, 1, 0), gtsam::Point3(1, 0, 0)); Eigen::MatrixXd C_covar = Eigen::MatrixXd::Zero(6, 6); C_covar.row(0) << 0.4, 0, 0, 0, 0.1, -0.1; C_covar.row(1) << 0, 0.4, 0, -0.1, 0, 0.2; C_covar.row(2) << 0, 0, 0.4, 0.1, -0.2, 0; C_covar.row(3) << 0, -0.1, 0.1, 0.51, 0, 0; C_covar.row(4) << 0.1, 0, -0.2, 0, 0.61, -0.1; C_covar.row(5) << -0.1, 0.2, 0, 0, -0.1, 0.61; C.covariance_matrix = C_covar; B = A.between(C); gtsam::Pose3 B_pose = gtsam::Pose3(gtsam::Rot3(0, 0, 1, 0), gtsam::Point3(1, 0, 0)); EXPECT(gtsam::assert_equal(B_pose, B.pose)); Eigen::MatrixXd B_covar = 0.1 * Eigen::MatrixXd::Identity(6, 6); EXPECT(gtsam::assert_equal(B_covar, B.covariance_matrix)); // check with monte carlo result size_t sample_size = 1000; Eigen::MatrixXd cov = Eigen::MatrixXd::Zero(6, 6); for (size_t i = 0; i < sample_size; i++) { normal_rv noiseA(A.covariance_matrix); gtsam::Pose3 A_mc = A.pose.expmap(noiseA()); normal_rv noiseB(B.covariance_matrix); gtsam::Pose3 B_mc = B.pose.expmap(noiseB()); gtsam::Pose3 C_mc = A_mc.compose(B_mc); gtsam::Vector6 eps = gtsam::Pose3::Logmap(C.pose.inverse() * C_mc); cov = cov + eps * eps.transpose(); } cov = cov / sample_size; EXPECT(gtsam::assert_equal(cov, C.covariance_matrix, 0.1)); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr); } /* ************************************************************************* */
36.853448
79
0.560234
[ "transform" ]
7fc1319e42e1de513e8050f8476cf1627895c93e
6,160
h++
C++
test/7/include/addentitydialog.h++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
test/7/include/addentitydialog.h++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
test/7/include/addentitydialog.h++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
#ifndef ADD_ENTITY_DIALOG_HPP_DEF__ #define ADD_ENTITY_DIALOG_HPP_DEF__ #include<string> #include<rexio/tk/button.h++> #include<rexio/tk/rootwindow.h++> #include<rexio/tk/window.h++> #include<boost/array.hpp> #include "boost/mpl/for_each.hpp" #include <boost/type_traits/is_base_of.hpp> #include "mapdata.h++" #include "alert.h++" #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> class MapData; #include "entity.h++" class CanAttack; class CanMove; class Warrior; //! Magic dialog for adding new entities: typelist independent base class AddEntityDialogBase: public Scr::Tk::Window { template<typename T> friend class Selector; private: int selection; public: //! number of columns static const size_t num_columns=9; //! default display style for selector static const Scr::DisplayStyle SelectorDisplayStyle1; //! default display style for focused selector static const Scr::DisplayStyle SelectorDisplayStyle2; //! selector button (used to select entity to produce; one button //! for one row of table, one row for one unit) class SelectorBase:public Scr::Tk::Button { friend class AddEntityDialogBase; protected: //! member array: contents of row boost::array<std::string, AddEntityDialogBase::num_columns> columns; public: //! constructor - basic setup. All parameters have default //! values and meaning the same as for Scr::Tk::Button explicit SelectorBase(const Scr::DisplayStyle& _style = SelectorDisplayStyle1, const Scr::DisplayStyle& _activeStyle = SelectorDisplayStyle2); //! display button void OnRedraw(Scr::Screen &screen)throw(); ~SelectorBase()throw() {} }; protected: //!widths of columns boost::array<int,num_columns> columns; //! header (usually empty) std::string header; //! additional setup - may be used by constructors of derived classes void AfterConstructorSetup()throw(); public: //! places dialog in window w. AddEntityDialogBase( Scr::Tk::Window & w, Scr::Uint hmax); //! default onredraw action void OnRedraw(Scr::Screen &screen)throw(); //! On key pressed actions: arrows to select option, enter to //! accept it. overrides default window behaviour void OnKeyDown(Scr::Key key)throw(); private: //! Unregister and destroy self void Suicide()throw(); public: //! process resize event virtual void OnResize()throw(); virtual void OnUnFocus(FocusPolicy focustype)throw(); virtual void OnFocus(FocusPolicy focustype)throw(); ~AddEntityDialogBase()throw(); }; /*! MPL based implementation of AddEntityDialog: constructor fills table with properties of all types listed within EntitiesList EntitiesList is boost::mpl meta-container for all types, that will be availble */ template <typename EntitiesList> class AddEntityDialog: AddEntityDialogBase { private: //! where we want to add that entity Scr::Position p1; //! which map does position above refer to MapData * pMD1; Entity * whoproduce; public: //! object, that represents specific class from EntitiesList template<typename T> class Selector:public SelectorBase { public: static const boost::true_type boost_true; //! print value in column, where static condition (refer to //! doc. for constructor) is fulfilled template <typename F> void PrintValue(F valuesrc, int col, boost::true_type = boost_true) { std::stringstream ss; ss << valuesrc(); columns[col].assign(ss.str()); } //! print value in column, where static condition (refer to //! doc. for constructor) is not fulfilled template <typename F> void PrintValue(F valuesrc, int col, boost::false_type) { columns[col].assign("N/A"); } public: //! Sets values of all columns. uses PrintValue function's //! tird parameter to call methods, which aren't present for //! all entity typed (using boost::is_base_of static condition) Selector(const Scr::DisplayStyle& _style = SelectorDisplayStyle1, const Scr::DisplayStyle& _activeStyle = SelectorDisplayStyle2) :SelectorBase( _style, _activeStyle) { namespace bl=boost::lambda; // must refer to bl::bind explicitly fo prevent name // conflict against boost::mpl::bind T E1; boost::is_base_of<CanAttack,T> can_attack; boost::is_base_of<CanMove,T> can_move; columns[0].assign(E1.GetName()); PrintValue(bl::bind(&Entity::GetCost,&E1),1); { std::stringstream ss; if (E1.GetCost()>=0) ss << E1.GetCost(); else ss << "0 (profit: "<< -E1.GetCost()<<')'; columns[2].assign(ss.str()); } PrintValue(bl::bind(&Entity::GetCostPT,&E1),2); columns[3].push_back(E1.GetSymbol()); PrintValue(bl::bind(&Entity::GetArmor,&E1),4); PrintValue(bl::bind(&Warrior::GetDamage,&E1),5,can_attack); PrintValue(bl::bind(&Warrior::GetRange,&E1),6,can_attack); PrintValue(bl::bind(&Warrior::GetAPMax,&E1),7,can_move); columns[8].assign(EntityTraits(E1)); } //! inserts item virtual void OnAction()throw() { T * pE1 = new T; AddEntityDialog&AF1(static_cast<AddEntityDialog&>(GetParent())); try { AF1.whoproduce->Produce(AF1.p1, SPE(pE1)); } catch (Scr::Exception & e) { Alert(GetParent().GetRootWindow(), e.what(), AddEntityDialogBase::SelectorDisplayStyle1); return; } RedrawRequest(); } }; //! mpl::foreach functor is only purpose for this class class DescribeEntity { AddEntityDialog&AF1; public: DescribeEntity(AddEntityDialog&AF) :AF1(AF){} template <typename T> void operator()(T e) { AF1.AddWidget(*(new Selector<T>)); } }; //!\param w: root window //!\param hmax: maximum height of window //!\param p: position on map, where facility will be constructed //!\param pMD: map, where position p will be verified //! AddEntityDialog( Scr::Tk::Window & w, Scr::Uint hmax, Scr::Position p, MapData * pMD, Entity * _whoproduce) :AddEntityDialogBase(w,hmax),p1(p),pMD1(pMD),whoproduce(_whoproduce) { boost::mpl::for_each<EntitiesList>(DescribeEntity(*this)); AfterConstructorSetup(); } ~AddEntityDialog()throw() {} }; #endif
29.056604
79
0.696753
[ "object" ]
7fc3e9684c39743a27c0c8522368401fab74facb
25,237
cpp
C++
GRBL-Arduino-Library-master/planner.cpp
aixiwang/logo2grbl
44b248605f08f5e378aaa79b7c2ab24c201d79ee
[ "BSD-3-Clause" ]
null
null
null
GRBL-Arduino-Library-master/planner.cpp
aixiwang/logo2grbl
44b248605f08f5e378aaa79b7c2ab24c201d79ee
[ "BSD-3-Clause" ]
null
null
null
GRBL-Arduino-Library-master/planner.cpp
aixiwang/logo2grbl
44b248605f08f5e378aaa79b7c2ab24c201d79ee
[ "BSD-3-Clause" ]
null
null
null
/* planner.c - buffers movement commands and manages the acceleration profile plan Part of Grbl Copyright (c) 2009-2011 Simen Svale Skogsrud Copyright (c) 2011-2012 Sungeun K. Jeon Copyright (c) 2011 Jens Geisler Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ /* The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis. */ #include <inttypes.h> #include <stdlib.h> #include "planner.h" #include "nuts_bolts.h" #include "stepper.h" #include "settings.h" #include "config.h" #include "protocol.h" static block_t block_buffer[BLOCK_BUFFER_SIZE]; // A ring buffer for motion instructions static volatile uint8_t block_buffer_head; // Index of the next block to be pushed static volatile uint8_t block_buffer_tail; // Index of the block to process now static uint8_t next_buffer_head; // Index of the next buffer head // Define planner variables typedef struct { int32_t position[3]; // The planner position of the tool in absolute steps. Kept separate // from g-code position for movements requiring multiple line motions, // i.e. arcs, canned cycles, and backlash compensation. float previous_unit_vec[3]; // Unit vector of previous path line segment float previous_nominal_speed; // Nominal speed of previous path line segment } planner_t; static planner_t pl; // Returns the index of the next block in the ring buffer // NOTE: Removed modulo (%) operator, which uses an expensive divide and multiplication. static uint8_t next_block_index(uint8_t block_index) { block_index++; if (block_index == BLOCK_BUFFER_SIZE) { block_index = 0; } return(block_index); } // Returns the index of the previous block in the ring buffer static uint8_t prev_block_index(uint8_t block_index) { if (block_index == 0) { block_index = BLOCK_BUFFER_SIZE; } block_index--; return(block_index); } // Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the // given acceleration: static float estimate_acceleration_distance(float initial_rate, float target_rate, float acceleration) { return( (target_rate*target_rate-initial_rate*initial_rate)/(2*acceleration) ); } /* + <- some maximum rate we don't care about /|\ / | \ / | + <- final_rate / | | initial_rate -> +----+--+ ^ ^ | | intersection_distance distance */ // This function gives you the point at which you must start braking (at the rate of -acceleration) if // you started at speed initial_rate and accelerated until this point and want to end at the final_rate after // a total travel of distance. This can be used to compute the intersection point between acceleration and // deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed) static float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance) { return( (2*acceleration*distance-initial_rate*initial_rate+final_rate*final_rate)/(4*acceleration) ); } // Calculates the maximum allowable speed at this point when you must be able to reach target_velocity // using the acceleration within the allotted distance. // NOTE: sqrt() reimplimented here from prior version due to improved planner logic. Increases speed // in time critical computations, i.e. arcs or rapid short lines from curves. Guaranteed to not exceed // BLOCK_BUFFER_SIZE calls per planner cycle. static float max_allowable_speed(float acceleration, float target_velocity, float distance) { return( sqrt(target_velocity*target_velocity-2*acceleration*distance) ); } // The kernel called by planner_recalculate() when scanning the plan from last to first entry. static void planner_reverse_pass_kernel(block_t *previous, block_t *current, block_t *next) { if (!current) { return; } // Cannot operate on nothing. if (next) { // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and // check for maximum allowable speed reductions to ensure maximum possible planned speed. if (current->entry_speed != current->max_entry_speed) { // If nominal length true, max junction speed is guaranteed to be reached. Only compute // for max allowable speed if block is decelerating and nominal length is false. if ((!current->nominal_length_flag) && (current->max_entry_speed > next->entry_speed)) { current->entry_speed = min( current->max_entry_speed, max_allowable_speed(-settings.acceleration,next->entry_speed,current->millimeters)); } else { current->entry_speed = current->max_entry_speed; } current->recalculate_flag = true; } } // Skip last block. Already initialized and set for recalculation. } // planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This // implements the reverse pass. static void planner_reverse_pass() { uint8_t block_index = block_buffer_head; block_t *block[3] = {NULL, NULL, NULL}; while(block_index != block_buffer_tail) { block_index = prev_block_index( block_index ); block[2]= block[1]; block[1]= block[0]; block[0] = &block_buffer[block_index]; planner_reverse_pass_kernel(block[0], block[1], block[2]); } // Skip buffer tail/first block to prevent over-writing the initial entry speed. } // The kernel called by planner_recalculate() when scanning the plan from first to last entry. static void planner_forward_pass_kernel(block_t *previous, block_t *current, block_t *next) { if(!previous) { return; } // Begin planning after buffer_tail // If the previous block is an acceleration block, but it is not long enough to complete the // full speed change within the block, we need to adjust the entry speed accordingly. Entry // speeds have already been reset, maximized, and reverse planned by reverse planner. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck. if (!previous->nominal_length_flag) { if (previous->entry_speed < current->entry_speed) { float entry_speed = min( current->entry_speed, max_allowable_speed(-settings.acceleration,previous->entry_speed,previous->millimeters) ); // Check for junction speed change if (current->entry_speed != entry_speed) { current->entry_speed = entry_speed; current->recalculate_flag = true; } } } } // planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This // implements the forward pass. static void planner_forward_pass() { uint8_t block_index = block_buffer_tail; block_t *block[3] = {NULL, NULL, NULL}; while(block_index != block_buffer_head) { block[0] = block[1]; block[1] = block[2]; block[2] = &block_buffer[block_index]; planner_forward_pass_kernel(block[0],block[1],block[2]); block_index = next_block_index( block_index ); } planner_forward_pass_kernel(block[1], block[2], NULL); } /* STEPPER RATE DEFINITION +--------+ <- nominal_rate / \ nominal_rate*entry_factor -> + \ | + <- nominal_rate*exit_factor +-------------+ time --> */ // Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors. // The factors represent a factor of braking and must be in the range 0.0-1.0. // This converts the planner parameters to the data required by the stepper controller. // NOTE: Final rates must be computed in terms of their respective blocks. static void calculate_trapezoid_for_block(block_t *block, float entry_factor, float exit_factor) { block->initial_rate = ceil(block->nominal_rate*entry_factor); // (step/min) block->final_rate = ceil(block->nominal_rate*exit_factor); // (step/min) int32_t acceleration_per_minute = block->rate_delta*ACCELERATION_TICKS_PER_SECOND*60.0; // (step/min^2) int32_t accelerate_steps = ceil(estimate_acceleration_distance(block->initial_rate, block->nominal_rate, acceleration_per_minute)); int32_t decelerate_steps = floor(estimate_acceleration_distance(block->nominal_rate, block->final_rate, -acceleration_per_minute)); // Calculate the size of Plateau of Nominal Rate. int32_t plateau_steps = block->step_event_count-accelerate_steps-decelerate_steps; // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will // have to use intersection_distance() to calculate when to abort acceleration and start braking // in order to reach the final_rate exactly at the end of this block. if (plateau_steps < 0) { accelerate_steps = ceil( intersection_distance(block->initial_rate, block->final_rate, acceleration_per_minute, block->step_event_count)); accelerate_steps = max(accelerate_steps,0); // Check limits due to numerical round-off accelerate_steps = min(accelerate_steps,block->step_event_count); plateau_steps = 0; } block->accelerate_until = accelerate_steps; block->decelerate_after = accelerate_steps+plateau_steps; } /* PLANNER SPEED DEFINITION +--------+ <- current->nominal_speed / \ current->entry_speed -> + \ | + <- next->entry_speed +-------------+ time --> */ // Recalculates the trapezoid speed profiles for flagged blocks in the plan according to the // entry_speed for each junction and the entry_speed of the next junction. Must be called by // planner_recalculate() after updating the blocks. Any recalulate flagged junction will // compute the two adjacent trapezoids to the junction, since the junction speed corresponds // to exit speed and entry speed of one another. static void planner_recalculate_trapezoids() { uint8_t block_index = block_buffer_tail; block_t *current; block_t *next = NULL; while(block_index != block_buffer_head) { current = next; next = &block_buffer[block_index]; if (current) { // Recalculate if current block entry or exit junction speed has changed. if (current->recalculate_flag || next->recalculate_flag) { // NOTE: Entry and exit factors always > 0 by all previous logic operations. calculate_trapezoid_for_block(current, current->entry_speed/current->nominal_speed, next->entry_speed/current->nominal_speed); current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed } } block_index = next_block_index( block_index ); } // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated. calculate_trapezoid_for_block(next, next->entry_speed/next->nominal_speed, MINIMUM_PLANNER_SPEED/next->nominal_speed); next->recalculate_flag = false; } // Recalculates the motion plan according to the following algorithm: // // 1. Go over every block in reverse order and calculate a junction speed reduction (i.e. block_t.entry_speed) // so that: // a. The junction speed is equal to or less than the maximum junction speed limit // b. No speed reduction within one block requires faster deceleration than the one, true constant // acceleration. // 2. Go over every block in chronological order and dial down junction speed values if // a. The speed increase within one block would require faster acceleration than the one, true // constant acceleration. // // When these stages are complete all blocks have an entry speed that will allow all speed changes to // be performed using only the one, true constant acceleration, and where no junction speed is greater // than the max limit. Finally it will: // // 3. Recalculate trapezoids for all blocks using the recently updated junction speeds. Block trapezoids // with no updated junction speeds will not be recalculated and assumed ok as is. // // All planner computations are performed with doubles (float on Arduinos) to minimize numerical round- // off errors. Only when planned values are converted to stepper rate parameters, these are integers. static void planner_recalculate() { planner_reverse_pass(); planner_forward_pass(); planner_recalculate_trapezoids(); } void plan_reset_buffer() { block_buffer_tail = block_buffer_head; next_buffer_head = next_block_index(block_buffer_head); } void plan_init() { plan_reset_buffer(); memset(&pl, 0, sizeof(pl)); // Clear planner struct } void plan_discard_current_block() { if (block_buffer_head != block_buffer_tail) { block_buffer_tail = next_block_index( block_buffer_tail ); } } block_t *plan_get_current_block() { if (block_buffer_head == block_buffer_tail) { return(NULL); } return(&block_buffer[block_buffer_tail]); } // Returns the availability status of the block ring buffer. True, if full. uint8_t plan_check_full_buffer() { if (block_buffer_tail == next_buffer_head) { return(true); } return(false); } // Block until all buffered steps are executed or in a cycle state. Works with feed hold // during a synchronize call, if it should happen. Also, waits for clean cycle end. void plan_synchronize() { while (plan_get_current_block() || sys.state == STATE_CYCLE) { protocol_execute_runtime(); // Check and execute run-time commands if (sys.abort) { return; } // Check for system abort } } // Add a new linear movement to the buffer. x, y and z is the signed, absolute target position in // millimeters. Feed rate specifies the speed of the motion. If feed rate is inverted, the feed // rate is taken to mean "frequency" and would complete the operation in 1/feed_rate minutes. // All position data passed to the planner must be in terms of machine position to keep the planner // independent of any coordinate system changes and offsets, which are handled by the g-code parser. // NOTE: Assumes buffer is available. Buffer checks are handled at a higher level by motion_control. void plan_buffer_line(float x, float y, float z, float feed_rate, uint8_t invert_feed_rate) { // Prepare to set up new block block_t *block = &block_buffer[block_buffer_head]; // Calculate target position in absolute steps int32_t target[3]; target[X_AXIS] = lround(x*settings.steps_per_mm[X_AXIS]); target[Y_AXIS] = lround(y*settings.steps_per_mm[Y_AXIS]); target[Z_AXIS] = lround(z*settings.steps_per_mm[Z_AXIS]); // Compute direction bits for this block block->direction_bits = 0; if (target[X_AXIS] < pl.position[X_AXIS]) { block->direction_bits |= (1<<X_DIRECTION_BIT); } if (target[Y_AXIS] < pl.position[Y_AXIS]) { block->direction_bits |= (1<<Y_DIRECTION_BIT); } if (target[Z_AXIS] < pl.position[Z_AXIS]) { block->direction_bits |= (1<<Z_DIRECTION_BIT); } // Number of steps for each axis block->steps_x = labs(target[X_AXIS]-pl.position[X_AXIS]); block->steps_y = labs(target[Y_AXIS]-pl.position[Y_AXIS]); block->steps_z = labs(target[Z_AXIS]-pl.position[Z_AXIS]); block->step_event_count = max(block->steps_x, max(block->steps_y, block->steps_z)); // Bail if this is a zero-length block if (block->step_event_count == 0) { return; }; // Compute path vector in terms of absolute step target and current positions float delta_mm[3]; delta_mm[X_AXIS] = (target[X_AXIS]-pl.position[X_AXIS])/settings.steps_per_mm[X_AXIS]; delta_mm[Y_AXIS] = (target[Y_AXIS]-pl.position[Y_AXIS])/settings.steps_per_mm[Y_AXIS]; delta_mm[Z_AXIS] = (target[Z_AXIS]-pl.position[Z_AXIS])/settings.steps_per_mm[Z_AXIS]; block->millimeters = sqrt(delta_mm[X_AXIS]*delta_mm[X_AXIS] + delta_mm[Y_AXIS]*delta_mm[Y_AXIS] + delta_mm[Z_AXIS]*delta_mm[Z_AXIS]); float inverse_millimeters = 1.0/block->millimeters; // Inverse millimeters to remove multiple divides // Calculate speed in mm/minute for each axis. No divide by zero due to previous checks. // NOTE: Minimum stepper speed is limited by MINIMUM_STEPS_PER_MINUTE in stepper.c float inverse_minute; if (!invert_feed_rate) { inverse_minute = feed_rate * inverse_millimeters; } else { inverse_minute = 1.0 / feed_rate; } block->nominal_speed = block->millimeters * inverse_minute; // (mm/min) Always > 0 block->nominal_rate = ceil(block->step_event_count * inverse_minute); // (step/min) Always > 0 // Compute the acceleration rate for the trapezoid generator. Depending on the slope of the line // average travel per step event changes. For a line along one axis the travel per step event // is equal to the travel/step in the particular axis. For a 45 degree line the steppers of both // axes might step for every step event. Travel per step event is then sqrt(travel_x^2+travel_y^2). // To generate trapezoids with contant acceleration between blocks the rate_delta must be computed // specifically for each line to compensate for this phenomenon: // Convert universal acceleration for direction-dependent stepper rate change parameter block->rate_delta = ceil( block->step_event_count*inverse_millimeters * settings.acceleration / (60 * ACCELERATION_TICKS_PER_SECOND )); // (step/min/acceleration_tick) // Compute path unit vector float unit_vec[3]; unit_vec[X_AXIS] = delta_mm[X_AXIS]*inverse_millimeters; unit_vec[Y_AXIS] = delta_mm[Y_AXIS]*inverse_millimeters; unit_vec[Z_AXIS] = delta_mm[Z_AXIS]*inverse_millimeters; // Compute maximum allowable entry speed at junction by centripetal acceleration approximation. // Let a circle be tangent to both previous and current path line segments, where the junction // deviation is defined as the distance from the junction to the closest edge of the circle, // colinear with the circle center. The circular segment joining the two paths represents the // path of centripetal acceleration. Solve for max velocity based on max acceleration about the // radius of the circle, defined indirectly by junction deviation. This may be also viewed as // path width or max_jerk in the previous grbl version. This approach does not actually deviate // from path, but used as a robust way to compute cornering speeds, as it takes into account the // nonlinearities of both the junction angle and junction velocity. // NOTE: This is basically an exact path mode (G61), but it doesn't come to a complete stop unless // the junction deviation value is high. In the future, if continuous mode (G64) is desired, the // math here is exactly the same. Instead of motioning all the way to junction point, the machine // will just need to follow the arc circle defined above and check if the arc radii are no longer // than half of either line segment to ensure no overlapping. Right now, the Arduino likely doesn't // have the horsepower to do these calculations at high feed rates. float vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles. if ((block_buffer_head != block_buffer_tail) && (pl.previous_nominal_speed > 0.0)) { // Compute cosine of angle between previous and current path. (prev_unit_vec is negative) // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity. float cos_theta = - pl.previous_unit_vec[X_AXIS] * unit_vec[X_AXIS] - pl.previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS] - pl.previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ; // Skip and use default max junction speed for 0 degree acute junction. if (cos_theta < 0.95) { vmax_junction = min(pl.previous_nominal_speed,block->nominal_speed); // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds. if (cos_theta > -0.95) { // Compute maximum junction velocity based on maximum acceleration and junction deviation float sin_theta_d2 = sqrt(0.5*(1.0-cos_theta)); // Trig half angle identity. Always positive. vmax_junction = min(vmax_junction, sqrt(settings.acceleration * settings.junction_deviation * sin_theta_d2/(1.0-sin_theta_d2)) ); } } } block->max_entry_speed = vmax_junction; // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED. float v_allowable = max_allowable_speed(-settings.acceleration,MINIMUM_PLANNER_SPEED,block->millimeters); block->entry_speed = min(vmax_junction, v_allowable); // Initialize planner efficiency flags // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then // the current block and next block junction speeds are guaranteed to always be at their maximum // junction speeds in deceleration and acceleration, respectively. This is due to how the current // block nominal speed limits both the current and next maximum junction speeds. Hence, in both // the reverse and forward planners, the corresponding block junction speed will always be at the // the maximum junction speed and may always be ignored for any speed reduction checks. if (block->nominal_speed <= v_allowable) { block->nominal_length_flag = true; } else { block->nominal_length_flag = false; } block->recalculate_flag = true; // Always calculate trapezoid for new block // Update previous path unit_vector and nominal speed memcpy(pl.previous_unit_vec, unit_vec, sizeof(unit_vec)); // pl.previous_unit_vec[] = unit_vec[] pl.previous_nominal_speed = block->nominal_speed; // Update buffer head and next buffer head indices block_buffer_head = next_buffer_head; next_buffer_head = next_block_index(block_buffer_head); // Update planner position memcpy(pl.position, target, sizeof(target)); // pl.position[] = target[] planner_recalculate(); } // Reset the planner position vector (in steps). Called by the system abort routine. void plan_set_current_position(int32_t x, int32_t y, int32_t z) { pl.position[X_AXIS] = x; pl.position[Y_AXIS] = y; pl.position[Z_AXIS] = z; } // Re-initialize buffer plan with a partially completed block, assumed to exist at the buffer tail. // Called after a steppers have come to a complete stop for a feed hold and the cycle is stopped. void plan_cycle_reinitialize(int32_t step_events_remaining) { block_t *block = &block_buffer[block_buffer_tail]; // Point to partially completed block // Only remaining millimeters and step_event_count need to be updated for planner recalculate. // Other variables (step_x, step_y, step_z, rate_delta, etc.) all need to remain the same to // ensure the original planned motion is resumed exactly. block->millimeters = (block->millimeters*step_events_remaining)/block->step_event_count; block->step_event_count = step_events_remaining; // Re-plan from a complete stop. Reset planner entry speeds and flags. block->entry_speed = 0.0; block->max_entry_speed = 0.0; block->nominal_length_flag = false; block->recalculate_flag = true; planner_recalculate(); }
49.974257
119
0.69624
[ "vector" ]
7fc54578ea760d689d66704b6c2e5a20d7a75973
9,907
cpp
C++
week3/hammer-time/main.cpp
jonastheis/glitch
6fa97b1da6f018d979c46388b17abadef9f0b07e
[ "Apache-2.0" ]
1
2022-02-18T07:56:17.000Z
2022-02-18T07:56:17.000Z
week3/hammer-time/main.cpp
jonastheis/glitch
6fa97b1da6f018d979c46388b17abadef9f0b07e
[ "Apache-2.0" ]
null
null
null
week3/hammer-time/main.cpp
jonastheis/glitch
6fa97b1da6f018d979c46388b17abadef9f0b07e
[ "Apache-2.0" ]
1
2022-02-18T10:04:54.000Z
2022-02-18T10:04:54.000Z
#include <GLES3/gl3.h> #include <GLES3/gl3ext.h> #include <EGL/egl.h> #include <EGL/eglext.h> #include <stdio.h> #include <unistd.h> #include <iostream> #include <math.h> #include "size.h" #include "mem_util.h" #include "eglSetup.h" #include "shader.cpp" #include "allocator.h" #include "counters.h" using namespace std; Shader shader; unsigned int framebuffer; KGSLEntry cont_entries[64]; inline double log2(const double x) { return log(x) * M_LOG2E; } //assumes little endian void printBits(size_t const size, void const *const ptr) { unsigned char *b = (unsigned char *)ptr; unsigned char byte; int i, j; printf("+++ Bit-value: "); for (i = size - 1; i >= 0; i--) { for (j = 7; j >= 0; j--) { byte = (b[i] >> j) & 1; printf("%u", byte); } } puts(""); } void init_opengl_setup() { shader = Shader( "/data/local/tmp/papa/shaders/tr.vs", "/data/local/tmp/papa/shaders/tr.fs"); // execute shader.use(); } void view_texture(unsigned int textureId, int kgsl_index) { glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); // attach it to currently bound framebuffer object glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl; } // allocate data in memory auto *exportData = (unsigned char*)malloc(KB4); glReadPixels(0, 0, PAGE_TEXTURE_W, PAGE_TEXTURE_H, GL_RGBA, GL_UNSIGNED_BYTE, exportData); int flip = 0; for (int i = 0; i < KB4; i++) { if (exportData[i] != 0xff) { printf("++++ BIT FLIP IDENTIFIED\n"); printf("+++ INFO: [Texture-Id: %u][Bit-Index: %d][Byte-Index: %d][ByteValue: %x][8-byte-offset: %d]\n", cont_entries[kgsl_index].texture_id, (int)log2(exportData[i] ^ 0xff), i, exportData[i], i / 8); printBits(1, &exportData[i]); print_entries(cont_entries, kgsl_index, 1); // exit(0); flip = 1; for (int ii = 0; ii <KB4; ii++) { if (ii % 32 == 0) { printf("\n"); } if ( ii % 4 == 0 ) { printf(" "); } printf("%x,", exportData[ii]); } printf("\n"); } } if (!flip) { // printf("---- [%u] No Flip For You!\n", textureId); } free(exportData); } void init_framebuffer() { // allocate framebuffer glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); } void fill_texture(unsigned int textureId, unsigned char value) { auto *data = (unsigned char*)malloc(KB4); memset((void *)data, value, KB4); // write special values to texture glBindTexture(GL_TEXTURE_2D, textureId); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, PAGE_TEXTURE_W, PAGE_TEXTURE_H, GL_RGBA, GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, 0); free(data); } /** * Create plain 2D full coordinate system width/height (full screen) rectangle */ void createRectangle() { // prepare rectangle float vertices[] = { 1, 1, 0.0f, // top right 1, -1, 0.0f, // bottom right -1, -1, 0.0f, // bottom left -1, 1, 0.0f // top left }; unsigned int indices[] = { // note that we start from 0! 0, 1, 3, // first Triangle 1, 2, 3 // second Triangle }; unsigned int VAO, VBO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // binding one time is sufficient, because there is only 1 object to draw glBindVertexArray(VAO); } void init_debug() { GLuint texture; glGenTextures(1, (GLuint*)&texture); init_framebuffer(); createTexture2DRGBA(texture, NULL, PAGE_TEXTURE_W, PAGE_TEXTURE_H); // attach it to currently bound framebuffer object glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); // Render to our framebuffer glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl; } // create rectangle createRectangle(); } /** * View every pixel of the framebuffer */ void view_framebuffer() { // allocate data in memory auto *exportData = (unsigned char*)malloc(KB4); glReadPixels(0, 0, PAGE_TEXTURE_W, PAGE_TEXTURE_H, GL_RGBA, GL_UNSIGNED_BYTE, exportData); for (int i = 0; i <KB4; i++) { if (i % 32 == 0) { printf("\n"); } if (i % 4 == 0) { printf(" "); } printf("%u,", exportData[i]); } printf("\n"); free(exportData); } void bind_texture(unsigned int textureId, int i, char type, int offset) { char temp[20]; sprintf(temp, "%cTex0%d", type, i); // printf("++ Binding [%s] %d=[%d] -- offset: %d\n", temp, textureId, textureId%256, offset); GLuint uUniform = glGetUniformLocation(shader.ID, temp); glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, textureId); glUniform1i(uUniform, i); } void _prepare_hammer_time() { // example for hammering first bank x=hammer, .=eviction // 0001 0203 0405 0607 0809 1011 1213 1415 // |xxxx|----|----|----|----|----|----|----| // 1617 1819 2021 2223 2425 2627 2829 3031 // |----|----|----|----|----|----|----|----| // 3233 3435 3637 3839 4041 4243 4445 4647 // |xxxx|----|----|----|----|----|----|----| // 4849 5051 5253 5455 5657 5859 6061 6263 // |----|----|----|----|----|--..|....|....| for (int row = 0; row <= 16; row += 16) { printf("++ Prepare row [%d]\n", row/16); // fill textures in row n-1, n+1 with 0 for (int localOffset = 0; localOffset < 16; localOffset += 2) { int offset = row + localOffset; // printf("++ Hammering [%d][%d]\n", offset, offset+1); fill_texture(cont_entries[offset + 0].texture_id, 0x00); fill_texture(cont_entries[offset + 1].texture_id, 0x00); fill_texture(cont_entries[offset + 32].texture_id, 0x00); fill_texture(cont_entries[offset + 33].texture_id, 0x00); // fill textures in row n with 1 fill_texture(cont_entries[offset + 16].texture_id, 0xFF); fill_texture(cont_entries[offset + 17].texture_id, 0xFF); // pass hammer textures according to hammer pattern: jump to differnet row to trigger row buffer when hammering bind_texture(cont_entries[offset + 0].texture_id, 0, 'H', offset + 0); bind_texture(cont_entries[offset + 32].texture_id, 2, 'H', offset + 32); bind_texture(cont_entries[offset + 1].texture_id, 4, 'H', offset + 1); bind_texture(cont_entries[offset + 33].texture_id, 6, 'H', offset + 33); // select 5 textures for eviction if (row >= 16) { if (localOffset < 8) { // take 5 textures from end of first row: 11,12,13,14,15 for (int i = 0; i < 5; i++) { bind_texture(cont_entries[11 + i].texture_id, i == 4 ? 8 : i*2+1, 'H', 11 + i); } } else { // take 5 textures from beginning of first row: 0,1,2,3,4 for (int i = 0; i < 5; i++) { bind_texture(cont_entries[i].texture_id, i == 4 ? 8 : i*2+1, 'H', i); } } } else { if (localOffset < 8) { // take 5 textures from end of last row: 59,60,61,62,63 for (int i = 0; i < 5; i++) { bind_texture(cont_entries[59 + i].texture_id, i == 4 ? 8 : i*2+1, 'H', 59 + i); } } else { // take 5 textures from beginning of last row: 48,49,50,51,52 for (int i = 0; i < 5; i++) { bind_texture(cont_entries[48 + i].texture_id, i == 4 ? 8 : i*2+1, 'H', 48 + i); } } } // important: bind dummy texture last to prevent last texture error bind_texture(cont_entries[15].texture_id, 9, 'D', 15); glDrawArrays(GL_POINTS, 0, 1); // check hammered textures for bit flip // printf("+++ Checking [%d][%d]\n", offset + 16, offset + 17); view_texture(cont_entries[offset + 16].texture_id, offset+16); view_texture(cont_entries[offset + 17].texture_id, offset+17); } } } void prepare_hammer_time(){ for (int i = 0; i < 400000; i++) { allocate_cont(64, KB4, &cont_entries[0]); // print_entries(cont_entries, 0, 4); _prepare_hammer_time(); } } int main( int argc, char** argv ) { egl_setup(); init_opengl_setup(); init_framebuffer(); // ---------------------- Main Program: Run bitflip test ---------------------- prepare_hammer_time(); // ---------------------- Testing Setups ---------------------- // Option1) debug shader output with framebuffer // init_debug(); // allocate_cont(64, KB4, &cont_entries[0]); // print_entries(cont_entries, 0, 4); // _prepare_hammer_time(); // glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // view_framebuffer(); // Option2) Execute 1 pixel // glDrawArrays(GL_POINTS, 0, 1); // Option3) Execute 1 pixel with counters // counters_init(); // GLuint group_UCHE[] = {8, 9, 9}; // GLuint counter_UCHE[] = {0, 1, 2}; // GLuint num_target_counters = 3; // allocate_cont(64, KB4, &cont_entries[0]); // print_entries(cont_entries, 0, 4); // _prepare_hammer_time(); // perform_measurement(group_UCHE, counter_UCHE, num_target_counters); return 0; }
30.57716
117
0.608661
[ "render", "object" ]
7fc8da192d0962787aa999a1a82913b78fcb6dfa
5,604
cpp
C++
cdb/src/v20170320/model/Address.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
1
2022-01-27T09:27:34.000Z
2022-01-27T09:27:34.000Z
cdb/src/v20170320/model/Address.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
cdb/src/v20170320/model/Address.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cdb/v20170320/model/Address.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cdb::V20170320::Model; using namespace std; Address::Address() : m_vipHasBeenSet(false), m_vPortHasBeenSet(false), m_uniqVpcIdHasBeenSet(false), m_uniqSubnetHasBeenSet(false), m_descHasBeenSet(false) { } CoreInternalOutcome Address::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Vip") && !value["Vip"].IsNull()) { if (!value["Vip"].IsString()) { return CoreInternalOutcome(Core::Error("response `Address.Vip` IsString=false incorrectly").SetRequestId(requestId)); } m_vip = string(value["Vip"].GetString()); m_vipHasBeenSet = true; } if (value.HasMember("VPort") && !value["VPort"].IsNull()) { if (!value["VPort"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `Address.VPort` IsUint64=false incorrectly").SetRequestId(requestId)); } m_vPort = value["VPort"].GetUint64(); m_vPortHasBeenSet = true; } if (value.HasMember("UniqVpcId") && !value["UniqVpcId"].IsNull()) { if (!value["UniqVpcId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Address.UniqVpcId` IsString=false incorrectly").SetRequestId(requestId)); } m_uniqVpcId = string(value["UniqVpcId"].GetString()); m_uniqVpcIdHasBeenSet = true; } if (value.HasMember("UniqSubnet") && !value["UniqSubnet"].IsNull()) { if (!value["UniqSubnet"].IsString()) { return CoreInternalOutcome(Core::Error("response `Address.UniqSubnet` IsString=false incorrectly").SetRequestId(requestId)); } m_uniqSubnet = string(value["UniqSubnet"].GetString()); m_uniqSubnetHasBeenSet = true; } if (value.HasMember("Desc") && !value["Desc"].IsNull()) { if (!value["Desc"].IsString()) { return CoreInternalOutcome(Core::Error("response `Address.Desc` IsString=false incorrectly").SetRequestId(requestId)); } m_desc = string(value["Desc"].GetString()); m_descHasBeenSet = true; } return CoreInternalOutcome(true); } void Address::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_vipHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Vip"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_vip.c_str(), allocator).Move(), allocator); } if (m_vPortHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VPort"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_vPort, allocator); } if (m_uniqVpcIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UniqVpcId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_uniqVpcId.c_str(), allocator).Move(), allocator); } if (m_uniqSubnetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UniqSubnet"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_uniqSubnet.c_str(), allocator).Move(), allocator); } if (m_descHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Desc"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_desc.c_str(), allocator).Move(), allocator); } } string Address::GetVip() const { return m_vip; } void Address::SetVip(const string& _vip) { m_vip = _vip; m_vipHasBeenSet = true; } bool Address::VipHasBeenSet() const { return m_vipHasBeenSet; } uint64_t Address::GetVPort() const { return m_vPort; } void Address::SetVPort(const uint64_t& _vPort) { m_vPort = _vPort; m_vPortHasBeenSet = true; } bool Address::VPortHasBeenSet() const { return m_vPortHasBeenSet; } string Address::GetUniqVpcId() const { return m_uniqVpcId; } void Address::SetUniqVpcId(const string& _uniqVpcId) { m_uniqVpcId = _uniqVpcId; m_uniqVpcIdHasBeenSet = true; } bool Address::UniqVpcIdHasBeenSet() const { return m_uniqVpcIdHasBeenSet; } string Address::GetUniqSubnet() const { return m_uniqSubnet; } void Address::SetUniqSubnet(const string& _uniqSubnet) { m_uniqSubnet = _uniqSubnet; m_uniqSubnetHasBeenSet = true; } bool Address::UniqSubnetHasBeenSet() const { return m_uniqSubnetHasBeenSet; } string Address::GetDesc() const { return m_desc; } void Address::SetDesc(const string& _desc) { m_desc = _desc; m_descHasBeenSet = true; } bool Address::DescHasBeenSet() const { return m_descHasBeenSet; }
25.824885
136
0.662919
[ "model" ]
7fcf0ff663b026333e5b5603f671d5a49265efac
2,418
cpp
C++
examples/ExampleSimpleProtein.cpp
MadCatX/molmodel
5abde979e1780dcc61a4b05affcba6e116250585
[ "MIT" ]
null
null
null
examples/ExampleSimpleProtein.cpp
MadCatX/molmodel
5abde979e1780dcc61a4b05affcba6e116250585
[ "MIT" ]
1
2020-12-09T16:45:16.000Z
2020-12-09T16:56:52.000Z
examples/ExampleSimpleProtein.cpp
MadCatX/molmodel
5abde979e1780dcc61a4b05affcba6e116250585
[ "MIT" ]
4
2020-06-23T18:24:37.000Z
2021-04-29T14:44:25.000Z
/* -------------------------------------------------------------------------- * * SimTK Molmodel Example: Simple Protein * * -------------------------------------------------------------------------- * * This is the first example from the Molmodel User's Guide. It creates a * * small protein (a five-residue peptide), simulates it and generates a live * * animation while it is running. * * * * Authors: Christopher Bruns, Michael Sherman * * -------------------------------------------------------------------------- */ #include "Molmodel.h" #include <iostream> #include <exception> using namespace SimTK; int main() { try { // molecule-specialized simbody System CompoundSystem system; SimbodyMatterSubsystem matter(system); DecorationSubsystem decorations(system); // molecular force field DuMMForceFieldSubsystem forceField(system); forceField.loadAmber99Parameters(); // Create a five-residue protein. Neutral end caps are automatically // added unless you suppress them. This is // (Ace-) Ser-Ile-Met-Thr-Lys (-Nac). Protein protein("SIMTK"); protein.assignBiotypes(); system.adoptCompound(protein); // finalize mapping of atoms to bodies system.modelCompounds(); // show me a movie system.addEventReporter(new Visualizer::Reporter(system, 0.020)); // Maintain a constant temperature. (This isn't a very good // thermostat -- consider NoseHooverThermostat instead.) system.addEventHandler(new VelocityRescalingThermostat( system, 293.15, 0.1)); // Instantiate simbody model and get default state State state = system.realizeTopology(); // Relax the structure before dynamics run LocalEnergyMinimizer::minimizeEnergy(system, state, 15.0); // Simulate it. VerletIntegrator integ(system); TimeStepper ts(system, integ); ts.initialize(state); ts.stepTo(20.0); // 20ps return 0; } catch(const std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; return 1; } catch(...) { std::cerr << "ERROR: An unknown exception was raised" << std::endl; return 1; } }
33.123288
81
0.540116
[ "model" ]
7fd290523f84f745f571ca07e1361e04313b30a8
5,273
cpp
C++
relationships/wariancja.cpp
tehora/phd-sourcecodes
b8c9be03b6de012b886e3d3f43c9d179ec2d701b
[ "MIT" ]
null
null
null
relationships/wariancja.cpp
tehora/phd-sourcecodes
b8c9be03b6de012b886e3d3f43c9d179ec2d701b
[ "MIT" ]
null
null
null
relationships/wariancja.cpp
tehora/phd-sourcecodes
b8c9be03b6de012b886e3d3f43c9d179ec2d701b
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> #include <map> #include <string.h> #include <set> #include <unordered_map> using namespace std; #include "czytgraf.cpp" vector<int> indeg[2], outdeg[2]; int scanerr; #define MEMBER 0 #define FOLLOWER 1 const char *nameof(int t) { return t?"FOLLOWER":"MEMBER"; } struct edgedata { int ingraph[2]; int revgraph[2]; edgedata() { ingraph[0] = ingraph[1] = revgraph[0] = revgraph[1] = 0; } }; // wersja 1 long long vpair(int x, int y) { return (((long long)x)<<32) | y; } unordered_map<long long, edgedata> edata; // wersja 2 /* auto vpair(int i, int j) { return make_pair(i,j); } map<pair<int, int>, edgedata> edata; */ // long long qty[16]; bool STARE = false; int main(int argc, char ** argv) { printf("czytgraf0...\n"); czytgraf(argv[1], 0); printf("czytgraf1...\n"); czytgraf(argv[2], 1); printf("renumer...\n"); renumer(); // for(int i=0; i<M; i++) if(edges[i].t == FOLLOWER) swap(edges[i].a, edges[i].b); printf("invalid\n"); array<int, 2> narcyzy = {0, 0}; array<int, 2> repeated = {0, 0}; for(int i=0; i<M; i++) { edges[i].invalid = edges[i].a == edges[i].b; if(edges[i].invalid) narcyzy[edges[i].t]++; if(edges[i].a >= N || edges[i].b >= N || edges[i].a < 0 || edges[i].b < 0) { printf("invalid %d-%d t=%d\n", edges[i].a, edges[i].b, edges[i].t); edges[i].invalid = true; } if(edges[i].invalid) continue; { edgedata& ed(edata[vpair(edges[i].a, edges[i].b)]); if(ed.ingraph[edges[i].t]) { edges[i].invalid = true; repeated[edges[i].t]++; } else ed.ingraph[edges[i].t]++; } if(edges[i].invalid) continue; { edgedata& ed(edata[vpair(edges[i].b, edges[i].a)]); ed.revgraph[edges[i].t]++; } } for(int t=0; t<2; t++) printf("narcyzy = %d repeated = %d\n", narcyzy[t], repeated[t]); printf("in/outdeg\n"); for(int t=0; t<2; t++) { indeg[t].resize(N); outdeg[t].resize(N); for(int i=0; i<N; i++) indeg[t][i] = outdeg[t][i] = 0; } for(int i=0; i<M; i++) if(!edges[i].invalid) outdeg[edges[i].t][edges[i].a]++, indeg[edges[i].t][edges[i].b]++; printf("stat\n"); long long stat[2][5]; for(int t=0; t<2; t++) for(int l=0; l<5; l++) stat[t][l] = 0; for(int i=0; i<M; i++) { edge& ed(edges[i]); if(ed.invalid) continue; int t = ed.t; stat[t][0]++; } for(int i=0; i<M; i++) { edge& ed(edges[i]); if(ed.invalid) continue; int t = ed.t; bool rev = edata[vpair(ed.a, ed.b)].revgraph[t] == 1; if(rev) stat[t][1]++; stat[t][2] += outdeg[t][ed.b] - (rev?1:0); stat[t][3] += indeg[t][ed.a] - (rev?1:0); stat[t][4] += stat[t][0] - (rev?2:1) - outdeg[t][ed.b] - indeg[t][ed.a]; } const char *nazwy[5] = { "krawedzie poprawne", "krawedzie poprawne mutual", "dziwne dziadostwo sumujace stopnie wyjsciowe", "dziwne dziadostwo sumujace stopnie wejsciowe", "dziwne dziadostwo sumujace co sie da" }; for(int t=0; t<2; t++) for(int l=0; l<5; l++) printf("%d,%d: %Ld (%s)\n", t,l, stat[t][l], nazwy[l]); vector<int> notnarc; for(int i=0; i<N; i++) if(indeg[0][i] || outdeg[0][i] || indeg[1][i] || outdeg[1][i]) notnarc.push_back(i); int NN = notnarc.size(); long double N1 = 1.0 / NN; long double N2 = N1 / (NN-1); long double N3 = N2 / (NN-2); long double N4 = N3 / (NN-3); printf("NN = %d\n", NN); double valat = 0; for(auto it: edata) if(it.second.ingraph[0] && it.second.ingraph[1]) valat++; printf("common edges = %d\n", (int) valat); long double expected = stat[0][0] * (stat[1][0] * N2); long double expected2 = stat[0][0] * (stat[1][0] * N2) + stat[0][1] * (stat[1][1] * N2) + stat[0][2] * (stat[1][2] * N3) + stat[0][3] * (stat[1][3] * N3) + stat[0][4] * (stat[1][4] * N4); long double variance = expected2 - expected * expected; printf("N1 = %Lg\n", N1); printf("N2 = %Lg\n", N2); printf("N3 = %Lg\n", N3); printf("N4 = %Lg\n", N4); printf("expected = %Lf\n", expected); printf("expected2 = %Lf\n", expected2); printf("variance = %Lf\n", variance); printf("Markov = %Lf\n", expected / valat); printf("Czebyszew = %.20Lf\n", variance / (valat - expected) / (valat - expected)); long long NN2 = NN * (long long) NN; qty[0] = NN2 - NN; for(auto it: edata) { qty[0]--; int cod = 0; if(it.second.ingraph[0]) cod += 1; if(it.second.revgraph[0]) cod += 2; if(it.second.ingraph[1]) cod += 4; if(it.second.revgraph[1]) cod += 8; qty[cod]++; } const char* names[4] = {"G0", "G0'", "G1", "G1'"}; for(int u=0; u<16; u++) for(int v=0; v<16; v++) if((u|v) == u) { long long total = 0; for(int k=0; k<16; k++) if((k&v) == v && (k|u) == u) total += qty[k]; printf("%20Ld ", total); for(int c=0; c<4; c++) { if(((u^v)>>c) & 1) printf("?"); else if((u>>c) & 1) printf("1"); else printf("0"); } for(int c=0; c<4; c++) { printf(" %s", names[c]); if(((u^v)>>c) & 1) printf("?"); else if((u>>c) & 1) printf("=1"); else printf("=0"); } printf("\n"); } fflush(stdout); return 0; }
24.188073
89
0.522852
[ "vector" ]
7fddb23caa3a7f9909e0da61799cee59fe359321
586
hpp
C++
utilities/Loft.hpp
shaungoh01/-Uni-Computer-Graphic-Assignemny
ec5098c1c2f30f3abacb8de663511f25a8b64d0b
[ "MIT" ]
null
null
null
utilities/Loft.hpp
shaungoh01/-Uni-Computer-Graphic-Assignemny
ec5098c1c2f30f3abacb8de663511f25a8b64d0b
[ "MIT" ]
1
2019-09-06T07:46:49.000Z
2019-09-06T07:46:49.000Z
utilities/Loft.hpp
shaungoh01/-Uni-Computer-Graphic-Assignemny
ec5098c1c2f30f3abacb8de663511f25a8b64d0b
[ "MIT" ]
3
2016-01-09T13:50:55.000Z
2021-05-14T10:21:49.000Z
// // Loft.hpp // OpenGL-Utilities-XCODE // // Created by Yong Lian Hii on 30/12/2015. // Copyright © 2015 Yong Lian Hii. All rights reserved. // #ifndef Loft_hpp #define Loft_hpp #include "VecMatMath.hpp" #include <vector> class Loft { public: Loft(const std::vector<vec2> &points, const std::vector<vec3> &path); void init(); void draw(); private: const std::vector<vec2> &points2d; std::vector<vec3> directions; const std::vector<vec3> &path; std::vector<std::vector<vec3> > points3d; std::vector<vec3> splines; }; #endif /* Loft_hpp */
18.903226
73
0.650171
[ "vector" ]
8f12585146a22b7b8b134528214c131f2dbb068b
17,430
cpp
C++
Client/chatWindow.cpp
WuskieFTW1113/IV-MP-T4
ec4f193c90d23e07e6200dcb061ec8773be6bedc
[ "MIT" ]
2
2021-07-18T17:37:32.000Z
2021-08-04T12:33:51.000Z
Client/chatWindow.cpp
VittorioC97/IV-MP-T4
ec4f193c90d23e07e6200dcb061ec8773be6bedc
[ "MIT" ]
1
2022-02-22T03:26:50.000Z
2022-02-22T03:26:50.000Z
Client/chatWindow.cpp
WuskieFTW1113/IV-MP-T4
ec4f193c90d23e07e6200dcb061ec8773be6bedc
[ "MIT" ]
5
2021-06-17T06:41:00.000Z
2022-02-17T09:37:40.000Z
#include "chatWindow.h" #include "guiManager.h" #include "../GWEN/Include/Gwen/Input/Windows.h" #include "../GWEN/Include/Gwen/Controls/TextBox.h" #include "players.h" #include "easylogging++.h" #include "parseConnectionStates.h" #include "padCallBack.h" #include "CustomFiberThread.h" #include "playerList.h" #include "keyboard.h" #include "prepareClientToServerPacket.h" #include "../SharedDefines/packetsIds.h" #include <mutex> #include "chatInput.h" struct chatMsg { std::string msg; unsigned int hex; }; //std::map<int, std::vector<chatMsg> > chatWindowMsgs; //std::vector<chatMsg> chatDraw[10]; //std::vector<chatMsg> chatWindowMsgs[40]; std::mutex chatMutex; LONG ACTUAL_FONT_SIZE; bool chatMapInited = false; bool fontTested = false; ID3DXFont* chatFont = NULL; //Gwen::Controls::TextBox* chatInput = nullptr; //Gwen::Input::Windows* chatGwenInput = nullptr; /*unsigned int currentScroll = 1; unsigned int scrollBegin = 30; unsigned int scrollEnd = 40;*/ bool chatActive = false; bool chatVisible = true; std::mutex chatInputMutex; char chat_font[30] = "Arial"; int chat_size = 24; int chat_line_height2 = 1; int chat_quality = 4; size_t current_chat = 0; class chat_class { private: std::vector<chatMsg>* msgs[40]; int scroll; public: chat_class() { for(int i = 0; i < 40; i++) this->msgs[i] = new std::vector<chatMsg>; scroll = 1; } ~chat_class(){} void addMsg(std::vector<chatMsg>* tmsg) { delete this->msgs[39]; for(int i = 39; i > 0; i--) { this->msgs[i] = this->msgs[i - 1]; } this->msgs[0] = tmsg; size_t thisMsg = tmsg->size(); std::string logBuf; for(size_t i = 0; i < thisMsg; i++) logBuf.append(tmsg->at(i).msg); LINFO << logBuf; } int render(IDirect3DDevice9* pDevice, RECT r) { RECT shadow; LONG bufLeft = r.left; LONG bufRight = r.right; chatMutex.lock(); int cScroll = scroll * 10 - 1; int scrollOver = cScroll - 9; //Loops buf int i = cScroll; size_t msgVecSize = 0; size_t vecPos = 0; //Vector and Chat Line bufs chatMsg* bufMsg = NULL; std::vector<chatMsg>* bufVector = NULL; char* msg = ""; for(i; i >= scrollOver; i--) { if(i != cScroll) { r.top = r.bottom + 1; r.bottom += chat_size; r.left = bufLeft, r.right = bufRight; //Because of colored text } shadow = r; shadow.top = r.top + 1; shadow.bottom = r.bottom + 1; bufVector = this->msgs[i]; msgVecSize = bufVector->size(); if(msgVecSize == 0) { continue; } if(bufVector->at(0).msg.empty()) { continue; } vecPos = 0; for(vecPos; vecPos < msgVecSize; vecPos++) { bufMsg = &bufVector->at(vecPos); msg = &bufMsg->msg[0u]; if(chatFont->DrawText(NULL, msg, -1, &r, DT_CALCRECT, 0) != 0) { ACTUAL_FONT_SIZE = r.bottom - r.top; shadow.left = r.left + 1; shadow.right = r.right + 1; chatFont->DrawText(NULL, msg, -1, &shadow, DT_NOCLIP, 0xFF000000); chatFont->DrawText(NULL, msg, -1, &r, DT_NOCLIP, bufMsg->hex); r.left = r.right; // offset for next character. } } } chatMutex.unlock(); return shadow.bottom; } void changeScroll(bool up) { if((up && this->scroll == 4) || (!up && this->scroll == 1)) return; chatMutex.lock(); this->scroll = up ? scroll + 1 : scroll - 1; chatMutex.unlock(); } void wipe() { for(int i = 0; i < 40; i++) this->msgs[i]->clear(); } }; std::map<int, chat_class> cClasses; void setMsgScroll(unsigned int begin) { /* unsigned int end = begin + 10; if(begin > 30 || end > 40 || begin > end) { LINFO << "!Error: setMsgScroll: " << begin << ", " << end; begin = 30; end = 40; } unsigned int i = 0; chatMutex.lock(); for(begin; begin < end; begin++) { chatDraw[i] = chatWindowMsgs[begin]; i++; } chatMutex.unlock();*/ } void chatWindow::inputChat(DWORD key, bool down, bool alt) { chatInputMutex.lock(); chatInput::process(key, down, alt); chatInputMutex.unlock(); } void chatCreateDevice(IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS* pPresentParameters) { if(!chatMapInited) { /*for(int i = 0; i < 40; i++) { std::vector<chatMsg> trash; chatWindowMsgs[i] = trash; }*/ chatMapInited = true; } } void chatResetDevice(IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS* pPresentParameters) { LINFO << "chatResetDevice"; /*chatInput = new Gwen::Controls::TextBox(guiManager::getGwenCanvas()); chatInput->SetPos(guiManager::windowX() * 0.006f, guiManager::windowY() * 0.25f); chatInput->SetSize(guiManager::windowX() * 0.2f, guiManager::windowY() * 0.019f); chatInput->SetEditable(true); chatInput->Hide(); chatGwenInput = new Gwen::Input::Windows(); chatGwenInput->Initialize(guiManager::getGwenCanvas());*/ /*scrollBegin = 32; scrollEnd = 40; scrollBegin = 32; scrollEnd = 40;*/ if(chat_size == 24) //Standard size { chat_size = 13; if(guiManager::windowX() > 4000) chat_size = 45; else if(guiManager::windowX() > 3000) chat_size = 40; else if(guiManager::windowX() > 1900) chat_size = 26; else if(guiManager::windowX() > 1600) chat_size = 24; else if(guiManager::windowX() > 1000) chat_size = 20; else if(guiManager::windowX() > 700) chat_size = 15; } D3DXCreateFont(pDevice, chat_size, 0, FW_BOLD, 1, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, chat_font, &chatFont); //setMsgScroll(scrollBegin); } void chatLostDevice(IDirect3DDevice9* pDevice, bool clientControlled) { if(chatFont == NULL) { return; } LINFO << "chatLostDevice"; //chatInput = nullptr; chatFont->Release(); chatFont = NULL; } void chatDestroyDevice(IDirect3DDevice9* pDevice) { } void DrawLine(LPDIRECT3DDEVICE9 Device_Interface,int bx,int by,int bw,D3DCOLOR COLOR) { D3DRECT rec; rec.x1 = bx-bw;//makes line longer/shorter going lef rec.y1 = by;///base y rec.x2 = bx+bw;//makes line longer/shorter going right rec.y2 = by+1;//makes line one pixel tall Device_Interface->Clear(1,&rec,D3DCLEAR_TARGET,COLOR,0,0); } void DrawTrueLine(IDirect3DDevice9* pDevice, float x1, float y1, float x2, float y2, float width, bool antialias, DWORD color) { ID3DXLine *m_Line; D3DXCreateLine(pDevice, &m_Line); D3DXVECTOR2 line[] = {D3DXVECTOR2(x1, y1), D3DXVECTOR2(x2, y2)}; m_Line->SetWidth(width); if(antialias) m_Line->SetAntialias(1); m_Line->Begin(); m_Line->Draw(line, 2, color); m_Line->End(); m_Line->Release(); } void chatRender(IDirect3DDevice9* pDevice) { if(!chatVisible || playerList::isListActive()) { return; } else if(!chatFont || !chatMapInited) { LINFO << "Chat error: " << chatFont << ", " << chatMapInited; return; } RECT r; r.top = (guiManager::windowY() * 0.028f); r.bottom = r.top + chat_size; r.left = guiManager::windowX() * 0.006f; r.right = guiManager::windowX(); r.top = cClasses[current_chat].render(pDevice, r); if(chatActive) { chatInputMutex.lock(); try { r.top++; if(r.top <= r.bottom || r.bottom > guiManager::windowY()) r.top = r.bottom + ACTUAL_FONT_SIZE + 1; r.bottom = r.top + chat_size; r.left = guiManager::windowX() * 0.006f; r.right = guiManager::windowX(); if(chatInput::lastRepeat != 0 && !chatInput::lastChar.empty()) { clock_t cTime = clock(); if(cTime > chatInput::lastRepeat + 1000) { chatInput::lastRepeat = cTime; if(chatInput::lastChar == std::string("back")) { chatInput::popBackText(); } else { chatInput::text.append(chatInput::lastChar); } } } std::string buf = chatInput::text; size_t s = buf.size(); if(s > 0 && buf.at(s - 1) == ' ') { buf.at(s - 1) = '_'; //LINFO << "White space"; } const char* msg = buf.c_str(); RECT shadow; chatFont->DrawText(NULL, msg, -1, &r, DT_CALCRECT, 0); shadow.left = r.left + 1; shadow.right = r.right + 1; shadow.bottom = r.bottom; shadow.top = r.top; chatFont->DrawText(NULL, msg, -1, &shadow, DT_NOCLIP, 0xFF000000); chatFont->DrawText(NULL, msg, -1, &r, DT_NOCLIP, 0xFFFFFFFF); shadow.right = r.right + 3; DrawLine(pDevice, shadow.right, shadow.bottom, 2, 0xFFFFFFFF); } catch(std::exception& e) { LINFO << "!Error: chatInput: " << e.what(); } chatInputMutex.unlock(); } } void chatUpdateMsg(MSG msg) { /*if(chatInput != nullptr && chatInput->Visible()) { if(msg.wParam == VK_BACK) { std::string newString = std::string(chatInput->GetText().c_str()); if(newString.size() != 0) { newString.erase(newString.end() - 1, newString.end()); chatInput->SetText(newString.c_str()); } } else { chatGwenInput->ProcessMessage(msg); } } else { chatGwenInput->ProcessMessage(msg); }*/ } void chatWindow::showChatWindow(bool show) { if(show) { guiManager::guiPanel* chatPanel = new guiManager::guiPanel; chatPanel->create = &chatCreateDevice; chatPanel->destroy = &chatDestroyDevice; chatPanel->lost = &chatLostDevice; chatPanel->render = &chatRender; chatPanel->reset = &chatResetDevice; chatPanel->msgUpdate = &chatUpdateMsg; guiManager::addPanel(guiManager::CHAT_WINDOW, chatPanel); } else { //guiManager::deletePanel(guiManager::CHAT_WINDOW); } } bool chatWindow::isChatWindowActive() { return chatFont != NULL; } void addMsg(std::vector<chatMsg>& vec) { /* if(!chatMapInited) { LINFO << "!Warning: colored chat msgs denied (map not ready)"; return; } for(size_t i = 0; i < 39; i++) { chatWindowMsgs[i] = chatWindowMsgs[i + 1]; } chatWindowMsgs[39] = vec; std::string str; size_t vecSize = vec.size(); for(size_t i = 0; i < vecSize; ++i) { str.append(vec.at(i).msg); } setMsgScroll(scrollBegin); LINFO << str;*/ } void chatWindow::receivedChat(RakNet::BitStream& bsIn) { RakNet::RakString msg; bsIn.Read(msg); chatMsg m; m.msg = std::string(msg); bsIn.Read(m.hex); std::vector<chatMsg>* nv = new std::vector<chatMsg>; nv->push_back(m); //addMsg(nv); int customChat = 0; bsIn.Read(customChat); if(customChat != 0 && cClasses.find(customChat) == cClasses.end()) return; cClasses.at(customChat).addMsg(nv); } void chatWindow::receivedPlayerChat(RakNet::BitStream& bsIn) { int msgsCount = 0; bsIn.Read(msgsCount); if(msgsCount <= 0 || msgsCount > 10) { LINFO << "!Warning: colored chat msgs denied (invalid size)"; return; } std::vector<chatMsg>* nv = new std::vector<chatMsg>; RakNet::RakString msg; for(int i = 0; i < msgsCount; i++) { chatMsg m; msg.Clear(); bsIn.Read(msg); bsIn.Read(m.hex); m.msg = std::string(msg); nv->push_back(m); } int customChat = 0; bsIn.Read(customChat); if(customChat != 0 && cClasses.find(customChat) == cClasses.end()) return; //addMsg(nv); cClasses.at(customChat).addMsg(nv); } void chatWindow::customChatHandler(RakNet::BitStream& bsIn) { int chatId = 0; bsIn.Read(chatId); if(chatId < 0) return; bool exists = cClasses.find(chatId) != cClasses.end(); //OP list: 1 new, 2 delete, 3 wipe, 4 switch int op = 0; bsIn.Read(op); //Trying to alter a chat that doesnt exist if((op != 1 && !exists) || (op == 1 && exists)) return; chatMutex.lock(); if(op == 1) { cClasses[chatId] = chat_class(); } else if(op == 2) { if(current_chat == chatId) current_chat = 0; cClasses.erase(chatId); } else if(op == 3) { cClasses[chatId].wipe(); } else if(op == 4) { current_chat = chatId; } chatMutex.unlock(); RakNet::BitStream b; b.Write((MessageID)IVMP); b.Write(CUSTOM_CHAT); b.Write(chatId); b.Write(op); networkManager::sendBitStream(b); } void chatWindow::toggleChatInput() { //togglePlayerControls(false, false); /*chatInput->Show(); chatInput->Focus();*/ chatActive = true; } bool chatWindow::isChatInputActive() { return chatActive;//chatInput != nullptr ? chatInput->Visible() : false; } bool chatWindow::pageScrollAvailable() { return true; } void chatWindow::changeScroll(bool scrollUp) { /*if(scrollUp) { if(currentScroll > 3) { LINFO << "Scroll up failed: limit reached: " << currentScroll; return; } currentScroll++; } else if(!scrollUp ) { if(currentScroll < 2) { LINFO << "Scroll down failed: limit reached: " << currentScroll; return; } currentScroll--; } scrollBegin = 40 - (currentScroll * 10); scrollEnd = scrollBegin + 10; setMsgScroll(scrollBegin);*/ cClasses.at(current_chat).changeScroll(scrollUp); } bool PressT = false; void chatWindowPressT(bool altDown) { PressT = true; } bool PressEnter = false; void chatWindowPressEnter(bool altDown) { PressEnter = true; } bool PressPageUp = false; void chatWindowPressPageUp(bool altDown) { PressPageUp = true; } bool PressPageDown = false; void chatWindowPressPageDown(bool altDown) { PressPageDown = true; } bool PressArrowUp = false; void chatWindowPressArrowUp(bool altDown) { PressArrowUp = true; } bool PressArrowDown = false; void chatWindowPressArrowDown(bool altDown) { PressArrowDown = true; } bool PressEscUp = false; void chatWindowPressEsc(bool altDown) { PressEscUp = true; } void chatWindowPressF6(bool altDown) { chatVisible = !chatVisible; } void chatWindow::initKeyHook() { keyboard::registerFunc(0x54, chatWindowPressT, false); keyboard::registerFunc(0xC0, chatWindowPressT, false); keyboard::registerFunc(VK_RETURN, chatWindowPressEnter, true); keyboard::registerFunc(0x21, chatWindowPressPageUp, true); keyboard::registerFunc(0x22, chatWindowPressPageDown, true); keyboard::registerFunc(VK_UP, chatWindowPressArrowUp, true); keyboard::registerFunc(VK_DOWN, chatWindowPressArrowDown, true); keyboard::registerFunc(VK_ESCAPE, chatWindowPressEsc, false); keyboard::registerFunc(VK_F6, chatWindowPressF6, true); } void chatWindow::handleKeyPress() { if(PressT) //t { PressT = false; if(isChatWindowActive() && !isChatInputActive()) { subTask = 10; //if(!isPlayerEnteringCar()) //{ togglePlayerControls(CONTROL_CHAT, false, false); //} toggleChatInput(); //NativeInvoke::Invoke<u32>("DISABLE_PAUSE_MENU", 1); } } else if(PressEscUp) { PressEscUp = false; chatActive = false; if(!shouldPlayerBeFrozen()) { togglePlayerControls(CONTROL_CHAT, true, false); } } else if(PressEnter) //enter { PressEnter = false; if(!isChatWindowActive() || !isChatInputActive()) { return; } //NativeInvoke::Invoke<u32>("DISABLE_PAUSE_MENU", 0); //std::string inputText = chat_text;//std::string(chatInput->GetText().c_str()); chatInputMutex.lock(); try { bool size = chatInput::text.size() > 1; if(size) { //receivedChat(label->GetText().c_str()); std::string inputText = chatInput::text.substr(1, chatInput::text.size()); //LINFO << inputText; if(networkManager::isNetworkActive()) { if(inputText == std::string("/q")) { connectionLost("~b~Exiting server"); chatInput::enter(size); chatInputMutex.unlock(); //chatInput->SetText(""); //chatInput->Hide(); //Scripting::SetPlayerControl(players::getLocalPlayer().playerIndex, true); return; } RakNet::BitStream bsOut; RakNet::RakString text; text.Clear(); text = inputText.length() > 100 ? inputText.substr(0, 100).c_str() : inputText.c_str(); bsOut.Write((MessageID)IVMP); bsOut.Write(BILATERAL_MESSAGE); bsOut.Write(text); networkManager::getConnection()->peer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, networkManager::getConnection()->serverIp, false); } } //chatInput->SetText(""); //chatInput->Hide(); chatInput::enter(size); chatActive = false; if(!shouldPlayerBeFrozen()) { togglePlayerControls(CONTROL_CHAT, true, false); } } catch(std::exception& e) { LINFO << "!Error: ChatInput pressed enter: " << e.what(); } chatInputMutex.unlock(); } else if(PressPageUp/*keyboard::getKey(0x21)*/) { PressPageUp = false; if(playerList::isListActive()) { playerList::scrollUp(); return; } else if(!chatWindow::pageScrollAvailable()) //page up { return; } subTask = 11; changeScroll(true); } else if(PressPageDown/*keyboard::getKey(0x22)*/) { PressPageDown = false; if(playerList::isListActive()) { playerList::scrollDown(); return; } else if(!chatWindow::pageScrollAvailable()) //page up { return; } subTask = 121; changeScroll(false); } } #include <fstream> #include "../SharedDefines/paramHelper.h" void chatWindow::loadConfig() { cClasses[0] = chat_class(); std::ifstream infile("comMP//config.txt", std::ifstream::in); if(infile.is_open()) { std::string line; while(std::getline(infile, line)) { if(line.compare(0, 10, std::string("chat_font=")) == 0) { line.erase(0, 10); //chat_font = &line[0u]; sprintf_s(chat_font, "%s", line.substr(0, std::string::npos).c_str()); } else if(line.compare(0, 10, std::string("chat_size=")) == 0) { line.erase(0, 10); chat_size = paramHelper::isInt(line); if(chat_size > 42 || chat_size < 10) chat_size = 24; } else if(line.compare(0, 17, std::string("chat_line_height=")) == 0) { line.erase(0, 17); chat_line_height2 = paramHelper::isInt(line); if(chat_line_height2 < 1 || chat_line_height2 > 10) chat_line_height2 = 1; } else if(line.compare(0, 13, std::string("chat_quality=")) == 0) { line.erase(0, 13); chat_quality = paramHelper::isInt(line); } } } else LINFO << "Config.txt did not open: " << strerror(errno); infile.close(); }
22.403599
126
0.656856
[ "render", "vector" ]
8f1791f9a8db7a8fc35c697aeb159a27cf429062
6,805
cpp
C++
src/maze.cpp
ReneMolina13/UTEP-IEEE-Micromouse
63cdb35ea4d9d5c03fc2642d4023eb8a3e94548e
[ "MIT" ]
null
null
null
src/maze.cpp
ReneMolina13/UTEP-IEEE-Micromouse
63cdb35ea4d9d5c03fc2642d4023eb8a3e94548e
[ "MIT" ]
null
null
null
src/maze.cpp
ReneMolina13/UTEP-IEEE-Micromouse
63cdb35ea4d9d5c03fc2642d4023eb8a3e94548e
[ "MIT" ]
1
2022-02-18T22:11:57.000Z
2022-02-18T22:11:57.000Z
#include "maze.h" #include "stack.h" /*Virtual mouse object*/ mouse_t mouse = {.x = 0, .y = 0, .heading = NORTH}; /*Maze cells array*/ cell_t maze[MAZE_WIDTH][MAZE_HEIGHT]; /*TODO: We should be able to bitwise OR walls, right now this * function does not support it. Think of a way to do it! */ int8_t maze_set_wall(uint8_t x, uint8_t y, uint8_t wall) { if(CHECK_BOUNDARIES(x, y)) return -1; maze[x][y].walls |= wall; switch(wall) { case NORTH: maze[x][y-1].walls |= SOUTH; break; case EAST: maze[x+1][y].walls |= WEST; break; case SOUTH: maze[x][y+1].walls |= NORTH; break; case WEST: maze[x-1][y].walls |= EAST; break; } } int8_t maze_get_walls(uint8_t x, uint8_t y) { if(CHECK_BOUNDARIES(x, y)) return -1; return maze[x][y].walls; } int8_t maze_set_value(uint8_t x, uint8_t y, uint8_t value) { if(CHECK_BOUNDARIES(x, y)) return -1; maze[x][y].value = value; } int8_t maze_get_value(uint8_t x, uint8_t y) { if(CHECK_BOUNDARIES(x, y)) return -1; return maze[x][y].value; } cell_t *maze_get_cell(uint8_t x, uint8_t y) { return &maze[x][y]; } void maze_init(uint8_t target_x, uint8_t target_y) { if(CHECK_BOUNDARIES(target_x, target_y)) return; for(uint8_t y = 0; y < MAZE_HEIGHT; y++) { for(uint8_t x = 0; x < MAZE_WIDTH; x++) { maze[x][y].value = abs(target_x - x) + abs(target_y - y); maze[x][y].pos = X_POS(x) | Y_POS(y); if(x == 0) maze[x][y].walls |= WEST; if(x == (MAZE_WIDTH - 1)) maze[x][y].walls |= EAST; if(y == 0) maze[x][y].walls |= NORTH; if(y == (MAZE_HEIGHT - 1)) maze[x][y].walls |= SOUTH; } } } /*Print routine for VT100 terminals. Recommended terminal is putty*/ void maze_print(void) { /*Clear previous maze*/ Serial.print("\x1B[2J"); for(uint8_t y = 0; y < MAZE_HEIGHT; y++) { for(uint8_t x = 0; x < MAZE_WIDTH; x++) { uint8_t cy = 4*x + 1; uint8_t cx = 2*y + 1; /*Print cell value*/ Serial.print("\x1B["); Serial.print(cx+1); Serial.print(";"); Serial.print(cy+2); Serial.print("H"); Serial.print(maze[x][y].value, DEC); /*Print north wall if present*/ if(maze[x][y].walls & NORTH) { Serial.print("\x1B["); Serial.print(cx); Serial.print(";"); Serial.print(cy); Serial.print("H"); Serial.print("+---+"); } /*Print east wall if present*/ if(maze[x][y].walls & EAST) { Serial.print("\x1B["); Serial.print(cx+1); Serial.print(";"); Serial.print(cy+4); Serial.print("H"); Serial.print("|"); } /*Print south wall if present*/ if(maze[x][y].walls & SOUTH) { Serial.print("\x1B["); Serial.print(cx+2); Serial.print(";"); Serial.print(cy); Serial.print("H"); Serial.print("+---+"); } /*Print west wall if present*/ if(maze[x][y].walls & WEST) { Serial.print("\x1B["); Serial.print(cx+1); Serial.print(";"); Serial.print(cy); Serial.print("H"); Serial.print("|"); } } } /*Print mouse's position and heading*/ uint8_t mx = 2*mouse.y + 1; uint8_t my = 4*mouse.x + 1; Serial.print("\x1B["); Serial.print(mx+1); Serial.print(";"); Serial.print(my+2); Serial.print("H"); switch(mouse.heading) { case NORTH: Serial.print("^"); break; case EAST: Serial.print(">"); break; case SOUTH: Serial.print("V"); break; case WEST: Serial.print("<"); break; } } /*FlOOD FILL CODE GOES HERE***************************************************/ void flood_fill(int x, int y) { /*Neighbor offsets for all orientations*/ int8_t neighbor_offset[4][2] = { {0, -1}, {1, 0}, {0, 1}, {-1, 0}, }; /*Pointer to data structure. See https://overiq.com/c-programming-101/pointer-to-a-structure-in-c/ */ cell_t *current; cell_t *neighbor; /*Get current cell from maze*/ current = maze_get_cell(x, y); /*Push current cell to the stack*/ stack_push(current); /*Keep running until the stack is not empty*/ while(!stack_empty()) { /*Pop cell from the stack*/ stack_pop(current); /*If this is the target cell, then do nothing*/ if(current->value == 0) break; /*Get position from popped cell*/ uint8_t cx = GET_X_POS(current->pos); uint8_t cy = GET_Y_POS(current->pos); /*Find the open neighbor with the lowest value*/ uint8_t minimum = 255; for(int i = 0; i < 4; i++) { if((current->walls & (1 << i)) == 0) { /*Get neighborhs x and y coordinates*/ int8_t nx = cx + neighbor_offset[i][0]; int8_t ny = cy + neighbor_offset[i][1]; /*Get neighbor cell pointer from the maze*/ neighbor = maze_get_cell(nx, ny); /*If the neighbor is less than the minimum, * then set this cell value as the new minimum*/ if(neighbor->value < minimum) { minimum = neighbor->value; } } } /*If the curren cell value is not one less * than the minimum ... */ if(minimum != (current->value - 1)) { /*Increment the current cell value by the minimum + 1*/ current->value = minimum + 1; /*Push all neighbors into the stack*/ for(int i = 0; i < 4; i++) { /*Get neighborhs x and y coordinates*/ int8_t nx = cx + neighbor_offset[i][0]; int8_t ny = cy + neighbor_offset[i][1]; /*Check that cell is not out of bounds*/ if((nx > 0) && (nx < (MAZE_WIDTH - 1)) && (ny > 0) && (ny < (MAZE_HEIGHT - 1))) { /*Get neighbor cell pointer from the maze*/ neighbor = maze_get_cell(nx, ny); if(neighbor->value != 0) { /*Push the neighbor into the stack if the value * is not equal to 0*/ stack_push(neighbor); } } } } } } /*FlOOD FILL ENDS HERE********************************************************/ void mouse_set_x(int8_t x) { if(x > (MAZE_WIDTH - 1)) { x = MAZE_WIDTH - 1; } if(x < 0) { x = 0; } mouse.x = x; } void mouse_set_y(int8_t y) { if(y > (MAZE_HEIGHT - 1)) { y = MAZE_HEIGHT - 1; } if(y < 0) { y = 0; } mouse.y = y; } int8_t mouse_get_x(void) { return mouse.x; } int8_t mouse_get_y(void) { return mouse.y; } void mouse_set_heading(uint8_t heading) { mouse.heading = heading; } uint8_t mouse_get_heading(void) { return mouse.heading; }
22.384868
79
0.530051
[ "object" ]
8f2176f694b0448fc731946695e582adce35e1a5
1,619
cpp
C++
winter1843/winter.cpp
RenoirTan/dunjudge.me
0098cfd45609e4ac50aac0b2c943b1afb6aff818
[ "MIT" ]
null
null
null
winter1843/winter.cpp
RenoirTan/dunjudge.me
0098cfd45609e4ac50aac0b2c943b1afb6aff818
[ "MIT" ]
null
null
null
winter1843/winter.cpp
RenoirTan/dunjudge.me
0098cfd45609e4ac50aac0b2c943b1afb6aff818
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include "stringfunctions.h" using namespace std; int main() { cout << "Winter Clothes Scorer" << endl << "---------------------" << endl; string filename; ifstream infile; cout << "Enter name of file: "; cin >> filename; infile.open(filename + ".txt"); cout << endl << "Processing..."; if (infile.is_open()) { vector< string > filelines; string inputline; while (getline (infile, inputline)) { filelines.push_back( inputline ); }; cout << endl; if (filelines.size() <= 2) { cout << "Max Score: 0"; } else { int numclothes = (filelines.size() - 1); int clothes[numclothes][2]; int i, j, count; int maxcount = 0; string line; for (i = 0; i < numclothes; ++i) { line = filelines.at(i + 1); clothes[i][0] = stringtoint(line.substr(0, line.find(' '))); line.erase(0, (line.find(' ') + 1)); clothes[i][1] = stringtoint(line); }; for (i = 0; i < numclothes; ++i) { j = 0; count = 0; while (j < numclothes) { if (i == j) { ++j; } else { if (clothes[i][0] <= clothes[j][0] && clothes[i][1] >= clothes[j][1]) { ++count; }; }; ++j; //cout << "Count: " << count << endl; }; if (count > maxcount) { maxcount = count; }; }; cout << "Max Score: " << maxcount; }; } else { cout << endl << "File cannot be opened."; }; };
26.112903
83
0.479308
[ "vector" ]
8f27ba2b3a98fc55440757ad607da7236c7ee309
1,572
cc
C++
lang/cpp/reflection/rttr.cc
curoky/my-own-x
825273af2d73dff76562422ca87a077635ee870b
[ "Apache-2.0" ]
null
null
null
lang/cpp/reflection/rttr.cc
curoky/my-own-x
825273af2d73dff76562422ca87a077635ee870b
[ "Apache-2.0" ]
null
null
null
lang/cpp/reflection/rttr.cc
curoky/my-own-x
825273af2d73dff76562422ca87a077635ee870b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018-2022 curoky(cccuroky@gmail.com). * * This file is part of my-own-x. * See https://github.com/curoky/my-own-x for further info. * * 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 <catch2/catch.hpp> // for StringRef, TEST_CASE #include <rttr/registration.h> // for public_access, registration::class_, registration #include <rttr/type.h> // for type #include <vector> // for vector struct A { int a; int b; }; struct B { std::vector<A> as; }; struct C { A a; B b; }; RTTR_REGISTRATION { rttr::registration::class_<A>("A") .property("a", &A::a)(rttr::metadata("thrift", "1,required")) .property("b", &A::b)(rttr::metadata("thrift", "2,required")); rttr::registration::class_<B>("B").property("as", &B::as); rttr::registration::class_<C>("C").property("b", &C::b).property("a", &C::a); } TEST_CASE("basic usage", "[rttr]") { rttr::type t = rttr::type::get<A>(); for (auto& prop : t.get_properties()) { // REQUIRE(prop.get_name() == "a" || prop.get_name() == "b"); } }
29.111111
88
0.652672
[ "vector" ]
8f2a959af5bb92dd2fd8927e22bdad78a60a95c4
6,267
cpp
C++
Core/Unix/MacOSX/CoreMacOSX.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
2
2016-10-15T05:12:16.000Z
2016-11-06T16:19:53.000Z
Core/Unix/MacOSX/CoreMacOSX.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
14
2016-09-21T21:24:46.000Z
2016-11-15T07:54:21.000Z
Core/Unix/MacOSX/CoreMacOSX.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2016 nemesis project/mrn@sdf.org. All rights reserved. http://mrn.sixbit.org/ Governed by the BSD 2 Clause license, the full text of which is contained in the file License.txt included in nemesis binary and source code distribution packages. Based on TrueCrypt 7.1a, which was governed by the TrueCrypt license, which is also made available with nemesis. */ #include <fstream> #include <iostream> #include <string> #include <stdio.h> #include <unistd.h> #include <sys/param.h> #include <sys/ucred.h> #include <sys/mount.h> #include <sys/sysctl.h> #include <sys/types.h> #include <sys/wait.h> #include "CoreMacOSX.h" #include "Driver/Fuse/FuseService.h" #include "Core/Unix/CoreServiceProxy.h" namespace nemesis { CoreMacOSX::CoreMacOSX () { } CoreMacOSX::~CoreMacOSX () { } shared_ptr <VolumeInfo> CoreMacOSX::DismountVolume (shared_ptr <VolumeInfo> mountedVolume, bool ignoreOpenFiles, bool syncVolumeInfo) { if (!mountedVolume->VirtualDevice.IsEmpty() && mountedVolume->VirtualDevice.IsBlockDevice()) { list <string> args; args.push_back ("detach"); args.push_back (mountedVolume->VirtualDevice); if (ignoreOpenFiles) args.push_back ("-force"); try { Process::Execute ("hdiutil", args); } catch (ExecutedProcessFailed &e) { if (!ignoreOpenFiles) { string err = e.GetErrorOutput(); if (err.find ("couldn't unmount") != string::npos || err.find ("busy") != string::npos || err.find ("49153") != string::npos) { throw MountedVolumeInUse (SRC_POS); } } throw; } } if (syncVolumeInfo || mountedVolume->Protection == VolumeProtection::HiddenVolumeReadOnly) { sync(); VolumeInfoList ml = GetMountedVolumes (mountedVolume->Path); if (ml.size() > 0) mountedVolume = ml.front(); } list <string> args; args.push_back ("--"); args.push_back (mountedVolume->AuxMountPoint); for (int t = 0; true; t++) { try { Process::Execute ("umount", args); break; } catch (ExecutedProcessFailed&) { if (t > 10) throw; Thread::Sleep (200); } } try { mountedVolume->AuxMountPoint.Delete(); } catch (...) { } return mountedVolume; } void CoreMacOSX::CheckFilesystem (shared_ptr <VolumeInfo> mountedVolume, bool repair) const { list <string> args; args.push_back ("/Applications/Utilities/Disk Utility.app"); Process::Execute ("open", args); } void CoreMacOSX::MountAuxVolumeImage (const DirectoryPath &auxMountPoint, const MountOptions &options) const { // Check FUSE version char fuseVersionString[MAXHOSTNAMELEN + 1] = { 0 }; size_t fuseVersionStringLength = MAXHOSTNAMELEN; // if (sysctlbyname ("macfuse.version.number", fuseVersionString, &fuseVersionStringLength, NULL, 0) != 0) // throw HigherFuseVersionRequired (SRC_POS); // vector <string> fuseVersion = StringConverter::Split (string (fuseVersionString), "."); // if (fuseVersion.size() < 2) // throw HigherFuseVersionRequired (SRC_POS); // uint32 fuseVersionMajor = StringConverter::ToUInt32 (fuseVersion[0]); // uint32 fuseVersionMinor = StringConverter::ToUInt32 (fuseVersion[1]); // if (fuseVersionMajor < 1 || (fuseVersionMajor == 1 && fuseVersionMinor < 3)) // throw HigherFuseVersionRequired (SRC_POS); // Attach volume image, do not mount with hdiutil string volImage = string (auxMountPoint) + FuseService::GetVolumeImagePath(); list <string> args; list <string> du_args; args.push_back ("attach"); args.push_back ("-plist"); args.push_back ("-noautofsck"); args.push_back ("-imagekey"); args.push_back ("diskimage-class=CRawDiskImage"); args.push_back (volImage); args.push_back ("-nomount"); std::string xml; while (true) { try { xml = Process::Execute ("hdiutil", args); break; } catch (ExecutedProcessFailed &e) { if (e.GetErrorOutput().find ("noautofsck") != string::npos) { args.remove ("-noautofsck"); continue; } throw; } } size_t p = xml.find ("<key>dev-entry</key>"); if (p == string::npos) throw ParameterIncorrect (SRC_POS); p = xml.find ("<string>", p); if (p == string::npos) throw ParameterIncorrect (SRC_POS); p += 8; size_t e = xml.find ("</string>", p); if (e == string::npos) throw ParameterIncorrect (SRC_POS); DevicePath virtualDev = StringConverter::Trim (xml.substr (p, e - p)); cout << "virtualDev: " << StringConverter::Trim (xml.substr (p, e - p)); // If we're going to mount, do it with diskutil, in order to properly pass options to /Library/Filesystems utility. // This fixes mounting fuse-ext2 with read only flags. hdiutil with readonly flags, gives error 252 from probe // side effect may be, needing to dismount manually from application or terminal if no filesystem detected // will consider adding check to handle this condition and detach automatically // in order to mount fuse-ext2 respecting rw/ro status you must have adouble42 fork of fuse-ext2 installed // the /Library/Filesystems utility has been modified to respect the diskutil flag "rdonly" and otherwise return a // rw mount, in order not to break hdiutil automounts completely if (!options.NoFilesystem) { du_args.push_back("mount"); if (options.Protection == VolumeProtection::ReadOnly) du_args.push_back("readOnly"); if (options.MountPoint && !options.MountPoint->IsEmpty()) { if (string (*options.MountPoint).find (GetDefaultMountPointPrefix()) != 0) { du_args.push_back("-mountPoint"); du_args.push_back (*options.MountPoint); } } du_args.push_back(virtualDev); try { Process::Execute ("diskutil", du_args); } catch (ExecutedProcessFailed&) { throw; } } try { FuseService::SendAuxDeviceInfo (auxMountPoint, virtualDev); } catch (...) { try { list <string> args; args.push_back ("detach"); args.push_back (volImage); args.push_back ("-force"); Process::Execute ("hdiutil", args); } catch (ExecutedProcessFailed&) { } throw; } } auto_ptr <CoreBase> Core (new CoreServiceProxy <CoreMacOSX>); auto_ptr <CoreBase> CoreDirect (new CoreMacOSX); }
26.896996
134
0.670337
[ "vector" ]
8f31ce7f5fc959cc7feda900e728bc0229c00b1f
7,791
hpp
C++
willow/include/popart/liveness.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/include/popart/liveness.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/include/popart/liveness.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2020 Graphcore Ltd. All rights reserved. #ifndef GUARD_NEURALNET_LIVENESS_HPP #define GUARD_NEURALNET_LIVENESS_HPP #include <set> #include <utility> #include <vector> #include <popart/graphid.hpp> #include <popart/op.hpp> #include <popart/tensor.hpp> namespace popart { class Graph; class SubgraphOp; namespace liveness { class SubgraphCopyingStrategy; // A vector of Op*s comprising a call stack. using CallStack = std::vector<Op *>; // OP type and function in the global schedule enum class OpStatus { // Normal OP without subgraphs Normal = 0, // Subgraph entering Enter, CopyInput, // Subgraph loop carried CopyLoopCarried, // Subgraph exiting CopyOutput, CopyModified, Exit }; class LivenessNode { public: LivenessNode(const OpStatus status_, int index_, SubgraphIndex subgraphIndex, bool isDuplicate); LivenessNode(const CallStack &callStack_, const OpStatus status_, int index_, SubgraphIndex subgraphIndex, bool isDuplicate); // Operation associated with this node Op *getOp() const { return callStack.back(); } // Call stack of operators that call each other const CallStack &getCallStack() const { return callStack; } // Operation type and function in the global schedule OpStatus getStatus() const { return status; } // Input or output index of the Op associated with this node int getIndex() const { return index; } // For Enter, Exit, CopyInput, CopyOutput, CopyModified, CopyLoopCarried // nodes this signifies the subgraph called by the op. int getSubgraphIndex() const { return subgraphIndex; } // Determine if this node is a duplicate (duplicates are used for loops). bool getDuplicate() const { return isDuplicate; } // All tensor ids touched by this node const std::set<TensorId> &usedTensorIds() const { return usedIds; } // Pair of matching tensors inside/outside of the subgraph associated with the // index returned by getIndex on CopyOutput, CopyInput and CopyModified nodes const std::pair<TensorId, TensorId> &getTensorIds() const { return tensorIds; } // If the operation produces or fully modifies t bool isProducerOf(Tensor *t) const; // If the operation consumes t bool isConsumerOf(Tensor *t) const; private: void setUsedTensorIds(); void setTensorIds(); CallStack callStack; OpStatus status; int index; SubgraphIndex subgraphIndex; bool isDuplicate; std::pair<TensorId, TensorId> tensorIds; std::set<TensorId> usedIds; }; std::ostream &operator<<(std::ostream &os, const OpStatus &); std::ostream &operator<<(std::ostream &os, const LivenessNode &); // Build global schedule for liveness and call site analysis: // // A, B, C, D, E, ... : Non-subgraphing Op // X: CallOp or LoopOp (subgraphing) type Op // Y: IfOp (subgraphing) type Op // // + : OpStatus::Enter: subgraph enter // - : OpStatus::Exit: subgraph exit // n : OpStatus::Normal: non-subgraphing op // // Global schedule example: // 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 // n n n + - n n n n n n + - n n n // A B C X n n + - - X J K L M N O Z n n + - - Z P Q R // D E Y n n Y n n Y D E Y n n Y n n Y // F G H I F G H I // class LivenessAnalyzer { public: // List of pending copies. using PendingCopies = std::vector<LivenessNode>; LivenessAnalyzer(const Ir *ir_, const SubgraphCopyingStrategy *subgraphCopyingStrat); void apply(); // For a given unique op call stack (e.g. X->Y->F), // return the global schedule position (e.g. 7) int64_t getGlobalSchedulePosition(CallStack callStack) const; // Size of the global schedule (e.g. 34) size_t getOpScheduleSize() const { return opSchedule.size(); } // Return the call stack (e.g. X->Y->F), // at a given schedule position (e.g. 7) const LivenessNode &getOpScheduleAt(int64_t scheduleIndex) const { return opSchedule.at(scheduleIndex); } // Get a graph's local schedule. const std::vector<Op *> &getGraphOpSchedule(GraphId id) const { return graphOpSchedule.at(id); } // Return all global schedule positions (e.g. 7, 24) // where an Op is called (e.g. F) const std::vector<int64_t> &getScheduleIndices(Op *op) const { return opScheduleMap.at(op); } // Return all global schedule positions where a tensor is used const std::vector<int64_t> &getScheduleIndices(Tensor *t) const { return tensorScheduleMap.at(t->id); } // Return all global schedule positions where a tensor is used const std::vector<int64_t> &getScheduleIndices(TensorId tid) const { return tensorScheduleMap.at(tid); } // Given the position of an OpStatus::Enter (e.g. 6) // return the matching OpStatus::Exit positions (e.g. 9, 12) const std::vector<int64_t> &getCallSiteLinksAt(int64_t scheduleIndex) const { return callSiteLinks.at(scheduleIndex); } // Inverse of getCallSiteLinksAt (give positions of exit given an enter). const std::vector<int64_t> & getCallSiteLinksInvAt(int64_t scheduleIndex) const { return callSiteLinksInv.at(scheduleIndex); } // Graph call sites in total order (e.g. for the graph called by Y: 6, 23) const std::vector<Op *> &getGraphCallSites(GraphId id) const { return graphCallSiteOps.at(id); } private: // Global schedule including all subgraphs recursively void addToSchedule(const Graph *graphToAdd, bool isDuplicate, CallStack callStack, PendingCopies &pendingCopies); // Add a single liveness node to the schedule. Returns offset into schedule. int64_t addNodeToSchedule(const LivenessNode &nodeToAdd, PendingCopies &pendingCopies); // Process indices returned by SubgraphCopyStrategy. void processSubgraphCopyingStrategyIndices(PendingCopies &pendingCopies, std::vector<size_t> &chosenIndices); // Expand a subgraph. void expandSubgraph(const Graph *subgraph, bool isDuplicate, const CallStack &callStack, SubgraphIndex subgraphIndex, PendingCopies &pendingCopies); // Add a copies needed for subgraph to pendingCopies. The // SubgraphCopyingStrategy will be used to determine where they are added in // the schedule. void addCopiesToPending(const Graph *subgraph, bool isDuplicate, const CallStack &callStack, SubgraphIndex subgraphIndex, PendingCopies &pendingCopies); const Ir *ir; const SubgraphCopyingStrategy *subgraphCopyingStrat; // Mapping from graph id to the graph's final schedule std::map<GraphId, std::vector<Op *>> graphOpSchedule; // Global schedule (over all graphs) in final schedule order std::vector<LivenessNode> opSchedule; // Map of all schedule positions where an Op is called std::map<Op *, std::vector<int64_t>> opScheduleMap; // Map of all tensors and their usage location std::map<TensorId, std::vector<int64_t>> tensorScheduleMap; // Map of all OpStatus::Enter positions to the matching OpStatus::Exit // positions std::map<int64_t, std::vector<int64_t>> callSiteLinks; // Inverse of callSiteLinks std::map<int64_t, std::vector<int64_t>> callSiteLinksInv; // Map of all ops that call the graph referred to by GraphId std::map<GraphId, std::vector<Op *>> graphCallSiteOps; }; } // namespace liveness } // namespace popart #endif
32.194215
80
0.669619
[ "vector" ]
8f392b3a6e05cc654ba7214798079c14c0fe5486
8,499
hpp
C++
ESMF/src/Infrastructure/Mesh/src/Moab/moab/MeshTopoUtil.hpp
joeylamcy/gchp
0e1676300fc91000ecb43539cabf1f342d718fb3
[ "NCSA", "Apache-2.0", "MIT" ]
1
2018-07-05T16:48:58.000Z
2018-07-05T16:48:58.000Z
ESMF/src/Infrastructure/Mesh/src/Moab/moab/MeshTopoUtil.hpp
joeylamcy/gchp
0e1676300fc91000ecb43539cabf1f342d718fb3
[ "NCSA", "Apache-2.0", "MIT" ]
1
2022-03-04T16:12:02.000Z
2022-03-04T16:12:02.000Z
ESMF/src/Infrastructure/Mesh/src/Moab/moab/MeshTopoUtil.hpp
joeylamcy/gchp
0e1676300fc91000ecb43539cabf1f342d718fb3
[ "NCSA", "Apache-2.0", "MIT" ]
null
null
null
/** * MOAB, a Mesh-Oriented datABase, is a software component for creating, * storing and accessing finite element mesh data. * * Copyright 2004 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government * retains certain rights in this software. * * 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. * */ #ifndef MOAB_MESH_TOPO_UTIL_HPP #define MOAB_MESH_TOPO_UTIL_HPP #include "moab/Forward.hpp" namespace moab { /*! * \authors Tim Tautges * \date 2/04 * \brief MeshTopoUtil contains general mesh utility functions * */ class MeshTopoUtil { public: MeshTopoUtil(Interface *impl) : mbImpl(impl) {} ~MeshTopoUtil() {} //! generate all the AEntities bounding the vertices ErrorCode construct_aentities(const Range &vertices); //! given an entity, get its average position (avg vertex locations) ErrorCode get_average_position(Range &entities, double *avg_position); //! given an entity, get its average position (avg vertex locations) ErrorCode get_average_position(const EntityHandle entity, double *avg_position); //! given a set of entities, get their average position (avg vertex locations) ErrorCode get_average_position(const EntityHandle *entities, const int num_entities, double *avg_position); //! get (target_dim)-dimensional manifold entities connected to star_entity; that is, //! the entities with <= 1 connected (target_dim+2)-dimensional adjacent entities; //! for target_dim=3, just return all of them //! just insert into the list, w/o clearing manifold list first ErrorCode get_manifold(const EntityHandle star_entity, const int target_dim, Range &manifold); //! given an entity, find the entities of next higher dimension around //! that entity, ordered by connection through next higher dimension entities; //! if any of the star entities is in only entity of next higher dimension, //! on_boundary is returned true ErrorCode star_entities(const EntityHandle star_center, std::vector<EntityHandle> &star_entities, bool &bdy_entity, const EntityHandle starting_star_entity = 0, std::vector<EntityHandle> *star_entities_dp1 = NULL, Range *star_entities_candidates_dp1 = NULL); //! Get a series of (d+1)-dimensional stars around a d-dimensional entity, such that //! each star is on a (d+2)-manifold containing the d-dimensional entity; each star //! is either open or closed, and also defines a (d+2)-star whose entities are bounded by //! (d+1)-entities on the star and on the (d+2)-manifold ErrorCode star_entities_nonmanifold(const EntityHandle star_entity, std::vector<std::vector<EntityHandle> > &stars, std::vector<bool> *bdy_flags = NULL, std::vector<std::vector<EntityHandle> > *dp2_stars = NULL); //! given a star_center, a last_entity (whose dimension should be 1 greater than center) //! and last_dp1 (dimension 2 higher than center), returns the next star entity across //! last_dp1, and the next dp1 entity sharing next_entity; if star_candidates is non-empty, //! star must come from those ErrorCode star_next_entity(const EntityHandle star_center, const EntityHandle last_entity, const EntityHandle last_dp1, Range *star_candidates_dp1, EntityHandle &next_entity, EntityHandle &next_dp1); //! get "bridge" or "2nd order" adjacencies, going through dimension bridge_dim ErrorCode get_bridge_adjacencies(Range &from_entities, int bridge_dim, int to_dim, Range &to_ents, int num_layers = 1); //! get "bridge" or "2nd order" adjacencies, going through dimension bridge_dim ErrorCode get_bridge_adjacencies(const EntityHandle from_entity, const int bridge_dim, const int to_dim, Range &to_adjs); //! return a common entity of the specified dimension, or 0 if there isn't one EntityHandle common_entity(const EntityHandle ent1, const EntityHandle ent2, const int dim); //! return the opposite side entity given a parent and bounding entity. //! This function is only defined for certain types of parent/child types; //! See MBCN.hpp::OppositeSide for details. //! //! \param parent The parent element //! \param child The child element //! \param opposite_element The index of the opposite element ErrorCode opposite_entity(const EntityHandle parent, const EntityHandle child, EntityHandle &opposite_element); //! split entity which is non-manifold, that is, which has > 2 connected entities //! of next higher dimension; assumes that there are >= 2 connected regions of //! (d+2)-dimensional entities; a new d-entity is created for each region after the //! first, and it's made explicitly-adjacent to the region to which it corresponds ErrorCode split_entity_nonmanifold(EntityHandle split_ent, Range &old_adjs, Range &new_adjs, EntityHandle &new_entity); //! split entities that are manifold (shared by two or less entities of each higher dimension), //! optionally creating an entity of next higher dimension to fill the gap /** \param entities The entities to be split \param new_entities New entities, in order of correspondence to that of entities \param fill_entities If non-NULL, create an entity of next higher dimension to fill the gap, passing it back in *fill_entities */ ErrorCode split_entities_manifold(Range &entities, Range &new_entities, Range *fill_entities); //! split entities that are manifold (shared by two or less entities of each higher dimension), //! optionally creating an entity of next higher dimension to fill the gap /** \param entities The entities to be split \param new_entities New entities, in order of correspondence to that of entities \param fill_entities If non-NULL, create an entity of next higher dimension to fill the gap, passing it back in *fill_entities \param gowith_ents If non-NULL, each of the new entities will adj to the corresponding gowith entities after the split; this parameter is ignored for boundary split entities; in that case, the split entity remains on the boundary (i.e. not adj to any entity of higher dimension). Dimension of gowith_ents must be the same as entities. */ ErrorCode split_entities_manifold(EntityHandle *entities, const int num_entities, EntityHandle *new_entities, Range *fill_entities, EntityHandle *gowith_ents = NULL); //! return whether entity is equivalent to any other of same type and same vertices; //! if equivalent entity is found, it's returned in equiv_ents and return value is true, //! false otherwise. bool equivalent_entities(const EntityHandle entity, Range *equiv_ents = NULL); private: Interface *mbImpl; }; } // namespace moab #endif
48.016949
99
0.613131
[ "mesh", "vector" ]
8f3bf2ceaf3385f36c3c8845f1c984f7e1d691f0
19,763
cc
C++
models/test/test.cc
GilesStrong/cms_runII_dnn_models
830cb8435bec36223099ec583f0f36813b1e4397
[ "Apache-2.0" ]
null
null
null
models/test/test.cc
GilesStrong/cms_runII_dnn_models
830cb8435bec36223099ec583f0f36813b1e4397
[ "Apache-2.0" ]
1
2020-04-22T10:15:51.000Z
2020-04-22T10:15:51.000Z
models/test/test.cc
GilesStrong/cms_runII_dnn_models
830cb8435bec36223099ec583f0f36813b1e4397
[ "Apache-2.0" ]
1
2020-04-20T14:44:42.000Z
2020-04-20T14:44:42.000Z
// C++ #include <set> #include <stdexcept> #include <iostream> #include <string> #include <map> #include <sstream> #include <fstream> #include <assert.h> #include <vector> #include <cmath> // ROOT #include <Math/VectorUtil.h> #include <Math/LorentzVector.h> #include <Math/PtEtaPhiM4D.h> #include <Math/PxPyPzM4D.h> #include <TFile.h> #include <TTree.h> #include <TTreeReader.h> #include <TTreeReaderValue.h> // Plugins #include "cms_hh_tf_inference/inference/interface/inf_wrapper.hh" #include "cms_hh_proc_interface/processing/interface/feat_comp.hh" #include "cms_hh_proc_interface/processing/interface/evt_proc.hh" const double E_MASS = 0.0005109989; //GeV const double MU_MASS = 0.1056583715; //GeV std::string model_dir = "../../src/cms_runII_dnn_models/models/nonres_gluglu/"; std::string data_dir = "/eos/home-k/kandroso/cms-it-hh-bbtautau/anaTuples/"; using LorentzVectorPEP = ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<float>>; using LorentzVector = ROOT::Math::LorentzVector<ROOT::Math::PxPyPzM4D<float>>; std::vector<std::string>get_evt_names(const std::map<unsigned long, std::string>& id2name, const std::vector<unsigned long>& ids) { /* Match data IDs to aux names */ std::vector<std::string> names(ids.size()); for (unsigned int i = 0; i < ids.size(); i++) names[i] = id2name.at(ids[i]); return names; } int jet_cat_lookup(const std::string& jet_cat) { if (jet_cat == "2j") return 0; if (jet_cat == "2j0bR_noVBF") return 1; if (jet_cat == "2j1bR_noVBF") return 2; if (jet_cat == "2j2b+R_noVBF") return 3; if (jet_cat == "2j2Lb+B_noVBF") return 4; if (jet_cat == "2j1b+_VBFL") return 5; if (jet_cat == "2j1b+_VBF") return 6; if (jet_cat == "2j1b+_VBFT") return 7; throw std::invalid_argument("Unrecognised jet category: " + jet_cat); return -1; } int region_lookup(const std::string& region) { if (region == "OS_Isolated") return 0; if (region == "OS_AntiIsolated") return 1; if (region == "SS_Isolated") return 2; if (region == "SS_AntiIsolated") return 3; if (region == "SS_LooseIsolated") return 4; throw std::invalid_argument("Unrecognised region: " + region); return -1; } void sample_lookup(const std::string& sample, int& sample_id, Spin& spin, float& klambda, float& res_mass) { spin = nonres; res_mass = 125; klambda = 1; if (sample.find("GluGluSignal") != std::string::npos) { if (sample.find("NonRes") != std::string::npos) { sample_id = -12; try { klambda = std::stof(sample.substr(sample.find("_kl")+3)); } catch (...) { std::cout << "Error in sample " << sample << " attempting to parse " << sample.substr(sample.find("_kl")+3) << "\n"; assert(false); } } else if (sample.find("Radion") != std::string::npos) { spin = radion; try { res_mass = std::stof(sample.substr(sample.find("_M")+2)); } catch (...) { std::cout << "Error in sample " << sample << " attempting to parse " << sample.substr(sample.find("_M")+2) << "\n"; assert(false); } if (res_mass <= 400) { sample_id = -13; } else if (res_mass <= 600) { sample_id = -14; } else { sample_id = -15; } } else if (sample.find("Graviton") != std::string::npos) { spin = graviton; try { res_mass = std::stof(sample.substr(sample.find("_M")+2)); } catch (...) { std::cout << "Error in sample " << sample << " attempting to parse " << sample.substr(sample.find("_M")+2) << "\n"; assert(false); } if (res_mass <= 400) { sample_id = -16; } else if (res_mass <= 600) { sample_id = -17; } else { sample_id = -18; } } } else if (sample.find("VBFSignal") != std::string::npos) { if (sample.find("NonRes") != std::string::npos) { sample_id = -19; } else if (sample.find("Radion") != std::string::npos) { spin = radion; try { res_mass = std::stof(sample.substr(sample.find("_M")+2)); } catch (...) { std::cout << "Error in sample " << sample << " attempting to parse " << sample.substr(sample.find("_M")+2) << "\n"; assert(false); } if (res_mass <= 400) { sample_id = -20; } else if (res_mass <= 600) { sample_id = -21; } else { sample_id = -22; } } else if (sample.find("Graviton") != std::string::npos) { spin = graviton; try { res_mass = std::stof(sample.substr(sample.find("_M")+2)); } catch (...) { std::cout << "Error in sample " << sample << " attempting to parse " << sample.substr(sample.find("_M")+2) << "\n"; assert(false); } if (res_mass <= 400) { sample_id = -23; } else if (res_mass <= 600) { sample_id = -24; } else { sample_id = -25; } } } else if (sample.find("Data") != std::string::npos) { sample_id = 0; } else if (sample.find("TT") != std::string::npos) { sample_id = 1; } else if (sample.find("ttH") != std::string::npos) { sample_id = 2; } else if (sample.find("DY") != std::string::npos) { sample_id = 3; } else if (sample.find("Wjets") != std::string::npos) { sample_id = 4; } else if (sample.find("SM_Higgs") != std::string::npos) { sample_id = 5; } else if (sample.find("VH") != std::string::npos) { sample_id = 6; } else if (sample.find("VVV") != std::string::npos) { sample_id = 7; } else if (sample.find("EWK") != std::string::npos) { sample_id = 8; } else if (sample.find("VV") != std::string::npos) { sample_id = 9; } else if (sample.find("ST") != std::string::npos) { sample_id = 10; } else if (sample.find("ttV") != std::string::npos) { sample_id = 11; } else{ throw std::invalid_argument("Unrecognised sample: " + sample); } } int sample2class_lookup(const int& sample) { if (sample < 0) return 1; // Signal if (sample == 0) return -1; // Collider data return 0; // Background } void extract_flags(const std::vector<std::string>& name, int& sample, int& region, bool& syst_unc, bool& scale, int& jet_cat, int& cut, int& class_id, Spin& spin, float& klambda, float& res_mass, bool& is_boosted) { /* Extract event flags from name Example: "2j/NoCuts/SS_AntiIsolated/None/Central/DY_MC_M-10-50" */ std::string val; int tmp; jet_cat = -1; cut = -1; for (unsigned int n = 0; n < name.size(); n++) { std::istringstream iss(name[n]); int i = 0; while (std::getline(iss, val, '/')) { if (i == 0) { tmp = jet_cat_lookup(val); if (tmp > jet_cat) jet_cat = tmp; is_boosted = (jet_cat == 5); } else if (i == 5 && n == 0) { sample_lookup(val, sample, spin, klambda, res_mass); } i++; } class_id = sample2class_lookup(sample); } } std::map<unsigned long, std::string> build_id_map(TFile* in_file) { TTreeReader aux_reader("aux", in_file); TTreeReaderValue<std::vector<unsigned long>> rv_aux_id(aux_reader, "dataIds"); TTreeReaderValue<std::vector<std::string>> rv_aux_name(aux_reader, "dataId_names"); std::vector<unsigned long> ids; std::vector<std::string> names; while (aux_reader.Next()) { ids = *rv_aux_id; names = *rv_aux_name; } std::map<unsigned long, std::string> id2name; for (unsigned int i = 0; i < ids.size(); i++) id2name[ids[i]] = names[i]; return id2name; } std::vector<std::string> get_requested(std::string feat_file) { std::ifstream infile(feat_file); std::cout << "Reading features from file: " << feat_file << "\nFeatures:"; std::string line; std::vector<std::string> requested; while (std::getline(infile, line)) { std::cout << line << " "; requested.push_back(line); } std::cout << "\n"; infile.close(); return requested; } bool run_test_loop(std::string fname, InfWrapper wrapper, const int& n, const std::string& feat_file) { std::cout << "Reading data from file: " << fname << "\n"; TFile* in_file = TFile::Open(fname.c_str()); TTreeReader reader("muTau", in_file); std::vector<std::string> requested = get_requested(feat_file); EvtProc evt_proc(false, requested, true); // Enums Channel e_channel(muTau); std::string channel = "muTau"; Year e_year(y18); Spin spin(nonres); float klambda; float res_mass; // Meta info std::cout << "Extracting auxiliary data..."; TTreeReaderValue<unsigned long long> rv_evt(reader, "evt"); TTreeReaderValue<std::vector<unsigned long>> rv_id(reader, "dataIds"); std::map<unsigned long, std::string> id2name = build_id_map(in_file); std::cout << " Extracted\n"; std::vector<std::string> names; int sample, region, jet_cat, cut, n_vbf, class_id; unsigned long long int evt; bool scale, syst_unc, svfit_conv, hh_kinfit_conv; std::vector<unsigned long> ids; // HL feats TTreeReaderValue<float> rv_kinfit_mass(reader, "kinFit_m"); TTreeReaderValue<float> rv_kinfit_chi2(reader, "kinFit_chi2"); TTreeReaderValue<float> rv_mt2(reader, "MT2"); float kinfit_mass, kinfit_chi2, mt2; // Tagging TTreeReaderValue<float> rv_b_1_csv(reader, "b1_DeepFlavour"); TTreeReaderValue<float> rv_b_2_csv(reader, "b2_DeepFlavour"); float b_1_csv, b_2_csv; bool is_boosted; // SVFit feats TTreeReaderValue<float> rv_svfit_pT(reader, "SVfit_pt"); TTreeReaderValue<float> rv_svfit_eta(reader, "SVfit_eta"); TTreeReaderValue<float> rv_svfit_phi(reader, "SVfit_phi"); TTreeReaderValue<float> rv_svfit_mass(reader, "SVfit_m"); LorentzVectorPEP pep_svfit; LorentzVector svfit; // l1 feats TTreeReaderValue<float> rv_l_1_pT(reader, "tau1_pt"); TTreeReaderValue<float> rv_l_1_eta(reader, "tau1_eta"); TTreeReaderValue<float> rv_l_1_phi(reader, "tau1_phi"); TTreeReaderValue<float> rv_l_1_mass(reader, "tau1_m"); float l_1_mass; LorentzVectorPEP pep_l_1; LorentzVector l_1; // l2 feats TTreeReaderValue<float> rv_l_2_pT(reader, "tau2_pt"); TTreeReaderValue<float> rv_l_2_eta(reader, "tau2_eta"); TTreeReaderValue<float> rv_l_2_phi(reader, "tau2_phi"); TTreeReaderValue<float> rv_l_2_mass(reader, "tau2_m"); LorentzVectorPEP pep_l_2;\ LorentzVector l_2; // MET feats TTreeReaderValue<float> rv_met_pT(reader, "MET_pt"); TTreeReaderValue<float> rv_met_phi(reader, "MET_phi"); LorentzVectorPEP pep_met; LorentzVector met; // b1 feats TTreeReaderValue<float> rv_b_1_pT(reader, "b1_pt"); TTreeReaderValue<float> rv_b_1_eta(reader, "b1_eta"); TTreeReaderValue<float> rv_b_1_phi(reader, "b1_phi"); TTreeReaderValue<float> rv_b_1_mass(reader, "b1_m"); TTreeReaderValue<float> rv_b_1_hhbtag(reader, "b1_HHbtag"); TTreeReaderValue<float> rv_b_1_cvsl(reader, "b1_DeepFlavour_CvsL"); TTreeReaderValue<float> rv_b_1_cvsb(reader, "b1_DeepFlavour_CvsB"); float b_1_hhbtag, b_1_cvsl, b_1_cvsb; LorentzVectorPEP pep_b_1; LorentzVector b_1; // b2 feats TTreeReaderValue<float> rv_b_2_pT(reader, "b2_pt"); TTreeReaderValue<float> rv_b_2_eta(reader, "b2_eta"); TTreeReaderValue<float> rv_b_2_phi(reader, "b2_phi"); TTreeReaderValue<float> rv_b_2_mass(reader, "b2_m"); TTreeReaderValue<float> rv_b_2_hhbtag(reader, "b2_HHbtag"); TTreeReaderValue<float> rv_b_2_cvsl(reader, "b2_DeepFlavour_CvsL"); TTreeReaderValue<float> rv_b_2_cvsb(reader, "b2_DeepFlavour_CvsB"); float b_2_hhbtag, b_2_cvsl, b_2_cvsb; LorentzVectorPEP pep_b_2; LorentzVector b_2; // vbf1 feats TTreeReaderValue<float> rv_vbf_1_pT(reader, "VBF1_pt"); TTreeReaderValue<float> rv_vbf_1_eta(reader, "VBF1_eta"); TTreeReaderValue<float> rv_vbf_1_phi(reader, "VBF1_phi"); TTreeReaderValue<float> rv_vbf_1_mass(reader, "VBF1_m"); TTreeReaderValue<float> rv_vbf_1_hhbtag(reader, "VBF1_HHbtag"); TTreeReaderValue<float> rv_vbf_1_cvsl(reader, "VBF1_DeepFlavour_CvsL"); TTreeReaderValue<float> rv_vbf_1_cvsb(reader, "VBF1_DeepFlavour_CvsB"); float vbf_1_hhbtag, vbf_1_cvsl, vbf_1_cvsb; LorentzVectorPEP pep_vbf_1; LorentzVector vbf_1; // vbf2 feats TTreeReaderValue<float> rv_vbf_2_pT(reader, "VBF2_pt"); TTreeReaderValue<float> rv_vbf_2_eta(reader, "VBF2_eta"); TTreeReaderValue<float> rv_vbf_2_phi(reader, "VBF2_phi"); TTreeReaderValue<float> rv_vbf_2_mass(reader, "VBF2_m"); TTreeReaderValue<float> rv_vbf_2_hhbtag(reader, "VBF2_HHbtag"); TTreeReaderValue<float> rv_vbf_2_cvsl(reader, "VBF2_DeepFlavour_CvsL"); TTreeReaderValue<float> rv_vbf_2_cvsb(reader, "VBF2_DeepFlavour_CvsB"); float vbf_2_hhbtag, vbf_2_cvsl, vbf_2_cvsb; LorentzVectorPEP pep_vbf_2; LorentzVector vbf_2; std::vector<float> feat_vals; float pred; std::cout << "\tprepared.\nBeginning loop.\n"; long int c_event(0), n_tot_events(reader.GetEntries(true)); while (reader.Next()) { c_event++; if (c_event%1000 == 0) std::cout << c_event << " / " << n_tot_events << "\n"; ids = *rv_id; names = get_evt_names(id2name, ids); extract_flags(names, sample, region, syst_unc, scale, jet_cat, cut, class_id, spin, klambda, res_mass, is_boosted); // Load meta evt = *rv_evt; // Load HL feats kinfit_mass = *rv_kinfit_mass; kinfit_chi2 = *rv_kinfit_chi2; mt2 = *rv_mt2; b_1_hhbtag = *rv_b_1_hhbtag; b_2_hhbtag = *rv_b_2_hhbtag; vbf_1_hhbtag = *rv_vbf_1_hhbtag; vbf_2_hhbtag = *rv_vbf_2_hhbtag; b_1_cvsl = *rv_b_1_cvsl; b_2_cvsl = *rv_b_2_cvsl; vbf_1_cvsl = *rv_vbf_1_cvsl; vbf_2_cvsl = *rv_vbf_2_cvsl; b_1_cvsb = *rv_b_1_cvsb; b_2_cvsb = *rv_b_2_cvsb; vbf_1_cvsb = *rv_vbf_1_cvsb; vbf_2_cvsb = *rv_vbf_2_cvsb; // Load tagging b_1_csv = *rv_b_1_csv; b_2_csv = *rv_b_2_csv; // Load vectors pep_svfit.SetCoordinates(*rv_svfit_pT, *rv_svfit_eta, *rv_svfit_phi, *rv_svfit_mass); if (channel == "muTau") { // Fix mass for light leptons l_1_mass = MU_MASS; } else if (channel == "eTau") { l_1_mass = E_MASS; } else { l_1_mass = *rv_l_1_mass; } pep_l_1.SetCoordinates(*rv_l_1_pT, *rv_l_1_eta, *rv_l_1_phi, l_1_mass); pep_l_2.SetCoordinates(*rv_l_2_pT, *rv_l_2_eta, *rv_l_2_phi, *rv_l_2_mass); pep_met.SetCoordinates(*rv_met_pT, 0, *rv_met_phi, 0); pep_b_1.SetCoordinates(*rv_b_1_pT, *rv_b_1_eta, *rv_b_1_phi, *rv_b_1_mass); pep_b_2.SetCoordinates(*rv_b_2_pT, *rv_b_2_eta, *rv_b_2_phi, *rv_b_2_mass); pep_vbf_1.SetCoordinates(*rv_vbf_1_pT, *rv_vbf_1_eta, *rv_vbf_1_phi, *rv_vbf_1_mass); pep_vbf_2.SetCoordinates(*rv_vbf_2_pT, *rv_vbf_2_eta, *rv_vbf_2_phi, *rv_vbf_2_mass); svfit.SetCoordinates(pep_svfit.Px(), pep_svfit.Py(), pep_svfit.Pz(), pep_svfit.M()); l_1.SetCoordinates(pep_l_1.Px(), pep_l_1.Py(), pep_l_1.Pz(), pep_l_1.M()); l_2.SetCoordinates(pep_l_2.Px(), pep_l_2.Py(), pep_l_2.Pz(), pep_l_2.M()); met.SetCoordinates(pep_met.Px(), pep_met.Py(), 0, 0); b_1.SetCoordinates(pep_b_1.Px(), pep_b_1.Py(), pep_b_1.Pz(), pep_b_1.M()); b_2.SetCoordinates(pep_b_2.Px(), pep_b_2.Py(), pep_b_2.Pz(), pep_b_2.M()); vbf_1.SetCoordinates(pep_vbf_1.Px(), pep_vbf_1.Py(), pep_vbf_1.Pz(), pep_vbf_1.M()); vbf_2.SetCoordinates(pep_vbf_2.Px(), pep_vbf_2.Py(), pep_vbf_2.Pz(), pep_vbf_2.M()); // VBF n_vbf = 0; if ((jet_cat == 5) || (jet_cat == 6) || (jet_cat == 7)) { if (*rv_vbf_1_mass != std::numeric_limits<float>::lowest()) n_vbf++; if (*rv_vbf_2_mass != std::numeric_limits<float>::lowest()) n_vbf++; } // Convergence svfit_conv = *rv_svfit_mass > 0; hh_kinfit_conv = kinfit_chi2 > 0; feat_vals = evt_proc.process_as_vec(b_1, b_2, l_1, l_2, met, svfit, vbf_1, vbf_2, kinfit_mass, kinfit_chi2, mt2, is_boosted, b_1_csv, b_2_csv, e_channel, e_year, res_mass, spin, klambda, n_vbf, svfit_conv, hh_kinfit_conv, b_1_hhbtag, b_2_hhbtag, vbf_1_hhbtag, vbf_2_hhbtag, b_1_cvsl, b_2_cvsl, vbf_1_cvsl, vbf_2_cvsl, b_1_cvsb, b_2_cvsb, vbf_1_cvsb, vbf_2_cvsb, 0, 0, 0, true); std::cout << "Input features:\n"; for (unsigned int i=0; i < requested.size(); i++) std::cout << requested[i] << "\t:\t" << feat_vals[i] << "\n"; pred = wrapper.predict(feat_vals, evt); std::cout << "\nEvent " << c_event << " class " << class_id << " prediction " << pred << "\n"; if (c_event >= n && n > 0) break; } std::cout << "Loop complete.\n"; in_file->Close(); return true; } void show_help() { /* Show help for input arguments */ std::cout << "-n : number of events to run, default 1, set negative to run all events in file\n"; std::cout << "-m : model version to use, default 2020-03-11-0\n"; std::cout << "-d : data version to use, default 2020-02-14\n"; } std::map<std::string, std::string> get_options(int argc, char* argv[]) { /*Interpret input arguments*/ std::map<std::string, std::string> options; options.insert(std::make_pair("-n", "1")); // number of events options.insert(std::make_pair("-m", "2020-05-18-2")); // model version options.insert(std::make_pair("-d", "2020-05-11-mva")); // model version if (argc >= 2) { //Check if help was requested std::string option(argv[1]); if (option == "-h" || option == "--help") { show_help(); options.clear(); return options; } } for (int i = 1; i < argc; i = i+2) { std::string option(argv[i]); std::string argument(argv[i+1]); if (option == "-h" || option == "--help" || argument == "-h" || argument == "--help") { // Check if help was requested show_help(); options.clear(); return options; } options[option] = argument; } return options; } int main(int argc, char *argv[]) { std::map<std::string, std::string> options = get_options(argc, argv); // Parse arguments if (options.size() == 0) return 1; std::cout << "Instantiating wrapper\n"; InfWrapper wrapper(model_dir+options["-m"]+"/ensemble", 1, true); std::cout << "Wrapper instantiated\n"; std::cout << "\nBeginning test loop for ensemble\n"; assert(run_test_loop(data_dir+options["-d"]+"/2018_muTau_tuple.root", wrapper, std::stoi(options["-n"]), model_dir+options["-m"]+"/features.txt")); std::cout << "\nAll tests completed sucessfully\n"; return 0; }
38.827112
161
0.598796
[ "vector", "model" ]
8f431302c7ff55ddb64e4352241588a76cf329e4
14,912
hpp
C++
src/types/class_object.hpp
LePtitDev/lite-script
2bd3233586737b6e53d5748b03cc21d53702a6c2
[ "BSD-3-Clause" ]
6
2017-09-01T11:27:47.000Z
2020-01-16T18:53:10.000Z
src/types/class_object.hpp
LePtitDev/lite-script
2bd3233586737b6e53d5748b03cc21d53702a6c2
[ "BSD-3-Clause" ]
null
null
null
src/types/class_object.hpp
LePtitDev/lite-script
2bd3233586737b6e53d5748b03cc21d53702a6c2
[ "BSD-3-Clause" ]
null
null
null
///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// /* Copyright (C) 2017 LePtitDev All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. Author: Arthur Ferré <leptitdev.com> */ ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// #ifndef LITESCRIPT_TYPES_CLASS_OBJECT_HPP #define LITESCRIPT_TYPES_CLASS_OBJECT_HPP #include "../memory/type.hpp" namespace LiteScript { // The derived type CLASS OBJECT class _Type_CLASS_OBJECT : public Type { public: /** * Basic constructor */ _Type_CLASS_OBJECT(); /** * Try to assign the objet referenced with default values of this type * * @param object The object to assign * @return The same object referenced */ Object& AssignObject(Object& obj) override; /** * Frees allocated memory of an object (called when an object is destroyed) * * @param object The object which will be destroyed */ void ODestroy(Object& object) const override; /** * Assign an object with the content of an other object * * @param object_target The object which must be assign * @param object_src The object which must be copied * @return The object assigned referenced */ Variable OAssign(Variable& object_target, const Variable& object_src) const override; /** * Create the result object of unary plus operation * * @param object The object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OUnaryPlus(const Variable& object) const override; /** * Create the result object of unary minus operation * * @param object The object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OUnaryMinus(const Variable& object) const override; /** * Apply an increment operation and return referenced object * * @param object The object operand * @return The object referenced */ Variable OPreIncrement(Variable& object) const override; /** * Create an object copy of the referenced object and apply an increment operation on the * referenced object * * @param object The object operand * @return The object copy */ Variable OPostIncrement(Variable& object) const override; /** * Apply a decrement operation and return referenced object * * @param object The object operand * @return The object referenced */ Variable OPreDecrement(Variable& object) const override; /** * Create an object copy of the referenced object and apply a decrement operation on the * referenced object * * @param object The object operand * @return The object copy */ Variable OPostDecrement(Variable& object) const override; /** * Create the result object of addition operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OAdd(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of substraction operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OSubstract(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of multiplication operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OMultiply(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of division operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable ODivide(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of modulo operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OModulo(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of equality comparison * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation as boolean object */ Variable OEqual(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of inequality comparison * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation as boolean object */ Variable ONotEqual(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of superiority comparison * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation as boolean object */ Variable OGreater(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of inferiority comparison * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation as boolean object */ Variable OLess(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of superiority or equality comparison * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation as boolean object */ Variable OGreaterOrEqual(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of inferiority or equality comparison * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation as boolean object */ Variable OLessOrEqual(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of logical not operation * * @param object The object operand * @return The result of operation as boolean object */ Variable OLogicalNot(const Variable& object) const override; /** * Create the result object of logical and operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation as boolean object */ Variable OLogicalAnd(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of logical or operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation as boolean object */ Variable OLogicalOr(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of binary not operation * * @param object The object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OBitwiseNot(const Variable& object) const override; /** * Create the result object of binary and operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OBitwiseAnd(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of binary or operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OBitwiseOr(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of binary xor operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OBitwiseXor(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of left shift operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable OLeftShift(const Variable& object_1, const Variable& object_2) const override; /** * Create the result object of right shift operation * * @param object_1 The first object operand * @param object_2 The second object operand * @return The result of operation (null object if the type doesn't permit this operation) */ Variable ORightShift(const Variable& object_1, const Variable& object_2) const override; /** * Add the source object to the target object and return it * * @param object_target The target object * @param object_src The source object * @return The target object referenced */ Variable OAddAndAssign(Variable& object_target, const Variable& object_src) const override; /** * Substract the source object to the target object and return it * * @param object_target The target object * @param object_src The source object * @return The target object referenced */ Variable OSubstractAndAssign(Variable& object_target, const Variable& object_src) const override; /** * Multiply the source object to the target object and return it * * @param object_target The target object * @param object_src The source object * @return The target object referenced */ Variable OMultiplyAndAssign(Variable& object_target, const Variable& object_src) const override; /** * Divide the source object to the target object and return it * * @param object_target The target object * @param object_src The source object * @return The target object referenced */ Variable ODivideAndAssign(Variable& object_target, const Variable& object_src) const override; /** * Return the object contained in the object source and identified by the key object * * @param object_src The object source * @param object_key The object key * @return The object contained in the object source if success or the undefined object otherwise */ Variable OArray(Variable& object_src, const Variable& object_key) const override; /** * Return the object contained in the object source and identified by the member name * * @param object_src The object source * @param member_name The member name * @return The object contained in the object source if success or the undefined object otherwise */ Variable OMember(Variable& object_src, const char * member_name) const override; /** * Return the result of calling operation * * @param object The callable object * @param state The script state * @param args The argument list * @return The return result of calling operation */ Variable OCall(Variable& object, State& state, std::vector<Variable>& args) const override; /** * Return a string for describe the content of the object referenced * * @param object The object to describe * @return A description string */ std::string ToString(const Variable& object) const override; /** * Save the content of the object in a binary stream * * @param stream The stream * @param object The object to save * @param caller Caller to save a variable */ void Save(std::ostream& stream, Object& object, bool (Memory::*caller)(std::ostream&, unsigned int)) const override; /** * Load the content of the object in a binary stream * * @param stream The stream * @param object The object to load * @param caller Caller to load a variable */ void Load(std::istream& stream, Object& object, unsigned int (Memory::*caller)(std::istream&)) const override; /** * Refer itself and all variables in the referenced object for the garbage collector * * @param object The object to refer * @param caller The calling function for referring */ void GarbageCollector(const Variable& object, bool (Memory::*caller)(unsigned int)) const override; }; extern _Type_CLASS_OBJECT _type_class_object; } #endif //LITESCRIPT_CLASS_OBJECT_HPP
38.235897
124
0.613533
[ "object", "vector" ]
8f43e783d0f1781388b9676dabd40655c01d4747
411
cpp
C++
training-sheet/B/004. Caisa and Pylons.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
training-sheet/B/004. Caisa and Pylons.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
null
null
null
training-sheet/B/004. Caisa and Pylons.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define lli long long int #define endl "\n" #define MAX 2005 using namespace std; int main() { lli n, data, prev = 0, energy = 0; cin>>n; vector <lli> v1(n); lli ans = 0; for(lli i =0; i<n; i++) { cin>>data; if(energy < (data-prev)) { ans += ((data-prev)); energy = 0; prev = data; } else { energy += (prev - data); prev = data; } } cout<<ans; }
13.258065
35
0.53528
[ "vector" ]
8f4ed7f5de7080b6421eab96fb1a72a56717f5bb
5,217
cpp
C++
core/src/wallet/common/database/OperationDatabaseHelper.cpp
kodxana/lib-ledger-core
96f04d378b7747e1b80b49da7ae637eb33b23678
[ "MIT" ]
null
null
null
core/src/wallet/common/database/OperationDatabaseHelper.cpp
kodxana/lib-ledger-core
96f04d378b7747e1b80b49da7ae637eb33b23678
[ "MIT" ]
null
null
null
core/src/wallet/common/database/OperationDatabaseHelper.cpp
kodxana/lib-ledger-core
96f04d378b7747e1b80b49da7ae637eb33b23678
[ "MIT" ]
null
null
null
/* * * OperationDatabaseHelper * ledger-core * * Created by Pierre Pollastri on 31/05/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * 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 "OperationDatabaseHelper.h" #include "BlockDatabaseHelper.h" #include <crypto/SHA256.hpp> #include <wallet/bitcoin/database/BitcoinLikeTransactionDatabaseHelper.h> #include <database/soci-number.h> #include <database/soci-date.h> #include <database/soci-option.h> #include <bytes/serialization.hpp> #include <collections/strings.hpp> #include <wallet/bitcoin/keychains/P2PKHBitcoinLikeKeychain.hpp> #include <wallet/common/TrustIndicator.h> using namespace soci; namespace ledger { namespace core { std::string OperationDatabaseHelper::createUid(const std::string &accountUid, const std::string &txId, const api::OperationType type) { return SHA256::stringToHexHash(fmt::format("uid:{}+{}+{}", accountUid, txId, api::to_string(type))); } bool OperationDatabaseHelper::putOperation(soci::session &sql, const Operation &operation) { auto count = 0; std::string serializedTrust; serialization::saveBase64<TrustIndicator>(*operation.trust, serializedTrust); if (operation.block.nonEmpty()) { BlockDatabaseHelper::putBlock(sql, operation.block.getValue()); } auto blockUid = operation.block.map<std::string>([] (const Block& block) { return block.getUid(); }); sql << "SELECT COUNT(*) FROM operations WHERE uid = :uid", use(operation.uid), into(count); auto newOperation = count == 0; if (!newOperation) { sql << "UPDATE operations SET block_uid = :block_uid, trust = :trust WHERE uid = :uid" , use(blockUid) , use(serializedTrust) , use(operation.uid); updateBitcoinOperation(sql, operation, newOperation); return false; } else { auto type = api::to_string(operation.type); std::stringstream senders; std::stringstream recipients; std::string separator(","); strings::join(operation.senders, senders, separator); strings::join(operation.recipients, recipients, separator); auto sndrs = senders.str(); auto rcvrs = recipients.str(); sql << "INSERT INTO operations VALUES(" ":uid, :accout_uid, :wallet_uid, :type, :date, :senders, :recipients, :amount," ":fees, :block_uid, :currency_name, :trust" ")" , use(operation.uid), use(operation.accountUid), use(operation.walletUid), use(type), use(operation.date) , use(sndrs), use(rcvrs), use(operation.amount.toInt64()) , use(operation.fees), use(blockUid) , use(operation.currencyName), use(serializedTrust); updateBitcoinOperation(sql, operation, newOperation); return true; } } void OperationDatabaseHelper::updateBitcoinOperation(soci::session &sql, const Operation &operation, bool insert) { if (operation.bitcoinTransaction.nonEmpty()) { BitcoinLikeTransactionDatabaseHelper::putTransaction(sql, operation.accountUid, operation.bitcoinTransaction .getValue()); if (insert) sql << "INSERT INTO bitcoin_operations VALUES(:uid, :tx_hash)", use(operation.uid) , use(operation.bitcoinTransaction.getValue().hash); } } void OperationDatabaseHelper::queryOperations(soci::session &sql, int32_t from, int32_t to, bool complete, bool excludeDropped, std::vector<Operation> &out) { } } }
46.168142
129
0.608971
[ "vector" ]
8f5143a22a6501ae30ab9e6e486c03e9850784a9
7,815
cpp
C++
src/activity/GeneratorScreen.cpp
ArthurSonzogni/pigami
bc33ed2797ba1da534d9cd4337e59d33ce46d4c5
[ "MIT" ]
4
2019-12-19T17:08:04.000Z
2020-09-20T08:31:15.000Z
src/activity/GeneratorScreen.cpp
ArthurSonzogni/pigami
bc33ed2797ba1da534d9cd4337e59d33ce46d4c5
[ "MIT" ]
null
null
null
src/activity/GeneratorScreen.cpp
ArthurSonzogni/pigami
bc33ed2797ba1da534d9cd4337e59d33ce46d4c5
[ "MIT" ]
null
null
null
// Copyright 2019 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file. #include "activity/GeneratorScreen.hpp" #include <cmath> #include <fstream> #include <smk/Color.hpp> #include <smk/Input.hpp> #include <smk/Shape.hpp> #include <smk/Sprite.hpp> #include <smk/Text.hpp> #include <smk/Vibrate.hpp> #include "Generator.hpp" #include "Resources.hpp" const float tile_space = 0.6f; GeneratorScreen::GeneratorScreen(smk::Window& window, Activity* background_activity) : Activity(window), back_button_(window), background_activity_(background_activity) { back_button_.on_quit = [&] { on_quit(); }; } GeneratorScreen::Entry GeneratorScreen::BuildEntry(std::string level, int score) { auto plateau = std::make_unique<Plateau>(); plateau->Load(SavePath() + "/generated_level/" + level); int min_movement = Evaluation(*plateau); float dim = 0.5 * std::max(window().width(), window().height()); auto framebuffer = smk::Framebuffer(dim, dim); plateau->Draw(&framebuffer, dim, dim); plateau->Draw(&window(), dim, dim); return { level, std::move(plateau), score, min_movement, std::move(framebuffer), }; } void GeneratorScreen::OnEnter() { std::ifstream file(SavePath() + "/generated_level/list"); std::string level; std::string score; entries.clear(); while (std::getline(file, level) && std::getline(file, score)) entries.push_back(BuildEntry(level, std::stoi(score))); entries.push_back({"Generate", nullptr, 0, 0, smk::Framebuffer(100, 100)}); generate_dy_ = -10.f; touch_dx_ = 0.f; touch_dxx_ = 0.f; touched_ = false; selected_index_x = selected_index; selected_index_dx = 0.f; } void GeneratorScreen::Animate() { selected_index_dx += (selected_index - selected_index_x) * 0.003; selected_index_dx *= 0.9; selected_index_x += (selected_index - selected_index_x) * 0.03 + selected_index_dx; background_activity_->Animate(); generate_dy_ += (0.f - generate_dy_) * 0.1; } void GeneratorScreen::Step() { int selected_index_previous = selected_index; float width = window().width(); float height = window().height(); float zoom = std::min(width, height); bool select_by_touch = false; if (window().input().IsKeyPressed(GLFW_KEY_LEFT)) selected_index--; if (window().input().IsKeyPressed(GLFW_KEY_RIGHT)) selected_index++; if (window().input().IsKeyPressed(GLFW_KEY_ESCAPE)) on_quit(); if (window().input().touches().size()) { touched_ = true; for (auto& it : window().input().touches()) { auto& touch = it.second; auto delta = touch.data_points.back().position - touch.data_points.front().position; touch_dxx_ += ((delta.x - touch_dx_) - touch_dxx_) * 0.5f; touch_dx_ = delta.x; touch_position = touch.data_points.front().position; } } else { if (touched_) { touched_ = false; float trigger = std::min(window().width(), window().height()) * 0.01f; if (std::abs(touch_dx_) < trigger && std::abs(selected_index_dx) < 0.01f) { bool in_strip = std::abs((touch_position.y - window().height() * 0.5) / (zoom * tile_space)) < 0.5f; int new_selected_index = std::round( selected_index_x + (touch_position.x - window().width() * 0.5) / (zoom * tile_space)); int new_selected_index_clamped = new_selected_index; new_selected_index_clamped = std::max(new_selected_index_clamped, 0); new_selected_index_clamped = std::min(new_selected_index_clamped, (int)entries.size() - 1); if (new_selected_index_clamped == new_selected_index && in_strip) { smk::Vibrate(20); selected_index = new_selected_index_clamped; select_by_touch = true; } } else if (!select_by_touch) { selected_index_dx -= touch_dxx_ / (zoom * tile_space); selected_index_x -= touch_dx_ / (zoom * tile_space); selected_index = std::round(selected_index_x - 50.f * touch_dxx_ / (zoom * tile_space)); } touch_dx_ = 0.f; touch_dxx_ = 0.f; } } if (window().input().IsKeyReleased(GLFW_KEY_ENTER) || window().input().IsKeyReleased(GLFW_KEY_SPACE) || select_by_touch) { PlaySound(sound_menu_select); if (selected_index == (int)entries.size() - 1) on_generate(); else on_selected(); } back_button_.Step(); Animate(); selected_index = std::max(selected_index, 0); selected_index = std::min(selected_index, (int)entries.size() - 1); if (selected_index_previous != selected_index) PlaySound(sound_menu_change); } void GeneratorScreen::Draw() { window().Clear(smk::Color::Black); background_activity_->Draw(); glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFrontFace(GL_CCW); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); // Set the view. float width = window().width(); float height = window().height(); float zoom = std::min(width, height); smk::View view; view.SetCenter(0, 0); view.SetSize(width / zoom, height / zoom); window().SetShaderProgram(window().shader_program_2d()); window().SetView(view); auto square = smk::Shape::Square(); square.SetColor({0.f, 0.f, 0.f, 0.9}); square.SetScale(width / zoom, height / zoom); square.SetPosition(-width / zoom * 0.5, -height / zoom * 0.5); window().Draw(square); auto draw_level = [&](int level) { float dx = (level - selected_index_x) * tile_space; float dy = (level == (int)entries.size() - 1) ? generate_dy_ : 0.f; dx += touch_dx_ / zoom; // Tile with texture. { auto& framebuffer = entries[level].framebuffer; auto sprite = smk::Sprite(framebuffer); sprite.SetPosition(dx - 0.25, -0.2 + dy); sprite.SetScale(0.5 / framebuffer.color_texture().width(), 0.5 / framebuffer.color_texture().height()); window().Draw(sprite); } { square.SetPosition(dx - 0.25, -0.2 + dy); square.SetScale(0.5, 0.1); square.SetColor({0.f, 0.f, 0.f, 0.2f}); window().Draw(square); } // Title. { auto text = smk::Text(font_arial, entries[level].name); auto dimension = text.ComputeDimensions(); float scale = 0.05 / 70.0; text.SetColor(smk::Color::White); text.SetScale(scale, scale); text.SetPosition(dx - dimension.x * 0.5 * scale, -0.2f + dy); window().Draw(text); } // Min_movement. if (entries[level].nb_move_player != -1) { std::string score = std::to_string(entries[level].nb_move_player) + "/" + std::to_string(entries[level].nb_move_min); auto text = smk::Text(font_arial, score); auto dimension = text.ComputeDimensions(); float scale = 0.05 / 70.0; text.SetColor(smk::Color::White); text.SetScale(scale, scale); text.SetPosition(dx - dimension.x * 0.5 * scale, -0.2f + dy + 0.5); window().Draw(text); } }; for (int level = 0; level < (int)entries.size(); ++level) draw_level(level); back_button_.Draw(); } void GeneratorScreen::Save(int nb_move) { int& nb_player_move = entries[selected_index].nb_move_player; if (nb_player_move == -1) { nb_player_move = nb_move; } else { nb_player_move = std::min(nb_player_move, nb_move); } { std::ofstream file(SavePath() + "/generated_level/list"); for (int i = 0; i < (int)entries.size() - 1; ++i) { auto& entry = entries[i]; file << entry.name << std::endl; file << entry.nb_move_player << std::endl; } } SyncFilesystem(); }
31.639676
81
0.627383
[ "shape" ]
8f5ba4be60ac2e9950ad9ddc51ad811911f064e3
1,068
cpp
C++
Othuum/AhwassaGraphicsLib/Vertex/PositionNormalTextureVertex.cpp
Liech/Yathsou
95b6dda3c053bc25789cce416088e22f54a743b4
[ "MIT" ]
5
2021-04-20T17:00:41.000Z
2022-01-18T20:16:03.000Z
Othuum/AhwassaGraphicsLib/Vertex/PositionNormalTextureVertex.cpp
Liech/Yathsou
95b6dda3c053bc25789cce416088e22f54a743b4
[ "MIT" ]
7
2021-08-22T21:30:50.000Z
2022-01-14T16:56:34.000Z
Othuum/AhwassaGraphicsLib/Vertex/PositionNormalTextureVertex.cpp
Liech/Yathsou
95b6dda3c053bc25789cce416088e22f54a743b4
[ "MIT" ]
null
null
null
#include "PositionNormalTextureVertex.h" #include "IyathuumCoreLib/lib/glm/glm.hpp" #include <glad/glad.h> #include <vector> #include "Core/AttributeDescription.h" namespace Ahwassa { PositionNormalTextureVertex::PositionNormalTextureVertex() : position(0), normal(0), texture(0) { } PositionNormalTextureVertex::PositionNormalTextureVertex(glm::vec3 Position, glm::vec3 Normal, glm::vec2 Texture) { position = Position; normal = Normal; texture = Texture; } std::vector<AttributeDescription> PositionNormalTextureVertex::getBinding() { std::vector<AttributeDescription> result; result.push_back(AttributeDescription("position", 3, AttributeDescription::DataType::Float)); result.push_back(AttributeDescription("normal" , 3, AttributeDescription::DataType::Float)); result.push_back(AttributeDescription("texture" , 2, AttributeDescription::DataType::Float)); return result; } std::vector<AttributeDescription> PositionNormalTextureVertex::binding() { return PositionNormalTextureVertex::getBinding(); } }
34.451613
117
0.757491
[ "vector" ]
8f5bf097a698299e03faa2ec0959cf7af2350dd0
9,349
cpp
C++
applications/CompressiblePotentialFlowApplication/custom_utilities/potential_flow_utilities.cpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
1
2019-08-01T09:01:08.000Z
2019-08-01T09:01:08.000Z
applications/CompressiblePotentialFlowApplication/custom_utilities/potential_flow_utilities.cpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
null
null
null
applications/CompressiblePotentialFlowApplication/custom_utilities/potential_flow_utilities.cpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
null
null
null
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Inigo Lopez #include "custom_utilities/potential_flow_utilities.h" #include "compressible_potential_flow_application_variables.h" namespace Kratos { namespace PotentialFlowUtilities { template <int Dim, int NumNodes> array_1d<double, NumNodes> GetWakeDistances(const Element& rElement) { return rElement.GetValue(WAKE_ELEMENTAL_DISTANCES); } template <int Dim, int NumNodes> BoundedVector<double, NumNodes> GetPotentialOnNormalElement(const Element& rElement) { const int kutta = rElement.GetValue(KUTTA); array_1d<double, NumNodes> potentials; const auto r_geometry = rElement.GetGeometry(); if (kutta == 0) { for (unsigned int i = 0; i < NumNodes; i++) { potentials[i] = r_geometry[i].FastGetSolutionStepValue(VELOCITY_POTENTIAL); } } else { for (unsigned int i = 0; i < NumNodes; i++) { if (!r_geometry[i].GetValue(TRAILING_EDGE)) { potentials[i] = r_geometry[i].FastGetSolutionStepValue(VELOCITY_POTENTIAL); } else { potentials[i] = r_geometry[i].FastGetSolutionStepValue(AUXILIARY_VELOCITY_POTENTIAL); } } } return potentials; } template <int Dim, int NumNodes> BoundedVector<double, 2 * NumNodes> GetPotentialOnWakeElement( const Element& rElement, const array_1d<double, NumNodes>& rDistances) { const auto upper_potentials = GetPotentialOnUpperWakeElement<Dim, NumNodes>(rElement, rDistances); const auto lower_potentials = GetPotentialOnLowerWakeElement<Dim, NumNodes>(rElement, rDistances); BoundedVector<double, 2 * NumNodes> split_element_values; for (unsigned int i = 0; i < NumNodes; i++) { split_element_values[i] = upper_potentials[i]; split_element_values[NumNodes + i] = lower_potentials[i]; } return split_element_values; } template <int Dim, int NumNodes> BoundedVector<double, NumNodes> GetPotentialOnUpperWakeElement( const Element& rElement, const array_1d<double, NumNodes>& rDistances) { array_1d<double, NumNodes> upper_potentials; const auto r_geometry = rElement.GetGeometry(); for (unsigned int i = 0; i < NumNodes; i++){ if (rDistances[i] > 0.0){ upper_potentials[i] = r_geometry[i].FastGetSolutionStepValue(VELOCITY_POTENTIAL); } else{ upper_potentials[i] = r_geometry[i].FastGetSolutionStepValue(AUXILIARY_VELOCITY_POTENTIAL); } } return upper_potentials; } template <int Dim, int NumNodes> BoundedVector<double, NumNodes> GetPotentialOnLowerWakeElement( const Element& rElement, const array_1d<double, NumNodes>& rDistances) { array_1d<double, NumNodes> lower_potentials; const auto r_geometry = rElement.GetGeometry(); for (unsigned int i = 0; i < NumNodes; i++){ if (rDistances[i] < 0.0){ lower_potentials[i] = r_geometry[i].FastGetSolutionStepValue(VELOCITY_POTENTIAL); } else{ lower_potentials[i] = r_geometry[i].FastGetSolutionStepValue(AUXILIARY_VELOCITY_POTENTIAL); } } return lower_potentials; } template <int Dim, int NumNodes> array_1d<double, Dim> ComputeVelocity(const Element& rElement) { const int wake = rElement.GetValue(WAKE); if (wake == 0) return ComputeVelocityNormalElement<Dim,NumNodes>(rElement); else return ComputeVelocityUpperWakeElement<Dim,NumNodes>(rElement); } template <int Dim, int NumNodes> array_1d<double, Dim> ComputeVelocityNormalElement(const Element& rElement) { ElementalData<NumNodes, Dim> data; // Calculate shape functions GeometryUtils::CalculateGeometryData(rElement.GetGeometry(), data.DN_DX, data.N, data.vol); data.potentials = GetPotentialOnNormalElement<Dim,NumNodes>(rElement); return prod(trans(data.DN_DX), data.potentials); } template <int Dim, int NumNodes> array_1d<double, Dim> ComputeVelocityUpperWakeElement(const Element& rElement) { ElementalData<NumNodes, Dim> data; // Calculate shape functions GeometryUtils::CalculateGeometryData(rElement.GetGeometry(), data.DN_DX, data.N, data.vol); const auto& r_distances = GetWakeDistances<Dim,NumNodes>(rElement); data.potentials = GetPotentialOnUpperWakeElement<Dim,NumNodes>(rElement, r_distances); return prod(trans(data.DN_DX), data.potentials); } template <int Dim, int NumNodes> array_1d<double, Dim> ComputeVelocityLowerWakeElement(const Element& rElement) { ElementalData<NumNodes, Dim> data; // Calculate shape functions GeometryUtils::CalculateGeometryData(rElement.GetGeometry(), data.DN_DX, data.N, data.vol); const auto& r_distances = GetWakeDistances<Dim,NumNodes>(rElement); data.potentials = GetPotentialOnLowerWakeElement<Dim,NumNodes>(rElement, r_distances); return prod(trans(data.DN_DX), data.potentials); } template <int Dim, int NumNodes> double ComputeIncompressiblePressureCoefficient(const Element& rElement, const ProcessInfo& rCurrentProcessInfo) { const array_1d<double, 3> free_stream_velocity = rCurrentProcessInfo[FREE_STREAM_VELOCITY]; const double free_stream_velocity_norm = inner_prod(free_stream_velocity, free_stream_velocity); KRATOS_ERROR_IF(free_stream_velocity_norm < std::numeric_limits<double>::epsilon()) << "Error on element -> " << rElement.Id() << "\n" << "free_stream_velocity_norm must be larger than zero." << std::endl; array_1d<double, Dim> v = ComputeVelocity<Dim,NumNodes>(rElement); double pressure_coefficient = (free_stream_velocity_norm - inner_prod(v, v)) / free_stream_velocity_norm; // 0.5*(norm_2(free_stream_velocity) - norm_2(v)); return pressure_coefficient; } template <int Dim, int NumNodes> const bool CheckIfElementIsCutByDistance(const BoundedVector<double, NumNodes>& rNodalDistances) { // Initialize counters unsigned int number_of_nodes_with_positive_distance = 0; unsigned int number_of_nodes_with_negative_distance = 0; // Count how many element nodes are above and below the wake for (unsigned int i = 0; i < rNodalDistances.size(); i++) { if (rNodalDistances(i) < 0.0) { number_of_nodes_with_negative_distance += 1; } else { number_of_nodes_with_positive_distance += 1; } } // Elements with nodes above and below the wake are wake elements return number_of_nodes_with_negative_distance > 0 && number_of_nodes_with_positive_distance > 0; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Template instantiation // 2D template array_1d<double, 3> GetWakeDistances<2, 3>(const Element& rElement); template BoundedVector<double, 3> GetPotentialOnNormalElement<2, 3>(const Element& rElement); template BoundedVector<double, 2 * 3> GetPotentialOnWakeElement<2, 3>( const Element& rElement, const array_1d<double, 3>& rDistances); template BoundedVector<double, 3> GetPotentialOnUpperWakeElement<2, 3>( const Element& rElement, const array_1d<double, 3>& rDistances); template BoundedVector<double, 3> GetPotentialOnLowerWakeElement<2, 3>( const Element& rElement, const array_1d<double, 3>& rDistances); template array_1d<double, 2> ComputeVelocityNormalElement<2, 3>(const Element& rElement); template array_1d<double, 2> ComputeVelocityUpperWakeElement<2, 3>(const Element& rElement); template array_1d<double, 2> ComputeVelocityLowerWakeElement<2, 3>(const Element& rElement); template array_1d<double, 2> ComputeVelocity<2, 3>(const Element& rElement); template double ComputeIncompressiblePressureCoefficient<2, 3>(const Element& rElement, const ProcessInfo& rCurrentProcessInfo); template const bool CheckIfElementIsCutByDistance<2, 3>(const BoundedVector<double, 3>& rNodalDistances); // 3D template array_1d<double, 4> GetWakeDistances<3, 4>(const Element& rElement); template BoundedVector<double, 4> GetPotentialOnNormalElement<3, 4>(const Element& rElement); template BoundedVector<double, 2 * 4> GetPotentialOnWakeElement<3, 4>( const Element& rElement, const array_1d<double, 4>& rDistances); template BoundedVector<double, 4> GetPotentialOnUpperWakeElement<3, 4>( const Element& rElement, const array_1d<double, 4>& rDistances); template BoundedVector<double, 4> GetPotentialOnLowerWakeElement<3, 4>( const Element& rElement, const array_1d<double, 4>& rDistances); template array_1d<double, 3> ComputeVelocityNormalElement<3, 4>(const Element& rElement); template array_1d<double, 3> ComputeVelocityUpperWakeElement<3, 4>(const Element& rElement); template array_1d<double, 3> ComputeVelocityLowerWakeElement<3, 4>(const Element& rElement); template array_1d<double, 3> ComputeVelocity<3, 4>(const Element& rElement); template double ComputeIncompressiblePressureCoefficient<3, 4>(const Element& rElement, const ProcessInfo& rCurrentProcessInfo); template const bool CheckIfElementIsCutByDistance<3, 4>(const BoundedVector<double, 4>& rNodalDistances); } // namespace PotentialFlow } // namespace Kratos
39.614407
128
0.719221
[ "shape", "3d" ]
8f5de31d18a8a5f0f8d801ae4d7a2bb6898e689c
767
cc
C++
e2e/trt/src/criterion.cc
stanford-futuredata/smol
82e2356755133cd1516dfbbbc782707eca70a34c
[ "Apache-2.0" ]
1
2021-11-29T01:24:03.000Z
2021-11-29T01:24:03.000Z
e2e/trt/src/criterion.cc
stanford-futuredata/smol
82e2356755133cd1516dfbbbc782707eca70a34c
[ "Apache-2.0" ]
1
2021-11-29T09:29:14.000Z
2021-12-13T02:31:55.000Z
e2e/trt/src/criterion.cc
stanford-futuredata/smol
82e2356755133cd1516dfbbbc782707eca70a34c
[ "Apache-2.0" ]
1
2021-12-13T06:55:18.000Z
2021-12-13T06:55:18.000Z
#include <cassert> #include <iostream> #include "criterion.h" std::vector<bool> MaxCriterion::filter(const size_t kNbEl, std::vector<float> data) const { assert(data.size() % kNbEl == 0); const size_t kSingleSize = data.size() / kNbEl; std::vector<bool> ret(kNbEl); #pragma omp parallel for for (size_t i = 0; i < kNbEl; i++) { auto beg = data.begin() + i * kSingleSize; auto end = data.begin() + (i + 1) * kSingleSize; softmax(beg, end, beg); // Softmax modifies the iterators beg = data.begin() + i * kSingleSize; end = data.begin() + (i + 1) * kSingleSize; const float kMaxEl { *std::max_element(beg, end) }; if (kMaxEl < kCutoff_) { ret[i] = false; } else { ret[i] = true; } } return ret; }
24.741935
91
0.601043
[ "vector" ]
8f60096ad8306fb68060c01d94e1aae2bd7299cc
1,628
hpp
C++
include/landscapes/svo_serialization.v1.hpp
realazthat/landscapes
0d56d67beb5641b913100d86601fce8a5a63fb1c
[ "MIT", "WTFPL", "Unlicense", "0BSD" ]
32
2015-12-29T04:33:08.000Z
2021-04-08T01:46:44.000Z
include/landscapes/svo_serialization.v1.hpp
realazthat/landscapes
0d56d67beb5641b913100d86601fce8a5a63fb1c
[ "MIT", "WTFPL", "Unlicense", "0BSD" ]
null
null
null
include/landscapes/svo_serialization.v1.hpp
realazthat/landscapes
0d56d67beb5641b913100d86601fce8a5a63fb1c
[ "MIT", "WTFPL", "Unlicense", "0BSD" ]
2
2019-04-05T02:28:02.000Z
2019-06-11T07:59:53.000Z
#ifndef SVO_SERALIZATION_V1_HPP #define SVO_SERALIZATION_V1_HPP 1 #include <iosfwd> #include <vector> #include <tuple> #include <string> #include <memory> #include "svo_curves.h" #include "svo_tree.fwd.hpp" #include "svo_buffer.fwd.hpp" namespace svo{ typedef std::vector< std::tuple<vside_t, vcurve_t> > children_params_t; void serialize_slice(std::ostream& out, const svo_slice_t* slice); children_params_t unserialize_slice(std::istream& in, svo_slice_t* slice, bool load_empty_children); void serialize_string(std::ostream& out, const std::string& v); void serialize_buffer(std::ostream& out, const svo_cpu_buffer_t& buffer); void serialize_buffer_data(std::ostream& out, const svo_cpu_buffer_t& buffer); void serialize_buffers(std::ostream& out, const svo_cpu_buffers_t& buffers, std::size_t expected_entries); void serialize_declaration(std::ostream& out, const svo_declaration_t& declaration); void serialize_schema(std::ostream& out, const svo_schema_t& schema); void serialize_slice_child_info(std::ostream& out, const svo_slice_t* slice); std::string unserialize_string(std::istream& in); std::unique_ptr<svo_cpu_buffer_t> unserialize_buffer(std::istream& in); void unserialize_buffer_data(std::istream& in, svo_cpu_buffer_t& buffers, std::size_t expected_entries); void unserialize_buffers(std::istream& in, svo_cpu_buffers_t& buffers, std::size_t expected_entries); svo_declaration_t unserialize_declaration(std::istream& in); svo_schema_t unserialize_schema(std::istream& in); children_params_t unserialize_slice_child_info(std::istream& in, svo_slice_t* slice); } //namespace svo #endif
30.148148
106
0.796069
[ "vector" ]
8f66d9ec048160da9708fb64ca58f02914c37e9b
1,880
cpp
C++
LiberoEngine/src/Libero/Editor/Editor.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
LiberoEngine/src/Libero/Editor/Editor.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
LiberoEngine/src/Libero/Editor/Editor.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
#include "Liber_pch.h" #include "Editor.h" #include "ImGuiStyleLibrary.h" #include "MyWindows/MyImGuiWindows.h" #include "Libero/Settings/Settings.h" #include "Libero/Graphics/GraphicsMaster.h" namespace Libero { void Editor::Initialize() { const GraphicsContext& graphContx = GraphicsLocator::Get()->GetGraphicsContext(); IMGUI_CHECKVERSION(); ImGui::CreateContext(); m_IsInitialized = ImGui_ImplWin32_Init(graphContx.m_WindowHandle) && ImGui_ImplDX11_Init(graphContx.m_pDevice, graphContx.m_pDeviceContext); m_pIO = &ImGui::GetIO(); ImGuiStyles::GoldBlackTheme(); m_pIO->IniFilename = Settings::ImGui.iniFilePath.c_str(); InitWindows(); } void Editor::InitWindows() { m_Windows["Play"] = new ImGui_Play(); ImGui_Hierarchy* pHierarchy = new ImGui_Hierarchy(); m_Windows["Hierarchy"] = pHierarchy; m_Windows["TopMenu"] = new ImGui_TopMenu(); m_Windows["Resources"] = new ImGui_Resources(); m_Windows["Inspector"] = new ImGui_Inspector(*pHierarchy); m_Windows["Logger"] = new ImGui_Logger(); m_Windows["Editor"] = new ImGui_Editor(); for (auto& wPair : m_Windows) { wPair.second->EnableEdit(false); } } void Editor::Render() { if (!m_IsInitialized) return; m_pIO->WantCaptureMouse = true; m_pIO->ConfigFlags |= ImGuiConfigFlags_DockingEnable; ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); { // Render demo: ImGui::ShowDemoWindow(); // Render My Windows for (const auto& wPair : m_Windows) { wPair.second->ImGuiRender(); } } ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); } void Libero::Editor::Shutdown() { if (!m_IsInitialized) return; ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); for (auto& wPair : m_Windows) { delete wPair.second; wPair.second = nullptr; } } }
22.650602
142
0.710106
[ "render" ]
8f7f976e10e0334d17ebe6e41530bf8a7f19f6e4
23,628
hpp
C++
Commands/Shop.hpp
RealTimeChris/MBot-GameHouse-Cpp
d9039edd12c33d14d568a1881cb9086a7a165e9f
[ "Apache-2.0" ]
4
2021-08-18T20:00:49.000Z
2022-01-20T14:37:09.000Z
Commands/Shop.hpp
RealTimeChris/MBot-GameHouse-Cpp
d9039edd12c33d14d568a1881cb9086a7a165e9f
[ "Apache-2.0" ]
null
null
null
Commands/Shop.hpp
RealTimeChris/MBot-GameHouse-Cpp
d9039edd12c33d14d568a1881cb9086a7a165e9f
[ "Apache-2.0" ]
null
null
null
// Shop.hpp - Header for the "shop" command. // June 2, 2021 // Chris M. // https://github.com/RealTimeChris #pragma once #ifndef _SHOP_ #define _SHOP_ #include "Index.hpp" #include "HelperFunctions.hpp" namespace DiscordCoreAPI { enum class ItemsOrRoles { roles = 0, items = 1 }; vector<SelectOptionData> getSelectOptionsVector(DiscordGuild discordGuild, ItemsOrRoles itemsOrRoles) { discordGuild.getDataFromDB(); uint32_t maxIdx = 0; InventoryItem tempItem; uint32_t len = (uint32_t)discordGuild.data.guildShop.items.size(); for (uint32_t x = 0; x < len; x += 1) { maxIdx = x; for (uint32_t y = x + 1; y < len; y += 1) { if (discordGuild.data.guildShop.items.at(y).itemCost > discordGuild.data.guildShop.items.at(maxIdx).itemCost) { maxIdx = y; } } tempItem = discordGuild.data.guildShop.items.at(x); discordGuild.data.guildShop.items.at(x) = discordGuild.data.guildShop.items.at(maxIdx); discordGuild.data.guildShop.items.at(maxIdx) = tempItem; } maxIdx = 0; InventoryRole tempRole; len = (uint32_t)discordGuild.data.guildShop.roles.size(); for (uint32_t x = 0; x < len; x += 1) { maxIdx = x; for (uint32_t y = x + 1; y < len; y += 1) { if (discordGuild.data.guildShop.roles.at(y).roleCost > discordGuild.data.guildShop.roles.at(maxIdx).roleCost) { maxIdx = y; } } tempRole = discordGuild.data.guildShop.roles.at(x); discordGuild.data.guildShop.roles.at(x) = discordGuild.data.guildShop.roles.at(maxIdx); discordGuild.data.guildShop.roles.at(maxIdx) = tempRole; } discordGuild.writeDataToDB(); vector<SelectOptionData> returnVector; if (itemsOrRoles == ItemsOrRoles::items) { for (auto& value : discordGuild.data.guildShop.items) { SelectOptionData itemOptionData; itemOptionData.emoji.name = value.emoji; itemOptionData.description = "Cost: " + to_string(value.itemCost) + " Self-Mod: " + to_string(value.selfMod) + " Opp-Mod: " + to_string(value.oppMod); itemOptionData.label = value.itemName; itemOptionData.value = convertToLowerCase(value.itemName); itemOptionData._default = false; returnVector.push_back(itemOptionData); } } else { for (auto& value : discordGuild.data.guildShop.roles) { SelectOptionData roleOptionData; roleOptionData.description = "Cost: " + to_string(value.roleCost); roleOptionData.label = value.roleName; roleOptionData.value = convertToLowerCase(value.roleName); roleOptionData._default = false; returnVector.push_back(roleOptionData); } } SelectOptionData goBackOption; goBackOption.description = "Go back to the previous menu."; goBackOption.emoji.name = "❌"; goBackOption.label = "Go Back"; goBackOption.value = "go_back"; goBackOption._default = false; returnVector.push_back(goBackOption); return returnVector; } class Shop : public BaseFunction { public: Shop() { this->commandName = "shop"; this->helpDescription = "View the server's item and role shop!"; EmbedData msgEmbed; msgEmbed.setDescription("------\nSimply enter !shop , or /shop.\n------"); msgEmbed.setTitle("__**Shop Usage:**__"); msgEmbed.setTimeStamp(getTimeAndDate()); msgEmbed.setColor("FeFeFe"); this->helpEmbed = msgEmbed; } unique_ptr<BaseFunction> create() { return make_unique<Shop>(); } virtual void execute(BaseFunctionArguments args) { Channel channel = Channels::getCachedChannelAsync({ args.eventData.getChannelId() }).get(); bool areWeInADm = areWeInADM(args.eventData, channel); if (areWeInADm == true) { return; } InputEvents::deleteInputEventResponseAsync(args.eventData).get(); Guild guild = Guilds::getCachedGuildAsync({ args.eventData.getGuildId() }).get(); DiscordGuild discordGuild(guild); GuildMember guildMember = GuildMembers::getCachedGuildMemberAsync({ .guildMemberId = args.eventData.getAuthorId(),.guildId = args.eventData.getGuildId() }).get(); bool areWeAllowed = checkIfAllowedGamingInChannel(args.eventData, discordGuild); if (areWeAllowed == false) { return; } GuildMember botMember = GuildMembers::getCachedGuildMemberAsync({ .guildMemberId = args.discordCoreClient->getBotUser().id,.guildId = args.eventData.getGuildId() }).get(); if (!(botMember.permissions.checkForPermission(botMember, channel, Permission::Manage_Messages))) { string msgString = "------\n**I need the Manage Messages permission in this channel, for this command!**\n------"; EmbedData msgEmbed; msgEmbed.setAuthor(args.eventData.getUserName(), args.eventData.getAvatarUrl()); msgEmbed.setColor(discordGuild.data.borderColor); msgEmbed.setDescription(msgString); msgEmbed.setTimeStamp(getTimeAndDate()); msgEmbed.setTitle("__**Permissions Issue:**__"); if (args.eventData.eventType == InputEventType::Regular_Message) { RespondToInputEventData dataPackage(args.eventData); dataPackage.type = InputEventResponseType::Regular_Message; dataPackage.addMessageEmbed(msgEmbed); InputEventData event01 = InputEvents::respondToEvent(dataPackage); InputEvents::deleteInputEventResponseAsync(event01, 20000); } else if (args.eventData.eventType == InputEventType::Application_Command_Interaction) { RespondToInputEventData dataPackage(args.eventData); dataPackage.type = InputEventResponseType::Ephemeral_Interaction_Response; dataPackage.addMessageEmbed(msgEmbed); InputEventData event = InputEvents::respondToEvent(dataPackage); } return; } vector<Role> rolesArray = Roles::getGuildRolesAsync({ .guildId = args.eventData.getGuildId() }).get(); InputEventData event02 = args.eventData; for (uint32_t x = 0; x < discordGuild.data.guildShop.roles.size(); x+=1) { bool isRoleFound = false; InventoryRole shopRole = discordGuild.data.guildShop.roles[x]; for (auto& value2:rolesArray) { if (value2.id == shopRole.roleId) { isRoleFound = true; break; } } if (isRoleFound == false) { discordGuild.data.guildShop.roles.erase(discordGuild.data.guildShop.roles.begin() + x); discordGuild.writeDataToDB(); string msgString = "------\n**Removing guild role " + shopRole.roleName + " from guild cache!**\n------"; EmbedData msgEmbed; msgEmbed.setAuthor(args.eventData.getUserName(), args.eventData.getAvatarUrl()); msgEmbed.setColor(discordGuild.data.borderColor); msgEmbed.setDescription(msgString); msgEmbed.setTimeStamp(getTimeAndDate()); msgEmbed.setTitle("__**Removed Guild Role:**__"); if (args.eventData.eventType == InputEventType::Regular_Message) { RespondToInputEventData dataPackage(args.eventData); dataPackage.type = InputEventResponseType::Regular_Message; dataPackage.addMessageEmbed(msgEmbed); event02 = InputEvents::respondToEvent(dataPackage); InputEvents::deleteInputEventResponseAsync(event02, 20000); } else if (args.eventData.eventType == InputEventType::Application_Command_Interaction) { RespondToInputEventData dataPackage(args.eventData); dataPackage.type = InputEventResponseType::Interaction_Response; dataPackage.addMessageEmbed(msgEmbed); InputEvents::respondToEvent(dataPackage); } x -= 1; } } EmbedData msgEmbed; msgEmbed.setAuthor(args.eventData.getUserName(), args.eventData.getAvatarUrl()); msgEmbed.setDescription("------\n__**Select which part of the shop you would like to browse!**__\n------"); msgEmbed.setColor(discordGuild.data.borderColor); msgEmbed.setTimeStamp(getTimeAndDate()); msgEmbed.setTitle("__**Welcome to the Shop:**__"); EmbedData msgEmbedItems; msgEmbedItems.setAuthor(args.eventData.getUserName(), args.eventData.getAvatarUrl()); msgEmbedItems.setDescription("------\n__**Select one or more items which you would like to purchase, from the drop-down menu!**__\n------"); msgEmbedItems.setColor(discordGuild.data.borderColor); msgEmbedItems.setTimeStamp(getTimeAndDate()); msgEmbedItems.setTitle("__**Welcome to the Shop:**__"); EmbedData msgEmbedRoles; msgEmbedRoles.setAuthor(args.eventData.getUserName(), args.eventData.getAvatarUrl()); msgEmbedRoles.setDescription("------\n__**Select one or more roles which you would like to purchase, from the drop-down menu!**__\n------"); msgEmbedRoles.setColor(discordGuild.data.borderColor); msgEmbedRoles.setTimeStamp(getTimeAndDate()); msgEmbedRoles.setTitle("__**Welcome to the Shop:**__"); vector<SelectMenuResponseData> values; if (event02.eventType == InputEventType::Regular_Message) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Regular_Message; dataPackage.addMessageEmbed(msgEmbed); dataPackage.addButton(false, "items", "Items", ButtonStyle::Primary, "☑"); dataPackage.addButton(false, "roles", "Roles", ButtonStyle::Primary, "🔥"); dataPackage.addButton(false, "exit", "Exit", ButtonStyle::Danger, "❌"); event02 = InputEvents::respondToEvent (dataPackage); } else if (event02.eventType == InputEventType::Application_Command_Interaction) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Deferred_Response; event02 = InputEvents::respondToEvent(dataPackage); RespondToInputEventData dataPackage02(event02); dataPackage02.type = InputEventResponseType::Follow_Up_Message; dataPackage02.addMessageEmbed(msgEmbed); dataPackage02.addButton(false, "items", "Items", ButtonStyle::Primary, "☑"); dataPackage02.addButton(false, "roles", "Roles", ButtonStyle::Primary, "🔥"); dataPackage02.addButton(false, "exit", "Exit", ButtonStyle::Danger, "❌"); event02 = InputEvents::respondToEvent(dataPackage02); } while (1) { start: EmbedData currentEmbed; ButtonCollector newButton(event02); auto buttonData = newButton.collectButtonData(false, 60000, 1, args.eventData.getAuthorId()).get(); if (buttonData.at(0).buttonId== "items") { currentEmbed = msgEmbedItems; } else if (buttonData.at(0).buttonId == "roles") { currentEmbed = msgEmbedRoles; } if (buttonData.at(0).buttonId == "roles" || buttonData.at(0).buttonId == "items") { RespondToInputEventData dataPackage(buttonData.at(0).interactionData); dataPackage.addMessageEmbed(currentEmbed); if (buttonData.at(0).buttonId == "items") { vector<SelectOptionData> selectOptionDataItems = getSelectOptionsVector(discordGuild, ItemsOrRoles::items); dataPackage.addSelectMenu(false, "shop_menu_itmes", selectOptionDataItems, "Choose one or more items.", (int32_t)selectOptionDataItems.size(), 1); } else { vector<SelectOptionData> selectOptionDataRoles = getSelectOptionsVector(discordGuild, ItemsOrRoles::roles); dataPackage.addSelectMenu(false, "shop_menu_roles", selectOptionDataRoles, "Choose one or more roles.", (int32_t)selectOptionDataRoles.size(), 1); } InputEvents::respondToEvent(dataPackage); } else if (buttonData.at(0).buttonId == "exit" || buttonData.at(0).buttonId == "") { break; } SelectMenuCollector selectMenu(event02); values = selectMenu.collectSelectMenuData(false, 60000, 1, args.eventData.getAuthorId()).get(); for (auto& value : values) { for (auto& value2 : value.values) { if (value2 == "go_back" || values.size() == 0) { if (event02.eventType == InputEventType::Regular_Message) { RespondToInputEventData dataPackage02(value.interactionData); dataPackage02.type = InputEventResponseType::Regular_Message_Edit; dataPackage02.addMessageEmbed(msgEmbed); dataPackage02.addButton(false, "items", "Items", ButtonStyle::Primary, "☑"); dataPackage02.addButton(false, "roles", "Roles", ButtonStyle::Primary, "🔥"); dataPackage02.addButton(false, "exit", "Exit", ButtonStyle::Danger, "❌"); InputEvents::respondToEvent(dataPackage02); } else if (event02.eventType == InputEventType::Application_Command_Interaction) { RespondToInputEventData dataPackage02(value.interactionData); dataPackage02.type = InputEventResponseType::Follow_Up_Message_Edit; dataPackage02.addMessageEmbed(msgEmbed); dataPackage02.addButton(false, "items", "Items", ButtonStyle::Primary, "☑"); dataPackage02.addButton(false, "roles", "Roles", ButtonStyle::Primary, "🔥"); dataPackage02.addButton(false, "exit", "Exit", ButtonStyle::Danger, "❌"); InputEvents::respondToEvent(dataPackage02); } goto start; } } } break; } for (auto& value : values) { for (auto& value02 : value.values) { DiscordGuildMember discordGuildMember(guildMember); string objectName = value02; string objectType; int32_t objectShopIndex = 0; bool isFoundInShop = false; bool isFoundInInventory = false; for (uint32_t x = 0; x < discordGuild.data.guildShop.items.size(); x += 1) { if (objectName == convertToLowerCase(discordGuild.data.guildShop.items.at(x).itemName)) { isFoundInShop = true; objectShopIndex = x; objectType = "item"; break; } } for (uint32_t x = 0; x < discordGuild.data.guildShop.roles.size(); x += 1) { if (objectName == convertToLowerCase(discordGuild.data.guildShop.roles.at(x).roleName)) { isFoundInShop = true; objectShopIndex = x; objectType = "role"; break; } } for (uint32_t x = 0; x < discordGuildMember.data.roles.size(); x += 1) { if (objectName == convertToLowerCase(discordGuildMember.data.roles.at(x).roleName)) { isFoundInInventory = true; break; } } for (uint32_t x = 0; x < discordGuildMember.data.items.size(); x += 1) { if (objectName == convertToLowerCase(discordGuildMember.data.items.at(x).itemName)) { isFoundInInventory = true; break; } } if (isFoundInInventory == true) { string msgString = "------\n**Sorry, but you already have one of those " + objectType + "s.** \n------"; EmbedData msgEmbed02; msgEmbed02.setAuthor(guildMember.user.userName, guildMember.user.avatar); msgEmbed02.setColor(discordGuild.data.borderColor); msgEmbed02.setDescription(msgString); msgEmbed02.setTimeStamp(getTimeAndDate()); msgEmbed02.setTitle("__**Duplicate Object:**__"); if (args.eventData.eventType == InputEventType::Regular_Message) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Regular_Message; dataPackage.addMessageEmbed(msgEmbed02); InputEventData event01 = InputEvents::respondToEvent(dataPackage); InputEvents::deleteInputEventResponseAsync(event01, 20000); } else if (args.eventData.eventType == InputEventType::Application_Command_Interaction) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Follow_Up_Message;; dataPackage.addMessageEmbed(msgEmbed02); InputEventData event01 = InputEvents::respondToEvent(dataPackage); InputEvents::deleteInputEventResponseAsync(event01, 20000); } continue; } if (objectType == "role") { uint32_t roleCost = discordGuild.data.guildShop.roles.at(objectShopIndex).roleCost; uint32_t userBalance = discordGuildMember.data.currency.wallet; if (roleCost > userBalance) { string msgString = "------\n**Sorry, but you have insufficient funds in your wallet to purchase that!**\n------"; EmbedData msgEmbed03; msgEmbed03.setAuthor(guildMember.user.userName, guildMember.user.avatar); msgEmbed03.setColor(discordGuild.data.borderColor); msgEmbed03.setDescription(msgString); msgEmbed03.setTimeStamp(getTimeAndDate()); msgEmbed03.setTitle("__**Insufficient Funds:**__"); if (args.eventData.eventType == InputEventType::Regular_Message) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Regular_Message; dataPackage.addMessageEmbed(msgEmbed03); InputEventData event01 = InputEvents::respondToEvent(dataPackage); InputEvents::deleteInputEventResponseAsync(event01, 20000); } else if (args.eventData.eventType == InputEventType::Application_Command_Interaction) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Follow_Up_Message; dataPackage.addMessageEmbed(msgEmbed03); InputEventData event01 = InputEvents::respondToEvent(dataPackage); InputEvents::deleteInputEventResponseAsync(event01, 20000); } break; } auto botUser = args.discordCoreClient->getBotUser(); DiscordUser discordUser(botUser.userName, botUser.id); InventoryRole newRole = discordGuild.data.guildShop.roles.at(objectShopIndex); discordGuildMember.data.roles.push_back(newRole); discordGuildMember.data.currency.wallet -= roleCost; discordGuildMember.writeDataToDB(); uint32_t newBalance = discordGuildMember.data.currency.wallet; string roleID = discordGuild.data.guildShop.roles.at(objectShopIndex).roleId; Roles::addGuildMemberRoleAsync({ .guildId = args.eventData.getGuildId(), .userId = guildMember.user.id, .roleId = roleID }); string msgString = "------\nCongratulations! You've just purchased a new " + objectType + ".\n------\n__**It is as follows:**__ <@&" + newRole.roleId + "> (" + newRole.roleName + ")\n------\n__**Your new wallet balance:**__ " + to_string(newBalance) + " " + discordUser.data.currencyName + "\n------"; EmbedData msgEmbed04; msgEmbed04.setTitle("__**New Role Purchased:**__"); msgEmbed04.setTimeStamp(getTimeAndDate()); msgEmbed04.setDescription(msgString); msgEmbed04.setAuthor(guildMember.user.userName, guildMember.user.avatar); msgEmbed04.setColor(discordGuild.data.borderColor); if (args.eventData.eventType == InputEventType::Regular_Message) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Regular_Message; dataPackage.addMessageEmbed(msgEmbed04); InputEventData event01 = InputEvents::respondToEvent(dataPackage); } else if (args.eventData.eventType == InputEventType::Application_Command_Interaction) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Follow_Up_Message; dataPackage.addMessageEmbed(msgEmbed04); InputEventData event01 = InputEvents::respondToEvent(dataPackage); } uint32_t maxIdx = 0; uint32_t len = (uint32_t)discordGuildMember.data.roles.size(); for (uint32_t x = 0; x < len; x += 1) { maxIdx = x; for (uint32_t y = x + 1; y < len; y += 1) { if (discordGuildMember.data.roles.at(y).roleCost > discordGuildMember.data.roles.at(maxIdx).roleCost) { maxIdx = y; } } InventoryRole tempRole = discordGuildMember.data.roles.at(x); discordGuildMember.data.roles.at(x) = discordGuildMember.data.roles.at(maxIdx); discordGuildMember.data.roles.at(maxIdx) = tempRole; } discordGuildMember.writeDataToDB(); continue; } else if (objectType == "item") { uint32_t itemCost = discordGuild.data.guildShop.items.at(objectShopIndex).itemCost; uint32_t userBalance = discordGuildMember.data.currency.wallet; if (itemCost > userBalance) { string msgString = "------\n**Sorry, but you have insufficient funds in your wallet to purchase that!**\n------"; EmbedData msgEmbed06; msgEmbed06.setTimeStamp(getTimeAndDate()); msgEmbed06.setDescription(msgString); msgEmbed06.setAuthor(guildMember.user.userName, guildMember.user.avatar); msgEmbed06.setColor(discordGuild.data.borderColor); msgEmbed06.setTitle("__**Insufficient Funds:**__"); if (args.eventData.eventType == InputEventType::Regular_Message) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Regular_Message; dataPackage.addMessageEmbed(msgEmbed06); InputEventData event01 = InputEvents::respondToEvent(dataPackage); InputEvents::deleteInputEventResponseAsync(event01, 20000); } else if (args.eventData.eventType == InputEventType::Application_Command_Interaction) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Follow_Up_Message; dataPackage.addMessageEmbed(msgEmbed06); InputEventData event01 = InputEvents::respondToEvent(dataPackage); InputEvents::deleteInputEventResponseAsync(event01, 20000); } break; } InventoryItem newItem = discordGuild.data.guildShop.items.at(objectShopIndex); discordGuildMember.data.items.push_back(newItem); discordGuildMember.data.currency.wallet -= itemCost; discordGuildMember.writeDataToDB(); auto botUser = args.discordCoreClient->getBotUser(); DiscordUser discordUser(botUser.userName, botUser.id); string itemEmoji = discordGuild.data.guildShop.items.at(objectShopIndex).emoji; string itemName = discordGuild.data.guildShop.items.at(objectShopIndex).itemName; uint32_t newBalance = discordGuildMember.data.currency.wallet; string msgString = "------\nCongratulations!You've just purchased a new " + objectType + ".\n------\n__**It is as follows:**__ " + itemEmoji + itemName + "\n------\n__**Your new wallet balance:**__ " + to_string(newBalance) + " " + discordUser.data.currencyName + "\n------"; EmbedData msgEmbed05; msgEmbed05.setTitle("__**New Item Purchased:**__"); uint32_t maxIdx = 0; InventoryItem tempItem; uint32_t len = (uint32_t)discordGuildMember.data.items.size(); for (uint32_t x = 0; x < len; x += 1) { maxIdx = x; for (uint32_t y = x + 1; y < len; y += 1) { if (discordGuildMember.data.items.at(y).itemCost > discordGuildMember.data.items.at(maxIdx).itemCost) { maxIdx = y; } } tempItem = discordGuildMember.data.items.at(x); discordGuildMember.data.items.at(x) = discordGuildMember.data.items.at(maxIdx); discordGuildMember.data.items.at(maxIdx) = tempItem; } discordGuildMember.writeDataToDB(); msgEmbed05.setTimeStamp(getTimeAndDate()); msgEmbed05.setDescription(msgString); msgEmbed05.setAuthor(guildMember.user.userName, guildMember.user.avatar); msgEmbed05.setColor(discordGuild.data.borderColor); if (args.eventData.eventType == InputEventType::Regular_Message) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Regular_Message; dataPackage.addMessageEmbed(msgEmbed05); InputEventData event01 = InputEvents::respondToEvent(dataPackage); } else if (args.eventData.eventType == InputEventType::Application_Command_Interaction) { RespondToInputEventData dataPackage(event02); dataPackage.type = InputEventResponseType::Follow_Up_Message; dataPackage.addMessageEmbed(msgEmbed05); InputEventData event01 = InputEvents::respondToEvent(dataPackage); } } } } InputEvents::deleteInputEventResponseAsync(event02); discordGuild.writeDataToDB(); return; } virtual ~Shop() {}; }; } #endif
45.526012
307
0.703995
[ "object", "vector" ]
8f80a0a30f0f2db5ff7f7ecd4cfd126ef6c4bd86
3,984
cc
C++
mit6.828/homework/shell/command.cc
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
null
null
null
mit6.828/homework/shell/command.cc
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
1
2017-07-31T08:15:26.000Z
2017-07-31T08:15:26.000Z
mit6.828/homework/shell/command.cc
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
1
2019-10-06T16:52:31.000Z
2019-10-06T16:52:31.000Z
#include "command.h" #include "dirent.h" #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <cstring> #include <cstdlib> #include <unistd.h> using std::vector; using std::string; using std::shared_ptr; void Coloncommand::run_command() const { int status; if (fork() == 0) { first->run_command(); } wait(&status); second->run_command(); exit(EXIT_SUCCESS); } void Pipecommand::run_command() const { int p[2]; // Pipe fds int status = pipe(p); if (status != 0) { fprintf(stderr, "Failed creating pipe\n"); exit(EXIT_FAILURE); } // First command if (fork() == 0) { if (dup2(p[1], STDOUT_FILENO) == -1) { fprintf(stderr, "Failed dup2 stdout\n"); exit(EXIT_FAILURE); } close(p[1]); first->run_command(); } // Second Command if(fork() == 0) { close(p[1]); if (dup2(p[0], STDIN_FILENO) == -1) { fprintf(stderr, "Failed dup2 stdin\n"); exit(EXIT_FAILURE); } close(p[0]); second->run_command(); } // Shell wait for the two commands close(p[1]); close(p[0]); wait(&status); wait(&status); exit(EXIT_SUCCESS); } string Execommand::find_command(string command) { char *paths = getenv("PATH"); char *path_dir = strtok(paths, ":"); while (path_dir != NULL) { DIR* dir = opendir(path_dir); if (dir != NULL) { struct dirent* entry = NULL; while ((entry = readdir(dir)) != NULL) { if (strcmp(entry->d_name, command.c_str()) == 0) { /* char *path_found = malloc(strlen(path_dir) + strlen(command) + 2); path_found = strcat(path_found, path_dir); path_found = strcat(path_found, "/"); path_found = strcat(path_found, command); */ string path_found(path_dir); path_found += "/"; path_found += command; return path_found; } } } else { fprintf(stderr, "cannot open dir : %s\n", path_dir); } path_dir = strtok(NULL, ":"); } return string(); } void Execommand::run_command() const { //fprintf(stdout, "Running command\n"); //fprintf(stdout, "Running: args size %d\n", (int)args.size()); if (args.size() == 0) { exit(EXIT_FAILURE); } string cmdpath = find_command(args[0]); if (!cmdpath.empty()) { char** argv = new char*[args.size() + 1]; size_t i = 0; //fprintf(stdout, "command path is %s\n", cmdpath.c_str()); for (; i < args.size(); i++) { argv[i] = new char[args[i].size() + 1]; strcpy(argv[i], args[i].c_str()); //fprintf(stdout, "arg %d : %s\n", i, argv[i]); } argv[i] = 0; execv(cmdpath.c_str(), argv); } fprintf(stderr, "Failed to find the command\n"); exit(EXIT_SUCCESS); } void Redircommand::run_command() const { int openfd; if (type == '>') { openfd = open(file, mode, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); } else { openfd = open(file, mode); } if (openfd == -1) { fprintf(stderr, "Failed to open file %s\n", file); exit(EXIT_FAILURE); } if (dup2(openfd, fd) == -1) { fprintf(stderr, "Failed dupping\n"); } close(openfd); cmd->run_command(); } void Redircommand::set_args(const vector<string>& paras) { cmd->set_args(paras); } Redircommand::Redircommand(shared_ptr<Command> c, char *f, int t) : type(t), cmd(c), file(f) { mode = (type == '<') ? O_RDONLY : O_WRONLY|O_CREAT|O_TRUNC; fd = (type == '<') ? 0 : 1; }
23.162791
92
0.50251
[ "vector" ]
8f81f0fd4b2abd77bcc60af5396201357c4bcf3e
3,582
cpp
C++
OffscreenBrowserMain.cpp
mlalma/SimpleOffscreenBrowser
61c0ae4fb1858640e6a4d4a8e88e45061e1e81a8
[ "MIT" ]
7
2017-11-06T02:21:31.000Z
2021-03-31T20:17:12.000Z
OffscreenBrowserMain.cpp
mlalma/SimpleOffscreenBrowser
61c0ae4fb1858640e6a4d4a8e88e45061e1e81a8
[ "MIT" ]
null
null
null
OffscreenBrowserMain.cpp
mlalma/SimpleOffscreenBrowser
61c0ae4fb1858640e6a4d4a8e88e45061e1e81a8
[ "MIT" ]
2
2020-03-19T22:48:43.000Z
2021-11-12T17:35:57.000Z
/** * Simple example app using Chromium Embedded Framework * Lassi Maksimainen, 2014 */ #include <iostream> #include <fstream> #include <algorithm> #include <unistd.h> #include <memory> #include "include/cef_app.h" #include "OffscreenBrowserApp.h" #include "OffscreenBrowserClient.h" // Entrypoint to the whole application int main(int argc, char** argv) { // Initialize application object CefRefPtr<OffscreenBrowserApp> app = new OffscreenBrowserApp(); CefMainArgs main_args(argc, argv); int exit_code = CefExecuteProcess(main_args, app.get(), nullptr); if (exit_code >= 0) { return exit_code; } // Initialize the app without sandbox on for simplicity and cookies & page cache turned off CefSettings settings; settings.windowless_rendering_enabled = true; settings.single_process = true; settings.no_sandbox = true; settings.persist_session_cookies = false; CefString(&settings.user_agent).FromASCII("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36"); CefString(&settings.cache_path).FromASCII(""); CefInitialize(main_args, settings, app.get(), nullptr); // Create windowless browser host, disable also plugins that might be available on the system CefRefPtr<OffscreenBrowserClient> client = new OffscreenBrowserClient(); CefWindowInfo info; info.SetAsWindowless(nullptr, false); CefBrowserSettings browser_settings; browser_settings.plugins = STATE_DISABLED; CefRefPtr<CefBrowser> browser = CefBrowserHost::CreateBrowserSync(info, client.get(), "http://www.google.com", browser_settings, NULL); while (!client->GetBrowser()) { usleep(10000); } std::cout << std::endl; // Parse command line parameters std::string url; CefRefPtr<CefCommandLine> command_line = CefCommandLine::GetGlobalCommandLine(); url = command_line->GetSwitchValue("url"); if (url.empty()) { std::cout << "Use parameter --url to provide URL for the web page that will be fetched" << std::endl; return -1; } std::string dest; dest = command_line->GetSwitchValue("out"); if (dest.empty()) { std::cout << "Use parameter --out to provide location of the file where the fetched web page's HTML code will be dumped" << std::endl; std::cout << "Use 'stdout' for dumping the code to terminal" << std::endl; return -1; } // Loading time is given in seconds int loadingTime = 100; std::string time = command_line->GetSwitchValue("time"); if (!time.empty()) { loadingTime = atoi(time.c_str()) * 10; } // Start loading web page, wait for 10 seconds to ensure that javascript etc have been succesfully executed and then terminate load client->GetBrowser()->GetMainFrame()->LoadURL(url); std::cout << "Starting to load the page from URL: " << url << std::endl; std::cout << "Waiting for " << (loadingTime/10) << " secs to let everything load on the page" << std::endl; for (int i = 0; i < loadingTime; i++) { CefDoMessageLoopWork(); usleep(100 * 1000); } client->GetBrowser()->StopLoad(); CefDoMessageLoopWork(); // Get HTML source std::string source = client->GetHTMLSource(); // Dump source to terminal or to a file if (dest.compare("stdout") == 0) { std::cout << "==HTML-SOURCE-BEGIN==" << std::endl << std::flush; std::cout << source << std::endl << std::flush; std::cout << "==HTML-SOURCE-END==" << std::endl << std::flush; } else { std::cout << "starting to write page! " << std::endl; std::ofstream page; page.open(dest, std::ofstream::out); page << source; page.flush(); page.close(); } // Everything done, time to quit CefShutdown(); return 0; }
33.792453
152
0.709101
[ "object" ]
8f8d71ebfe6c30d0d8e83f66f5f505b598f6a5a9
3,012
cpp
C++
utils/L1/tests/stream_reorder/test.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-06-14T17:02:06.000Z
2021-06-14T17:02:06.000Z
utils/L1/tests/stream_reorder/test.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
null
null
null
utils/L1/tests/stream_reorder/test.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-04-28T05:58:38.000Z
2021-04-28T05:58:38.000Z
/* * Copyright 2019 Xilinx, 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 <vector> #include <iostream> #include <stdlib.h> #include "xf_utils_hw/stream_reorder.hpp" #define WS 4 #define W_STRM 16 #define NS (1024 * WS) void test_core_reorder(hls::stream<int>& order_cfg, hls::stream<ap_uint<W_STRM> >& istrm, hls::stream<bool>& e_istrm, hls::stream<ap_uint<W_STRM> >& ostrm, hls::stream<bool>& e_ostrm) { xf::common::utils_hw::streamReorder<ap_uint<W_STRM>, WS>(order_cfg, istrm, e_istrm, ostrm, e_ostrm); } int test_reorder() { hls::stream<int> cfg; hls::stream<ap_uint<W_STRM> > data_istrm; hls::stream<bool> e_data_istrm; hls::stream<ap_uint<W_STRM> > data_ostrm; hls::stream<bool> e_data_ostrm; ap_uint<W_STRM> ba[WS]; std::cout << std::dec << "W_STRM = " << W_STRM << std::endl; std::cout << std::dec << "WS = " << WS << std::endl; std::cout << std::dec << "NS = " << NS << std::endl; for (int i = 0; i < WS; ++i) { cfg.write(WS - i - 1); } for (int d = 1; d <= NS; ++d) { ap_uint<W_STRM> data = d; data_istrm.write(data); e_data_istrm.write(false); } e_data_istrm.write(true); test_core_reorder(cfg, data_istrm, e_data_istrm, data_ostrm, e_data_ostrm); std::cout << "================================" << std::endl; int nerror = 0; bool last = e_data_ostrm.read(); ap_uint<W_STRM> gld = 0; int c = 0; int total = 0; while (!last) { last = e_data_ostrm.read(); ba[c] = data_ostrm.read(); // std::cout<<" t= "<< total << " "<< ba[c] << std::endl; c++; total++; if (c == WS) { c = 0; for (int k = WS - 1; k >= 0; --k) { ap_uint<W_STRM> d = ba[k]; gld = gld + 1; if (d != gld) { nerror = 1; std::cout << "erro:" << " test data = " << d << " " << "gld data = " << gld << std::endl; } } // for } // if } // while if (total != NS) nerror = 1; if (nerror) { std::cout << "\nFAIL: " << nerror << "the order is wrong.\n"; } else { std::cout << "\nPASS: no error found.\n"; } return nerror; } int main() { return test_reorder(); }
31.375
104
0.520584
[ "vector" ]
8f8f40d4d8d54c3386cdddd1abd7fb7411347ecd
6,056
cpp
C++
src/rgbd_input.cpp
google/depth_fusion
6c8dc4ee88e8afa1c232f5e17391fc95c41b3253
[ "Apache-2.0" ]
12
2020-08-02T04:38:19.000Z
2022-01-29T06:16:51.000Z
src/rgbd_input.cpp
google/depth_fusion
6c8dc4ee88e8afa1c232f5e17391fc95c41b3253
[ "Apache-2.0" ]
null
null
null
src/rgbd_input.cpp
google/depth_fusion
6c8dc4ee88e8afa1c232f5e17391fc95c41b3253
[ "Apache-2.0" ]
5
2020-10-13T16:38:07.000Z
2021-10-12T16:12:22.000Z
// Copyright 2016 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 "rgbd_input.h" #include <cassert> #include "libcgt/camera_wrappers/Kinect1x/KinectUtils.h" #include "libcgt/camera_wrappers/PixelFormat.h" #include "libcgt/core/common/ArrayUtils.h" #include "libcgt/core/imageproc/ColorMap.h" #include "libcgt/core/imageproc/Swizzle.h" #include "input_buffer.h" using libcgt::camera_wrappers::PixelFormat; using libcgt::camera_wrappers::RGBDInputStream; using libcgt::camera_wrappers::kinect1x::rawDepthMapToMeters; using libcgt::core::arrayutils::copy; using libcgt::core::arrayutils::flipY; using libcgt::core::imageproc::linearRemapToLuminance; using libcgt::core::imageproc::RGBToBGR; RgbdInput::RgbdInput(InputType input_type, const char* filename) : input_type_(input_type) { if (input_type == InputType::OPENNI2) { std::vector<libcgt::camera_wrappers::StreamConfig> config; config.emplace_back( StreamType::COLOR, Vector2i{ 640, 480 }, PixelFormat::RGB_U888, 30, false ); config.emplace_back( StreamType::DEPTH, Vector2i{ 640, 480 }, PixelFormat::DEPTH_MM_U16, 30, false ); openni2_camera_ = std::make_unique<OpenNI2Camera>(config); openni2_buffer_rgb_.resize(openni2_camera_->colorConfig().resolution); openni2_buffer_depth_.resize(openni2_camera_->depthConfig().resolution); openni2_frame_.color = openni2_buffer_rgb_.writeView(); openni2_frame_.depth = openni2_buffer_depth_.writeView(); openni2_camera_->start(); } else if (input_type == InputType::FILE) { file_input_stream_ = std::make_unique<RGBDInputStream>(filename); // Find the rgb stream. // TODO: take a dependency on cpp11-range for(int i = 0; i < file_input_stream_->metadata().size(); ++i) { const auto& metadata = file_input_stream_->metadata()[i]; if(metadata.type == StreamType::COLOR && metadata.format == PixelFormat::RGB_U888) { color_stream_id_ = i; color_metadata_ = metadata; break; } } // Find the depth stream. // TODO: take a dependency on cpp11-range for (int i = 0; i < file_input_stream_->metadata().size(); ++i) { const auto& metadata = file_input_stream_->metadata()[i]; if (metadata.type == StreamType::DEPTH) { raw_depth_stream_id_ = i; depth_metadata_ = metadata; break; } } } } Vector2i RgbdInput::colorSize() const { return color_metadata_.size; } Vector2i RgbdInput::depthSize() const { return depth_metadata_.size; } // TODO: simplify: read only rgb, etc // TODO: by default, read all void RgbdInput::read(InputBuffer* buffer, bool* rgb_updated, bool* depth_updated) { assert(rgb_updated != nullptr); assert(depth_updated != nullptr); // TODO: warn if input buffer is the wrong size. Resize it? *rgb_updated = false; *depth_updated = false; if (input_type_ == InputType::OPENNI2) { // TODO: if closed, return false bool succeeded = openni2_camera_->pollOne(openni2_frame_); if (openni2_frame_.colorUpdated) { // Copy the buffer, flipping it upside down for OpenGL. copy<uint8x3>(openni2_frame_.color, flipY(buffer->color_rgb.writeView())); // Convert RGB to BGR for OpenCV. RGBToBGR(openni2_frame_.color, buffer->color_bgr_ydown.writeView()); buffer->color_timestamp_ns = openni2_frame_.colorTimestampNS; buffer->color_frame_index = openni2_frame_.colorFrameNumber; *rgb_updated = openni2_frame_.colorUpdated; } if (openni2_frame_.depthUpdated) { rawDepthMapToMeters(openni2_frame_.depth, buffer->depth_meters, false, true); buffer->depth_timestamp_ns = openni2_frame_.depthTimestampNS; buffer->depth_frame_index = openni2_frame_.depthFrameNumber; *depth_updated = openni2_frame_.depthUpdated; } } else if (input_type_ == InputType::FILE) { uint32_t stream_id; int64_t timestamp_ns; int32_t frame_index; Array1DReadView<uint8_t> src = file_input_stream_->read( stream_id, frame_index, timestamp_ns); if (src.notNull()) { if (stream_id == color_stream_id_) { Array2DReadView<uint8x3> src_rgb( src.pointer(), color_metadata_.size); // Copy the buffer, flipping it upside down for OpenGL. copy<uint8x3>(src_rgb, flipY(buffer->color_rgb.writeView())); // Convert RGB to BGR for OpenCV. RGBToBGR(src_rgb, buffer->color_bgr_ydown.writeView()); buffer->color_timestamp_ns = timestamp_ns; buffer->color_frame_index = frame_index; //RGBToBGR(src_rgb, buffer->color_bgr_ydown.writeView()); //bool succeeded = copy(src_rgb, flipY(buffer->color_rgb.writeView())); *rgb_updated = true; // *rgb_updated = succeeded; } else if (stream_id == raw_depth_stream_id_ ) { buffer->depth_timestamp_ns = timestamp_ns; buffer->depth_frame_index = frame_index; if (depth_metadata_.format == PixelFormat::DEPTH_MM_U16) { Array2DReadView<uint16_t> src_depth(src.pointer(), depth_metadata_.size); rawDepthMapToMeters(src_depth, buffer->depth_meters, false); *depth_updated = true; } else if(depth_metadata_.format == PixelFormat::DEPTH_M_F32) { Array2DReadView<float> src_depth(src.pointer(), depth_metadata_.size); bool succeeded = copy(src_depth, buffer->depth_meters.writeView()); *depth_updated = succeeded; } } } } }
36.263473
80
0.693362
[ "vector" ]
8f964d9bc8d81debc4a12ed454736bad7721b331
6,006
cpp
C++
src/Samples/src/samples/animations/animations_scene.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
277
2017-05-18T08:27:10.000Z
2022-03-26T01:31:37.000Z
src/Samples/src/samples/animations/animations_scene.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
77
2017-09-03T15:35:02.000Z
2022-03-28T18:47:20.000Z
src/Samples/src/samples/animations/animations_scene.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
37
2017-03-30T03:36:24.000Z
2022-01-28T08:28:36.000Z
#include <babylon/animations/animation.h> #include <babylon/animations/ianimation_key.h> #include <babylon/cameras/arc_rotate_camera.h> #include <babylon/engines/scene.h> #include <babylon/interfaces/irenderable_scene.h> #include <babylon/lights/point_light.h> #include <babylon/materials/standard_material.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/mesh_builder.h> #include <babylon/samples/babylon_register_sample.h> namespace BABYLON { namespace Samples { /** * @brief Animations scene. Example demonstrating how to add animations. * @see https://doc.babylonjs.com/babylon101/animations */ struct AnimationsScene : public IRenderableScene { AnimationsScene(ICanvas*) { } ~AnimationsScene() override = default; const char* getName() override { return "Animations Scene"; } void initializeScene(ICanvas* canvas, Scene* scene) override { // Create a light auto light = PointLight::New("Omni", Vector3(0.f, 100.f, 100.f), scene); light->intensity = 1.f; // Create a camera auto camera = ArcRotateCamera::New("Camera", 0.f, 0.8f, 100.f, Vector3::Zero(), scene); // Attach the camera to the canvas camera->attachControl(canvas, true); // Boxes // - Box 1 auto box1 = Mesh::CreateBox("Box1", 10.f, scene); box1->position().x = -20.f; // - Box 2 BoxOptions options; options.size = 10.f; options.setFaceColor(0, Color4(1.f, 0.f, 0.f, 1.f)); // Red options.setFaceColor(5, Color4(1.f, 1.f, 0.f, 1.f)); // Yellow options.setFaceColor(1, Color4(0.f, 1.f, 0.f, 1.f)); // Green options.setFaceColor(4, Color4(0.f, 0.f, 1.f, 1.f)); // Blue options.setFaceColor(2, Color4(1.f, 0.f, 1.f, 1.f)); // Magenta options.setFaceColor(3, Color4(0.5f, 0.f, 0.5f, 1.f)); // Purple auto box2 = MeshBuilder::CreateBox("Box2", options, scene); // - Box 3 auto box3 = MeshBuilder::CreateBox("Box1", options, scene); box3->position().x = -20.f; box3->position().z = -30.f; auto materialBox = StandardMaterial::New("texture1", scene); materialBox->diffuseColor = Color3::Green(); auto materialBox2 = StandardMaterial::New("texture2", scene); // Applying materials box1->material = materialBox; box2->material = materialBox2; // Positioning box box2->position().x = 20.f; // Creation of a scaling animation with box 1 //------------------------------------------- // Create a scaling animation at 30 FPS auto animationBox1 = Animation::New("scalingAnimation", "scaling.x", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); // Animation keys std::vector<IAnimationKey> keysBox1{ // At the animation key 0, the value of scaling is "1" IAnimationKey(0, AnimationValue(1.f)), // At the animation key 20, the value of scaling is "0.2" IAnimationKey(20, AnimationValue(0.2f)), // At the animation key 100, the value of scaling is "1" IAnimationKey(100, AnimationValue(1.f)), }; // Adding keys to the animation object animationBox1->setKeys(keysBox1); // Then add the animation object to box1 box1->animations.emplace_back(animationBox1); // Finally, launch animations on box1, from key 0 to key 100 with loop // activated scene->beginAnimation(box1, 0, 100, true); // Creation of a rotation animation with box 2 //-------------------------------------------- // Create a scaling animation at 30 FPS auto animationBox2RotX = Animation::New("rotationAnimation", "rotation.x", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); // Animation keys std::vector<IAnimationKey> keysRotation{ IAnimationKey(0, AnimationValue(0.f)), IAnimationKey(20, AnimationValue(Math::PI)), IAnimationKey(100, AnimationValue(Math::PI2)), }; // Adding keys to the animation object animationBox2RotX->setKeys(keysRotation); // Then add the animation object to box1 box2->animations.emplace_back(animationBox2RotX); // Finally, launch animations on box2, from key 0 to key 100 with loop // activated scene->beginAnimation(box2, 0, 100, true); // Creation of a rotation animation with box 3 //-------------------------------------------- // Create a scaling animation at 30 FPS auto animationBox3RotX = Animation::New("rotationAnimation", "rotation.x", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); auto animationBox3RotY = Animation::New("rotationAnimation", "rotation.y", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); auto animationBox3RotZ = Animation::New("rotationAnimation", "rotation.z", 30, Animation::ANIMATIONTYPE_FLOAT, Animation::ANIMATIONLOOPMODE_CYCLE); // Animation keys keysRotation = { IAnimationKey(0, AnimationValue(0.f)), IAnimationKey(25, AnimationValue(Math::PI_2)), IAnimationKey(50, AnimationValue(Math::PI)), IAnimationKey(100, AnimationValue(Math::PI2)), }; // Adding keys to the animation object animationBox3RotX->setKeys(keysRotation); animationBox3RotY->setKeys(keysRotation); animationBox3RotZ->setKeys(keysRotation); // Then add the animation object to box1 box3->animations.emplace_back(animationBox3RotX); box3->animations.emplace_back(animationBox3RotY); box3->animations.emplace_back(animationBox3RotZ); // Finally, launch animations on box2, from key 0 to key 100 with loop // activated scene->beginAnimation(box3, 0, 100, true); } }; // end of struct AnimationsScene BABYLON_REGISTER_SAMPLE("Animations", AnimationsScene) } // end of namespace Samples } // end of namespace BABYLON
35.964072
93
0.655012
[ "mesh", "object", "vector" ]
8f9a27af0a9bbe43cdcba73432ff824df46ee456
20,264
cpp
C++
rtree/rtree.cpp
josecleiton/GIS-RTree-Project
970cf3868b926d20ee9173408ee3a18bd877b70c
[ "MIT" ]
3
2018-08-25T12:15:14.000Z
2018-10-18T11:35:19.000Z
rtree/rtree.cpp
josecleiton/GIS-RTree-Project
970cf3868b926d20ee9173408ee3a18bd877b70c
[ "MIT" ]
null
null
null
rtree/rtree.cpp
josecleiton/GIS-RTree-Project
970cf3868b926d20ee9173408ee3a18bd877b70c
[ "MIT" ]
1
2018-10-10T11:51:59.000Z
2018-10-10T11:51:59.000Z
#include "rtree.hpp" #include "variaveis.hpp" namespace SpatialIndex{ Chave::Chave(Retangulo _mbr, streampos _dado): MBR(_mbr), ChildPtr(_dado){ } Chave::Chave(){ Ponto A, B; Retangulo vazio(A, B); this->MBR = vazio; } Chave::Chave(Node*& No){ Retangulo R1 = No->GetRetangulo(); Chave k(R1, No->DiskPos); *this = k; } bool Chave::Ajusta(Retangulo& alvo){ bool modificado = false; this->MBR.Ajusta(alvo, modificado); return modificado; } Node::Node(Retangulo& R, streampos& PosR){ Chave k(R, PosR); Chaves.push_back(k); Nivel = FOLHA; } Node::Node(unsigned nivel, vector<Chave>& itens): Nivel(nivel), Chaves(itens){ } Node::Node(Node*& no1, Node*& no2){ Nivel = INTERNO; list<Node*> chavesNovaRaiz; chavesNovaRaiz.push_back(no1); chavesNovaRaiz.push_back(no2); for(auto &item: chavesNovaRaiz){ Retangulo MBR_NovaChave(item->GetRetangulo()); Chave novaChave(MBR_NovaChave, item->DiskPos); Chaves.push_back(novaChave); delete item; } this->SalvarNo(); } Node::Node(streampos& no){ bool active = false; root.File().seekg(no, fstream::beg); root.File().read(reinterpret_cast<char*>(&active), sizeof(bool)); if(active){ unsigned numChaves; root.File().read(reinterpret_cast<char*>(&Nivel), sizeof(unsigned)); root.File().read(reinterpret_cast<char*>(&numChaves), sizeof(unsigned)); this->Chaves.resize(numChaves); for(unsigned i=0; i<numChaves; i++) root.File().read(reinterpret_cast<char*>(&(Chaves[i])), sizeof(Chave)); this->DiskPos = no; } else cerr << "Página inválida! Reorganize antes de fazer outra requisição." << endl; } streampos Node::SalvarNo(){ unsigned numChaves = static_cast<unsigned>(this->Chaves.size()); bool active = true; Chave key(Retangulo(), 0); if(DiskPos) root.File().seekp(this->DiskPos, fstream::beg); else{ root.File().seekp(0, fstream::end); this->DiskPos = root.File().tellp(); } root.File().write(reinterpret_cast<char*>(&active), sizeof(bool)); root.File().write(reinterpret_cast<char*>(&(this->Nivel)), sizeof(unsigned)); root.File().write(reinterpret_cast<char*>(&numChaves), sizeof(unsigned)); for(unsigned i=0; i<MAXCHAVES; i++){ if(i<numChaves) root.File().write(reinterpret_cast<char*>(&(this->Chaves[i])), sizeof(Chave)); else root.File().write(reinterpret_cast<char*>(&key), sizeof(Chave)); } return this->DiskPos; } streampos Node::Delete(){ bool active = false; root.File().seekp(this->DiskPos, fstream::beg); root.File().write(reinterpret_cast<char*>(&active), sizeof(bool)); return this->DiskPos; } /* bool Node::Cresce(Retangulo& EntryMBR, unsigned indexChave){ bool cresceu = false; //this->Chaves[indexChave].MBR.CresceParaConter(EntryMBR, cresceu); return cresceu; } */ Retangulo Node::GetRetangulo(){ vector<double> CoordOrigem(2, DBL_MAX), CoordDestino(2, DBL_MIN); vector<pair<double, double>> CoordTemporarias(2); // Possíveis coordenadas min/max a serem avaliadas pela rotina for(auto item: Chaves){ CoordTemporarias[0] = make_pair(item.MBR.GetDiagonal().GetOrigem().GetX(), item.MBR.GetDiagonal().GetOrigem().GetY()); CoordTemporarias[1] = make_pair(item.MBR.GetDiagonal().GetDestino().GetX(), item.MBR.GetDiagonal().GetDestino().GetY()); if(CoordTemporarias[0].first < CoordOrigem[0]) CoordOrigem[0] = CoordTemporarias[0].first; if(CoordTemporarias[0].second < CoordOrigem[1]) CoordOrigem[1] = CoordTemporarias[0].second; if(CoordTemporarias[1].first > CoordDestino[0]) CoordDestino[0] = CoordTemporarias[1].first; if(CoordTemporarias[1].second > CoordDestino[1]) CoordDestino[1] = CoordTemporarias[1].second; } Ponto Origem(CoordOrigem[0], CoordOrigem[1]), Destino(CoordDestino[0], CoordDestino[1]); return Retangulo(Origem, Destino); } RTree::RTree(){ this->treeFile.open(RTREE_FILENAME, fstream::binary|fstream::in|fstream::out); if(!ArquivoVazio()){ if(this->treeFile.is_open()){ streampos PosicaoDaRaiz; this->treeFile.read(reinterpret_cast<char*>(&PosicaoDaRaiz), sizeof(streampos)); this->treeFile.read(reinterpret_cast<char*>(&(this->count)), sizeof(unsigned)); this->treeFile.read(reinterpret_cast<char*>(&(this->altura)), sizeof(unsigned)); this->treeFile.read(reinterpret_cast<char*>(&(this->registros)), sizeof(size_t)); this->raiz = new Node(PosicaoDaRaiz); } else{ cerr << "Exceção ao ler/abrir o arquivo: " << RTREE_FILENAME << endl; cerr << strerror(errno) << endl; abort(); } } else this->raiz = nullptr; } bool RTree::ArquivoVazio(){ if(this->treeFile.is_open()){ streampos inicio, fim; inicio = this->treeFile.tellg(); this->treeFile.seekg(0, fstream::end); fim = this->treeFile.tellg(); this->treeFile.seekg(0, fstream::beg); return inicio == fim; } else{ cerr << RTREE_FILENAME << " " << strerror(errno) << endl; abort(); } } RTree::~RTree(){ if(raiz != nullptr){ this->treeFile.seekp(0, fstream::beg); this->treeFile.write(reinterpret_cast<char*>(&(this->raiz->DiskPos)), sizeof(streampos)); this->treeFile.write(reinterpret_cast<char*>(&(this->count)), sizeof(unsigned)); this->treeFile.write(reinterpret_cast<char*>(&(this->altura)), sizeof(unsigned)); this->treeFile.write(reinterpret_cast<char*>(&(this->registros)), sizeof(size_t)); delete this->raiz; } this->treeFile.close(); } void RTree::CriaArvore(Retangulo& MbrForma, streampos& pos){ Node* root = new Node(MbrForma, pos); streampos posicao = 1; this->count = 1u; this->altura = 0u; this->registros = 1ull; this->treeFile.write(reinterpret_cast<char*>(&posicao), sizeof(streampos)); this->treeFile.write(reinterpret_cast<char*>(&(this->count)), sizeof(unsigned)); this->treeFile.write(reinterpret_cast<char*>(&(this->altura)), sizeof (unsigned)); this->treeFile.write(reinterpret_cast<char*>(&(this->registros)), sizeof(size_t)); root->DiskPos = this->treeFile.tellp(); this->treeFile.seekp(0, fstream::beg); this->treeFile.write(reinterpret_cast<char*>(&(root->DiskPos)), sizeof(streampos)); this->raiz = root; root->SalvarNo(); } fstream& RTree::File(){ return this->treeFile; } bool RTree::ApagarArvore(){ if(raiz != nullptr){ delete raiz; raiz = nullptr; } this->treeFile.close(); fstream temp(RTREE_FILENAME, fstream::binary|fstream::out); if(temp.is_open()){ temp.close(); this->treeFile.open(RTREE_FILENAME, fstream::binary|fstream::out|fstream::in); if(this->treeFile.is_open()) return true; } cerr << "Arquivo: " << RTREE_FILENAME << " não foi reaberto." << endl; cerr << strerror(errno) << endl; abort(); } unsigned RTree::GetCount(){ return this->count; } unsigned RTree::GetAltura(){ return this->altura; } size_t RTree::GetRegistros(){ return this->registros; } bool RTree::IsEmpty(){ return !count; } Node* RTree::NodePtr(){ return this->raiz; } bool RTree::Busca(Node* no, Retangulo& K, list<NodeAux>& q){ unsigned i = 0; NodeAux temp; if(!no->Folha()){ Node* aux = nullptr; for(auto item: no->Chaves){ if(item.MBR.Contem(K)){ aux = new Node(item.ChildPtr); if(Busca(aux, K, q)){ temp.ptr = no; temp.index = i; q.push_back(temp); return true; } delete aux; } i++; } return false; } for(auto item: no->Chaves){ if(item.MBR == K){ temp.ptr = no; temp.index = i; q.push_back(temp); return true; } i++; } return false; } bool RTree::Busca(Node* no, Chave& K, list<NodeAux>& q){ unsigned i = 0; NodeAux temp; if(!no->Folha()){ Node* aux = nullptr; for(auto item: no->Chaves){ if(item.MBR.Contem(K.MBR)){ aux = new Node(item.ChildPtr); if(Busca(aux, K, q)){ temp.ptr = no; temp.index = i; q.push_back(temp); return true; } delete aux; } i++; } return false; } for(auto item: no->Chaves){ if(item == K){ temp.ptr = no; temp.index = i; q.push_back(temp); return true; } i++; } return false; } list<Chave> RTree::Busca(Ponto& P){ streampos RaizPos = root.NodePtr()->DiskPos; list<Chave> ListadeNo = Traversal(RaizPos, P), resultado; for(auto item: ListadeNo){ if(item.MBR.Contem(P)) resultado.push_back(item); } return resultado; } list<Chave> RTree::Traversal(streampos& no, Ponto& P){ list<Chave> LC; Node* aux = new Node(no); if(!aux->Folha()){ for(auto item: aux->Chaves) if(item.MBR.Contem(P)) LC.splice(LC.end(), Traversal(item.ChildPtr, P)); } else for(auto item: aux->Chaves) LC.push_back(item); delete aux; return LC; } void RTree::Inserir(Retangulo& MbrForma, streampos& pos){ Node* no = root.NodePtr(); registros++; if(no == nullptr) return CriaArvore(MbrForma, pos); stack<NodeAux> CaminhoNo; while(!no->Folha()) no = EscolhaSubArvore(no, CaminhoNo, MbrForma); // if(!CaminhoNo.empty()) // CaminhoNo.pop(); Chave Key(MbrForma, pos); InserirNo(no, CaminhoNo, Key); Kai(CaminhoNo); } void RTree::Inserir(Chave& K){ Chave A = K; Node* no = root.NodePtr(); if(no == nullptr) return CriaArvore(A.MBR, A.Dado); stack<NodeAux> CaminhoNo; while(!no->Folha()) no = EscolhaSubArvore(no, CaminhoNo, A.MBR); // if(!CaminhoNo.empty()) // CaminhoNo.pop(); InserirNo(no, CaminhoNo, A); Kai(CaminhoNo); } void RTree::InserirNo(Node* &No, stack<NodeAux>& caminho, Chave& inserir){ No->Chaves.push_back(inserir); if(No->Overflow()) return DividirEAjustar(No, caminho); No->SalvarNo(); AjustaCaminho(caminho, No->GetRetangulo()); } Node* RTree::EscolhaSubArvore(Node* &no, stack<NodeAux>& caminho, Retangulo& MbrForma){ vector<pair<NodeAux, double>> contem; NodeAux temp; temp.ptr = no; unsigned index = 0; for(auto chave: no->Chaves){ if(chave.MBR.Contem(MbrForma)){ NodeAux aux(new Node(chave.ChildPtr), index); contem.push_back(make_pair(aux, chave.MBR.GetArea())); } index++; } Node* resultado = nullptr; if(!contem.empty()){ size_t max = 0; for(auto it = contem.begin()+1; it != contem.end(); it++) if(it->second > contem[max].second) max = it-contem.begin(); swap(contem[max].first.ptr, resultado); for(auto &candidato: contem) // LIBERA O RESTO if(candidato.first.ptr != nullptr) delete candidato.first.ptr; temp.index = contem.front().first.index; caminho.push(temp); return resultado; } // SE NENHUMA CHAVE CONTER A FORMA, ESCOLHA O QUE PRECISA CRESCER MENOS (menor crescimento da área) double aux = 0.0; pair<double, unsigned> escolha = make_pair(no->Chaves[0].MBR.CresceParaConter(MbrForma).GetArea(), 0); for(unsigned i=1; i < no->Chaves.size(); i++){ aux = no->Chaves[i].MBR.CresceParaConter(MbrForma).GetArea(); if(aux < escolha.first) escolha = make_pair(aux, i); } temp.index = escolha.second; caminho.push(temp); resultado = new Node(no->Chaves[escolha.second].ChildPtr); return resultado; } void RTree::AjustaCaminho(stack<NodeAux>& caminho, Retangulo R){ if(!caminho.empty()){ // .INDEX = POSIÇÃO DO NÓ ATUAL NO PAI // .PTR = PONTEIRO PARA O PAI NodeAux pai = caminho.top(); if(pai.ptr->Chaves[pai.index].Ajusta(R)){ pai.ptr->SalvarNo(); Retangulo R = pai.ptr->GetRetangulo(); if(pai.ptr != this->raiz) delete pai.ptr; caminho.pop(); AjustaCaminho(caminho, R); } } } void RTree::DividirEAjustar(Node* &no, stack<NodeAux>& caminho){ bool isRoot = (no == raiz); Node* novoNo = Divide(no); count++; // quantidade de nós na árvore cresce em 1 if(!isRoot){ Chave chaveNovoNo(novoNo); NodeAux pai = caminho.top(); // .INDEX = POSIÇÃO DO NÓ ATUAL NO PAI // .PTR = PONTEIRO PARA O PAI caminho.pop(); Retangulo R = no->GetRetangulo(); delete novoNo; delete no; if(pai.ptr->Chaves[pai.index].Ajusta(R)) pai.ptr->SalvarNo(); InserirNo(pai.ptr, caminho, chaveNovoNo); } else CriaNovaRaiz(no, novoNo); } void RTree::CriaNovaRaiz(Node* &no, Node* &novoNo){ Node* novaRaiz = new Node(no, novoNo); raiz = novaRaiz; count++; altura++; } /* * CÓDIGO ABAIXO RETIRADO DO LIVRO: * SPATIAL DATABASES WITH APPLICATION TO GIS - RIGGAUX */ Node* RTree::Divide(Node* &no){ Retangulo J; pair<unsigned, unsigned> escolhas; unsigned lenNo = static_cast<unsigned>(no->Chaves.size()); double worst = 0.0, d1, d2, expansion = 0.0; for(unsigned i=0; i < lenNo; i++){ for(unsigned j=i+1; j < lenNo; j++){ J = no->Chaves[i].MBR.CresceParaConter(no->Chaves[j].MBR); double k = J.GetArea() - no->Chaves[i].MBR.GetArea() - no->Chaves[j].MBR.GetArea(); if(k > worst){ worst = k; escolhas = make_pair(i, j); } } } vector<Chave> ChavesRestantes, G1(1), G2(1); G1[0] = no->Chaves[escolhas.first]; G2[0] = no->Chaves[escolhas.second]; Node* NoG1 = new Node(no->Nivel, G1); Node* NoG2 = new Node(no->Nivel, G2); Node* BestGroup = nullptr; unsigned BestKey = 0u; Retangulo Aux1, Aux2; for(auto &item: no->Chaves) if(item != *(G1.begin()) and item != *(G2.begin())) ChavesRestantes.push_back(item); while(!ChavesRestantes.empty()){ unsigned i = 0; BestKey = i; expansion = -50.0; // mudar BestGroup = nullptr; for(auto &item: ChavesRestantes){ Aux1 = NoG1->GetRetangulo(); Aux2 = NoG2->GetRetangulo(); d1 = item.MBR.CresceParaConter(Aux1).GetArea()-item.MBR.GetArea(); d2 = item.MBR.CresceParaConter(Aux2).GetArea()-item.MBR.GetArea(); if(d2 - d1 > expansion){ BestGroup = NoG1; BestKey = i; expansion = d2 - d1; } else if(d1 - d2 > expansion){ BestGroup = NoG2; BestKey = i; expansion = d1 - d2; } i++; } if(BestGroup != nullptr){ BestGroup->Chaves.push_back(ChavesRestantes[BestKey]); ChavesRestantes.erase(ChavesRestantes.begin()+BestKey); } if(NoG1->Chaves.size() == MINCHAVES - ChavesRestantes.size()){ for(auto &item: ChavesRestantes) NoG1->Chaves.push_back(item); ChavesRestantes.clear(); } else if(NoG2->Chaves.size() == MINCHAVES - ChavesRestantes.size()){ for(auto &item: ChavesRestantes) NoG2->Chaves.push_back(item); ChavesRestantes.clear(); } } NoG1->DiskPos = no->DiskPos; delete no; no = NoG1; no->SalvarNo(); NoG2->SalvarNo(); return NoG2; } bool RTree::Remove(Chave& K){ list<NodeAux> toStack; stack<NodeAux> caminho; Busca(root.NodePtr(), K, toStack); while(!toStack.empty()){ caminho.push(toStack.back()); toStack.pop_back(); } Remove(caminho); return root.NodePtr()->Chaves.empty(); //SE A RAIZ ESTIVER VAZIA } bool RTree::Remove(list<NodeAux>& toStack){ stack<NodeAux> caminho; while(!toStack.empty()){ caminho.push(toStack.back()); toStack.pop_back(); } Remove(caminho); return root.NodePtr()->Chaves.empty(); //SE A RAIZ ESTIVER VAZIA } void RTree::Remove(stack<NodeAux>& Caminho){ list<Chave> ChavesExcedentes = Reorganizar(Caminho); this->registros -= ChavesExcedentes.size(); Reinserir(ChavesExcedentes); Kai(Caminho); } list<Chave> RTree::Reorganizar(stack<NodeAux>& Caminho){ list<Chave> Q; if(Caminho.empty()) return Q; NodeAux No = Caminho.top(); No.ptr->Chaves.erase(No.ptr->Chaves.begin()+No.index); if(No.ptr->Folha()) registros--; if(No.ptr != root.NodePtr()){ if(No.ptr->Chaves.size() < MINCHAVES){ this->count--; Q.splice(Q.end(), EncontreAsFolhas(No.ptr, true)); Caminho.pop(); Q.splice(Q.end(), Reorganizar(Caminho)); } else{ No.ptr->SalvarNo(); AjustaCaminho(Caminho, No.ptr->GetRetangulo()); } } return Q; } void RTree::Reinserir(list<Chave>& ChavesExcedentes){ for(auto &item: ChavesExcedentes) Inserir(item.MBR, item.Dado); ChavesExcedentes.clear(); } list<Chave> RTree::EncontreAsFolhas(Node* no, bool remove){ // CUIDADO COM ESSE METODO list<Chave> LC; if(no->Folha()){ for(auto item: no->Chaves) LC.push_back(item); } else{ Node* aux = nullptr; for(auto item: no->Chaves){ aux = new Node(item.ChildPtr); LC.splice(LC.end(), EncontreAsFolhas(aux, remove)); } } if(no != raiz){ if(remove) no->Delete(); delete no; } return LC; } bool Node::Folha(){ return (Nivel == FOLHA); } bool Node::Overflow(){ return (Chaves.size() > MAXCHAVES); } void Kai(stack<NodeAux>& pilha){ Node* raiz = root.NodePtr(); Node* aux = nullptr; while(!pilha.empty()){ aux = pilha.top().ptr; if(aux != nullptr and aux != raiz) delete aux; pilha.pop(); } } void Kai(list<NodeAux>& DS){ Node* raiz = root.NodePtr(), *aux = nullptr; while(!DS.empty()){ aux = DS.back().ptr; if(aux != nullptr and aux != raiz) delete aux; DS.pop_back(); } } bool operator==(const Chave& A, const Chave& B){ return (A.ChildPtr == B.ChildPtr or A.Dado == B.Dado) and A.MBR == B.MBR; } bool operator!=(const Chave& A, const Chave& B){ return !(A == B); } bool operator<(const Chave& A, const Chave& B){ return A.MBR < B.MBR; } bool operator>(const Chave& A, const Chave& B){ return A.MBR > B.MBR; } Hash::Hash(){ this->path = H_FILENAME; } Hash::~Hash(){ if(this->handle != nullptr) delete this->handle; } void Hash::Insere(string id, streampos& forma){ fstream forma_file(path+"id_"+id+".bin", fstream::app|fstream::binary); if(forma_file.is_open()){ forma_file.write(reinterpret_cast<char*>(&forma), sizeof(streampos)); forma_file.close(); } else{ cerr << "ERRO NA ABERTURA DO ARQUIVO: " << H_FILENAME << id+".bin" << endl; cerr << strerror(errno) << endl; abort(); } } vector<streampos>* Hash::SelectAll(string& query){ if(this->handle != nullptr){ delete this->handle; this->handle = nullptr; } vector<streampos>* result = new vector<streampos>; fstream file(path+"id_"+query+".bin", fstream::in|fstream::binary); streampos aux; if(file.is_open()){ while(file.read(reinterpret_cast<char*>(&aux), sizeof(streampos))) result->push_back(aux); file.close(); } this->handle = result; return result; } } // NAMESPACE SPATIALINDEX
29.843888
128
0.579303
[ "vector" ]
8f9fefa509b42d63385b47151beed33c308d5cc3
3,309
hpp
C++
src/image_pca_factorized_problem.hpp
jmbuena/img_align_lib
1c9a8f876c20e0b4226ac0ecfab4c76e11d4ec21
[ "BSD-3-Clause" ]
17
2015-05-14T19:37:46.000Z
2021-05-25T18:01:06.000Z
src/image_pca_factorized_problem.hpp
jmbuena/img_align_lib
1c9a8f876c20e0b4226ac0ecfab4c76e11d4ec21
[ "BSD-3-Clause" ]
2
2015-03-13T10:03:04.000Z
2015-03-13T10:51:19.000Z
src/image_pca_factorized_problem.hpp
jmbuena/img_align_lib
1c9a8f876c20e0b4226ac0ecfab4c76e11d4ec21
[ "BSD-3-Clause" ]
14
2015-02-02T00:13:12.000Z
2021-12-14T03:37:10.000Z
// ----------------------------------------------------------------------------- /** * @brief Problem using a PCA of images * @author Jose M. Buenaposada * @date 2012/08/11 * @version $revision$ * * $id$ * * Grupo de investigación en Percepción Computacional y Robótica) * (Perception for Computers & Robots research Group) * Facultad de Informática (Computer Science School) * Universidad Politécnica de Madrid (UPM) (Madrid Technical University) * http://www.dia.fi.upm.es/~pcr * */ // ----------------------------------------------------------------------------- // ------------------ RECURSION PROTECTION ------------------------------------- #ifndef IMAGE_PCA_FACTORIZED_PROBLEM_HPP #define IMAGE_PCA_FACTORIZED_PROBLEM_HPP // ----------------------- INCLUDES -------------------------------------------- #include "factorized_jacobian_problem.hpp" #include "image_pca_model.hpp" #include <boost/shared_ptr.hpp> #include <vector> #include <opencv/cv.h> namespace upm { namespace pcr { // ---------------------------------------------------------------------------- /** * Definition of an smart pointer to the ImagePCAFactorizedProblem type */ // ----------------------------------------------------------------------------- class ImagePCAFactorizedProblem; typedef boost::shared_ptr<ImagePCAFactorizedProblem> ImagePCAFactorizedProblemPtr; // ----------------------------------------------------------------------------- /** * Definition of a container of smart pointers to ImagePCAFactorizedProblem class */ // ----------------------------------------------------------------------------- typedef std::vector<ImagePCAFactorizedProblem> ImagePCAFactorizedProblems; // ---------------------------------------------------------------------------- /** * @class ImagePCAFactorizedProblem * @brief The interface for the ImagePCAFactorizedProblem to be used with Optimizer * * The factorization methods assume that the optimization problem jacobian J, * can be factorized into J=M0*Sigma matrix where Sigma matrix depends only * on the motion parameters and M0 matrix depends only on the object model * features and coordinates. */ // ----------------------------------------------------------------------------- class ImagePCAFactorizedProblem: public FactorizedJacobianProblem { public: ImagePCAFactorizedProblem ( ImagePCAModelPtr object_model, MotionModelPtr motion_model ); virtual ~ImagePCAFactorizedProblem (); virtual double computeCostFunction ( cv::Mat& residual_vector, cv::Mat& params, cv::Mat& delta_params, cv::Mat& image ); virtual cv::Mat computeResidual ( cv::Mat& image, cv::Mat& params ); virtual cv::Mat updateMotionParams ( cv::Mat& params, cv::Mat& inc_params ); cv::Mat computeInverseJacobian ( cv::Mat& params ); protected: virtual cv::Mat computeSigmaMatrix ( cv::Mat& params ) = 0; virtual cv::Mat computeM0Matrix () = 0; virtual void initialize (); ImagePCAModelPtr m_pca_model; cv::Mat m_M0t_NB; cv::Mat m_M0t_NB_M0; /** This is the last rectified (warped image) seen as a vector */ cv::Mat m_features_vector; }; }; }; // namespace #endif
25.651163
83
0.541251
[ "object", "vector", "model" ]
8faa0108eccf4eb35cbf2bc6b9efeb913f552463
1,389
hpp
C++
Demo/LAppFaceDetect.hpp
skygoo/faceRig
02c39666e6b5125b01909f64fc3a9335437531c0
[ "Apache-2.0" ]
13
2019-09-29T04:36:47.000Z
2022-01-19T03:24:13.000Z
Demo/LAppFaceDetect.hpp
xuyuxi1997/faceRig
02c39666e6b5125b01909f64fc3a9335437531c0
[ "Apache-2.0" ]
1
2022-03-17T15:56:00.000Z
2022-03-17T15:56:00.000Z
Demo/LAppFaceDetect.hpp
xuyuxi1997/faceRig
02c39666e6b5125b01909f64fc3a9335437531c0
[ "Apache-2.0" ]
6
2019-09-12T04:27:03.000Z
2022-01-04T03:32:21.000Z
// // LAppFaceDetect.hpp // Demo // // Created by sky on 2019/9/8. // #ifndef LAppFaceDetect_hpp #define LAppFaceDetect_hpp #include <opencv2/opencv.hpp> #include <opencv2/face.hpp> #endif /* LAppFaceDetect_hpp */ using namespace std; using namespace cv; using namespace cv::face; class LAppFaceDetect{ public: LAppFaceDetect(); virtual ~LAppFaceDetect(); static LAppFaceDetect* GetInstance(); static void ReleaseInstance(); VideoCapture* camera; std::string modelPath; CascadeClassifier faceDetector; // 创建Facemark类的对象 Ptr<Facemark> facemark = FacemarkLBF::create(); //人脸容器 vector<Rect> faces; // 人脸关键点的容器 vector< vector<Point2f> > landmarks; float x_rotate = 0.0f; float y_rotate = 0.0f; float z_rotate = 0.0f; float left_eye = 1.0f; float right_eye = 1.0f; float eyebrow_left = 0.0f; float eyebrow_right = 0.0f; float mouth_open = 0.0f; Mat frame,gray; void faceDetect(); private: double meter(double A, double B, double C, double x, double y); double eyebrow_move(Point2f &p1, Point2f &p2, double slope, double last, double rate); double eye_open(Point2f &p1, Point2f &p2, Point2f &v11, Point2f &v12, Point2f &v21, Point2f &v22, double last, double rate); void faceControl(vector<Point2f> face); };
21.369231
128
0.651548
[ "vector" ]
8fab4b66d2cf99863e6df56925e0f24a641f04e4
7,862
cxx
C++
Utilities/XcedeLib/XcedeCatalog.cxx
NIRALUser/BatchMake
1afeb15fa5bd18be6e4a56f4349eb6368a91441e
[ "Unlicense" ]
null
null
null
Utilities/XcedeLib/XcedeCatalog.cxx
NIRALUser/BatchMake
1afeb15fa5bd18be6e4a56f4349eb6368a91441e
[ "Unlicense" ]
null
null
null
Utilities/XcedeLib/XcedeCatalog.cxx
NIRALUser/BatchMake
1afeb15fa5bd18be6e4a56f4349eb6368a91441e
[ "Unlicense" ]
null
null
null
#include "XcedeCatalog.h" #include <curl.h> std::ofstream* xcedeOutputFile = NULL; bool xcede_write_buffer = false; std::string xcedeHttpReply = ""; CURL* xcedeCurl; static size_t outputFunction(char *buffer, size_t size, size_t nitems, void *userp) { if(xcedeOutputFile) { xcedeOutputFile->write(buffer,size*nitems); } if(xcede_write_buffer) { xcedeHttpReply += buffer; } size *= nitems; return size; } XcedeCatalog::XcedeCatalog() { m_LoginUrl = "http://rigel/midas/mymidas.php"; m_Url = ""; m_Catalog = ""; } void XcedeCatalog::Login(std::string login, std::string password) { std::string loginUrl = m_LoginUrl; curl_global_init(CURL_GLOBAL_ALL); xcedeCurl = curl_easy_init(); if(!xcedeCurl) { std::cout << "Cannot Initialize Curl!" << std::endl; } std::string log = "Email="; log += login; log += "&Password="; log += password; log += "&Submit=Log%20In"; // Retrieve cookie session curl_easy_setopt(xcedeCurl,CURLOPT_COOKIEJAR,"Cookie.txt"); curl_easy_setopt(xcedeCurl, CURLOPT_POST, 1); curl_easy_setopt(xcedeCurl, CURLOPT_WRITEFUNCTION, outputFunction); curl_easy_setopt(xcedeCurl, CURLOPT_WRITEDATA, NULL); curl_easy_setopt(xcedeCurl, CURLOPT_POSTFIELDS, log.c_str()); curl_easy_setopt(xcedeCurl, CURLOPT_URL, loginUrl.c_str()); curl_easy_perform(xcedeCurl); } xmlDocPtr XcedeCatalog::ParseDoc(std::string docname) { xmlDocPtr doc; xmlNodePtr cur; doc = xmlParseFile(docname.c_str()); if (doc == NULL ) { std::cout<<"Document not parsed successfully"<<std::endl; return (NULL); } cur = xmlDocGetRootElement(doc); if (cur == NULL) { std::cerr<<"empty document"<<std::endl; xmlFreeDoc(doc); return (NULL); } if (xmlStrcmp(cur->name, (const xmlChar *) "XCEDE")) { std::cerr<<"document of the wrong type, root node != Xcede"<<std::endl; xmlFreeDoc(doc); return (NULL); } xmlCleanupParser(); return(doc); } std::vector<std::string> XcedeCatalog::GetUrls(xmlDocPtr doc, std::string catalogID) { xmlXPathObjectPtr result; xmlNodeSetPtr nodeset; std::string nameSpace = "xcede"; std::string nameSpaceUrl = "http://www.xcede.org/xcede-2"; std::string Request = "//" + nameSpace; if(catalogID != "") { Request += ":catalog[@ID=\""; Request += catalogID; Request += "\"]//@uri"; } else { Request += ":entry/@uri"; } std::vector<std::string> listOfValues; xmlChar *xpathRequest =(xmlChar*) Request.c_str(); result = this->GetNodeSet(doc, xpathRequest, nameSpace, nameSpaceUrl); if (result) { nodeset = result->nodesetval; for (int i=0; i < nodeset->nodeNr; i++) { xmlChar *value = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode,1); listOfValues.push_back((char*) value); xmlFree(value); } xmlXPathFreeObject (result); } return listOfValues; } std::vector<std::string> XcedeCatalog::GetNames(xmlDocPtr doc, std::string catalogID) { xmlXPathObjectPtr result; xmlNodeSetPtr nodeset; std::string nameSpace = "xcede"; std::string nameSpaceUrl = "http://www.xcede.org/xcede-2"; std::string Request = "//" + nameSpace; if(catalogID != "") { Request += ":catalog[@ID=\""; Request += catalogID; Request += "\"]//@name"; } else { Request += ":entry/@name"; } std::vector<std::string> listOfValues; xmlChar *xpathRequest =(xmlChar*) Request.c_str(); result = this->GetNodeSet(doc, xpathRequest, nameSpace, nameSpaceUrl); if (result) { nodeset = result->nodesetval; for (int i=0; i < nodeset->nodeNr; i++) { xmlChar *value = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode,1); listOfValues.push_back((char*) value); xmlFree(value); } xmlXPathFreeObject (result); } return listOfValues; } xmlXPathObjectPtr XcedeCatalog::GetNodeSet (xmlDocPtr doc, xmlChar *xpath, std::string nameSpace, std::string nameSpaceUrl) { xmlXPathInit(); xmlXPathContextPtr context; xmlXPathObjectPtr result; context = xmlXPathNewContext(doc); xmlXPathRegisterNs(context, BAD_CAST nameSpace.c_str(), BAD_CAST nameSpaceUrl.c_str()); if (context == NULL) { std::cerr<<"Error in xmlXPathNewContext"<<std::endl; return NULL; } result = xmlXPathEvalExpression(xpath, context); xmlXPathFreeContext(context); if (result == NULL) { std::cerr<<"Error in xmlXPathEvalExpression"<<std::endl; return NULL; } if(xmlXPathNodeSetIsEmpty(result->nodesetval)) { xmlXPathFreeObject(result); return NULL; } return result; } std::vector<std::string> XcedeCatalog::GetXcedeDataSets(xmlDocPtr doc, std::string CataloID, std::string login, std::string password) { if(!(login == "" && password == "")) { xcede_write_buffer = true; this->Login(login, password); xcede_write_buffer = false; } //Get all the Urls, and the Names std::vector<std::string> urls = this->GetUrls(doc, CataloID); std::vector<std::string> filenames = this->GetNames(doc, CataloID); std::vector<std::string> dataSet; for(int i=0; i<(int)urls.size() ; i++) { std::string newData = urls[i]; newData += ";"; newData += filenames[i]; dataSet.push_back(newData); } return dataSet; } bool XcedeCatalog::DownloadXcedeDatasets(std::string xcedeDataSet, std::string directory, std::string login, std::string password) { std::string filename = this->GetXcedeFilename(xcedeDataSet); std::string url = this->GetXcedeUrl(xcedeDataSet); if(!(login == "" && password == "")) { xcede_write_buffer = true; this->Login(login, password); xcede_write_buffer = false; } else { curl_global_init(CURL_GLOBAL_ALL); xcedeCurl = curl_easy_init(); if(!xcedeCurl) { std::cout << "Cannot Initialize Curl!" << std::endl; } curl_easy_setopt(xcedeCurl, CURLOPT_WRITEFUNCTION, outputFunction); curl_easy_setopt(xcedeCurl, CURLOPT_WRITEDATA, NULL); } xcedeOutputFile = new std::ofstream; std::string::size_type loc = filename.find( "/", 0); while(loc != std::string::npos ) { std::string newDir = filename; newDir.erase(loc, (filename.length())-loc); directory += "/" + newDir; filename.erase(0, loc+1); loc = filename.find( "/", 0); } itksys::SystemTools::MakeDirectory(directory.c_str()); std::string newfilename = directory + "/" + filename; xcedeOutputFile->open(newfilename.c_str(), std::ios::binary); if(!xcedeOutputFile->is_open()) { std::cout << "Cannot open fic" << std::endl; } curl_easy_setopt(xcedeCurl, CURLOPT_HTTPGET, 1); curl_easy_setopt(xcedeCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(xcedeCurl, CURLOPT_NOPROGRESS, false); curl_easy_setopt(xcedeCurl, CURLOPT_FOLLOWLOCATION,true); curl_easy_setopt(xcedeCurl, CURLOPT_PROGRESSDATA, this); CURLcode res = curl_easy_perform(xcedeCurl); curl_easy_cleanup(xcedeCurl); if (res != CURLE_OK) { fprintf(stderr, "Curl perform failed: %s\n", curl_easy_strerror(res)); xcedeOutputFile->close(); xcedeOutputFile = NULL; return false; } xcedeOutputFile->close(); xcedeOutputFile = NULL; return true; } std::string XcedeCatalog::GetXcedeFilename(std::string xcedeDataSet) { std::string::size_type loc = xcedeDataSet.rfind(";", xcedeDataSet.size()); std::string filename = xcedeDataSet.substr(loc+1); return filename; } std::string XcedeCatalog::GetXcedeUrl(std::string xcedeDataSet) { std::string::size_type loc = xcedeDataSet.rfind(";", xcedeDataSet.size()); std::string url = xcedeDataSet.substr(0,loc); return url; }
24.56875
96
0.653905
[ "vector" ]
2633c0c6d4747903d596f6e48ed8d4656fe47251
552
hpp
C++
Code/Gfx/IGraphicDeviceChild.hpp
Mu-L/Luna-Engine-0.6
05ae1037f0d173589a535eb6ec2964f20d80e5c1
[ "MIT" ]
167
2020-06-17T06:09:41.000Z
2022-03-13T20:31:26.000Z
Code/Gfx/IGraphicDeviceChild.hpp
Mu-L/Luna-Engine-0.6
05ae1037f0d173589a535eb6ec2964f20d80e5c1
[ "MIT" ]
2
2020-07-11T15:12:50.000Z
2021-06-01T01:45:49.000Z
Code/Gfx/IGraphicDeviceChild.hpp
Mu-L/Luna-Engine-0.6
05ae1037f0d173589a535eb6ec2964f20d80e5c1
[ "MIT" ]
22
2020-06-12T02:26:10.000Z
2022-01-02T14:04:32.000Z
// Copyright 2018-2020 JXMaster. All rights reserved. /* * @file IDeviceChild.hpp * @author JXMaster * @date 2019/7/17 */ #pragma once #include <Core/Core.hpp> namespace Luna { namespace Gfx { struct IGraphicDevice; //! @interface IGraphicDeviceChild //! Represents a object that is managed by a graphic device (`IGraphicDevice`). struct IGraphicDeviceChild : public IObject { luiid("{324864f4-8489-4f6c-aa9b-2e96ea4c31ce}"); //! Get the parent device that manages this object. virtual IGraphicDevice* get_device() = 0; }; } }
22.08
81
0.711957
[ "object" ]
2634aff0cf7f2fa4b54627f7b84f9b29ce0187a7
6,970
cpp
C++
Chapter_4_Filtering_in_the_Frequency_Domain/Section_4_10.cpp
AlazzR/Digital-Image-Processing-Cpp
22573ff1aa2c8c8cc3dd6fb4ffaea07241aec47a
[ "CC0-1.0" ]
null
null
null
Chapter_4_Filtering_in_the_Frequency_Domain/Section_4_10.cpp
AlazzR/Digital-Image-Processing-Cpp
22573ff1aa2c8c8cc3dd6fb4ffaea07241aec47a
[ "CC0-1.0" ]
null
null
null
Chapter_4_Filtering_in_the_Frequency_Domain/Section_4_10.cpp
AlazzR/Digital-Image-Processing-Cpp
22573ff1aa2c8c8cc3dd6fb4ffaea07241aec47a
[ "CC0-1.0" ]
null
null
null
#include "Section_4_10_H_.h" coordinate::coordinate(int x, int y) { this->x = (x >= 0) ? x : 0; this->y = (y >= 0) ? y : 0; } int coordinate::getX() const { return this->x; } int coordinate::getY() const { return this->y; } bool customCompare::operator()(const coordinate& lhs, const coordinate& rhs) const { if ((lhs.getX() == rhs.getX()) && (lhs.getY() == rhs.getY())) { return true; } else return false; } size_t customHashing::operator()(const coordinate& obj)const { return std::hash<int>()(obj.getX()) ^ std::hash<int>()(obj.getY());//The hash value of x XORed with hash value of y to be stored in the bucket } std::unordered_set<coordinate, customHashing, customCompare> find_loc_to_suppress(cv::Mat & img, int width) { //Padding the image will increase the significant strength of along the vertical and horizontal axes of the spectrum, hence, if you don't want to pad you need to play around with the accepted intensity values. //When image is padded in it will darken the transformed image. See problem 4.42 cv::Mat pad = cv::Mat(img.rows * 2, img.cols * 2, CV_32FC1, cv::Scalar(0.0F)); std::unordered_set<coordinate, customHashing, customCompare> locationLocation; for (int i = 0; i < img.rows; i++) for (int j = 0; j < img.cols; j++) pad.at<float>(i, j) = img.at<uchar>(i, j); cv::Mat temp(pad.clone()); centering_image(temp, CV_32FC1); cv::Mat complex[2] = { temp, cv::Mat::zeros(pad.rows, pad.cols, CV_32FC1) }; cv::Mat dftImage; cv::merge(complex, 2, dftImage); cv::dft(dftImage, dftImage); img = dftImage.clone(); //In order to get the transformed image cv::split(dftImage, complex); cv::Mat mag = cv::Mat::zeros(complex[0].size(), CV_32FC1); cv::magnitude(complex[0], complex[1], mag); //Enhancing the figure float* ptr; for (int i = 0; i < mag.rows; i++) { ptr = mag.ptr<float>(i); for (int j = 0; j < mag.cols; j++) ptr[j] = std::log10(ptr[j] + 1); } std::cout << "Image size for the " << "Notch reject Filter: " << img.size() << std::endl; cv::normalize(mag, mag, 0.0F, 255.0F, CV_MINMAX); //std::cout << mag.at<float>(mag.rows / 2, mag.cols / 2) << std::endl; mag.convertTo(mag, CV_8UC1); //std::cout << mag << std::endl; //Finding the location of these peak frequencies cv::Mat colored[3] = { mag, mag, mag }; cv::Mat complete; cv::merge(colored, 3, complete); cv::Mat interest_points = cv::Mat::zeros(mag.rows, mag.cols, CV_8UC1); uchar* ptrComplete; uchar* ptrRed; cv::Mat magTemp = mag.clone(); for (int i = 0; i < mag.rows; i++) { ptrComplete = magTemp.ptr<uchar>(i); ptrRed = interest_points.ptr<uchar>(i); for (int j = 0; j < mag.cols; j++) if ((ptrComplete[j] >= 160) && (ptrComplete[j] <= 255)) { ptrRed[j] = 255; if ((i == (mag.rows / 2)) || (j == (mag.cols / 2)) || ((i >= (mag.rows / 2 - 50)) && (i <= (mag.rows / 2 + 50))) || ((j >= (mag.cols / 2 - 50)) && (j <= (mag.cols / 2 + 50)))) { ptrComplete[j] = 0; }//suppress uninteresting points else { int posX = 0; int posY = 0; int count = 0; cv::Mat temp = cv::Mat(magTemp, cv::Rect((int)(j - width), (int)(i - width), 2 * width, 2 * width)); for(int t1 =0; t1 < 2 * width; t1++) for (int t2 = 0; t2 < 2 * width; t2++) { if ((temp.at<uchar>(t1, t2)>= 160) && (temp.at<uchar>(t1, t2) <= 255)) { posX += i - width + t1; posY += j - width + t2; count += 1; } } posX = (int)(posX / count); posY = (int)(posY / count); std::vector<int> positions; locationLocation.insert(coordinate(posY, posX)); cv::Point p(posY, posX); cv::circle(complete, p, 2.5, cv::Scalar(0, 0, 255)); } } } /* for (std::vector<std::vector<int>>::iterator itr = locationLocation.begin(); itr != locationLocation.end(); itr++) { for (std::vector<int>::iterator itr2 = itr->begin(); itr2 != itr->end(); itr2++) std::cout << *itr2 << "\t"; std::cout << std::endl; } */ //cv::add(colored[0], interest_points, colored[0]); for (std::unordered_set<coordinate, customHashing, customCompare>::iterator itr = locationLocation.begin(); itr != locationLocation.end(); itr++) std::cout << "Coordinate of interest point: " <<itr->getX() << ":" << itr->getY() << std::endl; cv::imshow("Colored Image", complete); cv::waitKey(1000); cv::destroyAllWindows(); cv::imwrite("../bin/Section_4_10/Magnitude_car_Moire.jpg", mag); cv::imwrite("../bin/Section_4_10/Magnitude_car_Moire_with_circles.jpg", complete); return locationLocation; } cv::Mat creating_notch(int P, int Q, float D0, int uk, int vk, int n) { cv::Mat notch = cv::Mat::zeros(P, Q, CV_32FC1); float* ptrNotch; for (int i = 0; i < notch.rows; i++) { ptrNotch = notch.ptr<float>(i); for (int j = 0; j < notch.cols; j++) { float t1 = std::sqrt(std::pow(i - P/2- uk, 2) + std::pow(j - Q/2 - vk, 2)); ptrNotch[j] = 1.0F / (1.0F + std::pow(D0 / t1, n)); } } return notch; } void filtering_by_notch(const cv::Mat& img, float D0, int n) { cv::Mat tempPad= img.clone(); std::unordered_set<coordinate, customHashing, customCompare> location = find_loc_to_suppress(tempPad, 40);//passed by reference, tempPad will be the DFT version of the image int P = tempPad.rows; int Q = tempPad.cols; std::cout << "Padded Image size: " << tempPad.size() << std::endl; cv::Mat notchFilter = cv::Mat::ones(tempPad.size(), CV_32FC1); for (std::unordered_set<coordinate, customHashing, customCompare>::iterator itr1 = location.begin(); itr1 != location.end(); itr1++) { cv::multiply(creating_notch(P, Q, D0, itr1->getY() + P/2, itr1->getX() + Q/2, n), notchFilter, notchFilter); cv::multiply(creating_notch(P, Q, D0, -1 * itr1->getY() + P/2, -1 * itr1->getX() + Q/2, n), notchFilter, notchFilter); } cv::Mat complex[2]; cv::split(tempPad, complex); cv::multiply(complex[0], notchFilter, complex[0]); cv::multiply(complex[1], notchFilter, complex[1]); cv::Mat mag; cv::magnitude(complex[0], complex[1], mag); float* ptr; for (int i = 0; i < mag.rows; i++) { ptr = mag.ptr<float>(i); for (int j = 0; j < mag.cols; j++) ptr[j] = std::log10(ptr[j] + 1); } cv::normalize(mag, mag, 0.0F, 255.0F, CV_MINMAX); mag.convertTo(mag, CV_8UC1); cv::normalize(notchFilter, notchFilter, 0.0F, 255.0F, CV_MINMAX); notchFilter.convertTo(notchFilter, CV_8UC1); cv::imwrite("../bin/Section_4_10/Magnitude_car_Moire_After_notch_filter.jpg", mag); cv::imwrite("../bin/Section_4_10/notch_" + std::to_string(n) + ".jpg", notchFilter); cv::Mat dftImage; cv::merge(complex, 2, dftImage); cv::dft(dftImage, dftImage, cv::DFT_INVERSE | cv::DFT_SCALE | cv::DFT_REAL_OUTPUT); rescaling_intensities(dftImage); cv::Mat finalImage(dftImage, cv::Rect(0, 0, img.cols, img.rows)); rescaling_intensities(finalImage); finalImage.convertTo(finalImage, CV_8UC1); cv::imwrite("../bin/Section_4_10/Car_Moire_After_notch_filtering_" + std::to_string(n) +".jpg", finalImage); }
34.334975
210
0.626112
[ "vector" ]
26355f51f06a6bf6b9076e86f36947725512abdc
19,228
cpp
C++
higan/target-higan/presentation/presentation.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
10
2019-12-19T01:19:41.000Z
2021-02-18T16:30:29.000Z
higan/target-higan/presentation/presentation.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
higan/target-higan/presentation/presentation.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
#include "../higan.hpp" #include "about.cpp" unique_pointer<AboutWindow> aboutWindow; unique_pointer<Presentation> presentation; Presentation::Presentation() { presentation = this; systemsMenu.setText("Systems"); systemMenu.setVisible(false); settingsMenu.setText("Settings"); sizeMenu.setText("Size"); updateSizeMenu(); outputMenu.setText("Output"); centerViewport.setText("Center").onActivate([&] { settings["View/Output"].setValue("Center"); resizeViewport(); }); scaleViewport.setText("Scale").onActivate([&] { settings["View/Output"].setValue("Scale"); resizeViewport(); }); stretchViewport.setText("Stretch").onActivate([&] { settings["View/Output"].setValue("Stretch"); resizeViewport(); }); if(settings["View/Output"].text() == "Center") centerViewport.setChecked(); if(settings["View/Output"].text() == "Scale") scaleViewport.setChecked(); if(settings["View/Output"].text() == "Stretch") stretchViewport.setChecked(); adaptiveSizing.setText("Adaptive Sizing").setChecked(settings["View/Adaptive"].boolean()).onToggle([&] { settings["View/Adaptive"].setValue(adaptiveSizing.checked()); resizeWindow(); }); aspectCorrection.setText("Aspect Correction").setChecked(settings["View/AspectCorrection"].boolean()).onToggle([&] { settings["View/AspectCorrection"].setValue(aspectCorrection.checked()); resizeWindow(); }); showOverscanArea.setText("Show Overscan Area").setChecked(settings["View/Overscan"].boolean()).onToggle([&] { settings["View/Overscan"].setValue(showOverscanArea.checked()); resizeWindow(); }); videoEmulationMenu.setText("Emulation"); blurEmulation.setText("Blurring").setChecked(settings["Video/BlurEmulation"].boolean()).onToggle([&] { settings["Video/BlurEmulation"].setValue(blurEmulation.checked()); if(emulator) emulator->set("Blur Emulation", blurEmulation.checked()); }); colorEmulation.setText("Colors").setChecked(settings["Video/ColorEmulation"].boolean()).onToggle([&] { settings["Video/ColorEmulation"].setValue(colorEmulation.checked()); if(emulator) emulator->set("Color Emulation", colorEmulation.checked()); }); scanlineEmulation.setText("Scanlines").setChecked(settings["Video/ScanlineEmulation"].boolean()).setVisible(false).onToggle([&] { settings["Video/ScanlineEmulation"].setValue(scanlineEmulation.checked()); if(emulator) emulator->set("Scanline Emulation", scanlineEmulation.checked()); }); videoShaderMenu.setText("Shader"); videoShaderNone.setText("None").onActivate([&] { settings["Video/Shader"].setValue("None"); program->updateVideoShader(); }); videoShaderBlur.setText("Blur").onActivate([&] { settings["Video/Shader"].setValue("Blur"); program->updateVideoShader(); }); loadShaders(); synchronizeVideo.setText("Synchronize Video").setChecked(settings["Video/Synchronize"].boolean()).setVisible(false).onToggle([&] { settings["Video/Synchronize"].setValue(synchronizeVideo.checked()); video->setBlocking(synchronizeVideo.checked()); }); synchronizeAudio.setText("Synchronize Audio").setChecked(settings["Audio/Synchronize"].boolean()).onToggle([&] { settings["Audio/Synchronize"].setValue(synchronizeAudio.checked()); audio->setBlocking(synchronizeAudio.checked()); }); muteAudio.setText("Mute Audio").setChecked(settings["Audio/Mute"].boolean()).onToggle([&] { settings["Audio/Mute"].setValue(muteAudio.checked()); program->updateAudioEffects(); }); showStatusBar.setText("Show Status Bar").setChecked(settings["View/StatusBar"].boolean()).onToggle([&] { settings["View/StatusBar"].setValue(showStatusBar.checked()); if(!showStatusBar.checked()) { layout.remove(statusLayout); } else { layout.append(statusLayout, Size{~0, StatusHeight}); } if(visible()) resizeWindow(); }); showSystemSettings.setIcon(Icon::Device::Storage).setText("Systems ...").onActivate([&] { settingsManager->show(0); }); showVideoSettings.setIcon(Icon::Device::Display).setText("Video ...").onActivate([&] { settingsManager->show(1); }); showAudioSettings.setIcon(Icon::Device::Speaker).setText("Audio ...").onActivate([&] { settingsManager->show(2); }); showInputSettings.setIcon(Icon::Device::Joypad).setText("Input ...").onActivate([&] { if(emulator) { //default input panel to current core's input settings for(auto item : settingsManager->input.emulatorList.items()) { if(systemMenu.text() == item.text()) { item.setSelected(); settingsManager->input.emulatorList.doChange(); break; } } } settingsManager->show(3); }); showHotkeySettings.setIcon(Icon::Device::Keyboard).setText("Hotkeys ...").onActivate([&] { settingsManager->show(4); }); showAdvancedSettings.setIcon(Icon::Action::Settings).setText("Advanced ...").onActivate([&] { settingsManager->show(5); }); toolsMenu.setText("Tools").setVisible(false); saveQuickStateMenu.setText("Save Quick State"); saveSlot1.setText("Slot 1").onActivate([&] { program->saveState(1); }); saveSlot2.setText("Slot 2").onActivate([&] { program->saveState(2); }); saveSlot3.setText("Slot 3").onActivate([&] { program->saveState(3); }); saveSlot4.setText("Slot 4").onActivate([&] { program->saveState(4); }); saveSlot5.setText("Slot 5").onActivate([&] { program->saveState(5); }); loadQuickStateMenu.setText("Load Quick State"); loadSlot1.setText("Slot 1").onActivate([&] { program->loadState(1); }); loadSlot2.setText("Slot 2").onActivate([&] { program->loadState(2); }); loadSlot3.setText("Slot 3").onActivate([&] { program->loadState(3); }); loadSlot4.setText("Slot 4").onActivate([&] { program->loadState(4); }); loadSlot5.setText("Slot 5").onActivate([&] { program->loadState(5); }); pauseEmulation.setText("Pause Emulation").onToggle([&] { program->togglePause(); }); cheatEditor.setIcon(Icon::Edit::Replace).setText("Cheat Editor ...").onActivate([&] { toolsManager->show(0); }); stateManager.setIcon(Icon::Application::FileManager).setText("State Manager ...").onActivate([&] { toolsManager->show(1); }); manifestViewer.setIcon(Icon::Emblem::Text).setText("Manifest Viewer ...").onActivate([&] { toolsManager->show(2); }); gameNotes.setIcon(Icon::Emblem::Text).setText("Game Notes ...").onActivate([&] { toolsManager->show(3); }); helpMenu.setText("Help"); documentation.setIcon(Icon::Application::Browser).setText("Documentation ...").onActivate([&] { invoke("https://doc.byuu.org/higan/"); }); credits.setIcon(Icon::Application::Browser).setText("Credits ...").onActivate([&] { invoke("https://doc.byuu.org/higan/credits/"); }); about.setIcon(Icon::Prompt::Question).setText("About ...").onActivate([&] { aboutWindow->setCentered(*this).setVisible().setFocused(); }); viewport.setDroppable().onDrop([&](vector<string> locations) { if(!locations || !directory::exists(locations.first())) return; program->gameQueue.append(locations.first()); program->load(); }).onSize([&] { configureViewport(); }); iconLayout.setAlignment(0.0); image icon{Resource::Icon}; icon.alphaBlend(0x000000); iconCanvas.setIcon(icon); if(!settings["View/StatusBar"].boolean()) { layout.remove(statusLayout); } auto font = Font().setBold(); auto back = Color{ 32, 32, 32}; auto fore = Color{255, 255, 255}; spacerLeft.setBackgroundColor(back); statusMessage.setFont(font); statusMessage.setAlignment(0.0); statusMessage.setBackgroundColor(back); statusMessage.setForegroundColor(fore); statusInfo.setFont(font); statusInfo.setAlignment(1.0); statusInfo.setBackgroundColor(back); statusInfo.setForegroundColor(fore); statusInfo.setText("Unloaded"); spacerRight.setBackgroundColor(back); onSize([&] { resizeViewport(); }); onClose([&] { program->quit(); }); settings["View/Multiplier"].setValue(2); setTitle({"higan v", Emulator::Version}); setBackgroundColor({0, 0, 0}); resizeWindow(); setCentered(); #if defined(PLATFORM_MACOS) about.setVisible(false); Application::Cocoa::onAbout([&] { about.doActivate(); }); Application::Cocoa::onActivate([&] { setFocused(); }); Application::Cocoa::onPreferences([&] { showInputSettings.doActivate(); }); Application::Cocoa::onQuit([&] { doClose(); }); #endif } auto Presentation::updateEmulatorMenu() -> void { if(!emulator) return; auto information = emulator->information(); systemMenu.reset(); for(auto& port : emulator->ports()) { Menu menu{&systemMenu}; menu.setProperty("portID", port.id); menu.setText(port.name); if(port.name.beginsWith("Expansion") || port.name.beginsWith("Extension")) { menu.setIcon(Icon::Device::Storage); } else { menu.setIcon(Icon::Device::Joypad); } auto path = string{information.name, "/", port.name}.replace(" ", ""); auto deviceName = settings(path).text(); auto deviceID = emulator->connected(port.id); Group devices; for(auto& device : emulator->devices(port.id)) { MenuRadioItem item{&menu}; item.setProperty("deviceID", device.id); item.setText(device.name); item.onActivate([=] { settings(path).setValue(device.name); emulator->connect(port.id, device.id); updateEmulatorDeviceSelections(); }); devices.append(item); if(deviceName == device.name) item.doActivate(); if(!deviceName && deviceID == device.id) item.doActivate(); } if(devices.objectCount() == 0) { menu.setVisible(false); } } if(systemMenu.actionCount()) { systemMenu.append(MenuSeparator()); } if(information.resettable) { systemMenu.append(MenuItem().setText("Soft Reset").setIcon(Icon::Action::Refresh).onActivate([&] { program->softReset(); })); } systemMenu.append(MenuItem().setText("Power Cycle").setIcon(Icon::Action::Refresh).onActivate([&] { program->powerCycle(); })); systemMenu.append(MenuItem().setText("Unload").setIcon(Icon::Media::Eject).onActivate([&] { program->unload(); })); updateEmulatorDeviceSelections(); } auto Presentation::updateEmulatorDeviceSelections() -> void { if(!emulator) return; for(auto& port : emulator->ports()) { for(auto& action : systemMenu->actions()) { auto portID = action.property("portID"); if(portID && portID.natural() == port.id) { if(auto menu = action.cast<Menu>()) { auto deviceID = emulator->connected(port.id); for(auto& action : menu.actions()) { if(auto item = action.cast<MenuRadioItem>()) { if(item.property("deviceID").natural() == deviceID) { item.setChecked(); } } } } } } } } auto Presentation::updateSizeMenu() -> void { assert(sizeMenu.actionCount() == 0); //should only be called once //determine the largest multiplier that can be used by the largest monitor found uint height = 1; for(uint monitor : range(Monitor::count())) { height = max(height, Monitor::workspace(monitor).height()); } uint multipliers = max(1, height / 240); for(uint multiplier : range(1, multipliers + 1)) { MenuRadioItem item{&sizeMenu}; item.setProperty("multiplier", multiplier); item.setText({multiplier, "x (", 240 * multiplier, "p)"}); item.onActivate([=] { settings["View/Multiplier"].setValue(multiplier); resizeWindow(); }); sizeGroup.append(item); } for(auto item : sizeGroup.objects<MenuRadioItem>()) { if(settings["View/Multiplier"].natural() == item.property("multiplier").natural()) { item.setChecked(); } } sizeMenu.append(MenuSeparator()); sizeMenu.append(MenuItem().setIcon(Icon::Action::Remove).setText("Shrink Window To Size").onActivate([&] { resizeWindow(); })); sizeMenu.append(MenuItem().setIcon(Icon::Place::Settings).setText("Center Window").onActivate([&] { setCentered(); })); } auto Presentation::configureViewport() -> void { uint width = viewport.geometry().width(); uint height = viewport.geometry().height(); if(video) video->configure(width, height, 60, 60); } auto Presentation::clearViewport() -> void { if(!emulator || !emulator->loaded()) viewportLayout.setPadding(); if(!visible() || !video) return; uint32_t* output; uint length = 0; uint width = 16; uint height = 16; if(video->acquire(output, length, width, height)) { for(uint y : range(height)) { auto line = output + y * (length >> 2); for(uint x : range(width)) *line++ = 0xff000000; } video->release(); video->output(); } } auto Presentation::resizeViewport() -> void { uint layoutWidth = viewportLayout.geometry().width(); uint layoutHeight = viewportLayout.geometry().height(); uint width = 320; uint height = 240; if(emulator) { auto display = emulator->displays().first(); width = display.width; height = display.height; if(settings["View/AspectCorrection"].boolean()) width *= display.aspectCorrection; if(!settings["View/Overscan"].boolean()) { if(display.type == Emulator::Interface::Display::Type::CRT) { uint overscanHorizontal = settings["View/Overscan/Horizontal"].natural(); uint overscanVertical = settings["View/Overscan/Vertical"].natural(); width -= overscanHorizontal * 2; height -= overscanVertical * 2; } } } if(visible() && !fullScreen()) { uint widthMultiplier = layoutWidth / width; uint heightMultiplier = layoutHeight / height; uint multiplier = max(1, min(widthMultiplier, heightMultiplier)); settings["View/Multiplier"].setValue(multiplier); for(auto item : sizeGroup.objects<MenuRadioItem>()) { if(auto property = item.property("multiplier")) { if(property.natural() == multiplier) item.setChecked(); } } } if(!emulator || !emulator->loaded()) return clearViewport(); if(!video) return; uint viewportWidth; uint viewportHeight; if(settings["View/Output"].text() == "Center") { uint widthMultiplier = layoutWidth / width; uint heightMultiplier = layoutHeight / height; uint multiplier = min(widthMultiplier, heightMultiplier); viewportWidth = width * multiplier; viewportHeight = height * multiplier; } else if(settings["View/Output"].text() == "Scale") { double widthMultiplier = (double)layoutWidth / width; double heightMultiplier = (double)layoutHeight / height; double multiplier = min(widthMultiplier, heightMultiplier); viewportWidth = width * multiplier; viewportHeight = height * multiplier; } else if(settings["View/Output"].text() == "Stretch" || 1) { viewportWidth = layoutWidth; viewportHeight = layoutHeight; } //center viewport within viewportLayout by use of viewportLayout padding uint paddingWidth = layoutWidth - viewportWidth; uint paddingHeight = layoutHeight - viewportHeight; viewportLayout.setPadding({ paddingWidth / 2, paddingHeight / 2, paddingWidth - paddingWidth / 2, paddingHeight - paddingHeight / 2 }); } auto Presentation::resizeWindow() -> void { if(fullScreen()) return; if(maximized()) setMaximized(false); uint width = 320; uint height = 240; uint multiplier = max(1, settings["View/Multiplier"].natural()); uint statusHeight = settings["View/StatusBar"].boolean() ? StatusHeight : 0; if(emulator) { auto display = emulator->displays().first(); width = display.width; height = display.height; if(settings["View/AspectCorrection"].boolean()) width *= display.aspectCorrection; if(!settings["View/Overscan"].boolean()) { if(display.type == Emulator::Interface::Display::Type::CRT) { uint overscanHorizontal = settings["View/Overscan/Horizontal"].natural(); uint overscanVertical = settings["View/Overscan/Vertical"].natural(); width -= overscanHorizontal * 2; height -= overscanVertical * 2; } } } setMinimumSize({width, height + statusHeight}); setSize({width * multiplier, height * multiplier + statusHeight}); layout.setGeometry(layout.geometry()); resizeViewport(); } auto Presentation::toggleFullScreen() -> void { if(!fullScreen()) { if(settings["View/StatusBar"].boolean()) { layout.remove(statusLayout); } menuBar.setVisible(false); setFullScreen(true); video->setExclusive(settings["Video/Exclusive"].boolean()); if(video->exclusive()) setVisible(false); if(!input->acquired()) input->acquire(); resizeViewport(); } else { if(input->acquired()) input->release(); if(video->exclusive()) setVisible(true); video->setExclusive(false); setFullScreen(false); menuBar.setVisible(true); if(settings["View/StatusBar"].boolean()) { layout.append(statusLayout, Size{~0, StatusHeight}); } resizeWindow(); setCentered(); } } auto Presentation::loadSystems() -> void { systemsMenu.reset(); for(auto system : settings.find("Systems/System")) { if(!system["Visible"].boolean()) continue; MenuItem item{&systemsMenu}; string name = system.text(); string filename = system["Load"].text(); string load = Location::base(filename).trimRight("/", 1L); string alias = system["Alias"].text(); item.setIcon(load ? (image)Icon::Emblem::Folder : (image)Icon::Device::Storage); item.setText({alias ? alias : load ? load : name, " ..."}); item.onActivate([=] { for(auto& emulator : program->emulators) { auto information = emulator->information(); if(name == information.name) { if(filename) program->gameQueue.append(filename); program->load(*emulator); break; } } }); } //add icarus menu option -- but only if icarus binary is present if(execute("icarus", "--name").output.strip() == "icarus") { if(systemsMenu.actionCount()) systemsMenu.append(MenuSeparator()); MenuItem item{&systemsMenu}; item.setIcon(Icon::Emblem::File); item.setText("Load ROM File ..."); item.onActivate([&] { audio->clear(); if(auto location = execute("icarus", "--import")) { program->gameQueue.append(location.output.strip()); program->load(); } }); } } auto Presentation::loadShaders() -> void { auto pathname = locate("shaders/"); if(settings["Video/Driver"].text() == "OpenGL 3.2") { for(auto shader : directory::folders(pathname, "*.shader")) { if(videoShaders.objectCount() == 2) videoShaderMenu.append(MenuSeparator()); MenuRadioItem item{&videoShaderMenu}; item.setText(string{shader}.trimRight(".shader/", 1L)).onActivate([=] { settings["Video/Shader"].setValue({pathname, shader}); program->updateVideoShader(); }); videoShaders.append(item); } } if(settings["Video/Shader"].text() == "None") videoShaderNone.setChecked(); if(settings["Video/Shader"].text() == "Blur") videoShaderBlur.setChecked(); for(auto radioItem : videoShaders.objects<MenuRadioItem>()) { if(settings["Video/Shader"].text() == string{pathname, radioItem.text(), ".shader/"}) { radioItem.setChecked(); } } }
36.835249
132
0.663928
[ "geometry", "vector" ]
2638a920953ad07ac13b0f54254dafedf877d021
47,687
cpp
C++
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Uno.Data.Json.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Uno.Data.Json.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Uno.Data.Json.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on '(multiple files)'. // WARNING: Changes might be lost if you edit this file directly. #include <Uno.Bool.h> #include <Uno.Char.h> #include <Uno.Collections.Dicti-87d2e37d.h> #include <Uno.Collections.Dictionary-2.h> #include <Uno.Collections.Enume-8ddd045.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.List-1.h> #include <Uno.Data.Json.Array.h> #include <Uno.Data.Json.AtomicValue-1.h> #include <Uno.Data.Json.Boolean.h> #include <Uno.Data.Json.JsonDataType.h> #include <Uno.Data.Json.JsonException.h> #include <Uno.Data.Json.JsonReader.h> #include <Uno.Data.Json.JsonWriter.h> #include <Uno.Data.Json.Null.h> #include <Uno.Data.Json.Number.h> #include <Uno.Data.Json.Object.h> #include <Uno.Data.Json.Parser.h> #include <Uno.Data.Json.String.h> #include <Uno.Data.Json.Value.h> #include <Uno.Double.h> #include <Uno.Exception.h> #include <Uno.Int.h> #include <Uno.IO.StringReader.h> #include <Uno.IO.TextReader.h> #include <Uno.Object.h> #include <Uno.String.h> #include <Uno.Text.StringBuilder.h> #include <Uno.UInt.h> static uString* STRINGS[17]; static uType* TYPES[11]; namespace g{ namespace Uno{ namespace Data{ namespace Json{ // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonValue.uno // ------------------------------------------------------------------------------------------- // internal sealed class Array :90 // { static void Array_build(uType* type) { ::TYPES[0] = ::g::Uno::Collections::List_typeof()->MakeType(::g::Uno::Data::Json::Value_typeof(), NULL); type->SetFields(0, ::TYPES[0/*Uno.Collections.List<Uno.Data.Json.Value>*/], offsetof(Array, _values), 0); } uType* Array_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Data::Json::Value_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(Array); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.Array", options); type->fp_build_ = Array_build; type->fp_ctor_ = (void*)Array__New1_fn; return type; } // public generated Array() :90 void Array__ctor_1_fn(Array* __this) { __this->ctor_1(); } // internal void Add(Uno.Data.Json.Value v) :94 void Array__Add_fn(Array* __this, ::g::Uno::Data::Json::Value* v) { __this->Add(v); } // public int get_Count() :104 void Array__get_Count_fn(Array* __this, int32_t* __retval) { *__retval = __this->Count(); } // public Uno.Data.Json.Value get_Item(int index) :101 void Array__get_Item_fn(Array* __this, int32_t* index, ::g::Uno::Data::Json::Value** __retval) { *__retval = __this->Item(*index); } // public generated Array New() :90 void Array__New1_fn(Array** __retval) { *__retval = Array::New1(); } // public generated Array() [instance] :90 void Array::ctor_1() { _values = ((::g::Uno::Collections::List*)::g::Uno::Collections::List::New1(::TYPES[0/*Uno.Collections.List<Uno.Data.Json.Value>*/])); ctor_(); } // internal void Add(Uno.Data.Json.Value v) [instance] :94 void Array::Add(::g::Uno::Data::Json::Value* v) { uStackFrame __("Uno.Data.Json.Array", "Add(Uno.Data.Json.Value)"); ::g::Uno::Collections::List__Add_fn(uPtr(_values), v); } // public int get_Count() [instance] :104 int32_t Array::Count() { uStackFrame __("Uno.Data.Json.Array", "get_Count()"); return uPtr(_values)->Count(); } // public Uno.Data.Json.Value get_Item(int index) [instance] :101 ::g::Uno::Data::Json::Value* Array::Item(int32_t index) { uStackFrame __("Uno.Data.Json.Array", "get_Item(int)"); ::g::Uno::Data::Json::Value* ret2; return (::g::Uno::Collections::List__get_Item_fn(uPtr(_values), uCRef<int32_t>(index), &ret2), ret2); } // public generated Array New() [static] :90 Array* Array::New1() { Array* obj1 = (Array*)uNew(Array_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonValue.uno // ------------------------------------------------------------------------------------------- // internal abstract class AtomicValue<T> :17 // { static void AtomicValue_build(uType* type) { type->SetFields(0, type->T(0), (uintptr_t)0, uFieldFlagsConstrained); } uType* AtomicValue_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Data::Json::Value_typeof(); options.FieldCount = 1; options.GenericCount = 1; options.ObjectSize = sizeof(AtomicValue); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.AtomicValue`1", options); type->fp_build_ = AtomicValue_build; type->fp_ToString = (void(*)(uObject*, uString**))AtomicValue__ToString_fn; return type; } // protected AtomicValue(T val) :22 void AtomicValue__ctor_1_fn(AtomicValue* __this, void* val) { __this->ctor_(); __this->_val() = val; } // public override sealed string ToString() :27 void AtomicValue__ToString_fn(AtomicValue* __this, uString** __retval) { uStackFrame __("Uno.Data.Json.AtomicValue`1", "ToString()"); return *__retval = ::g::Uno::Object::ToString(uBoxPtr(__this->__type->GetBase(AtomicValue_typeof())->T(0), uPtr(__this->_val()), U_ALLOCA(__this->__type->GetBase(AtomicValue_typeof())->T(0)->ObjectSize))), void(); } // public T get_Value() :20 void AtomicValue__get_Value_fn(AtomicValue* __this, uTRef __retval) { return __retval.Store(__this->_val()), void(); } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonValue.uno // ------------------------------------------------------------------------------------------- // internal sealed class Boolean :33 // { // static generated Boolean() :33 static void Boolean__cctor__fn(uType* __type) { Boolean::True_ = Boolean::New1(true); Boolean::False_ = Boolean::New1(false); } static void Boolean_build(uType* type) { type->SetBase(::g::Uno::Data::Json::AtomicValue_typeof()->MakeType(::g::Uno::Bool_typeof(), NULL)); type->SetFields(1, type, (uintptr_t)&Boolean::True_, uFieldFlagsStatic, type, (uintptr_t)&Boolean::False_, uFieldFlagsStatic); } uType* Boolean_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Data::Json::AtomicValue_typeof(); options.FieldCount = 3; options.ObjectSize = sizeof(Boolean); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.Boolean", options); type->fp_build_ = Boolean_build; type->fp_cctor_ = Boolean__cctor__fn; return type; } // private Boolean(bool b) :35 void Boolean__ctor_2_fn(Boolean* __this, bool* b) { __this->ctor_2(*b); } // private Boolean New(bool b) :35 void Boolean__New1_fn(bool* b, Boolean** __retval) { *__retval = Boolean::New1(*b); } uSStrong<Boolean*> Boolean::True_; uSStrong<Boolean*> Boolean::False_; // private Boolean(bool b) [instance] :35 void Boolean::ctor_2(bool b) { ::g::Uno::Data::Json::AtomicValue__ctor_1_fn(this, uCRef(b)); } // private Boolean New(bool b) [static] :35 Boolean* Boolean::New1(bool b) { Boolean* obj1 = (Boolean*)uNew(Boolean_typeof()); obj1->ctor_2(b); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonDataType.uno // ---------------------------------------------------------------------------------------------- // public enum JsonDataType :3 uEnumType* JsonDataType_typeof() { static uSStrong<uEnumType*> type; if (type != NULL) return type; type = uEnumType::New("Uno.Data.Json.JsonDataType", ::g::Uno::Int_typeof(), 7); type->SetLiterals( "Error", -1LL, "Null", 0LL, "Number", 1LL, "String", 2LL, "Boolean", 3LL, "Array", 4LL, "Object", 5LL); return type; } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonException.uno // ----------------------------------------------------------------------------------------------- // public sealed class JsonException :3 // { static void JsonException_build(uType* type) { type->SetFields(4); } ::g::Uno::Exception_type* JsonException_typeof() { static uSStrong< ::g::Uno::Exception_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Exception_typeof(); options.FieldCount = 4; options.ObjectSize = sizeof(JsonException); options.TypeSize = sizeof(::g::Uno::Exception_type); type = (::g::Uno::Exception_type*)uClassType::New("Uno.Data.Json.JsonException", options); type->fp_build_ = JsonException_build; return type; } // internal JsonException(string message) :5 void JsonException__ctor_3_fn(JsonException* __this, uString* message) { __this->ctor_3(message); } // internal JsonException New(string message) :5 void JsonException__New4_fn(uString* message, JsonException** __retval) { *__retval = JsonException::New4(message); } // internal JsonException(string message) [instance] :5 void JsonException::ctor_3(uString* message) { ctor_1(message); } // internal JsonException New(string message) [static] :5 JsonException* JsonException::New4(uString* message) { JsonException* obj1 = (JsonException*)uNew(JsonException_typeof()); obj1->ctor_3(message); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonReader.uno // -------------------------------------------------------------------------------------------- // public sealed class JsonReader :8 // { static void JsonReader_build(uType* type) { ::STRINGS[0] = uString::Const("Json node is not an array"); ::TYPES[1] = ::g::Uno::Data::Json::Boolean_typeof(); ::TYPES[2] = ::g::Uno::Data::Json::Number_typeof(); ::TYPES[3] = ::g::Uno::Data::Json::String_typeof(); ::TYPES[4] = ::g::Uno::Data::Json::Object_typeof(); ::TYPES[5] = ::g::Uno::Data::Json::Array_typeof(); ::TYPES[6] = ::g::Uno::Data::Json::Null_typeof(); ::TYPES[7] = ::g::Uno::String_typeof()->Array(); type->SetFields(0, ::g::Uno::Data::Json::Value_typeof(), offsetof(JsonReader, _value), 0); type->Reflection.SetFunctions(9, new uFunction("AsBool", NULL, (void*)JsonReader__AsBool_fn, 0, false, ::g::Uno::Bool_typeof(), 0), new uFunction("AsNumber", NULL, (void*)JsonReader__AsNumber_fn, 0, false, ::g::Uno::Double_typeof(), 0), new uFunction("AsString", NULL, (void*)JsonReader__AsString_fn, 0, false, ::g::Uno::String_typeof(), 0), new uFunction("get_Count", NULL, (void*)JsonReader__get_Count_fn, 0, false, ::g::Uno::Int_typeof(), 0), new uFunction("get_Item", NULL, (void*)JsonReader__get_Item_fn, 0, false, type, 1, ::g::Uno::Int_typeof()), new uFunction("get_Item", NULL, (void*)JsonReader__get_Item1_fn, 0, false, type, 1, ::g::Uno::String_typeof()), new uFunction("get_JsonDataType", NULL, (void*)JsonReader__get_JsonDataType_fn, 0, false, ::g::Uno::Data::Json::JsonDataType_typeof(), 0), new uFunction("get_Keys", NULL, (void*)JsonReader__get_Keys_fn, 0, false, ::TYPES[7/*string[]*/], 0), new uFunction("Parse", NULL, (void*)JsonReader__Parse_fn, 0, true, type, 1, ::g::Uno::String_typeof())); } uType* JsonReader_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 1; options.ObjectSize = sizeof(JsonReader); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.JsonReader", options); type->fp_build_ = JsonReader_build; return type; } // private JsonReader(Uno.Data.Json.Value value) :12 void JsonReader__ctor__fn(JsonReader* __this, ::g::Uno::Data::Json::Value* value) { __this->ctor_(value); } // public bool AsBool() :109 void JsonReader__AsBool_fn(JsonReader* __this, bool* __retval) { *__retval = __this->AsBool(); } // public double AsNumber() :104 void JsonReader__AsNumber_fn(JsonReader* __this, double* __retval) { *__retval = __this->AsNumber(); } // public string AsString() :99 void JsonReader__AsString_fn(JsonReader* __this, uString** __retval) { *__retval = __this->AsString(); } // public int get_Count() :76 void JsonReader__get_Count_fn(JsonReader* __this, int32_t* __retval) { *__retval = __this->Count(); } // public Uno.Data.Json.JsonReader get_Item(int index) :32 void JsonReader__get_Item_fn(JsonReader* __this, int32_t* index, JsonReader** __retval) { *__retval = __this->Item(*index); } // public Uno.Data.Json.JsonReader get_Item(string key) :19 void JsonReader__get_Item1_fn(JsonReader* __this, uString* key, JsonReader** __retval) { *__retval = __this->Item1(key); } // public Uno.Data.Json.JsonDataType get_JsonDataType() :61 void JsonReader__get_JsonDataType_fn(JsonReader* __this, int32_t* __retval) { *__retval = __this->JsonDataType(); } // public string[] get_Keys() :44 void JsonReader__get_Keys_fn(JsonReader* __this, uArray** __retval) { *__retval = __this->Keys(); } // private JsonReader New(Uno.Data.Json.Value value) :12 void JsonReader__New1_fn(::g::Uno::Data::Json::Value* value, JsonReader** __retval) { *__retval = JsonReader::New1(value); } // public static explicit operator string(Uno.Data.Json.JsonReader value) :114 void JsonReader__op_Explicit1_fn(JsonReader* value, uString** __retval) { *__retval = JsonReader::op_Explicit1(value); } // public static explicit operator bool(Uno.Data.Json.JsonReader value) :124 void JsonReader__op_Explicit3_fn(JsonReader* value, bool* __retval) { *__retval = JsonReader::op_Explicit3(value); } // public static Uno.Data.Json.JsonReader Parse(string json) :54 void JsonReader__Parse_fn(uString* json, JsonReader** __retval) { *__retval = JsonReader::Parse(json); } // private JsonReader(Uno.Data.Json.Value value) [instance] :12 void JsonReader::ctor_(::g::Uno::Data::Json::Value* value) { _value = value; } // public bool AsBool() [instance] :109 bool JsonReader::AsBool() { uStackFrame __("Uno.Data.Json.JsonReader", "AsBool()"); bool ret2; return (::g::Uno::Data::Json::AtomicValue__get_Value_fn(uPtr(uCast< ::g::Uno::Data::Json::Boolean*>(_value, ::TYPES[1/*Uno.Data.Json.Boolean*/])), &ret2), ret2); } // public double AsNumber() [instance] :104 double JsonReader::AsNumber() { uStackFrame __("Uno.Data.Json.JsonReader", "AsNumber()"); double ret3; return (::g::Uno::Data::Json::AtomicValue__get_Value_fn(uPtr(uCast< ::g::Uno::Data::Json::Number*>(_value, ::TYPES[2/*Uno.Data.Json.Number*/])), &ret3), ret3); } // public string AsString() [instance] :99 uString* JsonReader::AsString() { uStackFrame __("Uno.Data.Json.JsonReader", "AsString()"); uString* ret4; return (::g::Uno::Data::Json::AtomicValue__get_Value_fn(uPtr(uCast< ::g::Uno::Data::Json::String*>(_value, ::TYPES[3/*Uno.Data.Json.String*/])), &ret4), ret4); } // public int get_Count() [instance] :76 int32_t JsonReader::Count() { uStackFrame __("Uno.Data.Json.JsonReader", "get_Count()"); ::g::Uno::Data::Json::Object* obj = uAs< ::g::Uno::Data::Json::Object*>(_value, ::TYPES[4/*Uno.Data.Json.Object*/]); if (obj != NULL) return uPtr(obj)->Count(); ::g::Uno::Data::Json::Array* array = uAs< ::g::Uno::Data::Json::Array*>(_value, ::TYPES[5/*Uno.Data.Json.Array*/]); if (array != NULL) return uPtr(array)->Count(); return 0; } // public Uno.Data.Json.JsonReader get_Item(int index) [instance] :32 JsonReader* JsonReader::Item(int32_t index) { uStackFrame __("Uno.Data.Json.JsonReader", "get_Item(int)"); ::g::Uno::Data::Json::Array* array = uAs< ::g::Uno::Data::Json::Array*>(_value, ::TYPES[5/*Uno.Data.Json.Array*/]); if (array == NULL) U_THROW(::g::Uno::Exception::New2(::STRINGS[0/*"Json node i...*/])); return JsonReader::New1(uPtr(array)->Item(index)); } // public Uno.Data.Json.JsonReader get_Item(string key) [instance] :19 JsonReader* JsonReader::Item1(uString* key) { uStackFrame __("Uno.Data.Json.JsonReader", "get_Item(string)"); ::g::Uno::Data::Json::Object* obj = uAs< ::g::Uno::Data::Json::Object*>(_value, ::TYPES[4/*Uno.Data.Json.Object*/]); if ((obj == NULL) || !uPtr(obj)->ContainsKey(key)) return NULL; return JsonReader::New1(uPtr(obj)->Item(key)); } // public Uno.Data.Json.JsonDataType get_JsonDataType() [instance] :61 int32_t JsonReader::JsonDataType() { if (uIs((::g::Uno::Data::Json::Value*)_value, ::TYPES[2/*Uno.Data.Json.Number*/])) return 1; if (uIs((::g::Uno::Data::Json::Value*)_value, ::TYPES[1/*Uno.Data.Json.Boolean*/])) return 3; if (uIs((::g::Uno::Data::Json::Value*)_value, ::TYPES[3/*Uno.Data.Json.String*/])) return 2; if (uIs((::g::Uno::Data::Json::Value*)_value, ::TYPES[5/*Uno.Data.Json.Array*/])) return 4; if (uIs((::g::Uno::Data::Json::Value*)_value, ::TYPES[4/*Uno.Data.Json.Object*/])) return 5; if (uIs((::g::Uno::Data::Json::Value*)_value, ::TYPES[6/*Uno.Data.Json.Null*/])) return 0; return -1; } // public string[] get_Keys() [instance] :44 uArray* JsonReader::Keys() { uStackFrame __("Uno.Data.Json.JsonReader", "get_Keys()"); ::g::Uno::Data::Json::Object* obj = uAs< ::g::Uno::Data::Json::Object*>(_value, ::TYPES[4/*Uno.Data.Json.Object*/]); if (obj == NULL) return uArray::New(::TYPES[7/*string[]*/], 0); return uPtr(obj)->Keys(); } // private JsonReader New(Uno.Data.Json.Value value) [static] :12 JsonReader* JsonReader::New1(::g::Uno::Data::Json::Value* value) { JsonReader* obj1 = (JsonReader*)uNew(JsonReader_typeof()); obj1->ctor_(value); return obj1; } // public static explicit operator string(Uno.Data.Json.JsonReader value) [static] :114 uString* JsonReader::op_Explicit1(JsonReader* value) { uStackFrame __("Uno.Data.Json.JsonReader", "op_Explicit(Uno.Data.Json.JsonReader)~string"); return uPtr(value)->AsString(); } // public static explicit operator bool(Uno.Data.Json.JsonReader value) [static] :124 bool JsonReader::op_Explicit3(JsonReader* value) { uStackFrame __("Uno.Data.Json.JsonReader", "op_Explicit(Uno.Data.Json.JsonReader)~bool"); return uPtr(value)->AsBool(); } // public static Uno.Data.Json.JsonReader Parse(string json) [static] :54 JsonReader* JsonReader::Parse(uString* json) { uStackFrame __("Uno.Data.Json.JsonReader", "Parse(string)"); return JsonReader::New1(::g::Uno::Data::Json::Parser::Parse(::g::Uno::IO::StringReader::New1(json))); } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonWriter.uno // -------------------------------------------------------------------------------------------- // public static class JsonWriter :5 // { static void JsonWriter_build(uType* type) { ::STRINGS[1] = uString::Const("\\\""); ::STRINGS[2] = uString::Const("\\\\"); ::STRINGS[3] = uString::Const("\\b"); ::STRINGS[4] = uString::Const("\\f"); ::STRINGS[5] = uString::Const("\\n"); ::STRINGS[6] = uString::Const("\\r"); ::STRINGS[7] = uString::Const("\\t"); ::STRINGS[8] = uString::Const("\\u{0:x4}"); ::STRINGS[9] = uString::Const("\""); ::TYPES[8] = uObject_typeof()->Array(); type->Reflection.SetFunctions(1, new uFunction("QuoteString", NULL, (void*)JsonWriter__QuoteString_fn, 0, true, ::g::Uno::String_typeof(), 1, ::g::Uno::String_typeof())); } uClassType* JsonWriter_typeof() { static uSStrong<uClassType*> type; if (type != NULL) return type; uTypeOptions options; options.TypeSize = sizeof(uClassType); type = uClassType::New("Uno.Data.Json.JsonWriter", options); type->fp_build_ = JsonWriter_build; return type; } // private static void EscapeString(string str, Uno.Text.StringBuilder sb) :33 void JsonWriter__EscapeString1_fn(uString* str, ::g::Uno::Text::StringBuilder* sb) { JsonWriter::EscapeString1(str, sb); } // public static string QuoteString(string str) :12 void JsonWriter__QuoteString_fn(uString* str, uString** __retval) { *__retval = JsonWriter::QuoteString(str); } // private static void EscapeString(string str, Uno.Text.StringBuilder sb) [static] :33 void JsonWriter::EscapeString1(uString* str, ::g::Uno::Text::StringBuilder* sb) { uStackFrame __("Uno.Data.Json.JsonWriter", "EscapeString(string,Uno.Text.StringBuilder)"); for (int32_t i = 0; i < uPtr(str)->Length(); ++i) { char16_t ch = uPtr(str)->Item(i); switch (ch) { case '"': { uPtr(sb)->Append2(::STRINGS[1/*"\\\""*/]); break; } case '\\': { uPtr(sb)->Append2(::STRINGS[2/*"\\\\"*/]); break; } case 8: { uPtr(sb)->Append2(::STRINGS[3/*"\\b"*/]); break; } case 12: { uPtr(sb)->Append2(::STRINGS[4/*"\\f"*/]); break; } case 10: { uPtr(sb)->Append2(::STRINGS[5/*"\\n"*/]); break; } case 13: { uPtr(sb)->Append2(::STRINGS[6/*"\\r"*/]); break; } case 9: { uPtr(sb)->Append2(::STRINGS[7/*"\\t"*/]); break; } default: { if ((int32_t)ch <= 31) uPtr(sb)->Append2(::g::Uno::String::Format(::STRINGS[8/*"\\u{0:x4}"*/], uArray::Init<uObject*>(::TYPES[8/*object[]*/], 1, uBox<int32_t>(::g::Uno::Int_typeof(), (int32_t)ch)))); else uPtr(sb)->Append(ch); break; } } } } // public static string QuoteString(string str) [static] :12 uString* JsonWriter::QuoteString(uString* str) { uStackFrame __("Uno.Data.Json.JsonWriter", "QuoteString(string)"); ::g::Uno::Text::StringBuilder* sb = ::g::Uno::Text::StringBuilder::New1(); sb->Append2(::STRINGS[9/*"\""*/]); JsonWriter::EscapeString1(str, sb); sb->Append2(::STRINGS[9/*"\""*/]); return sb->ToString(); } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonValue.uno // ------------------------------------------------------------------------------------------- // internal sealed class Null :10 // { // static generated Null() :10 static void Null__cctor__fn(uType* __type) { Null::Singleton_ = Null::New1(); } static void Null_build(uType* type) { type->SetFields(0, type, (uintptr_t)&Null::Singleton_, uFieldFlagsStatic); } uType* Null_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Data::Json::Value_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(Null); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.Null", options); type->fp_build_ = Null_build; type->fp_ctor_ = (void*)Null__New1_fn; type->fp_cctor_ = Null__cctor__fn; return type; } // private Null() :12 void Null__ctor_1_fn(Null* __this) { __this->ctor_1(); } // private Null New() :12 void Null__New1_fn(Null** __retval) { *__retval = Null::New1(); } uSStrong<Null*> Null::Singleton_; // private Null() [instance] :12 void Null::ctor_1() { ctor_(); } // private Null New() [static] :12 Null* Null::New1() { Null* obj1 = (Null*)uNew(Null_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonValue.uno // ------------------------------------------------------------------------------------------- // internal sealed class Number :41 // { static void Number_build(uType* type) { type->SetBase(::g::Uno::Data::Json::AtomicValue_typeof()->MakeType(::g::Uno::Double_typeof(), NULL)); type->SetFields(1); } uType* Number_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Data::Json::AtomicValue_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(Number); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.Number", options); type->fp_build_ = Number_build; return type; } // public Number(double d) :43 void Number__ctor_2_fn(Number* __this, double* d) { __this->ctor_2(*d); } // public Number New(double d) :43 void Number__New1_fn(double* d, Number** __retval) { *__retval = Number::New1(*d); } // public Number(double d) [instance] :43 void Number::ctor_2(double d) { ::g::Uno::Data::Json::AtomicValue__ctor_1_fn(this, uCRef(d)); } // public Number New(double d) [static] :43 Number* Number::New1(double d) { Number* obj1 = (Number*)uNew(Number_typeof()); obj1->ctor_2(d); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonValue.uno // ------------------------------------------------------------------------------------------- // internal sealed class Object :51 // { static void Object_build(uType* type) { ::TYPES[9] = ::g::Uno::Collections::Dictionary_typeof()->MakeType(::g::Uno::String_typeof(), ::g::Uno::Data::Json::Value_typeof(), NULL); ::TYPES[10] = ::g::Uno::Collections::EnumerableExtensions_typeof()->MakeMethod(9/*ToArray<string>*/, ::g::Uno::String_typeof(), NULL); type->SetFields(0, ::TYPES[9/*Uno.Collections.Dictionary<string, Uno.Data.Json.Value>*/], offsetof(Object, _values), 0); } uType* Object_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Data::Json::Value_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(Object); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.Object", options); type->fp_build_ = Object_build; type->fp_ctor_ = (void*)Object__New1_fn; return type; } // public generated Object() :51 void Object__ctor_1_fn(Object* __this) { __this->ctor_1(); } // public void Add(string key, Uno.Data.Json.Value val) :76 void Object__Add_fn(Object* __this, uString* key, ::g::Uno::Data::Json::Value* val) { __this->Add(key, val); } // public bool ContainsKey(string key) :84 void Object__ContainsKey_fn(Object* __this, uString* key, bool* __retval) { *__retval = __this->ContainsKey(key); } // public int get_Count() :65 void Object__get_Count_fn(Object* __this, int32_t* __retval) { *__retval = __this->Count(); } // public Uno.Data.Json.Value get_Item(string key) :70 void Object__get_Item_fn(Object* __this, uString* key, ::g::Uno::Data::Json::Value** __retval) { *__retval = __this->Item(key); } // public string[] get_Keys() :57 void Object__get_Keys_fn(Object* __this, uArray** __retval) { *__retval = __this->Keys(); } // public generated Object New() :51 void Object__New1_fn(Object** __retval) { *__retval = Object::New1(); } // public generated Object() [instance] :51 void Object::ctor_1() { _values = ((::g::Uno::Collections::Dictionary*)::g::Uno::Collections::Dictionary::New1(::TYPES[9/*Uno.Collections.Dictionary<string, Uno.Data.Json.Value>*/])); ctor_(); } // public void Add(string key, Uno.Data.Json.Value val) [instance] :76 void Object::Add(uString* key, ::g::Uno::Data::Json::Value* val) { uStackFrame __("Uno.Data.Json.Object", "Add(string,Uno.Data.Json.Value)"); bool ret2; if ((::g::Uno::Collections::Dictionary__ContainsKey_fn(uPtr(_values), key, &ret2), ret2)) ::g::Uno::Collections::Dictionary__set_Item_fn(uPtr(_values), key, val); else ::g::Uno::Collections::Dictionary__Add_fn(uPtr(_values), key, val); } // public bool ContainsKey(string key) [instance] :84 bool Object::ContainsKey(uString* key) { uStackFrame __("Uno.Data.Json.Object", "ContainsKey(string)"); bool ret3; return (::g::Uno::Collections::Dictionary__ContainsKey_fn(uPtr(_values), key, &ret3), ret3); } // public int get_Count() [instance] :65 int32_t Object::Count() { uStackFrame __("Uno.Data.Json.Object", "get_Count()"); return uPtr(_values)->Count(); } // public Uno.Data.Json.Value get_Item(string key) [instance] :70 ::g::Uno::Data::Json::Value* Object::Item(uString* key) { uStackFrame __("Uno.Data.Json.Object", "get_Item(string)"); ::g::Uno::Data::Json::Value* ret4; return (::g::Uno::Collections::Dictionary__get_Item_fn(uPtr(_values), key, &ret4), ret4); } // public string[] get_Keys() [instance] :57 uArray* Object::Keys() { uStackFrame __("Uno.Data.Json.Object", "get_Keys()"); return (uArray*)::g::Uno::Collections::EnumerableExtensions::ToArray(::TYPES[10/*Uno.Collections.EnumerableExtensions.ToArray<string>*/], (uObject*)((::g::Uno::Collections::Dictionary__KeyCollection*)uPtr(_values)->Keys())); } // public generated Object New() [static] :51 Object* Object::New1() { Object* obj1 = (Object*)uNew(Object_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\Parser.uno // ---------------------------------------------------------------------------------------- // internal sealed class Parser :8 // { static void Parser_build(uType* type) { ::STRINGS[10] = uString::Const("Expected end of file"); ::STRINGS[11] = uString::Const("false"); ::STRINGS[12] = uString::Const("null"); ::STRINGS[13] = uString::Const("Expected ':'"); ::STRINGS[14] = uString::Const("true"); ::STRINGS[15] = uString::Const("Unexpected character: "); ::STRINGS[16] = uString::Const("Unexpected end of file"); type->SetDependencies( ::g::Uno::Data::Json::Boolean_typeof(), ::g::Uno::Data::Json::Null_typeof()); type->SetFields(0, ::g::Uno::IO::TextReader_typeof(), offsetof(Parser, _json), 0); } uType* Parser_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 1; options.DependencyCount = 2; options.ObjectSize = sizeof(Parser); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.Parser", options); type->fp_build_ = Parser_build; return type; } // private Parser(Uno.IO.TextReader json) :12 void Parser__ctor__fn(Parser* __this, ::g::Uno::IO::TextReader* json) { __this->ctor_(json); } // private void Advance() :308 void Parser__Advance_fn(Parser* __this) { __this->Advance(); } // private char Consume() :299 void Parser__Consume_fn(Parser* __this, char16_t* __retval) { *__retval = __this->Consume(); } // private bool Eof() :265 void Parser__Eof_fn(Parser* __this, bool* __retval) { *__retval = __this->Eof(); } // private static uint GetHexValue(char hexChar) :257 void Parser__GetHexValue_fn(char16_t* hexChar, uint32_t* __retval) { *__retval = Parser::GetHexValue(*hexChar); } // private static bool IsHexValue(char ch) :250 void Parser__IsHexValue_fn(char16_t* ch, bool* __retval) { *__retval = Parser::IsHexValue(*ch); } // private bool IsNumericStartChar(char c) :125 void Parser__IsNumericStartChar_fn(Parser* __this, char16_t* c, bool* __retval) { *__retval = __this->IsNumericStartChar(*c); } // private Parser New(Uno.IO.TextReader json) :12 void Parser__New1_fn(::g::Uno::IO::TextReader* json, Parser** __retval) { *__retval = Parser::New1(json); } // public static Uno.Data.Json.Value Parse(Uno.IO.TextReader json) :17 void Parser__Parse_fn(::g::Uno::IO::TextReader* json, ::g::Uno::Data::Json::Value** __retval) { *__retval = Parser::Parse(json); } // private Uno.Data.Json.Array ParseArray() :130 void Parser__ParseArray_fn(Parser* __this, ::g::Uno::Data::Json::Array** __retval) { *__retval = __this->ParseArray(); } // private Uno.Data.Json.Boolean ParseFalse() :59 void Parser__ParseFalse_fn(Parser* __this, ::g::Uno::Data::Json::Boolean** __retval) { *__retval = __this->ParseFalse(); } // private void ParseKeyword(string keyword) :49 void Parser__ParseKeyword_fn(Parser* __this, uString* keyword) { __this->ParseKeyword(keyword); } // private Uno.Data.Json.Null ParseNull() :71 void Parser__ParseNull_fn(Parser* __this, ::g::Uno::Data::Json::Null** __retval) { *__retval = __this->ParseNull(); } // private Uno.Data.Json.Number ParseNumber() :77 void Parser__ParseNumber_fn(Parser* __this, ::g::Uno::Data::Json::Number** __retval) { *__retval = __this->ParseNumber(); } // private Uno.Data.Json.Object ParseObject() :155 void Parser__ParseObject_fn(Parser* __this, ::g::Uno::Data::Json::Object** __retval) { *__retval = __this->ParseObject(); } // private string ParseRawString() :192 void Parser__ParseRawString_fn(Parser* __this, uString** __retval) { *__retval = __this->ParseRawString(); } // private Uno.Data.Json.String ParseString() :187 void Parser__ParseString_fn(Parser* __this, ::g::Uno::Data::Json::String** __retval) { *__retval = __this->ParseString(); } // private Uno.Data.Json.Boolean ParseTrue() :65 void Parser__ParseTrue_fn(Parser* __this, ::g::Uno::Data::Json::Boolean** __retval) { *__retval = __this->ParseTrue(); } // private Uno.Data.Json.Value ParseValue() :26 void Parser__ParseValue_fn(Parser* __this, ::g::Uno::Data::Json::Value** __retval) { *__retval = __this->ParseValue(); } // private char Peek() :290 void Parser__Peek_fn(Parser* __this, char16_t* __retval) { *__retval = __this->Peek(); } // private void SkipWhiteSpace() :270 void Parser__SkipWhiteSpace_fn(Parser* __this) { __this->SkipWhiteSpace(); } // private static Uno.Data.Json.JsonException UnexpectedCharacter(char c) :318 void Parser__UnexpectedCharacter_fn(char16_t* c, ::g::Uno::Data::Json::JsonException** __retval) { *__retval = Parser::UnexpectedCharacter(*c); } // private static Uno.Data.Json.JsonException UnexpectedEndOfFile() :313 void Parser__UnexpectedEndOfFile_fn(::g::Uno::Data::Json::JsonException** __retval) { *__retval = Parser::UnexpectedEndOfFile(); } // private Parser(Uno.IO.TextReader json) [instance] :12 void Parser::ctor_(::g::Uno::IO::TextReader* json) { _json = json; } // private void Advance() [instance] :308 void Parser::Advance() { uStackFrame __("Uno.Data.Json.Parser", "Advance()"); uPtr(_json)->Read(); } // private char Consume() [instance] :299 char16_t Parser::Consume() { uStackFrame __("Uno.Data.Json.Parser", "Consume()"); int32_t ret = uPtr(_json)->Read(); if (ret < 0) U_THROW(Parser::UnexpectedEndOfFile()); return (char16_t)ret; } // private bool Eof() [instance] :265 bool Parser::Eof() { uStackFrame __("Uno.Data.Json.Parser", "Eof()"); return uPtr(_json)->Peek() < 0; } // private bool IsNumericStartChar(char c) [instance] :125 bool Parser::IsNumericStartChar(char16_t c) { return ::g::Uno::Char::IsDigit(c) || (c == '-'); } // private Uno.Data.Json.Array ParseArray() [instance] :130 ::g::Uno::Data::Json::Array* Parser::ParseArray() { uStackFrame __("Uno.Data.Json.Parser", "ParseArray()"); Advance(); ::g::Uno::Data::Json::Array* a = ::g::Uno::Data::Json::Array::New1(); while (!Eof()) { SkipWhiteSpace(); char16_t c = Peek(); if (c == ']') { Advance(); return a; } ::g::Uno::Data::Json::Value* v = ParseValue(); uPtr(a)->Add(v); SkipWhiteSpace(); c = Peek(); if (c == ',') { Advance(); continue; } else if (c == ']') { Advance(); return a; } else U_THROW(Parser::UnexpectedCharacter(c)); } U_THROW(Parser::UnexpectedEndOfFile()); } // private Uno.Data.Json.Boolean ParseFalse() [instance] :59 ::g::Uno::Data::Json::Boolean* Parser::ParseFalse() { uStackFrame __("Uno.Data.Json.Parser", "ParseFalse()"); ParseKeyword(::STRINGS[11/*"false"*/]); return ::g::Uno::Data::Json::Boolean::False(); } // private void ParseKeyword(string keyword) [instance] :49 void Parser::ParseKeyword(uString* keyword) { uStackFrame __("Uno.Data.Json.Parser", "ParseKeyword(string)"); for (int32_t i = 0; i < uPtr(keyword)->Length(); ++i) { char16_t ch = Consume(); if (uPtr(keyword)->Item(i) != ch) U_THROW(Parser::UnexpectedCharacter(ch)); } } // private Uno.Data.Json.Null ParseNull() [instance] :71 ::g::Uno::Data::Json::Null* Parser::ParseNull() { uStackFrame __("Uno.Data.Json.Parser", "ParseNull()"); ParseKeyword(::STRINGS[12/*"null"*/]); return ::g::Uno::Data::Json::Null::Singleton(); } // private Uno.Data.Json.Number ParseNumber() [instance] :77 ::g::Uno::Data::Json::Number* Parser::ParseNumber() { uStackFrame __("Uno.Data.Json.Parser", "ParseNumber()"); ::g::Uno::Text::StringBuilder* sb = ::g::Uno::Text::StringBuilder::New1(); if (Peek() == '-') uPtr(sb)->Append(Consume()); char16_t c = Peek(); if (!::g::Uno::Char::IsDigit(c)) U_THROW(Parser::UnexpectedCharacter(c)); sb->Append(c); Advance(); if (c != '0') while (!Eof() && ::g::Uno::Char::IsDigit(Peek())) uPtr(sb)->Append(Consume()); if (!Eof() && (Peek() == '.')) { uPtr(sb)->Append(Consume()); if (!::g::Uno::Char::IsDigit(Peek())) U_THROW(Parser::UnexpectedCharacter(Peek())); while (!Eof() && ::g::Uno::Char::IsDigit(Peek())) uPtr(sb)->Append(Consume()); } if (!Eof() && (::g::Uno::Char::ToLower(Peek()) == 'e')) { uPtr(sb)->Append(Consume()); if ((Peek() == '+') || (Peek() == '-')) uPtr(sb)->Append(Consume()); if (!::g::Uno::Char::IsDigit(Peek())) U_THROW(Parser::UnexpectedCharacter(Peek())); while (!Eof() && ::g::Uno::Char::IsDigit(Peek())) uPtr(sb)->Append(Consume()); } return ::g::Uno::Data::Json::Number::New1(::g::Uno::Double::Parse(sb->ToString())); } // private Uno.Data.Json.Object ParseObject() [instance] :155 ::g::Uno::Data::Json::Object* Parser::ParseObject() { uStackFrame __("Uno.Data.Json.Parser", "ParseObject()"); Advance(); ::g::Uno::Data::Json::Object* obj = ::g::Uno::Data::Json::Object::New1(); while (!Eof()) { SkipWhiteSpace(); char16_t c = Peek(); if (c == '}') { Advance(); return obj; } uString* key = ParseRawString(); SkipWhiteSpace(); c = Peek(); if (c != ':') U_THROW(::g::Uno::Exception::New2(::STRINGS[13/*"Expected ':'"*/])); Advance(); ::g::Uno::Data::Json::Value* val = ParseValue(); uPtr(obj)->Add(key, val); SkipWhiteSpace(); c = Peek(); if (c == ',') { Advance(); continue; } else if (c == '}') { Advance(); return obj; } else U_THROW(Parser::UnexpectedCharacter(c)); } U_THROW(Parser::UnexpectedEndOfFile()); } // private string ParseRawString() [instance] :192 uString* Parser::ParseRawString() { uStackFrame __("Uno.Data.Json.Parser", "ParseRawString()"); char16_t ch = Consume(); if (ch != '"') U_THROW(Parser::UnexpectedCharacter(ch)); ::g::Uno::Text::StringBuilder* sb = ::g::Uno::Text::StringBuilder::New1(); ch = Consume(); while (ch != '"') { if (ch == '\\') { char16_t ch2 = Consume(); switch (ch2) { case '\\': { uPtr(sb)->Append('\\'); break; } case '/': { uPtr(sb)->Append('/'); break; } case '"': { uPtr(sb)->Append('"'); break; } case 'n': { uPtr(sb)->Append(10); break; } case 'r': { uPtr(sb)->Append(13); break; } case 't': { uPtr(sb)->Append(9); break; } case 'b': { uPtr(sb)->Append(8); break; } case 'f': { uPtr(sb)->Append(12); break; } case 'u': { uint32_t value = 0U; for (int32_t i = 0; i < 4; ++i) { char16_t ch3 = Consume(); if (!Parser::IsHexValue(ch3)) U_THROW(Parser::UnexpectedCharacter(ch3)); value = (value << 4) | Parser::GetHexValue(ch3); } uPtr(sb)->Append((char16_t)value); break; } default: { uPtr(sb)->Append(ch); sb->Append(ch2); break; } } } else uPtr(sb)->Append(ch); ch = Consume(); } return sb->ToString(); } // private Uno.Data.Json.String ParseString() [instance] :187 ::g::Uno::Data::Json::String* Parser::ParseString() { uStackFrame __("Uno.Data.Json.Parser", "ParseString()"); return ::g::Uno::Data::Json::String::New1(ParseRawString()); } // private Uno.Data.Json.Boolean ParseTrue() [instance] :65 ::g::Uno::Data::Json::Boolean* Parser::ParseTrue() { uStackFrame __("Uno.Data.Json.Parser", "ParseTrue()"); ParseKeyword(::STRINGS[14/*"true"*/]); return ::g::Uno::Data::Json::Boolean::True(); } // private Uno.Data.Json.Value ParseValue() [instance] :26 ::g::Uno::Data::Json::Value* Parser::ParseValue() { uStackFrame __("Uno.Data.Json.Parser", "ParseValue()"); if (Eof()) return ::g::Uno::Data::Json::Null::Singleton(); SkipWhiteSpace(); char16_t c = Peek(); switch (c) { case '"': return ParseString(); case '{': return ParseObject(); case '[': return ParseArray(); case 'f': return ParseFalse(); case 't': return ParseTrue(); case 'n': return ParseNull(); default: { if (IsNumericStartChar(c)) return ParseNumber(); U_THROW(Parser::UnexpectedCharacter(c)); } } } // private char Peek() [instance] :290 char16_t Parser::Peek() { uStackFrame __("Uno.Data.Json.Parser", "Peek()"); int32_t ret = uPtr(_json)->Peek(); if (ret < 0) U_THROW(Parser::UnexpectedEndOfFile()); return (char16_t)ret; } // private void SkipWhiteSpace() [instance] :270 void Parser::SkipWhiteSpace() { uStackFrame __("Uno.Data.Json.Parser", "SkipWhiteSpace()"); while (!Eof()) { char16_t c = Peek(); switch (c) { case ' ': case 9: case 10: case 13: { Advance(); break; } default: return; } } } // private static uint GetHexValue(char hexChar) [static] :257 uint32_t Parser::GetHexValue(char16_t hexChar) { if ((uint32_t)hexChar >= 65U) return (uint32_t)hexChar - 55U; else return (uint32_t)hexChar - 48U; } // private static bool IsHexValue(char ch) [static] :250 bool Parser::IsHexValue(char16_t ch) { return (((ch >= '0') && (ch <= '9')) || ((ch >= 'a') && (ch <= 'f'))) || ((ch >= 'A') && (ch <= 'F')); } // private Parser New(Uno.IO.TextReader json) [static] :12 Parser* Parser::New1(::g::Uno::IO::TextReader* json) { Parser* obj1 = (Parser*)uNew(Parser_typeof()); obj1->ctor_(json); return obj1; } // public static Uno.Data.Json.Value Parse(Uno.IO.TextReader json) [static] :17 ::g::Uno::Data::Json::Value* Parser::Parse(::g::Uno::IO::TextReader* json) { uStackFrame __("Uno.Data.Json.Parser", "Parse(Uno.IO.TextReader)"); Parser* p = Parser::New1(json); ::g::Uno::Data::Json::Value* v = p->ParseValue(); p->SkipWhiteSpace(); if (!p->Eof()) U_THROW(::g::Uno::Data::Json::JsonException::New4(::STRINGS[10/*"Expected en...*/])); return v; } // private static Uno.Data.Json.JsonException UnexpectedCharacter(char c) [static] :318 ::g::Uno::Data::Json::JsonException* Parser::UnexpectedCharacter(char16_t c) { return ::g::Uno::Data::Json::JsonException::New4(::g::Uno::String::op_Addition1(::STRINGS[15/*"Unexpected ...*/], uBox<char16_t>(::g::Uno::Char_typeof(), c))); } // private static Uno.Data.Json.JsonException UnexpectedEndOfFile() [static] :313 ::g::Uno::Data::Json::JsonException* Parser::UnexpectedEndOfFile() { return ::g::Uno::Data::Json::JsonException::New4(::STRINGS[16/*"Unexpected ...*/]); } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonValue.uno // ------------------------------------------------------------------------------------------- // internal sealed class String :46 // { static void String_build(uType* type) { type->SetBase(::g::Uno::Data::Json::AtomicValue_typeof()->MakeType(::g::Uno::String_typeof(), NULL)); type->SetFields(1); } uType* String_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Data::Json::AtomicValue_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(String); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.String", options); type->fp_build_ = String_build; return type; } // public String(string d) :48 void String__ctor_2_fn(String* __this, uString* d) { __this->ctor_2(d); } // public String New(string d) :48 void String__New1_fn(uString* d, String** __retval) { *__retval = String::New1(d); } // public String(string d) [instance] :48 void String::ctor_2(uString* d) { ::g::Uno::Data::Json::AtomicValue__ctor_1_fn(this, d); } // public String New(string d) [static] :48 String* String::New1(uString* d) { String* obj1 = (String*)uNew(String_typeof()); obj1->ctor_2(d); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Data.Json\1.9.0\Source\JsonValue.uno // ------------------------------------------------------------------------------------------- // internal abstract class Value :6 // { static void Value_build(uType* type) { } uType* Value_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.ObjectSize = sizeof(Value); options.TypeSize = sizeof(uType); type = uClassType::New("Uno.Data.Json.Value", options); type->fp_build_ = Value_build; return type; } // protected generated Value() :6 void Value__ctor__fn(Value* __this) { __this->ctor_(); } // protected generated Value() [instance] :6 void Value::ctor_() { } // } }}}} // ::g::Uno::Data::Json
29.024346
228
0.605113
[ "object" ]
263e9f6fcb336e80e3f1e5e5dd97c9a69acfa99b
6,907
hpp
C++
head/MMapHeadWithTrie.hpp
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
head/MMapHeadWithTrie.hpp
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
head/MMapHeadWithTrie.hpp
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
#pragma once #include <stdint.h> #include <atomic> #include <boost/filesystem.hpp> #include <unordered_map> #include <unordered_set> #include "base/Atomic.hpp" #include "base/Error.hpp" #include "base/Logging.hpp" #include "base/Mutex.hpp" #include "base/ThreadPool.hpp" #include "base/WaitGroup.hpp" #include "block/BlockInterface.hpp" #include "db/AppenderInterface.hpp" #include "head/LFStripeSeries.hpp" #include "head/StripeSeries.hpp" #include "index/MemPostings.hpp" #ifdef USE_PERSISTENT_CEDAR #include "third_party/persistent_cedarpp.h" #else #include "third_party/cedarpp.h" #endif #include "leveldb/db.h" #include "leveldb/db/log_writer.h" #include "tsdbutil/MMapLinuxManager.hpp" #include "tsdbutil/tsdbutils.hpp" namespace leveldb { class Status; class WritableFile; namespace log { class Writer; } } // namespace leveldb namespace tsdb { namespace head { class MMapHeadWithTrieAppender; class MMapHeadWithTrie { public: friend class MMapStripeSeries; friend class MMapStripeGroups; friend class MMapHeadWithTrieAppender; // For labels. std::unique_ptr<leveldb::WritableFile> log_file_; std::unique_ptr<leveldb::log::Writer> log_writer_; // For TS/Group samples. std::atomic<int> cur_samples_log_seq_; std::unique_ptr<leveldb::WritableFile> samples_log_file_; std::unique_ptr<leveldb::log::Writer> samples_log_writer_; // For flush marks. std::atomic<int> cur_flushes_log_seq_; std::unique_ptr<leveldb::WritableFile> flushes_log_file_; std::unique_ptr<leveldb::log::Writer> flushes_log_writer_; std::atomic<int> active_samples_logs_; // number of active samples logs. std::string dir_; std::string idx_dir_; base::AtomicInt64 min_time; base::AtomicInt64 max_time; base::AtomicInt64 valid_time; // Shouldn't be lower than the max_time of the // last persisted block base::AtomicUInt64 last_series_id; // All series addressable by hash or id std::unique_ptr<MMapStripeSeries> series_; std::unique_ptr<MMapStripeGroups> groups_; mutable base::RWMutexLock mutex_; #if USE_PERSISTENT_CEDAR std::unique_ptr<pcedar::da<char>> symbols_; mutable std::unique_ptr<pcedar::da<char>> label_names_; mutable std::unique_ptr<pcedar::da<char>> label_values_; #else std::unique_ptr<cedar::da<char>> symbols_; mutable std::unique_ptr<cedar::da<char>> label_names_; mutable std::unique_ptr<cedar::da<char>> label_values_; #endif std::unique_ptr<MMapXORChunk> xor_array_; std::unique_ptr<MMapGroupXORChunk> group_xor_array_; #if USE_MMAP_LABELS std::unique_ptr<MMapLabels> mmap_labels_; std::unique_ptr<MMapGroupLabels> mmap_group_labels_; #endif std::unique_ptr<index::MemPostingsWithTrie> posting_list; leveldb::DB* db_; base::MutexLock bg_log_clean_stop_mutex_; base::Condition bg_log_clean_stop_signal_; bool bg_log_clean_stopped_; error::Error err_; MMapHeadWithTrie(uint64_t last_series_id, const std::string& dir, const std::string& idx_dir, leveldb::DB* db); ~MMapHeadWithTrie(); leveldb::Status recover_index_from_log(); #if USE_MMAP_LABELS void recover_index_from_mmap(); void recover_group_index_from_mmap(); #endif leveldb::Status recover_samples_from_log(); leveldb::Status clean_samples_logs(); leveldb::Status try_extend_samples_logs(); leveldb::Status try_extend_flushes_logs(); void _print_usage(); void set_db(leveldb::DB* db) { db_ = db; } int num_tags() { return label_values_->num_keys(); } void update_min_max_time(int64_t mint, int64_t maxt); std::unique_ptr<db::AppenderInterface> head_appender(bool write_flush_mark); std::unique_ptr<db::AppenderInterface> appender(bool write_flush_mark = true); std::unique_ptr<MMapHeadWithTrieAppender> TEST_appender(); leveldb::Status write_flush_marks( const std::vector<::leveldb::log::RefFlush>& marks); // tombstones returns a TombstoneReader over the block's deleted data. std::pair<std::unique_ptr<tombstone::TombstoneReaderInterface>, bool> tombstones() const; int64_t MinTime() const { return const_cast<base::AtomicInt64*>(&min_time)->get(); } int64_t MaxTime() const { return const_cast<base::AtomicInt64*>(&max_time)->get(); } // init_time initializes a head with the first timestamp. This only needs to // be called for a completely fresh head with an empty WAL. Returns true if // the initialization took an effect. bool init_time(int64_t t); bool overlap_closed(int64_t mint, int64_t maxt) const { // The block itself is a half-open interval // [pb.meta.MinTime, pb.meta.MaxTime). return MinTime() <= maxt && mint < MaxTime(); } void purge_time(int64_t); // If there are 2 threads calling this function at the same time, // it can be the situation that the 2 threads both generate an id. // But only one will be finally push into StripeSeries, and the other id // and its corresponding std::shared_ptr<MemSeries> will be abandoned. // // In a word, this function is thread-safe. std::pair<MMapMemSeries*, bool> get_or_create(uint64_t hash, const label::Labels& lset); std::pair<MMapMemGroup*, bool> get_or_create_group( uint64_t hash, const label::Labels& group_lset); #if USE_MMAP_LABELS std::pair<MMapMemSeries*, bool> get_or_create_with_id( uint64_t id, uint64_t hash, const label::Labels& lset, bool alloc_mmap_slot, int64_t mmap_labels_idx); std::pair<MMapMemGroup*, bool> get_or_create_group_with_id( uint64_t id, uint64_t hash, const label::Labels& group_lset, bool alloc_mmap_slot, int64_t mmap_labels_idx); #else std::pair<MMapMemSeries*, bool> get_or_create_with_id( uint64_t id, uint64_t hash, const label::Labels& lset, bool alloc_mmap_slot); std::pair<MMapMemGroup*, bool> get_or_create_group_with_id( uint64_t id, uint64_t hash, const label::Labels& group_lset, bool alloc_mmap_slot); #endif error::Error error() const { return err_; } // Note(Alec), from HeadIndexReader. std::set<std::string> symbols(); // const std::deque<std::string> &symbols_deque() const; std::vector<std::string> label_values(const std::string& name); std::pair<std::unique_ptr<index::PostingsInterface>, bool> postings( const std::string& name, const std::string& value) const; bool series(uint64_t ref, label::Labels& lset, std::string* chunk_contents); bool group(uint64_t ref, const std::vector<::tsdb::label::MatcherInterface*>& l, std::vector<int>* slots, label::Labels* group_lset, std::vector<label::Labels>* individual_lsets, std::string* chunk_contents); std::vector<std::string> label_names() const; std::unique_ptr<index::PostingsInterface> sorted_postings( std::unique_ptr<index::PostingsInterface>&& p); }; } // namespace head } // namespace tsdb
31.253394
80
0.72955
[ "vector" ]
2640dc18f22533335bebca3e8faf6be036d1e6f9
27,442
hpp
C++
plll/src/lattices/matrixconversion.hpp
KudrinMatvey/myfplll
99fa018201097b6c078c00721cdc409cdcd4092c
[ "MIT" ]
null
null
null
plll/src/lattices/matrixconversion.hpp
KudrinMatvey/myfplll
99fa018201097b6c078c00721cdc409cdcd4092c
[ "MIT" ]
null
null
null
plll/src/lattices/matrixconversion.hpp
KudrinMatvey/myfplll
99fa018201097b6c078c00721cdc409cdcd4092c
[ "MIT" ]
null
null
null
/* Copyright (c) 2011-2014 University of Zurich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef PLLL_INCLUDE_GUARD__MATRIX_CONVERSION_HPP #define PLLL_INCLUDE_GUARD__MATRIX_CONVERSION_HPP namespace plll { template<class IntTypeContext> class MatrixConversion /* Given an arithmetic::Integer matrix, provides conversions of this matrix to other integer types (specified by the given integer context). Conversion is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: IntTypeContext & d_ic; linalg::math_matrix<arithmetic::Integer> & d_A; linalg::math_matrix<typename IntTypeContext::Integer> d_B; bool d_auto_conversion_on_destruction; public: MatrixConversion(IntTypeContext & ic, linalg::math_matrix<arithmetic::Integer> & A, bool auto_conversion_on_destruction = true, bool begin_now = false) : d_ic(ic), d_A(A), d_auto_conversion_on_destruction(auto_conversion_on_destruction) { if (begin_now) begin(); } ~MatrixConversion() { if (d_auto_conversion_on_destruction) end(); } void begin() // Makes sure that d_B contains content of d_A (if possible). Until the call of end(), no // modifications should be done to d_A. { d_B.resize(d_A.rows(), d_A.cols(), linalg::Initialize(d_ic)); for (unsigned i = 0; i < d_A.rows(); ++i) for (unsigned j = 0; j < d_A.cols(); ++j) convert(d_B(i, j), d_A(i, j), d_ic); } void end() // Makes sure that d_A contains content of d_B. From now on, no calls to matrix() should be // made. The content of d_A can be freely modified from now on. { update_original(); d_B.resize(0, 0); } inline void update_original() // Same as calling end() and then begin(): makes sure that d_A equals d_B. { d_A.resize(d_B.rows(), d_B.cols()); for (unsigned i = 0; i < d_A.rows(); ++i) for (unsigned j = 0; j < d_A.cols(); ++j) convert(d_A(i, j), d_B(i, j), arithmetic::IntegerContext()); } inline linalg::math_matrix<typename IntTypeContext::Integer> & matrix() // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_B; } inline const linalg::math_matrix<typename IntTypeContext::Integer> & matrix() const // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_B; } }; template<> class MatrixConversion<arithmetic::IntegerContext> { private: linalg::math_matrix<arithmetic::Integer> & d_A; public: inline MatrixConversion(arithmetic::IntegerContext &, linalg::math_matrix<arithmetic::Integer> & A, bool = true, bool = false) : d_A(A) { } inline void begin() { } inline void end() { } inline void update_original() { } inline linalg::math_matrix<arithmetic::Integer> & matrix() { return d_A; } inline const linalg::math_matrix<arithmetic::Integer> & matrix() const { return d_A; } }; template<class IntTypeContext> class VectorConversion /* Given an arithmetic::Integer vector, provides conversions of this vector to other integer types (specified by the given integer context). Conversion is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: IntTypeContext & d_ic; linalg::math_rowvector<arithmetic::Integer> & d_v; linalg::math_rowvector<typename IntTypeContext::Integer> d_w; bool d_auto_conversion_on_destruction; public: VectorConversion(IntTypeContext & ic, linalg::math_rowvector<arithmetic::Integer> & A, bool auto_conversion_on_destruction = true, bool begin_now = false) : d_ic(ic), d_v(A), d_auto_conversion_on_destruction(auto_conversion_on_destruction) { if (begin_now) begin(); } ~VectorConversion() { if (d_auto_conversion_on_destruction) end(); } void begin() // Makes sure that d_w contains content of d_v (if possible). Until the call of end(), no // modifications should be done to d_v. { d_w.resize(d_v.size(), linalg::Initialize(d_ic)); for (unsigned i = 0; i < d_v.size(); ++i) convert(d_w[i], d_v[i], d_ic); } void end() // Makes sure that d_v contains content of d_w. From now on, no calls to matrix() should be // made. The content of d_v can be freely modified from now on. { update_original(); d_w.resize(0); } inline void update_original() // Same as calling end() and then begin(): makes sure that d_v equals d_w. { d_v.resize(d_w.size()); for (unsigned i = 0; i < d_v.size(); ++i) convert(d_v[i], d_w[i], arithmetic::IntegerContext()); } inline linalg::math_rowvector<typename IntTypeContext::Integer> & vector() // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_w; } inline const linalg::math_rowvector<typename IntTypeContext::Integer> & vector() const // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_w; } }; template<> class VectorConversion<arithmetic::IntegerContext> { private: linalg::math_rowvector<arithmetic::Integer> & d_v; public: inline VectorConversion(arithmetic::IntegerContext &, linalg::math_rowvector<arithmetic::Integer> & A, bool = true, bool = false) : d_v(A) { } inline void begin() { } inline void end() { } inline void update_original() { } inline linalg::math_rowvector<arithmetic::Integer> & vector() { return d_v; } inline const linalg::math_rowvector<arithmetic::Integer> & vector() const { return d_v; } }; template<class IntTypeContext> class ValueConversion /* Given an arithmetic::Integer value, provides conversions of this value to other integer types (specified by the given integer context). Conversion is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: IntTypeContext & d_ic; arithmetic::Integer & d_v; typename IntTypeContext::Integer d_w; bool d_auto_conversion_on_destruction; public: ValueConversion(IntTypeContext & ic, arithmetic::Integer & A, bool auto_conversion_on_destruction = true, bool begin_now = false) : d_ic(ic), d_v(A), d_auto_conversion_on_destruction(auto_conversion_on_destruction) { if (begin_now) begin(); } ~ValueConversion() { if (d_auto_conversion_on_destruction) end(); } void begin() // Makes sure that d_w contains content of d_v (if possible). Until the call of end(), no // modifications should be done to d_v. { convert(d_w, d_v, d_ic); } void end() // Makes sure that d_v contains content of d_w. From now on, no calls to matrix() should be // made. The content of d_v can be freely modified from now on. { update_original(); } inline void update_original() // Same as calling end() and then begin(): makes sure that d_v equals d_w. { convert(d_v, d_w, arithmetic::IntegerContext()); } inline typename IntTypeContext::Integer & value() // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_w; } inline const typename IntTypeContext::Integer & value() const // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_w; } }; template<> class ValueConversion<arithmetic::IntegerContext> { private: arithmetic::Integer & d_v; public: inline ValueConversion(arithmetic::IntegerContext &, arithmetic::Integer & A, bool = true, bool = false) : d_v(A) { } inline void begin() { } inline void end() { } inline void update_original() { } inline arithmetic::Integer & value() { return d_v; } inline const arithmetic::Integer & value() const { return d_v; } }; template<class IntTypeContext> class MatrixConversion2 /* Given an IntTypeContext matrix, provides conversions of this matrix to arithmetic::Integer. Conversion is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: IntTypeContext & d_ic; linalg::math_matrix<typename IntTypeContext::Integer> & d_A; linalg::math_matrix<arithmetic::Integer> d_B; bool d_auto_conversion_on_destruction; public: MatrixConversion2(IntTypeContext & ic, linalg::math_matrix<typename IntTypeContext::Integer> & A, bool auto_conversion_on_destruction = true, bool begin_now = false) : d_ic(ic), d_A(A), d_auto_conversion_on_destruction(auto_conversion_on_destruction) { if (begin_now) begin(); } ~MatrixConversion2() { if (d_auto_conversion_on_destruction) end(); } void begin() // Makes sure that d_B contains content of d_A (if possible). Until the call of end(), no // modifications should be done to d_A. { d_B.resize(d_A.rows(), d_A.cols()); for (unsigned i = 0; i < d_A.rows(); ++i) for (unsigned j = 0; j < d_A.cols(); ++j) convert(d_B(i, j), d_A(i, j), arithmetic::IntegerContext()); } void end() // Makes sure that d_A contains content of d_B. From now on, no calls to matrix() should be // made. The content of d_A can be freely modified from now on. { update_original(); d_B.resize(0, 0); } inline void update_original() // Same as calling end() and then begin(): makes sure that d_A equals d_B. { d_A.resize(d_B.rows(), d_B.cols(), linalg::Initialize(d_ic)); for (unsigned i = 0; i < d_A.rows(); ++i) for (unsigned j = 0; j < d_A.cols(); ++j) convert(d_A(i, j), d_B(i, j), d_ic); } inline linalg::math_matrix<arithmetic::Integer> & matrix() // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_B; } inline const linalg::math_matrix<arithmetic::Integer> & matrix() const // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_B; } }; template<> class MatrixConversion2<arithmetic::IntegerContext> { private: linalg::math_matrix<arithmetic::Integer> & d_A; public: inline MatrixConversion2(arithmetic::IntegerContext &, linalg::math_matrix<arithmetic::Integer> & A, bool = true, bool = false) : d_A(A) { } inline void begin() { } inline void end() { } inline void update_original() { } inline linalg::math_matrix<arithmetic::Integer> & matrix() { return d_A; } inline const linalg::math_matrix<arithmetic::Integer> & matrix() const { return d_A; } }; template<class IntTypeContext> class VectorConversion2 /* Given an IntTypeContext vector, provides conversions of this vector to arithmetic::Integer. Conversion is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: IntTypeContext & d_ic; linalg::math_rowvector<typename IntTypeContext::Integer> & d_v; linalg::math_rowvector<arithmetic::Integer> d_w; bool d_auto_conversion_on_destruction; public: VectorConversion2(IntTypeContext & ic, linalg::math_rowvector<typename IntTypeContext::Integer> & A, bool auto_conversion_on_destruction = true, bool begin_now = false) : d_ic(ic), d_v(A), d_auto_conversion_on_destruction(auto_conversion_on_destruction) { if (begin_now) begin(); } ~VectorConversion2() { if (d_auto_conversion_on_destruction) end(); } void begin() // Makes sure that d_w contains content of d_v (if possible). Until the call of end(), no // modifications should be done to d_v. { d_w.resize(d_v.size()); for (unsigned i = 0; i < d_v.size(); ++i) convert(d_w[i], d_v[i], arithmetic::IntegerContext()); } void end() // Makes sure that d_v contains content of d_w. From now on, no calls to matrix() should be // made. The content of d_v can be freely modified from now on. { update_original(); d_w.resize(0); } inline void update_original() // Same as calling end() and then begin(): makes sure that d_v equals d_w. { d_v.resize(d_w.size(), linalg::Initialize(d_ic)); for (unsigned i = 0; i < d_v.size(); ++i) convert(d_v[i], d_w[i], d_ic); } inline linalg::math_rowvector<arithmetic::Integer> & vector() // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_w; } inline const linalg::math_rowvector<arithmetic::Integer> & vector() const // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_w; } }; template<> class VectorConversion2<arithmetic::IntegerContext> { private: linalg::math_rowvector<arithmetic::Integer> & d_v; public: inline VectorConversion2(arithmetic::IntegerContext &, linalg::math_rowvector<arithmetic::Integer> & A, bool = true, bool = false) : d_v(A) { } inline void begin() { } inline void end() { } inline void update_original() { } inline linalg::math_rowvector<arithmetic::Integer> & vector() { return d_v; } inline const linalg::math_rowvector<arithmetic::Integer> & vector() const { return d_v; } }; template<class IntTypeContext> class ValueConversion2 /* Given an IntTypeContext value, provides conversions of this value to arithmetic::Integer. Conversion is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: IntTypeContext & d_ic; typename IntTypeContext::Integer & d_v; arithmetic::Integer d_w; bool d_auto_conversion_on_destruction; public: ValueConversion2(IntTypeContext & ic, typename IntTypeContext::Integer & A, bool auto_conversion_on_destruction = true, bool begin_now = false) : d_ic(ic), d_v(A), d_auto_conversion_on_destruction(auto_conversion_on_destruction) { if (begin_now) begin(); } ~ValueConversion2() { if (d_auto_conversion_on_destruction) end(); } void begin() // Makes sure that d_w contains content of d_v (if possible). Until the call of end(), no // modifications should be done to d_v. { convert(d_w, d_v, arithmetic::IntegerContext()); } void end() // Makes sure that d_v contains content of d_w. From now on, no calls to matrix() should be // made. The content of d_v can be freely modified from now on. { update_original(); } inline void update_original() // Same as calling end() and then begin(): makes sure that d_v equals d_w. { convert(d_v, d_w, d_ic); } inline arithmetic::Integer & value() // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_w; } inline const arithmetic::Integer & value() const // Valid between begin() and end(). Garuantee: the reference will *not* change between end() and // begin(). { return d_w; } }; template<> class ValueConversion2<arithmetic::IntegerContext> { private: arithmetic::Integer & d_v; public: inline ValueConversion2(arithmetic::IntegerContext &, arithmetic::Integer & A, bool = true, bool = false) : d_v(A) { } inline void begin() { } inline void end() { } inline void update_original() { } inline arithmetic::Integer & value() { return d_v; } inline const arithmetic::Integer & value() const { return d_v; } }; template<class IntTypeContext> class MatrixConversionConst /* Given an arithmetic::Integer matrix, provides conversions of this matrix to other integer types (specified by the given integer context). ConversionConst is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: linalg::math_matrix<typename IntTypeContext::Integer> d_B; public: MatrixConversionConst(IntTypeContext & ic, const linalg::math_matrix<arithmetic::Integer> & A) { d_B.resize(A.rows(), A.cols()); for (unsigned i = 0; i < A.rows(); ++i) for (unsigned j = 0; j < A.cols(); ++j) convert(d_B(i, j), A(i, j), ic); } inline const linalg::math_matrix<typename IntTypeContext::Integer> & matrix() const { return d_B; } }; template<> class MatrixConversionConst<arithmetic::IntegerContext> { private: const linalg::math_matrix<arithmetic::Integer> & d_A; public: inline MatrixConversionConst(arithmetic::IntegerContext &, const linalg::math_matrix<arithmetic::Integer> & A) : d_A(A) { } inline const linalg::math_matrix<arithmetic::Integer> & matrix() const { return d_A; } }; template<class IntTypeContext> class VectorConversionConst /* Given an arithmetic::Integer vector, provides conversions of this vector to other integer types (specified by the given integer context). ConversionConst is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: linalg::math_rowvector<typename IntTypeContext::Integer> d_w; public: VectorConversionConst(IntTypeContext & ic, const linalg::math_rowvector<arithmetic::Integer> & v) { d_w.resize(v.size()); for (unsigned i = 0; i < v.size(); ++i) convert(d_w[i], v[i], ic); } inline const linalg::math_rowvector<typename IntTypeContext::Integer> & vector() const { return d_w; } }; template<> class VectorConversionConst<arithmetic::IntegerContext> { private: const linalg::math_rowvector<arithmetic::Integer> & d_v; public: inline VectorConversionConst(arithmetic::IntegerContext &, const linalg::math_rowvector<arithmetic::Integer> & A) : d_v(A) { } inline const linalg::math_rowvector<arithmetic::Integer> & vector() const { return d_v; } }; template<class IntTypeContext> class ValueConversionConst /* Given an arithmetic::Integer value, provides conversions of this value to other integer types (specified by the given integer context). ConversionConst is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: typename IntTypeContext::Integer d_w; public: ValueConversionConst(IntTypeContext & ic, const arithmetic::Integer & v) { convert(d_w, v, ic); } inline const typename IntTypeContext::Integer & value() const { return d_w; } }; template<> class ValueConversionConst<arithmetic::IntegerContext> { private: const arithmetic::Integer & d_v; public: inline ValueConversionConst(arithmetic::IntegerContext &, const arithmetic::Integer & A) : d_v(A) { } inline const arithmetic::Integer & value() const { return d_v; } }; template<class IntTypeContext> class MatrixConversionConst2 /* Given an IntTypeContext matrix, provides conversions of this matrix to arithmetic::Integer. ConversionConst is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: linalg::math_matrix<arithmetic::Integer> d_B; public: MatrixConversionConst2(IntTypeContext & ic, const linalg::math_matrix<typename IntTypeContext::Integer> & A) { d_B.resize(A.rows(), A.cols()); for (unsigned i = 0; i < A.rows(); ++i) for (unsigned j = 0; j < A.cols(); ++j) convert(d_B(i, j), A(i, j), arithmetic::IntegerContext()); } inline const linalg::math_matrix<arithmetic::Integer> & matrix() const { return d_B; } }; template<> class MatrixConversionConst2<arithmetic::IntegerContext> { private: const linalg::math_matrix<arithmetic::Integer> & d_A; public: inline MatrixConversionConst2(arithmetic::IntegerContext &, const linalg::math_matrix<arithmetic::Integer> & A) : d_A(A) { } inline const linalg::math_matrix<arithmetic::Integer> & matrix() const { return d_A; } }; template<class IntTypeContext> class VectorConversionConst2 /* Given an IntTypeContext vector, provides conversions of this vector to arithmetic::Integer. ConversionConst is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: linalg::math_rowvector<arithmetic::Integer> d_w; public: VectorConversionConst2(IntTypeContext & ic, const linalg::math_rowvector<typename IntTypeContext::Integer> & v) { d_w.resize(v.size()); for (unsigned i = 0; i < v.size(); ++i) convert(d_w[i], v[i], arithmetic::IntegerContext()); } inline const linalg::math_rowvector<arithmetic::Integer> & vector() const { return d_w; } }; template<> class VectorConversionConst2<arithmetic::IntegerContext> { private: const linalg::math_rowvector<arithmetic::Integer> & d_v; public: inline VectorConversionConst2(arithmetic::IntegerContext &, const linalg::math_rowvector<arithmetic::Integer> & A) : d_v(A) { } inline const linalg::math_rowvector<arithmetic::Integer> & vector() const { return d_v; } }; template<class IntTypeContext> class ValueConversionConst2 /* Given an IntTypeContext value, provides conversions of this value to arithmetic::Integer. ConversionConst is done on-the-fly. In case arithmetic::IntegerContext is given, no conversion is done. */ { private: arithmetic::Integer d_w; public: ValueConversionConst2(IntTypeContext & ic, const typename IntTypeContext::Integer & v) { convert(d_w, v, arithmetic::IntegerContext()); } inline const arithmetic::Integer & value() const { return d_w; } }; template<> class ValueConversionConst2<arithmetic::IntegerContext> { private: const arithmetic::Integer & d_v; public: inline ValueConversionConst2(arithmetic::IntegerContext &, const arithmetic::Integer & A) : d_v(A) { } inline const arithmetic::Integer & value() const { return d_v; } }; } #endif
31.615207
176
0.576088
[ "vector" ]
264ff727b24d8decd25a28f260477550f76bc09a
2,992
cpp
C++
examples/example2.cpp
Zinlibs/Zoom
55cc8172043365f2c22e153f95a75dc510a27d5c
[ "Zlib" ]
3
2015-01-31T05:08:43.000Z
2016-04-22T17:24:41.000Z
examples/example2.cpp
pebbrian/Zoom
55cc8172043365f2c22e153f95a75dc510a27d5c
[ "Zlib" ]
null
null
null
examples/example2.cpp
pebbrian/Zoom
55cc8172043365f2c22e153f95a75dc510a27d5c
[ "Zlib" ]
2
2018-10-07T16:02:03.000Z
2019-03-18T05:50:45.000Z
//////////////////////////////////////////////////////////// /// Headers //////////////////////////////////////////////////////////// #include <SFML/Graphics.hpp> #include <Zoost/Geom.hpp> #include <Zoom/Shape.hpp> #include <Zoost/Converter.hpp> using namespace zin; //////////////////////////////////////////////////////////// /// Entry point of the application //////////////////////////////////////////////////////////// int main() { sf::RenderWindow app(sf::VideoMode(1000, 700, 32), "Zoom example 2"); app.setVerticalSyncEnabled(true); unsigned int frame = 0; Geom heart = Geom::polygon({{120, 60}, {140, 20}, {180, 0}, {220, 20}, {240, 80}, {220, 140}, {180, 180}, {120, 200}, {60, 180}, {20, 140}, {0, 80}, {20, 20}, {60, 0}, {100, 20}}); heart.setPosition(200, 100); heart.scale(1.5, 1.5); Shape heartShape(heart); heartShape.setFacesColor(Color::IndianRed); heartShape.setLiaisonsColor(Color::White); Geom snake = Geom::polygon({{0, 0}, {25, 100}, {40, 100}, {40, 0}, {100, 0}, {100, 100}, {120, 100}, {120, 0}, {180, 0}, {180, 100}, {200, 100}, {200, 0}, {260, 0}, {260, 100}, {275, 100}, {300, 0}, {300, 120}, {240, 120}, {240, 20}, {220, 20}, {220, 120}, {160, 120}, {160, 20}, {140, 20}, {140, 120}, {80, 120}, {80, 20}, {60, 20}, {60, 120}, {0, 120}}); snake.setPosition(130, 200); snake.scale(1.5, 1.5); Shape snakeShape(snake); snakeShape.setFacesColor(Color::SpringGreen); snakeShape.setLiaisonsColor(Color::White); Geom rectangle = Geom::rectangle({200, 200}, {400, 600}, 40); Shape rectangleShape(rectangle); rectangleShape.setFacesColor(Color::Blue); rectangleShape.setLiaisonsColor(Color::White); while( app.isOpen() ) { sf::Event event; while( app.pollEvent(event) ) { if( event.type == sf::Event::Closed ) app.close(); else if( event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape ) app.close(); else if( event.type == sf::Event::MouseWheelMoved ) { if( frame < 2 ) frame++; else frame = 0; if( frame == 0 ) heartShape.setDebugMode(heart.contains(Coords(event.mouseWheel.x, event.mouseWheel.y))); else if( frame == 1 ) snakeShape.setDebugMode(snake.contains(Coords(event.mouseWheel.x, event.mouseWheel.y))); else rectangleShape.setDebugMode(rectangle.contains(Coords(event.mouseWheel.x, event.mouseWheel.y))); } else if( event.type == sf::Event::MouseMoved ) { if( frame == 0 ) heartShape.setDebugMode(heart.contains(Coords(event.mouseMove.x, event.mouseMove.y))); else if( frame == 1 ) snakeShape.setDebugMode(snake.contains(Coords(event.mouseMove.x, event.mouseMove.y))); else rectangleShape.setDebugMode(rectangle.contains(Coords(event.mouseMove.x, event.mouseMove.y))); } } app.clear(sf::Color(30, 30, 30)); if( frame == 0 ) app.draw(heartShape); else if( frame == 1 ) app.draw(snakeShape); else app.draw(rectangleShape); app.display(); } return EXIT_SUCCESS; }
31.166667
357
0.587567
[ "shape" ]
2651737b8ff52e0f638ebac22d47dbcb521430a0
13,421
cpp
C++
src/testing.cpp
ibrahimvis/System-Monitor
a4a343b079205cefe5fd92f78f41bfa1858b3331
[ "MIT" ]
null
null
null
src/testing.cpp
ibrahimvis/System-Monitor
a4a343b079205cefe5fd92f78f41bfa1858b3331
[ "MIT" ]
null
null
null
src/testing.cpp
ibrahimvis/System-Monitor
a4a343b079205cefe5fd92f78f41bfa1858b3331
[ "MIT" ]
null
null
null
// #include <dirent.h> // #include <unistd.h> // #include <iostream> // for debugging // #include <sstream> // #include <string> // #include <vector> // #include "../include/format.h" // #include "../include/linux_parser.h" // #include "../include/process.h" // #include "../include/system.h" // using std::cout; // using std::endl; // using std::stof; // using std::string; // using std::to_string; // using std::vector; // float LinuxParser::MemoryUtilization() { // float shmem = 0.0; // float sreclaimable = 0.0; // float usedMem = 0.0, cachedMem = 0.0, totalMem = 0.0, freeMem = 0.0; // string line; // string key; // string value; // std::ifstream filestream(kProcDirectory + kMeminfoFilename); // if (filestream.is_open()) { // while (std::getline(filestream, line)) { // std::replace(line.begin(), line.end(), ' ', '_'); // std::replace(line.begin(), line.end(), ':', ' '); // std::istringstream linestream(line); // while (linestream >> key >> value) { // // value.erase(remove(value.begin(), value.end(), 'kB'), value.end()); // char chars[] = {'_', ' ', 'k', 'B'}; // for (char c : chars) { // value.erase(remove(value.begin(), value.end(), c), value.end()); // } // switch (key[0]) { // case 'M': // if (key == "MemTotal") { // totalMem = stof(value); // } else if (key == "MemFree") { // freeMem = stof(value); // } // // else if ((key == "MemShared") { sharedmem } // break; // case 'C': // if (key == "Cached") { // cachedMem = stof(value); // } // break; // case 'S': // if (key == "Shmem") { // shmem = stof(value); // } // if (key == "SReclaimable") { // sreclaimable = stof(value); // } // break; // } // // if (key == "PRETTY_NAME") { // // std::replace(value.begin(), value.end(), '_', ' '); // // std::cout << value << std::endl; // // // return value; // // } // } // } // } // usedMem = totalMem - freeMem; // cachedMem = cachedMem + sreclaimable - shmem; // std::cout << usedMem / 1000 << std::endl; // return usedMem + cachedMem; // } // int LinuxParser::TotalProcesses() { // string line, key, value; // float totalProcesses = 0.0; // std::ifstream file(kProcDirectory + kStatFilename); // if (file.is_open()) { // while (std::getline(file, line)) { // // line.replace(line.find(" "), line.length(), "_"); // std::istringstream line_s(line); // while (line_s >> key >> value) { // if (key == "processes") { // totalProcesses = stof(value); // } // } // } // } // return totalProcesses; // } // long LinuxParser::UpTime() { // long upTime = 0; // long suspendL, idleL; // string line, suspend, idle; // std::ifstream file(kProcDirectory + kUptimeFilename); // if (file.is_open()) { // std::getline(file, line); // std::istringstream line_s(line); // line_s >> suspend >> idle; // suspendL = std::stol(suspend); // // idleL = std::stol(idle); // upTime = suspendL; // } // return upTime; // } // vector<string> LinuxParser::CpuUtilization() { // vector<string> cpu{}; // string line; // std::ifstream file(kProcDirectory + kStatFilename); // if (file.is_open()) { // std::getline(file, line); // std::istringstream line_s(line); // while (!line_s.eof()) { // string token; // line_s >> token; // cpu.push_back(token); // } // cpu.erase(cpu.begin()); // } // return cpu; // } // string LinuxParser::Uid(int pid) { // string line; // string uid = "none"; // std::ifstream file(kProcDirectory + to_string(pid) + kStatusFilename); // if (file.is_open()) { // while (std::getline(file, line)) { // std::istringstream line_s(line); // string name, value, extra; // line_s >> name >> value >> extra; // if (name == "Uid:") { // uid = value; // break; // } // } // } // return uid; // } // string LinuxParser::User(int pid) { // string uid = Uid(pid); // string line; // string user; // std::ifstream file(kPasswordPath); // if (file.is_open()) { // while (getline(file, line)) { // // std::replace(line.begin(), line.end(), ' ', '_'); // std::replace(line.begin(), line.end(), ':', ' '); // std::istringstream linestream(line); // string passwd, uid2, gid, comment, home, bash; // linestream >> user >> passwd >> uid2 >> gid >> comment >> home >> bash; // if (uid2 == uid) { // break; // } // } // } // return user; // } // long LinuxParser::CpuUtilization(int pid) { // string line; // long cpu_usage; // std::ifstream file(kProcDirectory + to_string(pid) + kStatFilename); // if (file.is_open()) { // std::getline(file, line); // std::istringstream linestream(line); // string token; // int utime, stime, cutime, cstime, starttime; // /* // #14 utime - CPU time spent in user code, measured in clock ticks // #15 stime - CPU time spent in kernel code, measured in clock ticks // #16 cutime - Waited-for children's CPU time spent in user code (in clock // ticks) #17 cstime - Waited-for children's CPU time spent in kernel code (in // clock ticks) #22 starttime - Time when the process started, measured in // clock ticks // */ // for (int i = 0; i < 22 && linestream >> token; i++) { // switch (i) { // case 0: // std::cout << i << " " << token << std::endl; // break; // case 13: // utime = std::stoi(token); // std::cout << i << " " << token << std::endl; // break; // case 14: // stime = std::stoi(token); // std::cout << i << " " << token << std::endl; // break; // case 15: // cutime = std::stoi(token); // std::cout << i << " " << token << std::endl; // break; // case 16: // cstime = std::stoi(token); // std::cout << i << " " << token << std::endl; // break; // case 21: // starttime = std::stoi(token); // std::cout << i << " " << token << std::endl; // break; // } // // std::cout << i << " " << token << std::endl; // } // double total_time = utime + stime + cutime + cstime; // std::cout << "Total: " << total_time << std::endl; // double seconds = LinuxParser::UpTime() - (starttime / sysconf(_SC_CLK_TCK)); // std::cout << "Seconds: " << seconds << std::endl; // cpu_usage = 100 * ((total_time / sysconf(_SC_CLK_TCK)) / seconds); // std::cout << "cpu Usage: " << cpu_usage << std::endl; // } // return cpu_usage; // } // string LinuxParser::Ram(int pid) { // string line; // string key, value; // std::ifstream file(kProcDirectory + std::to_string(pid) + kStatusFilename); // while (std::getline(file, line)) { // std::istringstream linestream(line); // linestream >> key >> value; // if (key == "VmSize:") { // value = to_string(std::stol(value) / 1000); // break; // } // } // return value; // } // string LinuxParser::Command(int pid) { // string line; // string key, value; // std::ifstream file(kProcDirectory + std::to_string(pid) + kCmdlineFilename); // std::getline(file, line); // return line; // } // long LinuxParser::UpTime(int pid) { // string line; // long int uptime = 0; // std::ifstream file(kProcDirectory + to_string(pid) + kStatFilename); // if (file.is_open()) { // std::getline(file, line); // std::istringstream linestream(line); // string token; // for (int i = 0; i < 22 && linestream >> token; i++) { // if (i == 21) { // uptime = std::stol(token) / sysconf(_SC_CLK_TCK); // break; // } // } // return uptime; // } // return uptime; // } // vector<Process>& System::Processes() { // vector<int> pids = LinuxParser::Pids(); // for (int pid : pids) { // Process process = // Process(pid, LinuxParser::User(pid), LinuxParser::Command(pid), 0.0, // LinuxParser::Ram(pid), LinuxParser::UpTime(pid)); // processes_.push_back(process); // } // return processes_; // } // vector<int> LinuxParser::Pids() { // vector<int> pids; // DIR* directory = opendir(kProcDirectory.c_str()); // struct dirent* file; // while ((file = readdir(directory)) != nullptr) { // // Is this a directory? // if (file->d_type == DT_DIR) { // // Is every character of the name a digit? // string filename(file->d_name); // if (std::all_of(filename.begin(), filename.end(), isdigit)) { // int pid = stoi(filename); // pids.push_back(pid); // } // } // } // closedir(directory); // return pids; // } // int Process::Pid() { return pid; } // // TODO: Return this process's CPU utilization // float Process::CpuUtilization() { return cpuUtilz; } // // TODO: Return the command that generated this process // string Process::Command() { return command; } // // TODO: Return this process's memory utilization // string Process::Ram() { return ram; } // // TODO: Return the user (name) that generated this process // string Process::User() { return user; } // // TODO: Return the age of this process (in seconds) // long int Process::UpTime() { return uptime; } // long LinuxParser::Jiffies() { // vector<string> jiffies = LinuxParser::CpuUtilization(); // long total = 0; // for (string jiff : jiffies) { // total += std::stoi(jiff); // } // return total; // } // // TODO: Read and return the number of active jiffies for a PID // // REMOVE: [[maybe_unused]] once you define the function // long LinuxParser::ActiveJiffies(int pid) { // string line; // long cpu_usage; // std::ifstream file(kProcDirectory + to_string(pid) + kStatFilename); // if (file.is_open()) { // std::getline(file, line); // std::istringstream linestream(line); // string token; // int utime, stime, cutime, cstime, starttime; // /* // #14 utime - CPU time spent in user code, measured in clock ticks // #15 stime - CPU time spent in kernel code, measured in clock ticks // #16 cutime - Waited-for children's CPU time spent in user code (in clock // ticks) #17 cstime - Waited-for children's CPU time spent in kernel code (in // clock ticks) #22 starttime - Time when the process started, measured in // clock ticks // */ // for (int i = 0; i < 22 && linestream >> token; i++) { // switch (i) { // case 13: // utime = std::stoi(token); // //std::cout << i << " " << token << std::endl; // break; // case 14: // stime = std::stoi(token); // //std::cout << i << " " << token << std::endl; // break; // case 15: // cutime = std::stoi(token); // //std::cout << i << " " << token << std::endl; // break; // case 16: // cstime = std::stoi(token); // //std::cout << i << " " << token << std::endl; // break; // case 21: // starttime = std::stoi(token); // //std::cout << i << " " << token << std::endl; // break; // } // // std::cout << i << " " << token << std::endl; // } // double total_time = utime + stime + cutime + cstime; // // std::cout << "Total: " << total_time << std::endl; // double seconds = LinuxParser::UpTime() - (starttime / sysconf(_SC_CLK_TCK)); // // std::cout << "Seconds: " << seconds << std::endl; // cpu_usage = 100 * ((total_time / sysconf(_SC_CLK_TCK)) / seconds); // // std::cout << "cpu Usage: " << cpu_usage << std::endl; // } // return cpu_usage; // return 0; // } // // TODO: Read and return the number of active jiffies for the system // long LinuxParser::ActiveJiffies() { // vector<string> jiffies = LinuxParser::CpuUtilization(); // long total = 0; // for (int i = 0; i < 8; i++) { // total += std::stol(jiffies[i]); // } // return (total - std::stol(jiffies[kIOwait_]) - std::stol(jiffies[kIdle_])); // } // // TODO: Read and return the number of idle jiffies for the system // long LinuxParser::IdleJiffies() { // vector<string> jiffies = LinuxParser::CpuUtilization(); // long idle = std::stol(jiffies[kIdle_]) + std::stol(jiffies[kIOwait_]); // return idle; // } // int main() { // // float x = LinuxParser::MemoryUtilization(); // // int y = LinuxParser::TotalProcesses(); // // long z = LinuxParser::UpTime(); // // std::cout << z << std::endl; // // vector<string> temp = LinuxParser::CpuUtilization(); // // for (auto x: temp) { // // std::cout << x << std::endl; // // } // // string uid = LinuxParser::User(1764); // cout << LinuxParser::User(14966) << endl; // // System s; // // vector<Process> pro = s.Processes(); // // for (Process p : pro) { // // cout << p.Pid() << " " << p.User() << " " << p.Command() << endl; // // } // }
29.176087
83
0.523731
[ "vector" ]
2655b31bba7d2e8b28b71aa161aae85d29473811
6,095
cpp
C++
Development/External/wxWindows_2.4.0/src/common/sckaddr.cpp
addstone/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
37
2020-05-22T18:18:47.000Z
2022-03-19T06:51:54.000Z
Development/External/wxWindows_2.4.0/src/common/sckaddr.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
null
null
null
Development/External/wxWindows_2.4.0/src/common/sckaddr.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
27
2020-05-17T01:03:30.000Z
2022-03-06T19:10:14.000Z
///////////////////////////////////////////////////////////////////////////// // Name: sckaddr.cpp // Purpose: Network address manager // Author: Guilhem Lavaux // Modified by: // Created: 26/04/97 // RCS-ID: $Id: sckaddr.cpp,v 1.33.2.2 2002/11/09 10:53:27 RR Exp $ // Copyright: (c) 1997, 1998 Guilhem Lavaux // Licence: wxWindows license ///////////////////////////////////////////////////////////////////////////// #ifdef __GNUG__ #pragma implementation "sckaddr.h" #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_SOCKETS #ifndef WX_PRECOMP #include "wx/defs.h" #include "wx/object.h" #include "wx/log.h" #include "wx/intl.h" #include <stdio.h> #include <stdlib.h> #include <ctype.h> #if !defined(__MWERKS__) && !defined(__SALFORDC__) #include <memory.h> #endif #endif // !WX_PRECOMP #include "wx/gsocket.h" #include "wx/socket.h" #include "wx/sckaddr.h" IMPLEMENT_ABSTRACT_CLASS(wxSockAddress, wxObject) IMPLEMENT_DYNAMIC_CLASS(wxIPV4address, wxSockAddress) #ifdef ENABLE_IPV6 IMPLEMENT_DYNAMIC_CLASS(wxIPV6address, wxSockAddress) #endif #if defined(__UNIX__) && (!defined(__WXMAC__) || defined(__DARWIN__)) IMPLEMENT_DYNAMIC_CLASS(wxUNIXaddress, wxSockAddress) #endif // --------------------------------------------------------------------------- // wxIPV4address // --------------------------------------------------------------------------- void wxSockAddress::Init() { if ( !wxSocketBase::IsInitialized() ) { // we must do it before using GAddress_XXX functions (void)wxSocketBase::Initialize(); } } wxSockAddress::wxSockAddress() { Init(); m_address = GAddress_new(); } wxSockAddress::wxSockAddress(const wxSockAddress& other) : wxObject() { Init(); m_address = GAddress_copy(other.m_address); } wxSockAddress::~wxSockAddress() { GAddress_destroy(m_address); } void wxSockAddress::SetAddress(GAddress *address) { GAddress_destroy(m_address); m_address = GAddress_copy(address); } wxSockAddress& wxSockAddress::operator=(const wxSockAddress& addr) { SetAddress(addr.GetAddress()); return *this; } void wxSockAddress::Clear() { GAddress_destroy(m_address); m_address = GAddress_new(); } // --------------------------------------------------------------------------- // wxIPV4address // --------------------------------------------------------------------------- wxIPV4address::wxIPV4address() { } wxIPV4address::wxIPV4address(const wxIPV4address& other) : wxSockAddress(other) { } wxIPV4address::~wxIPV4address() { } bool wxIPV4address::Hostname(const wxString& name) { // Some people are sometimes fool. if (name == wxT("")) { wxLogWarning( _("Trying to solve a NULL hostname: giving up") ); return FALSE; } m_origHostname = name; return (GAddress_INET_SetHostName(m_address, name.mb_str()) == GSOCK_NOERROR); } bool wxIPV4address::Hostname(unsigned long addr) { bool rv = (GAddress_INET_SetHostAddress(m_address, addr) == GSOCK_NOERROR); if (rv) m_origHostname = Hostname(); else m_origHostname = wxEmptyString; return rv; } bool wxIPV4address::Service(const wxString& name) { return (GAddress_INET_SetPortName(m_address, name.mb_str(), "tcp") == GSOCK_NOERROR); } bool wxIPV4address::Service(unsigned short port) { return (GAddress_INET_SetPort(m_address, port) == GSOCK_NOERROR); } bool wxIPV4address::LocalHost() { return (GAddress_INET_SetHostName(m_address, "localhost") == GSOCK_NOERROR); } bool wxIPV4address::AnyAddress() { return (GAddress_INET_SetAnyAddress(m_address) == GSOCK_NOERROR); } wxString wxIPV4address::Hostname() { char hostname[1024]; hostname[0] = 0; GAddress_INET_GetHostName(m_address, hostname, 1024); return wxString::FromAscii(hostname); } unsigned short wxIPV4address::Service() { return GAddress_INET_GetPort(m_address); } wxSockAddress *wxIPV4address::Clone() const { wxIPV4address *addr = new wxIPV4address(*this); addr->m_origHostname = m_origHostname; return addr; } #if 0 // --------------------------------------------------------------------------- // wxIPV6address // --------------------------------------------------------------------------- wxIPV6address::wxIPV6address() : wxSockAddress() { } wxIPV6address::wxIPV6address(const wxIPV6address& other) : wxSockAddress(other) { } wxIPV6address::~wxIPV6address() { } bool wxIPV6address::Hostname(const wxString& name) { return (GAddress_INET_SetHostName(m_address, name.fn_str()) == GSOCK_NOERROR); } bool wxIPV6address::Hostname(unsigned char addr[16]) { return TRUE; } bool wxIPV6address::Service(const char *name) { return (GAddress_INET_SetPortName(m_address, name.fn_str()) == GSOCK_NOERROR); } bool wxIPV6address::Service(unsigned short port) { return (GAddress_INET_SetPort(m_address, port) == GSOCK_NOERROR); } bool wxIPV6address::LocalHost() { return (GAddress_INET_SetHostName(m_address, "localhost") == GSOCK_NOERROR); } const wxString& wxIPV6address::Hostname() { return wxString(GAddress_INET_GetHostName(m_address)); } unsigned short wxIPV6address::Service() { return GAddress_INET_GetPort(m_address); } #endif // 0 #if defined(__UNIX__) && (!defined(__WXMAC__) || defined(__DARWIN__)) // --------------------------------------------------------------------------- // wxUNIXaddress // --------------------------------------------------------------------------- wxUNIXaddress::wxUNIXaddress() : wxSockAddress() { } wxUNIXaddress::wxUNIXaddress(const wxUNIXaddress& other) : wxSockAddress(other) { } wxUNIXaddress::~wxUNIXaddress() { } void wxUNIXaddress::Filename(const wxString& fname) { GAddress_UNIX_SetPath(m_address, fname.fn_str()); } wxString wxUNIXaddress::Filename() { char path[1024]; path[0] = 0; GAddress_UNIX_GetPath(m_address, path, 1024); return wxString::FromAscii(path); } #endif // __UNIX__ #endif // wxUSE_SOCKETS
21.845878
87
0.622313
[ "object" ]
265c2cd988a10a5fe0f5c348043b4ee1723c18b3
13,978
cpp
C++
test/xlinq_distinct_test.cpp
trolleyyy/xlinq
af7de7bb109b09b44dac1915c01dd4b3fd1dbf71
[ "MIT" ]
6
2016-10-04T19:28:00.000Z
2018-02-09T02:20:08.000Z
test/xlinq_distinct_test.cpp
trolleyyy/xlinq
af7de7bb109b09b44dac1915c01dd4b3fd1dbf71
[ "MIT" ]
1
2016-11-07T06:00:02.000Z
2017-06-09T19:59:30.000Z
test/xlinq_distinct_test.cpp
trolleyyy/xlinq
af7de7bb109b09b44dac1915c01dd4b3fd1dbf71
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <xlinq/xlinq_from.h> #include <xlinq/xlinq_distinct.h> #include <list> #include <forward_list> #include <vector> using namespace std; using namespace xlinq; template<typename TVal> struct Hash { int operator()(const TVal& val) const { return (int)val; } }; template<typename TFirst, typename TSecond> struct Eq { bool operator()(const TFirst& first, const TSecond& second) const { return (first + first) == (second << 1); } }; TEST(XLinqDistinctTest, DistinctFromEnumerable) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct() >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(3, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(4, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(5, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctTest, DistinctEnumerable_CloneAndEqualsEnumeratorTest) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerable = from(numbers) >> distinct(); auto enumerator = enumerable >> getEnumerator(); ASSERT_TRUE(enumerator->next()); auto second = enumerator->clone(); ASSERT_TRUE(enumerator->equals(second)); ASSERT_TRUE(enumerator->next()); ASSERT_FALSE(enumerator->equals(second)); ASSERT_EQ(2, enumerator->current()); ASSERT_EQ(1, second->current()); while (enumerator->next()); ASSERT_EQ(1, second->current()); ASSERT_TRUE(second->next()); ASSERT_EQ(2, second->current()); } TEST(XLinqDistinctTest, DistinctFromBidirectionalEnumerable) { list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct() >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(3, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(4, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(5, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctTest, DistinctFromRandomAccessEnumerable) { vector<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct() >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(3, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(4, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(5, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctTest, DistinctWithEqCompFromEnumerable) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct(Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(3, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(4, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(5, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctTest, DistinctWithEqCompEnumerable_CloneAndEqualsEnumeratorTest) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerable = from(numbers) >> distinct(Eq<int, int>()); auto enumerator = enumerable >> getEnumerator(); ASSERT_TRUE(enumerator->next()); auto second = enumerator->clone(); ASSERT_TRUE(enumerator->equals(second)); ASSERT_TRUE(enumerator->next()); ASSERT_FALSE(enumerator->equals(second)); ASSERT_EQ(2, enumerator->current()); ASSERT_EQ(1, second->current()); while (enumerator->next()); ASSERT_EQ(1, second->current()); ASSERT_TRUE(second->next()); ASSERT_EQ(2, second->current()); } TEST(XLinqDistinctTest, DistinctWithEqCompFromBidirectionalEnumerable) { list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct(Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(3, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(4, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(5, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctTest, DistinctWithEqCompFromRandomAccessEnumerable) { vector<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct(Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(3, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(4, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(5, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctTest, DistinctFullFromEnumerable) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct(Hash<int>(), Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(3, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(4, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(5, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctTest, DistinctFullEnumerable_CloneAndEqualsEnumeratorTest) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerable = from(numbers) >> distinct(Hash<int>(), Eq<int, int>()); auto enumerator = enumerable >> getEnumerator(); ASSERT_TRUE(enumerator->next()); auto second = enumerator->clone(); ASSERT_TRUE(enumerator->equals(second)); ASSERT_TRUE(enumerator->next()); ASSERT_FALSE(enumerator->equals(second)); ASSERT_EQ(2, enumerator->current()); ASSERT_EQ(1, second->current()); while (enumerator->next()); ASSERT_EQ(1, second->current()); ASSERT_TRUE(second->next()); ASSERT_EQ(2, second->current()); } TEST(XLinqDistinctTest, DistinctFullFromBidirectionalEnumerable) { list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct(Hash<int>(), Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(3, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(4, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(5, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctTest, DistinctFullFromRandomAccessEnumerable) { vector<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct(Hash<int>(), Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(3, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(4, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(5, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctByTest, DistinctByFromEnumerable) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct_by([](int a) { return a % 2; } ) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctByTest, DistinctByEnumerable_CloneAndEqualsEnumeratorTest) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerable = from(numbers) >> distinct_by([](int a) { return a % 2; }); auto enumerator = enumerable >> getEnumerator(); ASSERT_TRUE(enumerator->next()); auto second = enumerator->clone(); ASSERT_TRUE(enumerator->equals(second)); ASSERT_TRUE(enumerator->next()); ASSERT_FALSE(enumerator->equals(second)); ASSERT_EQ(2, enumerator->current()); ASSERT_EQ(1, second->current()); while (enumerator->next()); ASSERT_EQ(1, second->current()); ASSERT_TRUE(second->next()); ASSERT_EQ(2, second->current()); } TEST(XLinqDistinctByTest, DistinctByFromBidirectionalEnumerable) { list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct_by([](int a) { return a % 2; } ) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctByTest, DistinctByFromRandomAccessEnumerable) { vector<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct_by([](int a) { return a % 2; } ) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctByTest, DistinctByWithEqCompFromEnumerable) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct_by([](int a) { return a % 2; }, Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctByTest, DistinctByWithEqCompEnumerable_CloneAndEqualsEnumeratorTest) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerable = from(numbers) >> distinct_by([](int a) { return a % 2; }, Eq<int, int>()); auto enumerator = enumerable >> getEnumerator(); ASSERT_TRUE(enumerator->next()); auto second = enumerator->clone(); ASSERT_TRUE(enumerator->equals(second)); ASSERT_TRUE(enumerator->next()); ASSERT_FALSE(enumerator->equals(second)); ASSERT_EQ(2, enumerator->current()); ASSERT_EQ(1, second->current()); while (enumerator->next()); ASSERT_EQ(1, second->current()); ASSERT_TRUE(second->next()); ASSERT_EQ(2, second->current()); } TEST(XLinqDistinctByTest, DistinctByWithEqCompFromBidirectionalEnumerable) { list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct_by([](int a) { return a % 2; }, Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctByTest, DistinctByWithEqCompFromRandomAccessEnumerable) { vector<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct_by([](int a) { return a % 2; }, Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctByTest, DistinctByFullFromEnumerable) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct_by([](int a) { return a % 2; }, Hash<int>(), Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctByTest, DistinctByFullEnumerable_CloneAndEqualsEnumeratorTest) { forward_list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerable = from(numbers) >> distinct_by([](int a) { return a % 2; }, Hash<int>(), Eq<int, int>()); auto enumerator = enumerable >> getEnumerator(); ASSERT_TRUE(enumerator->next()); auto second = enumerator->clone(); ASSERT_TRUE(enumerator->equals(second)); ASSERT_TRUE(enumerator->next()); ASSERT_FALSE(enumerator->equals(second)); ASSERT_EQ(2, enumerator->current()); ASSERT_EQ(1, second->current()); while (enumerator->next()); ASSERT_EQ(1, second->current()); ASSERT_TRUE(second->next()); ASSERT_EQ(2, second->current()); } TEST(XLinqDistinctByTest, DistinctByFullFromBidirectionalEnumerable) { list<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct_by([](int a) { return a % 2; }, Hash<int>(), Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_FALSE(enumerator->next()); } TEST(XLinqDistinctByTest, DistinctByFullFromRandomAccessEnumerable) { vector<int> numbers = { 1, 1, 2, 2, 2, 3, 4, 4, 5 }; auto enumerator = from(numbers) >> distinct_by([](int a) { return a % 2; }, Hash<int>(), Eq<int, int>()) >> getEnumerator(); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(1, enumerator->current()); ASSERT_TRUE(enumerator->next()); ASSERT_EQ(2, enumerator->current()); ASSERT_FALSE(enumerator->next()); }
34.51358
126
0.680498
[ "vector" ]
2660ec5d03f6f93b9d918d6e4924796b348876f9
642
cpp
C++
vol5/minimum-size-subarray-sum/minimum-size-subarray-sum.cpp
zeyuanxy/LeetCode
fab1b6ea07249d7024f37a8f4bbef9d397edc3ec
[ "MIT" ]
3
2015-12-07T05:40:08.000Z
2018-12-17T18:39:15.000Z
vol5/minimum-size-subarray-sum/minimum-size-subarray-sum.cpp
zeyuanxy/leet-code
fab1b6ea07249d7024f37a8f4bbef9d397edc3ec
[ "MIT" ]
null
null
null
vol5/minimum-size-subarray-sum/minimum-size-subarray-sum.cpp
zeyuanxy/leet-code
fab1b6ea07249d7024f37a8f4bbef9d397edc3ec
[ "MIT" ]
null
null
null
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { if (nums.empty()) { return 0; } int r = -1, sum = 0, ans = nums.size() + 1; for (int i = 0; i < nums.size(); ++i) { if (i > 0) { sum -= nums[i - 1]; } while (sum < s && r + 1 < nums.size()) { ++r; sum += nums[r]; } if (sum < s) { break; } ans = min(ans, r - i + 1); } if (ans == nums.size() + 1) { return 0; } return ans; } };
24.692308
52
0.317757
[ "vector" ]
266bd8731e498d2144fcb7cde2102bb991b0564e
2,922
cpp
C++
src/liblvr2/display/InteractivePointCloud.cpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
38
2019-06-19T15:10:35.000Z
2022-02-16T03:08:24.000Z
src/liblvr2/display/InteractivePointCloud.cpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
9
2019-06-19T16:19:51.000Z
2021-09-17T08:31:25.000Z
src/liblvr2/display/InteractivePointCloud.cpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
13
2019-04-16T11:50:32.000Z
2020-11-26T07:47:44.000Z
/** * Copyright (c) 2018, University Osnabrück * 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 University Osnabrück 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 University Osnabrück 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. */ /* * InteractivePointCloud.cpp * * Created on: 02.04.2012 * Author: Thomas Wiemann */ #include "lvr2/display/InteractivePointCloud.hpp" namespace lvr2 { InteractivePointCloud::InteractivePointCloud() { m_boundingBox = new BoundingBox<Vec>( Vec(-8, -8, -8), Vec(8, 8, 8) ); updateBuffer(PointBufferPtr()); } InteractivePointCloud::InteractivePointCloud(PointBufferPtr buffer) { m_boundingBox = new BoundingBox<Vec>( Vec(-8, -8, -8), Vec(8, 8, 8) ); updateBuffer(buffer); } InteractivePointCloud::~InteractivePointCloud() { } void InteractivePointCloud::render() { if(m_buffer) { glColor3f(1.0, 0.0, 0.0); glDrawArrays(GL_POINTS, 0, m_buffer->numPoints()); } } void InteractivePointCloud::updateBuffer(PointBufferPtr buffer) { if(buffer) { if(!m_boundingBox) { m_boundingBox = new BoundingBox<Vec>; m_boundingBox->expand(Vec(8000, 8000, 8000)); } size_t num_vertices = buffer->numPoints(); float* vertices = buffer->getPointArray().get(); // m_boundingBox = new BoundingBox<Vertex<float> >; // for (int i = 0; i < int(num_vertices); i++) // { // int index = 3 * i; // m_boundingBox->expand(vertices[index], vertices[index + 1], vertices[index + 2]); // } glVertexPointer(3, GL_FLOAT, 0, vertices); m_buffer = buffer; } } } /* namespace lvr2 */
28.930693
86
0.717659
[ "render" ]
266d2ad19a5e9f5cda6f4f1ac9dc03dbf98c4dbb
13,095
hpp
C++
modules/core/include/facekit/core/sys/stacktrace.hpp
cecabert/FaceKit
766a32fc7f65ae5deceeba5628c225631986c4d8
[ "Apache-2.0" ]
null
null
null
modules/core/include/facekit/core/sys/stacktrace.hpp
cecabert/FaceKit
766a32fc7f65ae5deceeba5628c225631986c4d8
[ "Apache-2.0" ]
null
null
null
modules/core/include/facekit/core/sys/stacktrace.hpp
cecabert/FaceKit
766a32fc7f65ae5deceeba5628c225631986c4d8
[ "Apache-2.0" ]
1
2017-11-29T12:03:08.000Z
2017-11-29T12:03:08.000Z
/** * @file stacktrace.hpp * @brief Class creating a StackTrace for debugging purpose. Would typically * been use in expection. * @ingroup core * * @author Christophe Ecabert * @date 10.07.18 * Copyright © 2018 Christophe Ecabert. All rights reserved. */ #ifndef __FACEKIT_STACKTRACE__ #define __FACEKIT_STACKTRACE__ #include <vector> #include "facekit/core/library_export.hpp" #include "facekit/core/status.hpp" /** * @namespace FaceKit * @brief Development space */ namespace FaceKit { /** * @class StackTraceFrame * @brief Provide an attribute class describing an element (frame) of the * current stacktrace. * @see: https://github.com/bloomberg/bde/blob/master/groups/bal/balst/ * @author Christophe Ecabert * @date 09.07.18 * @ingroup core */ class FK_EXPORTS StackTraceFrame { public: #pragma mark - #pragma mark Initialisation /** * @name StackTraceFrame * @fn StackTraceFrame(void) * @brief Constructor */ StackTraceFrame(void); /** * @name StackTraceFrame * @fn StackTraceFrame(const void* address, const std::string& library_name, const int& line_number, const std::string& mangled_symbol_name, const std::string& symbol_name, const std::size_t& offset, const std::string& src_file) * @brief Constructor * @param[in] address Frame address * @param[in] library_name Name of the executable or shared-object file * @param[in] line_number Line number * @param[in] mangled_symbol_name Mangled symnbol name * @param[in] symbol_name Unmangled symbol name * @param[in] offset Function offset * @param[in] src_file Source file */ StackTraceFrame(const void* address, const std::string& library_name, const int& line_number, const std::string& mangled_symbol_name, const std::string& symbol_name, const std::size_t& offset, const std::string& src_file); /** * @name StackTraceFrame * @fn StackTraceFrame(const StackTraceFrame& other) * @brief Copy constructor * @param[in] other Object to copy from */ StackTraceFrame(const StackTraceFrame& other) = default; /** * @name operator= * @fn StackTraceFrame& operator=(const StackTraceFrame& rhs) = default * @brief Assignment operator * @param[in] rhs Object to assign from * @return newly assigned operator */ StackTraceFrame& operator=(const StackTraceFrame& rhs) = default; /** * @name ~StackTraceFrame * @fn ~StackTraceFrame(void) = default * @brief Destructor */ ~StackTraceFrame(void) = default; #pragma mark - #pragma mark Usage /** * @name Print * @fn std::ostream& Print(std::ostream& stream, const size_t& level, const size_t& space) const * @brief Print this frame into a given stream * @param[in] stream Stream where to dump the frame * @param[in] level Level of the trace * @param[in] space Number of space to shift for each level * @return Stream used */ std::ostream& Print(std::ostream& stream, const size_t& level, const size_t& space) const; #pragma mark - #pragma mark Accessors /** * @name set_address * @fn void set_address(const void* address) * @brief Fill the address attribute * @param[in] address Frame's address */ void set_address(const void* address) { address_ = address; } /** * @name get_address * @fn const void* get_address(void) const * @brief Provide the frame's address * @return The return address in the parent function on the return from the * fild function */ const void* get_address(void) const { return address_; } /** * @name set_library_name * @fn void set_library_name(const std::string& name) * @brief Set the library's name for the frame * @param[in] name Library's name */ void set_library_name(const std::string& name) { library_name_ = name; } /** * @name get_library_name * @fn const std::string& get_library_name(void) const * @brief Provide the library's name for the frame * @return Executable / shared-object's name containing the parent function */ const std::string& get_library_name(void) const { return library_name_; } /** * @name set_line_number * @fn void set_line_number(const int& number) * @brief Set line number of the frame * @param[in] number Line number */ void set_line_number(const int& number) { line_number_ = number; } /** * @name get_line_number * @fn int get_line_number(void) const * @brief Provide the frame's line number * @return Line number */ int get_line_number(void) const { return line_number_; } /** * @name set_mangled_symbol_name * @fn void set_mangled_symbol_name(const std::string& name) * @brief Set symbol's mangled name * @param[in] name Symbol's mangled name */ void set_mangled_symbol_name(const std::string& name) { mangled_symbol_name_ = name; } /** * @name get_mangled_symbol_name * @fn const std::string& get_mangled_symbol_name(void) const * @brief Provide frame's mangled symbol's name * @return Mangled name of the parent function */ const std::string& get_mangled_symbol_name(void) const { return mangled_symbol_name_; } /** * @name set_symbol_name * @fn void set_symbol_name(const std::string& name) * @brief Set unmnagled symbol's name * @param[in] name Unmangled symbol's name */ void set_symbol_name(const std::string& name) { symbol_name_ = name; } /** * @name get_symbol_name * @fn const std::string& get_symbol_name(void) const * @brief Give the unmangled symbol's name of the frame * @return Unmangled synmbol name */ const std::string& get_symbol_name(void) const { return symbol_name_; } /** * @name set_offset * @fn void set_offset(const size_t& offset) * @brief Set symbol's offset * @param[in] offset Symbol's offset */ void set_offset(const size_t& offset) { offset_from_symbol_ = offset; } /** * @name get_offset * @fn size_t get_offset(void) const * @brief Give the symbol's offset * @return Offset from the start of the parent function to the call of the * child function */ size_t get_offset(void) const { return offset_from_symbol_; } /** * @name set_src_file_name * @fn void set_src_file_name(const std::string& name) * @brief Set the src filename of the frame's symbol * @param[in] name File name */ void set_src_file_name(const std::string& name) { src_file_name_ = name; } /** * @name get_src_file_name * @fn const std::string& get_src_file_name(void) const * @brief Give the source filename * @return Source file of the parent function */ const std::string& get_src_file_name(void) const { return src_file_name_; } #pragma mark - #pragma mark Predicates /** * @name IsAddressKnown * @fn bool IsAddressKnown(void) const * @brief Indicate if the address is known * @return True if the address has been set to some value, false otherwise */ bool IsAddressKnown(void) const; /** * @name IsLibraryNameKnown * @fn bool IsLibraryNameKnown(void) const * @brief Indicate if the library name has been set * @return True if the library has been set, false otherwise */ bool IsLibraryNameKnown(void) const; /** * @name IsLineNumberKnown * @fn bool IsLineNumberKnown(void) const * @brief Indicate if the line number has been set * @return True if the line number has been set, false otherwise */ bool IsLineNumberKnown(void) const; /** * @name IsMangledSymbolNameKnown * @fn bool IsMangledSymbolNameKnown(void) const * @brief Indicate if the mangled symbol's name has been set * @return True if the mangled symbol name has been set, false otherwise */ bool IsMangledSymbolNameKnown(void) const; /** * @name IsSymbolNameKnown * @fn bool IsSymbolNameKnown(void) const * @brief Indicate if the symbol's name has been set * @return True if the symbol's name has been set, false otherwise */ bool IsSymbolNameKnown(void) const; /** * @name IsOffsetKnown * @fn bool IsOffsetKnown(void) const * @brief Indicate if the offset is set * @return True if the offset has been set, false otherwise */ bool IsOffsetKnown(void) const; /** * @name IsSourceFileNameKnown * @fn bool IsSourceFileNameKnown(void) const * @brief Indicate if the source file is set * @return True if the source filename has been set, false otherwise */ bool IsSourceFileNameKnown(void) const; #pragma mark - #pragma mark Private private: /** Address: Return address in the `parent` (calling) function on the return from the `child` (called) function */ const void* address_; /** Library filename: Executable / Shared-object file name containing the parent function */ std::string library_name_; /** Line number: Line number in the `parent` function corresponding to a call to the `child` function */ int line_number_; /** Mangled Symbol Name: Mangled symbol name of the parent function */ std::string mangled_symbol_name_; /** Symbol Name: Unmangled symbol name */ std::string symbol_name_; /** Offset From Symbol: Offset from the start of the `parent` function to the the call of the `child` function */ std::size_t offset_from_symbol_; /** Source File Name: Name of the source file of the `parent` function */ std::string src_file_name_; }; /** * @class StackTrace * @brief Create a trace of the current stack for debugging purpose. Would * typically be used in within expection context. * @author Christophe Ecabert * @date 10.07.18 * @ingroup core */ class FK_EXPORTS StackTrace { public: #pragma mark - #pragma mark Initialisation /** * @name StackTrace * @fn StackTrace(void) * @brief Constructor */ StackTrace(void); /** * @name StackTrace * @fn StackTrace(const size_t& skip, const size_t& depth) * @brief Constructor * @param[in] skip Number of level to skip before recording the trace * @param[in] depth Depth of the trace */ StackTrace(const size_t& skip, const size_t& depth); /** * @name StackTrace * @fn StackTrace(const StackTrace& other) = default * @brief Copy constructor * @param[in] other Object to copy from */ StackTrace(const StackTrace& other) = default; /** * @name operator= * @fn StackTrace& operator=(const StackTrace& rhs) = default * @brief Assignment operator * @param[in] rhs Object to assign from * @return Newly assigned object */ StackTrace& operator=(const StackTrace& rhs) = default; /** * @name ~StackTrace * @fn ~StackTrace(void) = default * @brief Destructor */ ~StackTrace(void) = default; /** Default depth */ static constexpr size_t kDefaultDepth_ = 64; #pragma mark - #pragma mark Usage /** * @name ToString * @fn void ToString(std::string* str) const * @brief Convert the trace into a readable string * @param[out] str String holding formatted stack trace, or empty if * something went wrong. * @return Status of the operations */ Status ToString(std::string* str) const; /** * @name IsTraceValid * @fn bool IsTraceValid(void) const * @brief Indicate if the trace has been properly queried * return True if query was successful, false otherwise */ bool IsTraceValid(void) const { return trace_valid_; } /** * @name Size * @fn size_t Size(void) const * @brief Give the dimension of the trace * @return Trace's length */ size_t Size(void) const { return frames_.size(); } /** * @name At * @fn StackTraceFrame& At(const size_t& k) * @brief Provide access to the frame at position `k` (read/write) * @param[in] k Position of the frame to access * @return Frame's instance */ StackTraceFrame& At(const size_t& k) { return frames_.at(k); } #pragma mark - #pragma mark Private private: /** Stack frames */ std::vector<StackTraceFrame> frames_; /** Indicate if stack trace has been properly queried */ bool trace_valid_; }; } // namespace FaceKit #endif /* __FACEKIT_STACKTRACE__ */
28.654267
79
0.634135
[ "object", "vector" ]
2673384ce241b87fe609db7282ee562967272f06
4,096
cpp
C++
src/cropbox_filter.cpp
senceryazici/crazyflie-kinect-localization
060dc72a06106e1aedd8daf981297cc70c9e4edd
[ "MIT" ]
3
2020-08-17T22:21:42.000Z
2020-10-30T10:03:46.000Z
src/cropbox_filter.cpp
senceryazici/crazyflie-kinect-localization
060dc72a06106e1aedd8daf981297cc70c9e4edd
[ "MIT" ]
null
null
null
src/cropbox_filter.cpp
senceryazici/crazyflie-kinect-localization
060dc72a06106e1aedd8daf981297cc70c9e4edd
[ "MIT" ]
null
null
null
// Import dependencies #include <ros/ros.h> #include <string> #include <iostream> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <tf/transform_listener.h> #include <pcl_conversions/pcl_conversions.h> #include <sensor_msgs/PointCloud2.h> #include <pcl/filters/crop_box.h> // Definitions ros::Publisher pub; double x_min_value, x_max_value, y_min_value, y_max_value, z_min_value, z_max_value; tf::StampedTransform transform; std::string base_frame; std::string target_frame; int use_transform; void cloud_cb(const sensor_msgs::PointCloud2ConstPtr& cloud_msg) { sensor_msgs::PointCloud2 buffer_local; pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_transformed(new pcl::PointCloud<pcl::PointXYZRGB>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr temp_cloud(new pcl::PointCloud<pcl::PointXYZRGB>); //Create point cloud objects for downsampled_cloud and passed_cloud pcl::PCLPointCloud2* downsampled_cloud = new pcl::PCLPointCloud2; pcl::PCLPointCloud2ConstPtr cloudPtr(downsampled_cloud); pcl::PCLPointCloud2 passed_cloud; // Convert to PCL data type pcl_conversions::toPCL(*cloud_msg, *downsampled_cloud); if (use_transform) { // TODO: use pcl::CropBox<pcl::PointXYZRGB> cbox_filter; instead // to eliminate above line, pcl::toPCLPointCloud2(*cloud_transformed, *downsampled_cloud); // Extra conversion. pcl::fromPCLPointCloud2(*downsampled_cloud, *temp_cloud); pcl_ros::transformPointCloud(*temp_cloud, *cloud_transformed, transform); pcl::toPCLPointCloud2(*cloud_transformed, *downsampled_cloud); } // CropBox Filter, 3D Box filtering. pcl::CropBox<pcl::PCLPointCloud2> cbox_filter; // Set boundaries cbox_filter.setMin(Eigen::Vector4f(x_min_value, y_min_value, z_min_value, 1.0)); cbox_filter.setMax(Eigen::Vector4f(x_max_value, y_max_value, z_max_value, 1.0)); // Set input cloud cbox_filter.setInputCloud(cloudPtr); cbox_filter.filter(passed_cloud); // Convert to ROS data type sensor_msgs::PointCloud2 output_cloud; pcl_conversions::moveFromPCL(passed_cloud, output_cloud); output_cloud.header.frame_id = "/ws_center"; pub.publish(output_cloud); } int main(int argc, char **argv) { // Initialize ROS ros::init(argc, argv, "cropbox_filter"); ros::NodeHandle n; // Load parameters from launch file ros::NodeHandle nh_private("~"); nh_private.param<double>("x_min", x_min_value, 0.5); // 50 cm nh_private.param<double>("x_max", x_max_value, 15.0); // 15 meters nh_private.param<double>("y_min", y_min_value, 0.5); // 50 cm nh_private.param<double>("y_max", y_max_value, 15.0); // 15 meters nh_private.param<double>("z_min", z_min_value, 0.5); // 50 cm nh_private.param<double>("z_max", z_max_value, 15.0); // 15 meters nh_private.param<int>("use_transform", use_transform, 1); // 15 meters nh_private.param<std::string>("base_frame", base_frame, "scan"); nh_private.param<std::string>("target_frame", target_frame, "base_link"); if (use_transform) { ROS_WARN("The use_transform parameter is enabled, point cloud will be transformed from: %s, to: %s", base_frame.c_str(), target_frame.c_str()); } tf::TransformListener listener; listener.waitForTransform(target_frame, base_frame, ros::Time(0), ros::Duration(10.0) ); try { listener.lookupTransform(target_frame, base_frame, ros::Time(0), transform); } catch (tf::TransformException ex) { ROS_ERROR("TransformException: %s, BaseFrame: %s, TargetFrame: %s", ex.what(), base_frame.c_str(), target_frame.c_str()); ros::Duration(1.0).sleep(); // return -1; } // Create Subscriber and listen /cloud_downsampled topic ros::Subscriber sub = n.subscribe<sensor_msgs::PointCloud2>("points_in", 1, cloud_cb); // Create Publisher pub = n.advertise<sensor_msgs::PointCloud2>("points_out", 1); // Spin ros::spin(); return 0; }
33.57377
151
0.70459
[ "transform", "3d" ]
2678edc17a8a55a5bcb5338fb9b4bbf5580dd37e
638
cpp
C++
State/Transformer/RandomSlicer.cpp
vorpal-research/borealis
247ca1bb26690e2d605ffc57785151e86dccd5bb
[ "MIT" ]
null
null
null
State/Transformer/RandomSlicer.cpp
vorpal-research/borealis
247ca1bb26690e2d605ffc57785151e86dccd5bb
[ "MIT" ]
null
null
null
State/Transformer/RandomSlicer.cpp
vorpal-research/borealis
247ca1bb26690e2d605ffc57785151e86dccd5bb
[ "MIT" ]
1
2019-09-02T12:56:27.000Z
2019-09-02T12:56:27.000Z
// // Created by ice-phoenix on 4/29/15. // #include "State/Transformer/RandomSlicer.h" namespace borealis { RandomSlicer::RandomSlicer() : Base(FactoryNest{}), rd(), mtr(rd()) {} double RandomSlicer::getNextRandom() { return std::generate_canonical<double, 10>(mtr); } PredicateState::Ptr RandomSlicer::transform(PredicateState::Ptr ps) { size = ps->size(); return Base::transform(ps)->filter([](auto&& p) { return !!p; }); } Predicate::Ptr RandomSlicer::transformBase(Predicate::Ptr p) { if (getNextRandom() < (2.0 / size)) { return nullptr; } else { return p; } } } // namespace borealis
22
70
0.645768
[ "transform" ]
2685a15db85e44c22523524f4dc24c0c053e55d5
17,400
cpp
C++
src/core/accelerator.cpp
zq317157782/Narukami
c08fa4ee494961516cca97a8cdba3feba2e5f4dc
[ "MIT" ]
7
2019-08-25T08:18:33.000Z
2020-05-06T05:51:57.000Z
src/core/accelerator.cpp
zq317157782/Narukami
c08fa4ee494961516cca97a8cdba3feba2e5f4dc
[ "MIT" ]
1
2019-03-01T06:06:17.000Z
2019-03-01T06:06:17.000Z
src/core/accelerator.cpp
zq317157782/Narukami
c08fa4ee494961516cca97a8cdba3feba2e5f4dc
[ "MIT" ]
1
2020-02-25T06:33:38.000Z
2020-02-25T06:33:38.000Z
/* MIT License Copyright (c) 2019 ZhuQian 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 "core/accelerator.h" #include "core/progressreporter.h" NARUKAMI_BEGIN QBVHCollapseNode *collapse(MemoryArena &arena, const BVHBuildNode *subtree_root, uint32_t *total) { auto node = arena.alloc<QBVHCollapseNode>(1); (*total)++; node->childrens[0] = nullptr; node->childrens[1] = nullptr; node->childrens[2] = nullptr; node->childrens[3] = nullptr; if (is_leaf(subtree_root)) { node->data[0] = subtree_root; node->data[1] = nullptr; node->data[2] = nullptr; node->data[3] = nullptr; node->axis0 = 0; node->axis1 = 0; node->axis2 = 0; return node; } if (is_leaf(subtree_root->childrens[0])) { node->data[0] = subtree_root->childrens[0]; node->data[1] = nullptr; } else { node->data[0] = subtree_root->childrens[0]->childrens[0]; node->data[1] = subtree_root->childrens[0]->childrens[1]; if (!is_leaf(node->data[0])) { node->childrens[0] = collapse(arena, node->data[0], total); } if (!is_leaf(node->data[1])) { node->childrens[1] = collapse(arena, node->data[1], total); } } if (is_leaf(subtree_root->childrens[1])) { node->data[2] = subtree_root->childrens[1]; node->data[3] = nullptr; } else { node->data[2] = subtree_root->childrens[1]->childrens[0]; node->data[3] = subtree_root->childrens[1]->childrens[1]; if (!is_leaf(node->data[2])) { node->childrens[2] = collapse(arena, node->data[2], total); } if (!is_leaf(node->data[3])) { node->childrens[3] = collapse(arena, node->data[3], total); } } node->axis0 = subtree_root->split_axis; node->axis1 = subtree_root->childrens[0]->split_axis; node->axis2 = subtree_root->childrens[1]->split_axis; return node; } uint32_t flatten(std::vector<QBVHNode> &nodes, uint32_t depth, const QBVHCollapseNode *c_node, uint32_t *offset, uint32_t *max_depth) { auto cur_offset = (*offset); (*offset)++; init_QBVH_node(&nodes[cur_offset], depth, c_node); (*max_depth) = max((*max_depth), depth); if (c_node->childrens[0] != nullptr) { nodes[cur_offset].childrens[0] = flatten(nodes, depth + 1, c_node->childrens[0], offset, max_depth); } if (c_node->childrens[1] != nullptr) { nodes[cur_offset].childrens[1] = flatten(nodes, depth + 1, c_node->childrens[1], offset, max_depth); } if (c_node->childrens[2] != nullptr) { nodes[cur_offset].childrens[2] = flatten(nodes, depth + 1, c_node->childrens[2], offset, max_depth); } if (c_node->childrens[3] != nullptr) { nodes[cur_offset].childrens[3] = flatten(nodes, depth + 1, c_node->childrens[3], offset, max_depth); } //set QBVH's split axis nodes[cur_offset].axis0 = c_node->axis0; nodes[cur_offset].axis1 = c_node->axis1; nodes[cur_offset].axis2 = c_node->axis2; return cur_offset; } void get_traversal_orders(const QBVHNode &node, const Vector3f &dir, uint32_t orders[4]) { orders[0] = 0; orders[1] = 1; orders[2] = 2; orders[3] = 3; if (dir[node.axis1] <= 0) { std::swap(orders[0], orders[1]); } if (dir[node.axis2] <= 0) { std::swap(orders[2], orders[3]); } if (dir[node.axis0] <= 0) { std::swap(orders[0], orders[2]); std::swap(orders[1], orders[3]); } } TLAS::TLAS(const std::vector<shared<BLASInstance>> &instance_list) : _instances(instance_list) { STAT_INCREASE_COUNTER(blas_instance_num, instance_list.size()) std::vector<BLASInstanceInfo> instance_infos(instance_list.size()); for (uint32_t i = 0; i < instance_list.size(); ++i) { instance_infos[i] = BLASInstanceInfo(instance_list[i], i); } _bounds = get_max_bounds(instance_infos, 0, static_cast<uint32_t>(instance_infos.size())); MemoryArena arena; std::vector<shared<BLASInstance>> _ordered_instance_list; uint32_t total_build_node_num = 0; uint32_t total_collapse_node_num = 0; auto build_root = build(arena, 0, static_cast<uint32_t>(instance_infos.size()), instance_infos, _ordered_instance_list, &total_build_node_num); _instances = _ordered_instance_list; auto collapse_root = collapse(arena, build_root, &total_collapse_node_num); _nodes.resize(total_collapse_node_num); build_soa_instance_info(build_root); uint32_t offset = 0; _max_depth = 0; flatten(_nodes, 0, collapse_root, &offset, &_max_depth); STAT_INCREASE_MEMORY_COUNTER(QBVH_node_memory_cost, sizeof(QBVHNode) * total_collapse_node_num) } BVHBuildNode *TLAS::build(MemoryArena &arena, uint32_t start, uint32_t end, std::vector<BLASInstanceInfo> &instance_infos, std::vector<shared<BLASInstance>> &ordered, uint32_t *total) { auto node = arena.alloc<BVHBuildNode>(1); (*total)++; Bounds3f max_bounds = get_max_bounds(instance_infos, start, end); uint32_t num = end - start; if (num <= ACCELERATOR_ELEMENT_NUM_PER_LEAF) { //初始化叶子节点 uint32_t offset = static_cast<uint32_t>(ordered.size()); for (uint32_t i = start; i < end; i++) { ordered.push_back(_instances[instance_infos[i].instance_index]); } init_leaf(node, offset, num, max_bounds); } else { Bounds3f centroid_bounds; for (uint32_t i = start; i < end; i++) { centroid_bounds = _union(centroid_bounds, instance_infos[i].centroid); } auto dim = max_extent(centroid_bounds); if (centroid_bounds.min_point[dim] == centroid_bounds.max_point[dim]) { //degenerate auto mid = (start + end) / 2; std::nth_element(&instance_infos[start], &instance_infos[mid], &instance_infos[end - 1] + 1, [dim](const BLASInstanceInfo &p0, const BLASInstanceInfo &p1) { return p0.centroid[dim] < p1.centroid[dim]; }); init_interior(node, build(arena, start, mid, instance_infos, ordered, total), build(arena, mid, end, instance_infos, ordered, total), dim); } else if (num <= 2 * BLAS_ELEMENT_NUM_PER_LEAF) { auto mid = start + ACCELERATOR_ELEMENT_NUM_PER_LEAF; std::nth_element(&instance_infos[start], &instance_infos[mid], &instance_infos[end - 1] + 1, [dim](const BLASInstanceInfo &p0, const BLASInstanceInfo &p1) { return p0.centroid[dim] < p1.centroid[dim]; }); init_interior(node, build(arena, start, mid, instance_infos, ordered, total), build(arena, mid, end, instance_infos, ordered, total), dim); } else { //SAH BucketState bucket_infos[ACCELERATOR_SAH_BUCKET_NUM]; for (uint32_t i = start; i < end; ++i) { auto bucket_index = static_cast<int>(ACCELERATOR_SAH_BUCKET_NUM * offset(centroid_bounds, instance_infos[i].centroid)[dim]); bucket_index = min(bucket_index, ACCELERATOR_SAH_BUCKET_NUM - 1); bucket_infos[bucket_index].bounds = _union(bucket_infos[bucket_index].bounds, instance_infos[i].bounds); bucket_infos[bucket_index].count++; } //compute cost function float costs[ACCELERATOR_SAH_BUCKET_NUM - 1]; for (uint32_t i = 0; i < ACCELERATOR_SAH_BUCKET_NUM - 1; i++) { Bounds3f b0, b1; uint32_t count0 = 0, count1 = 0; for (uint32_t j = 0; j <= i; j++) { b0 = _union(b0, bucket_infos[j].bounds); count0 += bucket_infos[j].count; } for (uint32_t j = i + 1; j < ACCELERATOR_SAH_BUCKET_NUM; j++) { b1 = _union(b1, bucket_infos[j].bounds); count1 += bucket_infos[j].count; } costs[i] = 0.125f + (count0 * surface_area(b0) + count1 * surface_area(b1)) / surface_area(max_bounds); } float min_cost = costs[0]; int min_cost_bucket_index = 0; for (uint32_t i = 1; i < ACCELERATOR_SAH_BUCKET_NUM - 1; i++) { if (costs[i] < min_cost) { min_cost = costs[i]; min_cost_bucket_index = i; } } auto mid_ptr = std::partition(&instance_infos[start], &instance_infos[end - 1] + 1, [=](const BLASInstanceInfo &pi) { auto bucket_index = static_cast<int>(ACCELERATOR_SAH_BUCKET_NUM * between(centroid_bounds.min_point[dim], centroid_bounds.max_point[dim], pi.centroid[dim])); bucket_index = min(bucket_index, ACCELERATOR_SAH_BUCKET_NUM - 1); return bucket_index <= min_cost_bucket_index; }); auto mid = static_cast<uint32_t>(mid_ptr - &instance_infos[0]); init_interior(node, build(arena, start, mid, instance_infos, ordered, total), build(arena, mid, end, instance_infos, ordered, total), dim); } } return node; } std::vector<CompactBLASInstance> pack_instances(const std::vector<shared<BLASInstance>> &instance_list, uint32_t start, uint32_t count) { assert(count > 0); assert((start + count) <= instance_list.size()); uint32_t soa_count = (uint32_t)(count - 1) / SSE_WIDTH + 1; std::vector<Bounds3f> bounds_array; for (uint32_t i = 0; i < soa_count * SSE_WIDTH; ++i) { if (i < count) { bounds_array.push_back(instance_list[start + i]->bounds()); } else { bounds_array.push_back(Bounds3f()); } } std::vector<CompactBLASInstance> soa_instance_info; for (uint32_t i = 0; i < soa_count; ++i) { CompactBLASInstance instance; instance.bounds = load(&bounds_array[i * SSE_WIDTH]); instance.offset = start + i * SSE_WIDTH; soa_instance_info.push_back(instance); } return soa_instance_info; } void TLAS::build_soa_instance_info(BVHBuildNode *node) { if (is_leaf(node)) { auto instance_infos = pack_instances(_instances, node->offset, node->num); node->num = static_cast<uint32_t>(instance_infos.size()); node->offset = static_cast<uint32_t>(_compact_instances.size()); _compact_instances.insert(_compact_instances.end(), instance_infos.begin(), instance_infos.end()); } //codition-> the interior node must has two child node if (node->childrens[0] && node->childrens[1]) { build_soa_instance_info(node->childrens[0]); build_soa_instance_info(node->childrens[1]); } } bool TLAS::intersect(const Ray &ray, SurfaceInteraction *interaction) const { LocalStack<std::pair<const QBVHNode*,float>,MAX_LOCAL_STACK_DEEP> node_stack; RayPack soa_ray(ray.o, ray.d, ray.t_max); int is_positive[3] = {ray.d[0] >= 0 ? 1 : 0, ray.d[1] >= 0 ? 1 : 0, ray.d[2] >= 0 ? 1 : 0}; node_stack.push({&_nodes[0], 0.0f}); bool tlas_has_hit = false; while (!node_stack.empty()) { if (node_stack.top().second > ray.t_max) { node_stack.pop(); continue; } auto node = node_stack.pop().first; float4 box_t; auto box_hits = narukami::intersect(soa_ray.o, safe_rcp(soa_ray.d), float4(0), float4(soa_ray.t_max), is_positive, node->bounds, &box_t); bool push_child[4] = {false, false, false, false}; uint32_t orders[4]; get_traversal_orders((*node), ray.d, orders); for (uint32_t i = 0; i < 4; ++i) { uint32_t index = orders[i]; STAT_INCREASE_COUNTER(ordered_traversal_denom, 1) if (box_hits[index] && box_t[index] < ray.t_max) { STAT_INCREASE_COUNTER(ordered_traversal_num, 1) if (is_leaf(node->childrens[index])) { auto offset = leaf_offset(node->childrens[index]); auto num = leaf_num(node->childrens[index]); for (uint32_t j = offset; j < offset + num; ++j) { auto leaf_box_hits = narukami::intersect(soa_ray.o, safe_rcp(soa_ray.d), float4(0), float4(soa_ray.t_max), is_positive, _compact_instances[j].bounds); for (uint32_t k = 0; k < 4; k++) { if (leaf_box_hits[k]) { auto instance_offset = _compact_instances[j].offset + k; auto blas_instance = _instances[instance_offset]; bool has_hit = blas_instance->intersect(ray, interaction); if (has_hit) { { tlas_has_hit = true; } { //这里不需要更新ray的t_max,因为已经在blas中更新过了 soa_ray.t_max = float4(ray.t_max); } } } } } } else { push_child[index] = true; } } } for (uint32_t i = 0; i < 4; i++) { uint32_t index = orders[i]; if (push_child[index]) { node_stack.push({&_nodes[node->childrens[index]], box_t[index]}); } } } return tlas_has_hit; } bool TLAS::intersect(const Ray &ray) const { LocalStack<const QBVHNode*,MAX_LOCAL_STACK_DEEP> node_stack; RayPack soa_ray(ray); int is_positive[3] = {ray.d[0] >= 0 ? 1 : 0, ray.d[1] >= 0 ? 1 : 0, ray.d[2] >= 0 ? 1 : 0}; node_stack.push(&_nodes[0]); Point2f uv; while (!node_stack.empty()) { auto node =node_stack.pop(); float4 box_t; auto box_hits = narukami::intersect(soa_ray.o, safe_rcp(soa_ray.d), float4(0), float4(soa_ray.t_max), is_positive, node->bounds, &box_t); bool push_child[4] = {false, false, false, false}; uint32_t orders[4]; get_traversal_orders((*node), ray.d, orders); for (uint32_t i = 0; i < 4; ++i) { uint32_t index = orders[i]; STAT_INCREASE_COUNTER(ordered_traversal_denom, 1) if (box_hits[index]) { STAT_INCREASE_COUNTER(ordered_traversal_num, 1) if (is_leaf(node->childrens[index])) { auto offset = leaf_offset(node->childrens[index]); auto num = leaf_num(node->childrens[index]); for (uint32_t j = offset; j < offset + num; ++j) { auto leaf_box_hits = narukami::intersect(soa_ray.o, safe_rcp(soa_ray.d), float4(0), float4(soa_ray.t_max), is_positive, _compact_instances[j].bounds); for (uint32_t k = 0; k < 4; k++) { if (leaf_box_hits[k]) { auto instance_offset = _compact_instances[j].offset + k; auto blas_instance = _instances[instance_offset]; bool is_hit = blas_instance->intersect(ray); if (is_hit) { return true; } } } } } else { push_child[index] = true; } } } for (uint32_t i = 0; i < 4; i++) { uint32_t index = orders[i]; if (push_child[index]) { node_stack.push(&_nodes[node->childrens[index]]); } } } return false; } NARUKAMI_END
36.401674
216
0.565632
[ "vector" ]
2692f132c9d3de78d05d701f3d5aa37b78184cd4
3,139
cpp
C++
07/uva1603_fast.cpp
ericxie/aoapc
10092cebbc5b47364680ffecb5269d94349330e8
[ "MIT" ]
10
2019-11-10T10:37:23.000Z
2021-06-16T14:18:22.000Z
07/uva1603_fast.cpp
ericxie/aoapc
10092cebbc5b47364680ffecb5269d94349330e8
[ "MIT" ]
null
null
null
07/uva1603_fast.cpp
ericxie/aoapc
10092cebbc5b47364680ffecb5269d94349330e8
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> #include <cstring> long long grid[5][55]; int cnt[5]; inline int x2id(int x,int y,int n) { return (n + n + 1) * x + y;} inline int y2id(int x,int y,int n) { return (n + n + 1) * x + n + y;} std::vector<int> grids[5][55]; // grids[width][grid] std::vector<int> edges[5][60]; // edges[width][edge] const int numGrids[5] = {1,5,14,30,55}; const int numEdges[5] = {4,12,24,40,60}; int fullsz[5][55]; int currsz[5][55]; inline void addEdge(int n,int w,int x,int y,int k){ int i; for(i=0;i<w;i++) { grids[n][k].push_back(x2id(x,y+i,n+1)); grids[n][k].push_back(y2id(x+i,y,n+1)); grids[n][k].push_back(y2id(x+i,y+w,n+1)); grids[n][k].push_back(x2id(x+w,y+i,n+1)); fullsz[n][k] += 4; } //fprintf(stderr,"%d %d %d %d,%d: ",n,w,x,y,k); //for(i=0;i<fullsz[n][k];i++) fprintf(stderr,"%d%c",grids[n][k][i],",\n"[i==fullsz[n][k]-1]); } inline void gridEdge(){ int n,w,x,y,k; for(n=0;n<5;n++){ k = 0; for(w=1;w<=n+1;w++){ for(x=0;x<=n+1-w;x++) for(y=0;y<=n+1-w;y++) addEdge(n,w,x,y,k++); } } } inline void edgeGrid(){ int n,i,sz; for(n=0;n<5;n++){ sz = numGrids[n]; //fprintf(stderr,"size = %d , sz = %d\n",n+1,sz); for(i=0;i<sz;i++){ for(int eid : grids[n][i]){ //fprintf(stderr,"%d %d : %d\n",n,i,eid); edges[n][eid].push_back(i); } } // for(i=0;i<numEdges[n];i++){ // fprintf(stderr,"%d :",i); // for(auto x : edges[n][i]) fprintf(stderr," %d",x); // fprintf(stderr,"\n"); // } } } inline void del(int n,int &h,int eid){ for(int x : edges[n][eid]){ //fprintf(stderr,"del: %d ,currsz = %d, fullsz= %d, h = %d;",x,currsz[n][x],fullsz[n][x],h); if(currsz[n][x] == fullsz[n][x]) h--; currsz[n][x]--; //fprintf(stderr,"after : h = %d, currsz = %d\n",h,currsz[n][x]); } } inline void add(int n,int &h,int eid){ for(int x : edges[n][eid]){ //fprintf(stderr,"add: %d ,currsz = %d, fullsz= %d, h = %d;",x,currsz[n][x],fullsz[n][x],h); currsz[n][x]++; if(currsz[n][x] == fullsz[n][x]) h++; //fprintf(stderr,"after : h = %d, currsz = %d\n",h,currsz[n][x]); } } inline int findGrid(int n){ int i; for(i=0;i<numGrids[n];i++) if(currsz[n][i] == fullsz[n][i]) return i; return -1; } bool dfs(int maxd,int d,int n,int h){ //fprintf(stderr,"%d %d %d %d\n",maxd,d,n,h); if(h==0) return true; if(maxd == d) return false; int gid = findGrid(n); //fprintf(stderr,"gid : %d\n",gid); if(gid == -1) return true; for(int i=0; i< fullsz[n][gid]; i++){ del(n,h,grids[n][gid][i]); //fprintf(stderr,"eid : %d, del : %d\n",grids[n][gid][i],h); if(dfs(maxd,d+1,n,h)) return true; add(n,h,grids[n][gid][i]); //fprintf(stderr,"add : %d\n",h); } return false; } int ida(int n,int h){ int d; for(d = (h+n)/(n+1);d <= numGrids[n]; d++ ){ if(dfs(d,0,n,h)) return d; } return -1; } int main(){ int T,sz,i,n,h,t; gridEdge(); edgeGrid(); scanf("%d",&T); while(T--){ scanf("%d %d",&sz,&n); sz--; h = numGrids[sz]; for(i=0;i<h;i++) currsz[sz][i] = fullsz[sz][i]; for(i=0;i<n;i++) { scanf("%d",&t); del(sz,h,t-1); } printf("%d\n",ida(sz,h)); } return 0; }
23.780303
95
0.527875
[ "vector" ]
2694488349b203e72deed32109a9b63f3e4d2097
487
cpp
C++
Source/Renderer/SfmlRenderer.cpp
Hopson97/Slonda-Man
169f95b8db9f1cb694ab459973f98287e5979ab6
[ "MIT" ]
7
2021-03-11T14:29:49.000Z
2021-11-14T20:31:09.000Z
Source/Renderer/SfmlRenderer.cpp
Hopson97/Slonda-Man
169f95b8db9f1cb694ab459973f98287e5979ab6
[ "MIT" ]
null
null
null
Source/Renderer/SfmlRenderer.cpp
Hopson97/Slonda-Man
169f95b8db9f1cb694ab459973f98287e5979ab6
[ "MIT" ]
null
null
null
#include "SfmlRenderer.h" #include <iostream> #include "../GLLib/GLFunctions.h" void SfmlRenderer::add(const sf::Drawable& drawable) { m_sfmlDrawables.push_back(&drawable); } void SfmlRenderer::render(sf::RenderWindow& window) { //prep for SFML drawing GL::unbindAll(); window.pushGLStates(); window.resetGLStates(); for (auto& drawable : m_sfmlDrawables) { window.draw(*drawable); } window.popGLStates(); m_sfmlDrawables.clear(); }
18.037037
52
0.669405
[ "render" ]
269caeab38dc9052542e0105557bc80e5e1212f1
213
cpp
C++
assignment-2/src/renderer/shape.cpp
lherman-cs/cs4160
abcc582e59f139ba8d8e74600ee028f321b308fd
[ "Apache-2.0" ]
2
2019-04-18T21:28:18.000Z
2019-04-18T21:28:52.000Z
assignment-2/src/renderer/shape.cpp
lherman-cs/cs4160
abcc582e59f139ba8d8e74600ee028f321b308fd
[ "Apache-2.0" ]
null
null
null
assignment-2/src/renderer/shape.cpp
lherman-cs/cs4160
abcc582e59f139ba8d8e74600ee028f321b308fd
[ "Apache-2.0" ]
null
null
null
#include "renderer/shape.h" Shape::Shape(int x, int y, int w, int h, const std::vector<std::shared_ptr<const Shape>> &children) : x(x), y(y), w(w), h(h), children(children) {} Shape::~Shape() {}
30.428571
71
0.591549
[ "shape", "vector" ]
269f9742fc31421143b98ecccf315cfa1ba84ddb
3,581
cpp
C++
src/tasks/task-connect-points.cpp
NimaPng/tsid
23bbc6bace4f4623c2189535e71ba63bedbc4368
[ "BSD-2-Clause" ]
null
null
null
src/tasks/task-connect-points.cpp
NimaPng/tsid
23bbc6bace4f4623c2189535e71ba63bedbc4368
[ "BSD-2-Clause" ]
null
null
null
src/tasks/task-connect-points.cpp
NimaPng/tsid
23bbc6bace4f4623c2189535e71ba63bedbc4368
[ "BSD-2-Clause" ]
null
null
null
// // Created by nimapng on 10/10/21. // #include "tsid/math/utils.hpp" #include "tsid/tasks/task-connect-points.hpp" #include "tsid/robots/robot-wrapper.hpp" namespace tsid { namespace tasks { using namespace math; using namespace trajectories; using namespace pinocchio; TaskConnectPoints::TaskConnectPoints(const std::string &name, RobotWrapper &robot, const std::string &point1, const std::string &point2) : TaskMotion(name, robot), pt1(point1), pt2(point2), m_constraint(name, 6, robot.nv()) { assert(m_robot.model().existFrame(pt1)); assert(m_robot.model().existFrame(pt2)); pt1_id = m_robot.model().getFrameId(pt1); pt2_id = m_robot.model().getFrameId(pt2); m_p_error_vec.setZero(6); m_v_error_vec.setZero(6); m_Kp.setZero(6); m_Kd.setZero(6); m_a_des.setZero(6); m_J1.setZero(6, robot.nv()); m_J2.setZero(6, robot.nv()); m_mask.resize(1); m_mask.fill(1.); TaskMotion::setMask(m_mask); m_constraint.resize(dim(), (unsigned int) m_J1.cols()); } int TaskConnectPoints::dim() const { return int(1); } const Vector &TaskConnectPoints::Kp() const { return m_Kp; } const Vector &TaskConnectPoints::Kd() const { return m_Kd; } void TaskConnectPoints::Kp(ConstRefVector Kp) { assert(Kp.size() == 6); m_Kp = Kp; } void TaskConnectPoints::Kd(ConstRefVector Kd) { assert(Kd.size() == 6); m_Kd = Kd; } const ConstraintBase &TaskConnectPoints::getConstraint() const { return m_constraint; } const ConstraintBase &TaskConnectPoints::compute(const double, ConstRefVector, ConstRefVector v, Data &data) { SE3 oMi1, oMi2; Motion v1, v2; m_robot.framePosition(data, pt1_id, oMi1); m_robot.framePosition(data, pt2_id, oMi2); m_robot.frameVelocity(data, pt1_id, v1); m_robot.frameVelocity(data, pt2_id, v2); m_robot.frameClassicAcceleration(data, pt1_id, m_drift1); m_robot.frameClassicAcceleration(data, pt2_id, m_drift2); m_robot.frameJacobianLocal(data, pt1_id, m_J1); m_robot.frameJacobianLocal(data, pt2_id, m_J2); errorInSE3(oMi1, oMi2, m_p_error); // pos err in local frame m_p_error_vec = m_p_error.toVector(); m_v_error = v1 - v2; // vel err in local frame // desired acc in local frame m_a_des = -m_Kp.cwiseProduct(m_p_error_vec) - m_Kd.cwiseProduct(m_v_error.toVector()); m_v_error_vec = m_v_error.toVector(); Vector T, T_dot; Vector par; T.setZero(6); T_dot = T; T.head(3) = m_p_error.toVector().head(3); par = (m_J1 - m_J2) * v; T_dot.head(3) = par.head(3); m_constraint.matrix() = T.transpose() * (m_J1 - m_J2); m_constraint.vector() = T_dot.transpose() * par + T.transpose() * (m_drift1 - m_drift2).toVector(); return m_constraint; } } }
34.104762
117
0.527506
[ "vector", "model" ]
565516063817d457c9e1eb8f391dde1b86e0b691
1,272
cpp
C++
library/source/PathDependentDiscreteDOSU.cpp
calvin456/intro_derivative_pricing
0841fbc0344bee00044d67977faccfd2098b5887
[ "MIT" ]
5
2016-12-28T16:07:38.000Z
2022-03-11T09:55:57.000Z
library/source/PathDependentDiscreteDOSU.cpp
calvin456/intro_derivative_pricing
0841fbc0344bee00044d67977faccfd2098b5887
[ "MIT" ]
null
null
null
library/source/PathDependentDiscreteDOSU.cpp
calvin456/intro_derivative_pricing
0841fbc0344bee00044d67977faccfd2098b5887
[ "MIT" ]
5
2017-06-04T04:50:47.000Z
2022-03-17T17:41:16.000Z
//PathDependentDiscreteDOSU.cpp #include <cmath> #include <PathDependentDiscreteDOSU.h> PathDependentDiscreteDOSU::PathDependentDiscreteDOSU(const MJArray& LookAtTimes_, double DeliveryTime_, double Barrier_, std::shared_ptr<MyOption::Option> TheOption_, double Rebate_) : PathDependentDiscrete(LookAtTimes_, DeliveryTime_, Barrier_, Rebate_), TheOption(TheOption_) {} unsigned long PathDependentDiscreteDOSU::CashFlows(const MJArray& SpotValues, std::vector<MyCashFlow::CashFlow>& GeneratedFlows, method method_) const { GeneratedFlows[0].TimeIndex = 0; GeneratedFlows[0].Amount = Rebate; unsigned long _NumberOfTimes = NumberOfTimes - 1; double _Barrier; if (method_ == logscale) _Barrier = log(Barrier); else _Barrier = Barrier; //compute products of heaviside functions for (unsigned long i = 0; i < _NumberOfTimes; i++) if (_Barrier >= SpotValues[i]) return 1UL; if (method_ == logscale) GeneratedFlows[0].Amount = TheOption->GetValue(exp(SpotValues[_NumberOfTimes - 1])); else GeneratedFlows[0].Amount = TheOption->GetValue(SpotValues[_NumberOfTimes - 1]); return 1UL; } PathDependent* PathDependentDiscreteDOSU::clone() const { return new PathDependentDiscreteDOSU(*this); }
27.652174
86
0.738994
[ "vector" ]
565c8cab8fab534700bdf16a1c2f83caaf8442e5
8,142
cpp
C++
tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use_test.cpp
openharmony-gitee-mirror/communication_wifi
de1ca7ecb2b61d2385f6450fdadab7df9d3a4e37
[ "Apache-2.0" ]
1
2021-12-03T14:28:10.000Z
2021-12-03T14:28:10.000Z
tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use_test.cpp
openharmony-gitee-mirror/communication_wifi
de1ca7ecb2b61d2385f6450fdadab7df9d3a4e37
[ "Apache-2.0" ]
null
null
null
tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use_test.cpp
openharmony-gitee-mirror/communication_wifi
de1ca7ecb2b61d2385f6450fdadab7df9d3a4e37
[ "Apache-2.0" ]
1
2021-09-13T11:18:00.000Z
2021-09-13T11:18:00.000Z
/* * Copyright (c) 2021 Huawei Device 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. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include "mock_wifi_settings.h" #include "mock_wifi_ap_hal_interface.h" #include "operator_overload.h" #include "ap_config_use.h" using namespace OHOS; using ::testing::_; using ::testing::DoAll; using ::testing::Eq; using ::testing::Return; using ::testing::StrEq; using ::testing::ext::TestSize; namespace OHOS { namespace Wifi { std::vector<int> allowed5GFreq, allowed2GFreq; std::vector<int> allowed5GChan, allowed2GChan; std::vector<int> allowedFreqCom; std::map<BandType, std::vector<int32_t>> ChanTbs; class ApConfigUse_Test : public testing::Test { public: static void SetUpTestCase() {} static void TearDownTestCase() {} virtual void SetUp() { allowed5GFreq.clear(); allowed2GFreq.clear(); allowed2GChan.clear(); allowed5GChan.clear(); allowedFreqCom.clear(); ChanTbs.clear(); const int testFreq1 = 2412; const int testFreq2 = 2417; const int testFreq3 = 2472; const int testFreq4 = 2484; const int testFreq5 = 5170; const int testFreq6 = 5745; const int testFreq7 = 5825; allowed2GFreq.push_back(testFreq1); allowed2GFreq.push_back(testFreq2); allowed2GFreq.push_back(testFreq3); allowed2GFreq.push_back(testFreq4); allowed5GFreq.push_back(testFreq5); allowed5GFreq.push_back(testFreq6); allowed5GFreq.push_back(testFreq7); const int testChannel1 = 1; const int testChannel2 = 2; const int testChannel3 = 13; const int testChannel4 = 14; const int testChannel5 = 34; const int testChannel6 = 149; const int testChannel7 = 14; allowed2GChan.push_back(testChannel1); allowed2GChan.push_back(testChannel2); allowed2GChan.push_back(testChannel3); allowed2GChan.push_back(testChannel4); allowed5GChan.push_back(testChannel5); allowed5GChan.push_back(testChannel6); allowed5GChan.push_back(testChannel7); ChanTbs[BandType::BAND_2GHZ] = allowed2GChan; ChanTbs[BandType::BAND_5GHZ] = allowed5GChan; pApConfigUse = new ApConfigUse(); } virtual void TearDown() { allowed5GFreq.clear(); allowed2GFreq.clear(); allowed2GChan.clear(); allowed5GChan.clear(); allowedFreqCom.clear(); ChanTbs.clear(); delete pApConfigUse; pApConfigUse = nullptr; } public: ApConfigUse *pApConfigUse; }; /* TransformFrequencyIntoChannel */ HWTEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel, TestSize.Level1) { const int testFreq1 = 2412; const int testFreq2 = 2417; const int testFreq13 = 2472; const int testFreq14 = 2484; const int testFreq01 = 2411; const int testFreq02 = 2485; const int testFreq03 = 2473; const int testFreq04 = 5826; const int testFreq05 = 5169; const int testChannel34 = 5170; const int testChannel149 = 5745; const int testChannel165 = 5825; /* 2.4G success */ EXPECT_EQ(1, pApConfigUse->TransformFrequencyIntoChannel(testFreq1)); EXPECT_EQ(2, pApConfigUse->TransformFrequencyIntoChannel(testFreq2)); EXPECT_EQ(13, pApConfigUse->TransformFrequencyIntoChannel(testFreq13)); EXPECT_EQ(14, pApConfigUse->TransformFrequencyIntoChannel(testFreq14)); /* 5G success */ EXPECT_EQ(34, pApConfigUse->TransformFrequencyIntoChannel(testChannel34)); EXPECT_EQ(149, pApConfigUse->TransformFrequencyIntoChannel(testChannel149)); EXPECT_EQ(165, pApConfigUse->TransformFrequencyIntoChannel(testChannel165)); /* 2.4G failed */ EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq01)); EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq02)); EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq03)); /* 5G failed */ EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq04)); EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq05)); } /* TransformFrequencyIntoChannel_overload */ HWTEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel_1, TestSize.Level1) { const int testFreq1 = 2412; const int testFreq2 = 2417; const int testFreq3 = 2472; const int testFreq4 = 2484; const int testFreq5 = 5170; const int testFreq6 = 5745; const int testFreq7 = 5825; const int testFreq = -1; std::vector<int> FreqVector; FreqVector.push_back(testFreq1); FreqVector.push_back(testFreq2); FreqVector.push_back(testFreq3); FreqVector.push_back(testFreq4); FreqVector.push_back(testFreq5); FreqVector.push_back(testFreq6); FreqVector.push_back(testFreq7); FreqVector.push_back(testFreq); std::vector<int> FreqVector1 = FreqVector; int buf[] = {1, 2, 13, 14, 34, 149, 165}; std::vector<int> ChanVector; pApConfigUse->TransformFrequencyIntoChannel(FreqVector, ChanVector); for (unsigned long i = 0; i < (sizeof(buf) / 4); ++i) { EXPECT_EQ(buf[i], ChanVector[i]); } EXPECT_EQ(FreqVector1, FreqVector); } /* SetConfig */ HWTEST_F(ApConfigUse_Test, LogConfig_SUCCESS, TestSize.Level1) { HotspotConfig apConfig; apConfig.SetBand(BandType::BAND_2GHZ); HotspotConfig apConfig1 = apConfig; pApConfigUse->LogConfig(apConfig); EXPECT_EQ(apConfig1, apConfig); } /* IsValid24GHz */ HWTEST_F(ApConfigUse_Test, IsValid24GHz, TestSize.Level1) { EXPECT_FALSE(pApConfigUse->IsValid24GHz(2400)); EXPECT_FALSE(pApConfigUse->IsValid24GHz(2500)); EXPECT_TRUE(pApConfigUse->IsValid24GHz(2412)); EXPECT_TRUE(pApConfigUse->IsValid24GHz(2484)); EXPECT_FALSE(pApConfigUse->IsValid24GHz(2499)); } /* IsValid5GHz */ HWTEST_F(ApConfigUse_Test, IsValid5GHz, TestSize.Level1) { EXPECT_FALSE(pApConfigUse->IsValid5GHz(4900)); EXPECT_FALSE(pApConfigUse->IsValid5GHz(5169)); EXPECT_TRUE(pApConfigUse->IsValid5GHz(5170)); EXPECT_TRUE(pApConfigUse->IsValid5GHz(5825)); EXPECT_FALSE(pApConfigUse->IsValid5GHz(5827)); } /* CheckBandChannel */ HWTEST_F(ApConfigUse_Test, CheckBandChannel_1, TestSize.Level1) { HotspotConfig apConfig; apConfig.SetBand(BandType::BAND_2GHZ); apConfig.SetChannel(2); HotspotConfig apConfig1 = apConfig; std::vector<int32_t> band_2G_channel = { 1, 2, 3, 4, 5, 6, 7 }; std::vector<int32_t> band_5G_channel = { 149, 168, 169 }; ChannelsTable ChannelsTb = { { BandType::BAND_2GHZ, band_2G_channel }, { BandType::BAND_5GHZ, band_5G_channel } }; pApConfigUse->CheckBandChannel(apConfig, ChannelsTb); EXPECT_EQ(apConfig1, apConfig); } HWTEST_F(ApConfigUse_Test, CheckBandChannel_2, TestSize.Level1) { HotspotConfig apConfig; apConfig.SetBand(BandType::BAND_2GHZ); apConfig.SetChannel(9); std::vector<int32_t> band_2G_channel = { 1, 2, 3, 4, 5, 6, 7 }; std::vector<int32_t> band_5G_channel = { 149, 168, 169 }; ChannelsTable ChannelsTb = { { BandType::BAND_2GHZ, band_2G_channel }, { BandType::BAND_5GHZ, band_5G_channel } }; pApConfigUse->CheckBandChannel(apConfig, ChannelsTb); EXPECT_EQ(apConfig.GetChannel(), 6); EXPECT_EQ(apConfig.GetBand(), BandType::BAND_2GHZ); } HWTEST_F(ApConfigUse_Test, CheckBandChannel_3, TestSize.Level1) { HotspotConfig apConfig; ChannelsTable ChannelsTb; pApConfigUse->CheckBandChannel(apConfig, ChannelsTb); EXPECT_EQ(apConfig.GetChannel(), 6); EXPECT_EQ(apConfig.GetBand(), BandType::BAND_2GHZ); } } // namespace Wifi } // namespace OHOS
34.944206
118
0.711373
[ "vector" ]
565f5e24832c8958757905b91c298656872703b1
1,481
hpp
C++
include/enumerable.hpp
ZiJer/linqxx
2d89c6e912998273cf1e2bab60045f4f08ea055d
[ "MIT" ]
1
2020-04-15T00:57:33.000Z
2020-04-15T00:57:33.000Z
include/enumerable.hpp
ZiJer/linqxx
2d89c6e912998273cf1e2bab60045f4f08ea055d
[ "MIT" ]
null
null
null
include/enumerable.hpp
ZiJer/linqxx
2d89c6e912998273cf1e2bab60045f4f08ea055d
[ "MIT" ]
1
2020-05-08T21:22:32.000Z
2020-05-08T21:22:32.000Z
#pragma once #include <memory> // std::shared_ptr #include <optional> // std::optional #include <utility> // std::declval #include <vector> // std::vector namespace linqxx { template <typename T> class iterator; template <typename T> class enumerator { public: virtual std::optional<T> next() = 0; virtual ~enumerator(){}; }; template <typename T, typename TKey> class grouping_enumerable; template <typename T> class enumerable { public: using value_type = T; virtual std::unique_ptr<enumerator<T>> enumerate() = 0; iterator<T> begin(); iterator<T> end(); template <typename TF> std::shared_ptr<enumerable<T>> where(TF pred); template <typename TF, typename TResult = typename std::invoke_result<TF, const T &>::type> std::shared_ptr<enumerable<TResult>> select(TF selector); template <typename TF, typename TKey = typename std::invoke_result<TF, const T &>::type, class Hash = std::hash<TKey>, class Pred = std::equal_to<TKey>> std::shared_ptr<enumerable<std::shared_ptr<grouping_enumerable<T, TKey>>>> groupby(TF selector); template <typename TF, typename TResult = typename std::invoke_result<TF, const T &>::type::element_type::value_type> std::shared_ptr<enumerable<TResult>> selectmany(TF selector); T first(); T last(); std::vector<T> to_vector(); void for_each(void (*action)(T &)); protected: virtual std::shared_ptr<enumerable<T>> share() = 0; }; } // namespace linqxx
25.101695
156
0.686023
[ "vector" ]
566d9ee2b40d021b50ddb88f7a779c4fb6aea560
2,159
cpp
C++
codeBase/CodeJam/2010/2010_1B_A/2010_1B_A.cpp
suren3141/codeBase
10ed9a56aca33631dc8c419cd83859c19dd6ff09
[ "Apache-2.0" ]
3
2020-03-16T14:59:08.000Z
2021-07-28T20:51:53.000Z
codeBase/CodeJam/2010/2010_1B_A/2010_1B_A.cpp
suren3141/codeBase
10ed9a56aca33631dc8c419cd83859c19dd6ff09
[ "Apache-2.0" ]
2
2016-04-16T05:39:20.000Z
2016-06-06T12:24:56.000Z
codeBase/CodeJam/2010/2010_1B_A/2010_1B_A.cpp
killerilaksha/codeBase
91cbd950fc90066903e58311000784aeba4ffc02
[ "Apache-2.0" ]
18
2020-02-17T23:17:37.000Z
2021-07-28T20:52:13.000Z
/* Copyright Hackers' Club, University Of Peradeniya Author : E/13/181 (Samurdhi Karunarathne) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdio.h> #include <iostream> #include <vector> #include <map> #include <cmath> #include <climits> #include <algorithm> #include <sstream> using namespace std; typedef long long ll; typedef pair<ll, ll> pr; bool exist(vector<string> arr, string s, int len) { int n = len, l = 0, r = n - 1, x; while (l <= r) { x = (l + r) / 2; if (arr[x] == s) { return true; } else if (arr[x] > s) { r = x - 1; } else l = x + 1; } return false; } int main() { ios_base::sync_with_stdio(false); int t; cin >> t; for (int i = 0; i < t; i++) { vector<string> arr; int n, m, ans = 0, len = 0; cin >> n >> m; for (int j = 0; j < n; j++) { string s; cin >> s; arr.push_back(s); len++; } for (int j = 0; j < m; j++) { string parsed, input, check_str = ""; cin >> input; stringstream ss(input); while (getline(ss, parsed, '/')) { if (parsed != "") { //cout<<parsed<<" "<<endl; check_str += "/" + parsed; //cout<<check_str<<" "<<endl; sort(arr.begin(), arr.end()); if (!exist(arr, check_str, len)) { ans++; arr.push_back(check_str); len++; } } } } printf("Case #%d: %d\n", i + 1, ans ); } }
29.175676
72
0.512274
[ "vector" ]
5680063f1c15e38fa56a7e621e04deebe553ae57
670
hpp
C++
dataurus/include/table_t.hpp
TheofilosBel/sigmod2018
61b3cab644f6143dfe6b6b81421e418ff9b81556
[ "MIT" ]
28
2018-04-10T19:14:13.000Z
2021-06-25T23:54:50.000Z
dataurus/include/table_t.hpp
geooo109/sigmod2018-1
61b3cab644f6143dfe6b6b81421e418ff9b81556
[ "MIT" ]
null
null
null
dataurus/include/table_t.hpp
geooo109/sigmod2018-1
61b3cab644f6143dfe6b6b81421e418ff9b81556
[ "MIT" ]
12
2018-04-10T19:15:38.000Z
2019-12-29T15:44:16.000Z
#pragma once #include <vector> #include <unordered_map> #include "parallel_radix_join.h" #include "filter_job.h" typedef struct table_t table_t; typedef struct column_t column_t; struct column_t { uint64_t *values; uint64_t size; uint64_t table_index; unsigned id; }; struct table_t { /* Row Ids and relation Ids */ unsigned * row_ids; unsigned tups_num; unsigned rels_num; /* use the binfing to map the relations */ std::unordered_map<unsigned, unsigned> relations_bindings; /* Intermediate result falg */ bool intermediate_res; /* column_t pointer of column to join */ column_t *column_j; };
19.142857
62
0.686567
[ "vector" ]
5684e285b99db88e1bc03865f6291b688f32e5ea
689
cpp
C++
algorithms/cpp/119.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
3
2016-10-01T10:15:09.000Z
2017-07-09T02:53:36.000Z
algorithms/cpp/119.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
algorithms/cpp/119.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> getRow(int rowIndex) { vector<int> row(rowIndex+1, 0); row[0] = 1; for ( int i = 1; i <= rowIndex; i++ ) for ( int j = i; j > 0; j-- ) row[j] += row[j-1]; for ( int i = 0; i < rowIndex/2; i++ ) row[rowIndex-i] = row[i]; return row; } }; int main() { Solution solution; for ( int k = 0; k < 5; k++ ) { vector<int> result = solution.getRow(k); for ( int i = 0; i < (int)result.size(); i++ ) cout << result[i] << " "; cout << endl; } return 0; }
20.878788
54
0.45283
[ "vector" ]
569f78dd999f7f9bd592853fa4ce27e79bd640db
2,178
cpp
C++
sail/csrc/core/TensorBody.cpp
sail-ml/sail
e261ef22661aa267bcf32d1552be95d8b7255220
[ "BSD-3-Clause" ]
1
2021-04-28T16:29:02.000Z
2021-04-28T16:29:02.000Z
sail/csrc/core/TensorBody.cpp
sail-ml/sail
e261ef22661aa267bcf32d1552be95d8b7255220
[ "BSD-3-Clause" ]
56
2021-04-28T16:39:05.000Z
2021-07-29T01:13:25.000Z
sail/csrc/core/TensorBody.cpp
sail-ml/sail
e261ef22661aa267bcf32d1552be95d8b7255220
[ "BSD-3-Clause" ]
null
null
null
#include "TensorBody.h" #include "Tensor.h" #include "dtypes.h" #include "factories.h" #include "tensor_shape.h" #include "utils.h" namespace sail { TensorBody::TensorBody(void* _data, Dtype _dtype, TensorShape _shape, bool _view) : data(_data), dtype(_dtype), shape(new TensorShape(_shape)), view(_view), info(getAlignment(_dtype)), refcount_(0){}; TensorBody::TensorBody(Dtype _dtype, TensorShape _shape, bool _view) { dtype = _dtype; shape = new TensorShape(_shape); info = getAlignment(_dtype); refcount_ = 0; view = _view; data = _malloc_align(shape->numel(), info.alignment, info.dtype_size); }; TensorBody::~TensorBody() { if (data != nullptr) { if (!view) { std::free(data); // NOLINT } delete shape; if (_has_grad) { delete grad; } data = nullptr; shape = nullptr; grad = nullptr; } } void TensorBody::set_grad(Tensor& t) { if (t.is_view()) { t = clone(t); grad = new Tensor(t.get_body(), t.requires_grad); } else { grad = new Tensor(t.get_body(), t.requires_grad); } _has_grad = true; } Tensor TensorBody::get_grad() { return *grad; } void TensorBody::clear_grad() { delete grad; grad = nullptr; _has_grad = false; } void* TensorBody::get_data() { return data; } Dtype TensorBody::get_dtype() { return dtype; } TensorShape TensorBody::get_shape() { return *shape; } alignemnt_information TensorBody::get_info() { return info; } bool TensorBody::is_view() { return view; } bool TensorBody::has_grad() { return _has_grad; } void TensorBody::set_is_view(bool x) { view = x; } int TensorBody::get_ref_count() { return (int)refcount_; } void TensorBody::force_incref() { refcount_.fetch_add(1, std::memory_order_relaxed); } void TensorBody::force_decref() { refcount_.fetch_sub(1, std::memory_order_release); } void TensorBody::set_shape(const TensorShape& s) { delete shape; shape = new TensorShape(s.shape, s.strides); } long int* TensorBody::get_shape_ptr() { return shape->get_shape_ptr(); } } // namespace sail
26.240964
74
0.6382
[ "shape" ]
56a2125cacb7c93c62e99acd596905bf6d0b7d9f
828
hh
C++
hackt_docker/hackt/src/util/addressof.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/util/addressof.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/util/addressof.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "util/addressof.hh" Inspired by boost::utility::addressof. $Id: addressof.hh,v 1.1 2006/05/07 20:56:09 fang Exp $ */ #ifndef __UTIL_ADDRESSOF_H__ #define __UTIL_ADDRESSOF_H__ namespace util { //============================================================================= /** Since some compilers have trouble parsing address of operators. NOTE: this is not as smart as boost's implementation which elides the result of an overloaded unary & (address-of) operator, by using a combination of casts. \param T the object type, may be cv-qualified. \param t reference whose address is to be taken. */ template <class T> inline T* addressof(T& t) { return &t; } //============================================================================= } // end namespace util #endif // __UTIL_ADDRESSOF_H__
25.875
79
0.583333
[ "object" ]
56ab60f618e1a11d68f994f2820cac5af82efc6c
2,332
cpp
C++
uva/11228.cpp
btjanaka/competitive-programming-solutions
e3df47c18451802b8521ebe61ca71ee348e5ced7
[ "MIT" ]
3
2020-06-25T21:04:02.000Z
2021-05-12T03:33:19.000Z
uva/11228.cpp
btjanaka/competitive-programming-solutions
e3df47c18451802b8521ebe61ca71ee348e5ced7
[ "MIT" ]
null
null
null
uva/11228.cpp
btjanaka/competitive-programming-solutions
e3df47c18451802b8521ebe61ca71ee348e5ced7
[ "MIT" ]
1
2020-06-25T21:04:06.000Z
2020-06-25T21:04:06.000Z
// Author: btjanaka (Bryon Tjanaka) // Problem: (UVa) 11228 #include <bits/stdc++.h> #define GET(x) scanf("%d", &x) #define GED(x) scanf("%lf", &x) typedef long long ll; using namespace std; typedef pair<int, int> ii; struct UnionFind { vector<int> p, rank; int comps; UnionFind(int n) : p(n), rank(n, 0) { iota(p.begin(), p.end(), 0); comps = n; } int find(int i) { return i == p[i] ? i : (p[i] = find(p[i])); } bool same(int i, int j) { return find(i) == find(j); } void join(int i, int j) { if (!same(i, j)) { --comps; int x = find(i), y = find(j); if (rank[x] < rank[y]) { p[x] = y; } else { p[y] = x; if (rank[x] == rank[y]) ++rank[x]; } } } }; int main() { int ca; GET(ca); for (int caa = 1; caa <= ca; ++caa) { int n; double r; GET(n); GED(r); double coords[n][2]; for (int i = 0; i < n; ++i) { GED(coords[i][0]); GED(coords[i][1]); } // Create two sets of edges vector<pair<double, ii>> roads, railroads; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { double dx = coords[j][0] - coords[i][0]; double dy = coords[j][1] - coords[i][1]; double d = sqrt(dx * dx + dy * dy); if (d <= r) { roads.push_back({d, {i, j}}); } else { railroads.push_back({d, {i, j}}); } } } sort(roads.begin(), roads.end()); sort(railroads.begin(), railroads.end()); // Results int states = 0; double road_cost = 0.0; double railroad_cost = 0.0; UnionFind uf(n); // Select roads for (const pair<double, ii>& road : roads) { double cost = road.first; int u = road.second.first, v = road.second.second; if (uf.same(u, v)) continue; uf.join(u, v); road_cost += cost; } // Determine number of states states = uf.comps; // Select railroads for (const pair<double, ii>& railroad : railroads) { double cost = railroad.first; int u = railroad.second.first, v = railroad.second.second; if (uf.same(u, v)) continue; uf.join(u, v); railroad_cost += cost; } printf("Case #%d: %d %d %d\n", caa, states, (int)round(road_cost), (int)round(railroad_cost)); } return 0; }
23.089109
70
0.504717
[ "vector" ]
56ad09f4d141d51f3bcd468b840c39014acd0c72
488
cpp
C++
Source/Engine/ING/Source/ING/Rendering/StandardRP/Pass/UIPass/UIPass.cpp
n-c0d3r/ING
f858c973e1b31ffc6deb324fa52eda6323d2c165
[ "MIT" ]
2
2022-01-21T04:03:55.000Z
2022-03-19T08:54:00.000Z
Source/Engine/ING/Source/ING/Rendering/StandardRP/Pass/UIPass/UIPass.cpp
n-c0d3r/ING
f858c973e1b31ffc6deb324fa52eda6323d2c165
[ "MIT" ]
null
null
null
Source/Engine/ING/Source/ING/Rendering/StandardRP/Pass/UIPass/UIPass.cpp
n-c0d3r/ING
f858c973e1b31ffc6deb324fa52eda6323d2c165
[ "MIT" ]
null
null
null
/** * Include Header */ #include "UIPass.h" namespace ING { namespace Rendering { namespace StandardRP { /** * Constructors And Destructor */ UIPass::UIPass(const String& name) : IPass(name) { } UIPass::~UIPass() { } /** * Release Methods */ void UIPass::Release() { IPass::Release(); } /** * Methods */ bool UIPass::Render(IDeviceContext* context, Camera* camera) { return true; } } } }
8.561404
65
0.528689
[ "render" ]
56ae08b7403c3fc7ee1a60ccdb8a5dfff1a78dfd
15,503
cpp
C++
test/results_central_absolute_pose.cpp
mateus03/2018AMMPoseSolver
787886846199cd0864c4e59a6545c40c3120010a
[ "BSD-3-Clause" ]
5
2019-05-15T12:41:36.000Z
2020-09-07T10:42:52.000Z
test/results_central_absolute_pose.cpp
mateus03/2018AMMPoseSolver
787886846199cd0864c4e59a6545c40c3120010a
[ "BSD-3-Clause" ]
null
null
null
test/results_central_absolute_pose.cpp
mateus03/2018AMMPoseSolver
787886846199cd0864c4e59a6545c40c3120010a
[ "BSD-3-Clause" ]
1
2021-12-27T18:11:14.000Z
2021-12-27T18:11:14.000Z
/****************************************************************************** * Author: Laurent Kneip * * Contact: kneip.laurent@gmail.com * * License: Copyright (c) 2013 Laurent Kneip, ANU. 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 ANU 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 ANU 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. * ******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <iostream> #include <iomanip> #include <opengv/absolute_pose/methods.hpp> #include <opengv/absolute_pose/CentralAbsoluteAdapter.hpp> #include <opengv/math/cayley.hpp> #include <sstream> #include <fstream> #include <opengv/amm.hpp> #include <opengv/optimization_tools/objective_function_tools/GlobalPnPFunctionInfo.hpp> #include <opengv/optimization_tools/objective_function_tools/OptimalUPnPFunctionInfo.hpp> #include <opengv/optimization_tools/objective_function_tools/GlobalPnPInfiniteNormFunctionInfo.hpp> #include <opengv/optimization_tools/solver_tools/SolverToolsNoncentralRelativePose.hpp> #include "adapter_creator.hpp" #include "random_generators.hpp" #include "experiment_helpers.hpp" #include "time_measurement.hpp" #include <opengv/statistic/StatisticalInfoContainer.hpp> #include <opengv/statistic/iterations_info.hpp> using namespace std; using namespace Eigen; using namespace opengv; int main( int argc, char** argv ) { //initialize random seed initializeRandomSeed(); //set experiment parameters double noise = 0.0; double outlierFraction = 0.0; size_t numberPoints = 100; //Experience parameters int n_experiments = 500; int noise_levels = 10; std::ofstream error_file("absolute_pose_central_error.csv"); std::ofstream iterations_file("absolute_pose_central_iterations.csv"); std::vector<std::vector<StatisticalInfoContainer> > statistical_error_methods(8); for(int index = 0; index < noise_levels; index++){ double noise = 0.0 + 1 * index; int index_stat = 0; while(index_stat < n_experiments){ //create a random viewpoint pose translation_t position = generateRandomTranslation(2.0); rotation_t rotation = generateRandomRotation(0.5); transformation_t gt_transformation; gt_transformation.block<3,3>(0,0) = rotation; gt_transformation.block<3,1>(0,3) = position; transformation_t gt_transformation_amm; gt_transformation_amm.block<3,3>(0,0) = rotation.inverse(); gt_transformation_amm.block<3,1>(0,3) = -rotation.inverse() * position; //create a fake central camera translations_t camOffsets; rotations_t camRotations; generateCentralCameraSystem( camOffsets, camRotations ); //derive correspondences based on random point-cloud bearingVectors_t bearingVectors; points_t points; std::vector<int> camCorrespondences; //unused in the central case! Eigen::MatrixXd gt(3,numberPoints); generateRandom2D3DCorrespondences( position, rotation, camOffsets, camRotations, numberPoints, noise, outlierFraction, bearingVectors, points, camCorrespondences, gt ); //print the experiment characteristics printExperimentCharacteristics( position, rotation, noise, outlierFraction ); //create a central absolute adapter absolute_pose::CentralAbsoluteAdapter adapter( bearingVectors, points, rotation ); //timer struct timeval tic; struct timeval toc; size_t iterations = 10; std::vector<iterations_info> iterations_list; //run the experiments std::cout << "running Kneip's P3P (first three correspondences)" << std::endl; transformations_t p3p_kneip_transformations; transformation_t p3p_kneip_transformation; gettimeofday( &tic, 0 ); for(size_t i = 0; i < iterations; i++) p3p_kneip_transformations = absolute_pose::p3p_kneip(adapter); gettimeofday( &toc, 0 ); double p3p_kneip_time = TIMETODOUBLE(timeval_minus(toc,tic)) / iterations; choose_best_transformation(p3p_kneip_transformations, gt_transformation, p3p_kneip_transformation); StatisticalInfoContainer trial_statistical_info_p3p_kneip(noise, "p3p kneip", p3p_kneip_transformation, gt_transformation, p3p_kneip_time, iterations_list); std::cout << "running Gao's P3P (first three correspondences)" << std::endl; transformations_t p3p_gao_transformations; transformation_t p3p_gao_transformation; gettimeofday( &tic, 0 ); for(size_t i = 0; i < iterations; i++) p3p_gao_transformations = absolute_pose::p3p_gao(adapter); gettimeofday( &toc, 0 ); double p3p_gao_time = TIMETODOUBLE(timeval_minus(toc,tic)) / iterations; choose_best_transformation(p3p_gao_transformations, gt_transformation, p3p_gao_transformation); StatisticalInfoContainer trial_statistical_info_p3p_gao(noise, "p3p gao", p3p_gao_transformation, gt_transformation, p3p_gao_time, iterations_list); std::cout << "running epnp (all correspondences)" << std::endl; transformation_t epnp_transformation; gettimeofday( &tic, 0 ); for(size_t i = 0; i < iterations; i++) epnp_transformation = absolute_pose::epnp(adapter); gettimeofday( &toc, 0 ); double epnp_time = TIMETODOUBLE(timeval_minus(toc,tic)) / iterations; StatisticalInfoContainer trial_statistical_info_epnp(noise, "epnp", epnp_transformation, gt_transformation, epnp_time, iterations_list); std::cout << "running upnp with all correspondences" << std::endl; transformations_t upnp_transformations; transformation_t upnp_transformation; gettimeofday( &tic, 0 ); for(size_t i = 0; i < iterations; i++) upnp_transformations = absolute_pose::upnp(adapter); gettimeofday( &toc, 0 ); double upnp_time = TIMETODOUBLE(timeval_minus(toc,tic)) / iterations; choose_best_transformation(upnp_transformations, gt_transformation, upnp_transformation); StatisticalInfoContainer trial_statistical_info_upnp(noise, "upnp", upnp_transformation, gt_transformation, upnp_time, iterations_list); std::cout << "setting perturbed pose"; std::cout << "and performing nonlinear optimization" << std::endl; //add a small perturbation to the pose translation_t t_perturbed; rotation_t R_perturbed; getPerturbedPose( position, rotation, t_perturbed, R_perturbed, 0.1 ); transformation_t nonlinear_transformation; gettimeofday( &tic, 0 ); for(size_t i = 0; i < iterations; i++) { adapter.sett(t_perturbed); adapter.setR(R_perturbed); nonlinear_transformation = absolute_pose::optimize_nonlinear(adapter); } gettimeofday( &toc, 0 ); double nonlinear_time = TIMETODOUBLE(timeval_minus(toc,tic)) / iterations; StatisticalInfoContainer trial_statistical_info_nonlin(noise, "nonlin", nonlinear_transformation, gt_transformation, nonlinear_time, iterations_list); //Create solver pointer and solver tools SolverTools * solver_container = solver_container = new SolverToolsNoncentralRelativePose(); amm solver_object; std::default_random_engine generator; std::normal_distribution<double> distribution(0.0, 9 * (index + 1)); double angle = (M_PI / 90 ) * distribution(generator); std::cout << "The angle is: " << angle << std::endl; rotation_t error_rot = Eigen::Matrix3d::Identity(3,3); error_rot(0,0) = std::cos(angle);error_rot(0,1) = -std::sin(angle); error_rot(1,0) = std::sin(angle);error_rot(1,1) = std::cos(angle); std::cout << "Rotation error: " << std::endl << error_rot << std::endl; rotation_t rotation_init = rotation * error_rot; translation_t translation_init = position; rotation_init = rotation_init.inverse();//rotation_init.inverse(); translation_init = -rotation_init * translation_init; //AMM GlobalPnPFunctionInfo double tol = 1e-9; double step = 0.008; transformation_t global_pnp; ObjectiveFunctionInfo * info_container_amm_gpnp = new GlobalPnPFunctionInfo(adapter); gettimeofday(&tic,0); for(int i = 0; i < iterations; ++i){ global_pnp = solver_object.amm_solver( tol, rotation_init, translation_init, info_container_amm_gpnp, solver_container, step, iterations_list); } gettimeofday(&toc,0); delete info_container_amm_gpnp; double time_pnp_global = TIMETODOUBLE(timeval_minus(toc,tic)) / iterations; StatisticalInfoContainer trial_statistical_info_amm_global_pnp(noise, "amm gpnp", global_pnp, gt_transformation_amm, time_pnp_global, iterations_list); //AMM OptimalPnPFunctionInfo step = 0.0051; transformation_t optimal_upnp; ObjectiveFunctionInfo * info_container_optimal_upnp = new OptimalUPnPFunctionInfo(adapter); gettimeofday(&tic, 0); for(int i = 0; i < iterations; ++i){ optimal_upnp = solver_object.amm_solver( tol, rotation_init, translation_init, info_container_optimal_upnp, solver_container, step, iterations_list); } gettimeofday(&toc, 0); delete info_container_optimal_upnp; double time_optimal_upnp = TIMETODOUBLE(timeval_minus(toc,tic)) / iterations; StatisticalInfoContainer trial_statistical_info_amm_optimal_upnp(noise, "amm upnp", optimal_upnp, gt_transformation_amm, time_optimal_upnp, iterations_list); //AMM GlobalPnPFunction Infinite norm step = 0.45; tol = 1e-6; transformation_t infinite_norm_gpnp; ObjectiveFunctionInfo * info_container_inf_norm = new GlobalPnPInfiniteNormFunctionInfo(adapter, rotation_init, translation_init); gettimeofday(&tic, 0); for(int i = 0; i < iterations; ++i){ infinite_norm_gpnp = solver_object.amm_solver( tol, rotation_init.inverse(), -rotation_init.inverse() * translation_init, info_container_inf_norm, solver_container, step, iterations_list); } gettimeofday(&toc, 0); delete info_container_inf_norm; double time_infinite_norm_gpnp = TIMETODOUBLE(timeval_minus(toc,tic)) / iterations; StatisticalInfoContainer trial_statistical_info_amm_infinite_norm_gpnp(noise, "amm infinite norm", infinite_norm_gpnp, gt_transformation_amm, time_infinite_norm_gpnp, iterations_list); //The solver is no longer needed. So it can be erased delete solver_container; iterations_list.clear(); statistical_error_methods[0].push_back(trial_statistical_info_p3p_kneip); statistical_error_methods[1].push_back(trial_statistical_info_p3p_gao); statistical_error_methods[2].push_back(trial_statistical_info_epnp); statistical_error_methods[3].push_back(trial_statistical_info_upnp); statistical_error_methods[4].push_back(trial_statistical_info_nonlin); statistical_error_methods[5].push_back(trial_statistical_info_amm_global_pnp); statistical_error_methods[6].push_back(trial_statistical_info_amm_optimal_upnp); statistical_error_methods[7].push_back(trial_statistical_info_amm_infinite_norm_gpnp); index_stat++; //print the results /*std::cout << "results from Kneip's P3P algorithm:" << std::endl; std::cout << p3p_kneip_transformation << std::endl << std::endl; std::cout << "results from Gao's P3P algorithm:" << std::endl; std::cout << p3p_gao_transformation << std::endl << std::endl; std::cout << "results from epnp algorithm:" << std::endl; std::cout << epnp_transformation << std::endl << std::endl; std::cout << "results from upnp:" << std::endl; std::cout << upnp_transformation << std::endl << std::endl; std::cout << "results from nonlinear algorithm:" << std::endl; std::cout << nonlinear_transformation << std::endl << std::endl; std::cout << "the real transformation: " << std::endl; std::cout << gt_transformation << std::endl; std::cout << "the real transformation (amm)" << std::endl; std::cout << gt_transformation_amm << std::endl; std::cout << "results from gpnp amm" << std::endl; std::cout << global_pnp << std::endl << std::endl; std::cout << "results from upnp amm" << std::endl; std::cout << optimal_upnp << std::endl << std::endl; std::cout << "results from infinite norm gpnp" << std::endl; std::cout << infinite_norm_gpnp << std::endl << std::endl; std::cout << "timings from Kneip's P3P algorithm: "; std::cout << p3p_kneip_time << std::endl; std::cout << "timings from Gao's P3P algorithm: "; std::cout << p3p_gao_time << std::endl; std::cout << "timings from epnp algorithm: "; std::cout << epnp_time << std::endl; std::cout << "timings for the upnp algorithm: "; std::cout << upnp_time << std::endl; std::cout << "timings from nonlinear algorithm: "; std::cout << nonlinear_time << std::endl; std::cout << "timing for gpnp amm" << std::endl; std::cout << time_pnp_global << std::endl; std::cout << "timing for upnp amm" << std::endl; std::cout << time_optimal_upnp << std::endl; std::cout << "timing for infinite norm gpnp amm" << std::endl; std::cout << time_infinite_norm_gpnp << std::endl;*/ } } bool is_amm = false; for(int i = 0; i < statistical_error_methods.size(); ++i){ if(i > 4){ is_amm = true; } for(int j = 0; j < statistical_error_methods[i].size(); ++j){ statistical_error_methods[i][j].printInfo(error_file, iterations_file, is_amm); } } iterations_file.close(); error_file.close(); }
50.498371
190
0.683932
[ "vector" ]
56b23a0b4fcdc5b773cdef610dec2e346462cd49
908
cpp
C++
DEM/Game/src/AI/Navigation/NavMesh.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
15
2019-05-07T11:26:13.000Z
2022-01-12T18:26:45.000Z
DEM/Game/src/AI/Navigation/NavMesh.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
16
2021-10-04T17:15:31.000Z
2022-03-20T09:34:29.000Z
DEM/Game/src/AI/Navigation/NavMesh.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
2
2019-04-28T23:27:48.000Z
2019-05-07T11:26:18.000Z
#include "NavMesh.h" #include <DetourNavMesh.h> namespace DEM::AI { CNavMesh::CNavMesh(float AgentRadius, float AgentHeight, std::vector<U8>&& RawData, std::map<CStrID, CNavRegion>&& Regions) : _AgentRadius(AgentRadius) , _AgentHeight(AgentHeight) , _NavMeshData(std::move(RawData)) , _Regions(std::move(Regions)) { if (_pNavMesh = dtAllocNavMesh()) if (dtStatusFailed(_pNavMesh->init(_NavMeshData.data(), _NavMeshData.size(), 0))) dtFreeNavMesh(_pNavMesh); } //--------------------------------------------------------------------- CNavMesh::~CNavMesh() { if (_pNavMesh) dtFreeNavMesh(_pNavMesh); } //--------------------------------------------------------------------- const CNavRegion* CNavMesh::FindRegion(CStrID ID) const { auto It = _Regions.find(ID); return (It == _Regions.cend()) ? nullptr : &It->second; } //--------------------------------------------------------------------- }
27.515152
123
0.548458
[ "vector" ]
56b52d6d15726e4cdcc12c43ec8beaf5aa473617
23,718
cpp
C++
src/renderer/base/shader_preprocessor.cpp
nomadsinteractive/ark
52f84c6dbd5ca6bdd07d450b3911be1ffd995922
[ "Apache-2.0" ]
5
2018-03-28T09:14:55.000Z
2018-04-02T11:54:33.000Z
src/renderer/base/shader_preprocessor.cpp
nomadsinteractive/ark
52f84c6dbd5ca6bdd07d450b3911be1ffd995922
[ "Apache-2.0" ]
null
null
null
src/renderer/base/shader_preprocessor.cpp
nomadsinteractive/ark
52f84c6dbd5ca6bdd07d450b3911be1ffd995922
[ "Apache-2.0" ]
null
null
null
#include "renderer/base/shader_preprocessor.h" #include <regex> #include "core/types/global.h" #include "core/base/string_buffer.h" #include "core/base/string_table.h" #include "core/types/global.h" #include "core/util/strings.h" #include "renderer/base/pipeline_building_context.h" #include "renderer/base/pipeline_layout.h" #include "renderer/base/render_engine_context.h" #include "renderer/util/render_util.h" #define ARRAY_PATTERN "(?:\\[\\s*(\\d+)\\s*\\])?" #define VAR_TYPE_PATTERN "\\s+(int|uint8|float|[bi]?vec[234]|mat3|mat4|sampler2D|samplerCube)\\s+" #define ATTRIBUTE_PATTERN VAR_TYPE_PATTERN "(?:a_|v_)(\\w+)" ARRAY_PATTERN ";" #define UNIFORM_PATTERN "\\s+(\\w+)\\s+" "(u_\\w+)" ARRAY_PATTERN ";" #define INDENT_STR " " namespace ark { const char* ShaderPreprocessor::ANNOTATION_VERT_IN = "${vert.in}"; const char* ShaderPreprocessor::ANNOTATION_VERT_OUT = "${vert.out}"; const char* ShaderPreprocessor::ANNOTATION_FRAG_IN = "${frag.in}"; const char* ShaderPreprocessor::ANNOTATION_FRAG_OUT = "${frag.out}"; const char* ShaderPreprocessor::ANNOTATION_FRAG_COLOR = "${frag.color}"; static std::regex _INCLUDE_PATTERN("#include\\s*[<\"]([^>\"]+)[>\"]"); static std::regex _STRUCT_PATTERN("struct\\s+(\\w+)\\s*\\{([^}]+)\\}\\s*;"); static std::regex _IN_PATTERN("(?:attribute|varying|in)" ATTRIBUTE_PATTERN); static std::regex _UNIFORM_PATTERN("uniform" UNIFORM_PATTERN); static std::regex _SSBO_PATTERN("layout\\(std140, binding\\s*=\\s*(\\d+)\\)\\s+(?:(?:read|write)only\\s+)?buffer\\s+(\\w+)"); #ifndef ANDROID static char _STAGE_ATTR_PREFIX[PipelineInput::SHADER_STAGE_COUNT + 1][4] = {"a_", "v_", "t_", "e_", "g_", "f_", "c_"}; #else static char _STAGE_ATTR_PREFIX[PipelineInput::SHADER_STAGE_COUNT + 1][4] = {"a_", "v_", "f_", "c_"}; #endif ShaderPreprocessor::ShaderPreprocessor(sp<String> source, PipelineInput::ShaderStage shaderStage, PipelineInput::ShaderStage preShaderStage) : _source(std::move(source)), _shader_stage(shaderStage), _pre_shader_stage(preShaderStage), _version(0), _declaration_ins(_attribute_declarations, shaderStage == PipelineInput::SHADER_STAGE_VERTEX ? ANNOTATION_VERT_IN : ANNOTATION_FRAG_IN), _declaration_outs(_attribute_declarations, shaderStage == PipelineInput::SHADER_STAGE_VERTEX ? ANNOTATION_VERT_OUT : ANNOTATION_FRAG_OUT), _declaration_uniforms(_uniform_declarations, "uniform"), _declaration_samplers(_uniform_declarations, "uniform"), _pre_main(sp<String>::make()), _post_main(sp<String>::make()) { } void ShaderPreprocessor::addPreMainSource(const String& source) { *_pre_main = Strings::sprintf(INDENT_STR "%s\n%s", source.c_str(), _pre_main->c_str()); } void ShaderPreprocessor::addPostMainSource(const String& source) { *_post_main = Strings::sprintf("%s\n" INDENT_STR "%s", _post_main->c_str(), source.c_str()); } void ShaderPreprocessor::addOutputVarModifier(String modifier) { _output_var_modifiers.push_back(std::move(modifier)); } void ShaderPreprocessor::initialize(PipelineBuildingContext& context) { parseMainBlock(_source, context); parseDeclarations(); } void ShaderPreprocessor::initializeAsFirst(PipelineBuildingContext& context) { initialize(context); for(const auto& i : _main_block->_ins) context.addInputAttribute(Strings::capitalizeFirst(i._name), i._type); } static bool sanitizer(const std::smatch& match) { DWARN(false, match.str().c_str()); return false; }; void ShaderPreprocessor::parseMainBlock(const String& source, PipelineBuildingContext& buildingContext) { if(source.find("void main()") != String::npos) { DWARN(false, "Shader which contains main function will not be preprocessed by ark shader preprocessor. Try to replace it with \"vec4 ark_main(vec4 position, ...)\" for better flexibilty and compatibilty"); return; } DWARN(source.search(_IN_PATTERN, sanitizer), "Non-standard attribute declared above, move it into ark_main function's parameters will disable this warning."); static const std::regex FUNC_PATTERN("(vec4|void)\\s+ark_main\\(([^)]*)\\)"); source.search(FUNC_PATTERN, [this] (const std::smatch& m)->bool { const String prefix = m.prefix().str(); const String remaining = m.suffix().str(); String body; size_t prefixStart = parseFunctionBody(remaining, body); sp<String> fragment = sp<String>::make(); _main.push_back(sp<String>::make(prefix)); _main.push_back(fragment); _main.push_back(sp<String>::make(remaining.substr(prefixStart))); _main_block = sp<Function>::make("main", m[2].str(), m[1].str(), body.strip(), std::move(fragment)); return false; }); DCHECK(_main_block, "Parsing source error: \n%s\n Undefined ark_main in shader", source.c_str()); _main_block->parse(buildingContext); } void ShaderPreprocessor::parseDeclarations() { _main.replace(_INCLUDE_PATTERN, [this](const std::smatch& m) { const String filepath = m.str(); this->addInclude(m.str(), m[1].str()); return nullptr; }); auto structPatternReplacer = [this](const std::smatch& m) { const sp<String> declaration = sp<String>::make(m.str()); this->_struct_declarations.push_back(declaration); this->_struct_definitions.push_back(m[1].str(), m[2].str()); return nullptr; }; _includes.replace(_STRUCT_PATTERN, structPatternReplacer); _main.replace(_STRUCT_PATTERN, structPatternReplacer); _main.replace(_UNIFORM_PATTERN, [this](const std::smatch& m) { const sp<String> declaration = sp<String>::make(m.str()); uint32_t length = m[3].str().empty() ? 1 : Strings::parse<uint32_t>(m[3].str()); this->addUniform(m[1].str(), m[2].str(), length, declaration); return nullptr; }); auto ssboPattern = [this](const std::smatch& m) { _ssbos[m[2].str()] = Strings::parse<int32_t>(m[0].str()); return true; }; _includes.search(_SSBO_PATTERN, ssboPattern); _main.search(_SSBO_PATTERN, ssboPattern); if(!_main_block) return; _main_block->genDefinition(); { const String outVar = outputName(); _main.push_back(sp<String>::make("\n\nvoid main() {\n")); _main.push_back(_pre_main); if(outVar && _main_block->hasReturnValue()) _main.push_back(sp<String>::make(Strings::sprintf(INDENT_STR "%s = ", outVar.c_str()))); _main.push_back(sp<String>::make(_main_block->genOutCall(_pre_shader_stage, _shader_stage))); for(const String& i : _output_var_modifiers) { _main.push_back(sp<String>::make(" * ")); _main.push_back(sp<String>::make(i)); } _main.push_back(sp<String>::make(";")); _main.push_back(_post_main); _main.push_back(sp<String>::make("\n}\n\n")); } } ShaderPreprocessor::Preprocessed ShaderPreprocessor::preprocess() { return Preprocessed(_shader_stage, genDeclarations(_main.str())); } void ShaderPreprocessor::setupUniforms(Table<String, sp<Uniform>>& uniforms, int32_t& binding) { for(const auto& iter : _declaration_uniforms.vars()) { const String& name = iter.first; if(!uniforms.has(name)) { const Declaration& declare = iter.second; Uniform::Type type = Uniform::toType(declare.type()); uniforms.push_back(name, sp<Uniform>::make(name, declare.type(), type, type == Uniform::TYPE_STRUCT ? getUniformSize(type, declare.type()) : Uniform::getTypeSize(type), declare.length(), nullptr)); } } int32_t next = binding; for(const sp<Uniform>& i : uniforms.values()) { String::size_type pos = i->name().find('['); DCHECK(pos != 0, "Illegal uniform name: %s", i->name().c_str()); if(_main.contains(pos == String::npos ? i->name() : i->name().substr(0, pos))) { if(i->binding() == -1) { next = binding + 1; i->setBinding(binding); } if(!_declaration_uniforms.has(i->name())) { const String type = i->declaredType(); sp<String> declaration = sp<String>::make(i->declaration("uniform ")); _declaration_uniforms.vars().push_back(i->name(), Declaration(i->name(), type, i->length(), declaration)); if(pos == String::npos) _uniform_declarations.push_back(std::move(declaration)); } } } binding = next; } const char* ShaderPreprocessor::inVarPrefix() const { return _STAGE_ATTR_PREFIX[_pre_shader_stage + 1]; } const char* ShaderPreprocessor::outVarPrefix() const { return _STAGE_ATTR_PREFIX[_shader_stage + 1]; } void ShaderPreprocessor::inDeclare(const String& type, const String& name, int32_t location) { _declaration_ins.declare(type, inVarPrefix(), name, location); } void ShaderPreprocessor::outDeclare(const String& type, const String& name, int32_t location) { _declaration_outs.declare(type, outVarPrefix(), name, location); } void ShaderPreprocessor::linkNextStage(const String& returnValueName) { const char* varPrefix = outVarPrefix(); int32_t location = -1; if(_main_block->hasReturnValue()) _declaration_outs.declare(_main_block->_return_type, varPrefix, returnValueName, ++location); for(const Parameter& i : _main_block->_outs) _declaration_outs.declare(i._type, varPrefix, Strings::capitalizeFirst(i._name), ++location, i.getQualifierStr()); } void ShaderPreprocessor::linkPreStage(const ShaderPreprocessor& preStage, std::set<String>& passThroughVars) { linkParameters(_predefined_parameters, preStage, passThroughVars); linkParameters(_main_block->_ins, preStage, passThroughVars); } sp<Uniform> ShaderPreprocessor::getUniformInput(const String& name, Uniform::Type type) const { if(!_declaration_uniforms.has(name)) return nullptr; const Declaration& declaration = _declaration_uniforms.vars().at(name); DCHECK(Uniform::toType(declaration.type()) == type, "Uniform \"%s\" declared type: %s, but it should be %d", name.c_str(), declaration.type().c_str(), type); return sp<Uniform>::make(name, type, 1, nullptr); } String ShaderPreprocessor::outputName() const { #ifndef ANDROID static const char* sOutputNames[PipelineInput::SHADER_STAGE_COUNT] = {"gl_Position", "", "", "", ANNOTATION_FRAG_COLOR, ""}; #else static const char* sOutputNames[PipelineInput::SHADER_STAGE_COUNT] = {"gl_Position", ANNOTATION_FRAG_COLOR, ""}; #endif return sOutputNames[_shader_stage]; } size_t ShaderPreprocessor::parseFunctionBody(const String& s, String& body) const { String::size_type pos = s.find('{'); DCHECK(pos != String::npos, "Cannot parse function body: %s", s.c_str()); size_t end = Strings::parentheses(s, pos, '{', '}'); body = s.substr(pos + 1, end - 1).strip(); return end + 1; } void ShaderPreprocessor::addUniform(const String& type, const String& name, uint32_t length, const sp<String>& declaration) { Declaration uniform(name, type, length, declaration); if(type.startsWith("sampler")) _declaration_samplers.vars().push_back(name, std::move(uniform)); else _declaration_uniforms.vars().push_back(name, std::move(uniform)); _uniform_declarations.push_back(declaration); } uint32_t ShaderPreprocessor::getUniformSize(Uniform::Type type, const String& declaredType) const { if(type != Uniform::TYPE_STRUCT) return Uniform::getTypeSize(type); const String source = _struct_definitions.at(declaredType); uint32_t size = 0; for(const String& i : source.split(';')) { String vtype, vname; Strings::cut(i.strip(), vtype, vname, ' '); Uniform::Type t = Uniform::toType(vtype); size += getUniformSize(t, vtype.strip()); } return size; } void ShaderPreprocessor::linkParameters(const std::vector<ShaderPreprocessor::Parameter>& parameters, const ShaderPreprocessor& preStage, std::set<String>& passThroughVars) { for(const auto& i : parameters) if(i._modifier & Parameter::PARAMETER_MODIFIER_IN) { const String n = Strings::capitalizeFirst(i._name); inDeclare(i._type, n); if(!preStage._main_block->hasOutAttribute(n)) passThroughVars.insert(n); } } const char* ShaderPreprocessor::getOutAttributePrefix(PipelineInput::ShaderStage preStage) { return _STAGE_ATTR_PREFIX[preStage + 1]; } String ShaderPreprocessor::genDeclarations(const String& mainFunc) const { StringBuffer sb; if(_version && !_main.contains("#version ")) sb << "#version " << _version << '\n'; sb << '\n'; if(_predefined_macros.size()) { for(const String& i : _predefined_macros) sb << i << '\n'; sb << '\n'; } sb << _struct_declarations.str('\n'); sb << _includes.str('\n'); sb << _uniform_declarations.str('\n'); sb << _attribute_declarations.str('\n'); sb << mainFunc; return sb.str(); } void ShaderPreprocessor::addInclude(const String& source, const String& filepath) { const Global<StringTable> stringtable; sp<String> content; const String::size_type pos = filepath.find(':'); if(pos == String::npos) content = stringtable->getString(filepath, false); else content = stringtable->getString(filepath.substr(0, pos), filepath.substr(pos + 1).lstrip('/'), false); _includes.push_back(content ? std::move(content) : sp<String>::make(source)); } ShaderPreprocessor::Function::Function(String name, String params, String returnType, String body, sp<String> placeHolder) : _name(std::move(name)), _params(std::move(params)), _return_type(std::move(returnType)), _body(std::move(body)), _place_hoder(std::move(placeHolder)) { } void ShaderPreprocessor::Function::parse(PipelineBuildingContext& buildingContext) { uint32_t stride = 0; for(const String& i : _params.split(',')) { String s = i.strip(); Parameter param = parseParameter(s); if(param._modifier & Parameter::PARAMETER_MODIFIER_OUT) { const Attribute attr = RenderUtil::makePredefinedAttribute(param._name, param._type); _outs.push_back(std::move(param)); DWARN(attr.length() != 3 || stride % 16 == 0, "3-component out attribute \"%s\" ranged from %d to %d, some GPUs may not like this", attr.name().c_str(), stride, stride + attr.size()); stride += attr.size(); } else { buildingContext.addPredefinedAttribute(Strings::capitalizeFirst(param._name), param._type, PipelineInput::SHADER_STAGE_VERTEX); _ins.push_back(std::move(param)); } } } ShaderPreprocessor::Parameter ShaderPreprocessor::Function::parseParameter(const String& param) { int32_t modifier = Parameter::PARAMETER_MODIFIER_DEFAULT; String type, name; for(const String& i : param.split(' ')) { if(i == "in") { DCHECK(modifier == Parameter::PARAMETER_MODIFIER_DEFAULT, "Conflicts found in parameter(%s)'s qualifier", param.c_str()); modifier = Parameter::PARAMETER_MODIFIER_IN; continue; } if(i == "out") { DCHECK(modifier == Parameter::PARAMETER_MODIFIER_DEFAULT, "Conflicts found in parameter(%s)'s qualifier", param.c_str()); modifier = Parameter::PARAMETER_MODIFIER_OUT; continue; } if(i == "inout") { DCHECK(modifier == Parameter::PARAMETER_MODIFIER_DEFAULT, "Conflicts found in parameter(%s)'s qualifier", param.c_str()); modifier = Parameter::PARAMETER_MODIFIER_INOUT; continue; } if(!type) { type = i; continue; } DASSERT(!name); name = i; } DCHECK(type && name, "Cannot parse function arguments: %s", param.c_str()); return Parameter(std::move(type), std::move(name), static_cast<Parameter::Modifier>(modifier == Parameter::PARAMETER_MODIFIER_DEFAULT ? Parameter::PARAMETER_MODIFIER_IN : modifier)); } void ShaderPreprocessor::Function::genDefinition() { StringBuffer sb; sb << _return_type << " ark_" << _name << "("; const auto begin = _ins.begin(); for(auto iter = begin; iter != _ins.end(); ++iter) { if(iter != begin) sb << ", "; sb << "in " << iter->_type << " " << iter->_name; } for(const auto& i : _outs) sb << ", " << i.getQualifierStr() << " " << i._type << " " << i._name; sb << ") {\n " << _body << "\n}"; *_place_hoder = sb.str(); } String ShaderPreprocessor::Function::genOutCall(PipelineInput::ShaderStage preShaderStage, PipelineInput::ShaderStage shaderStage) const { StringBuffer sb; sb << "ark_main("; const auto begin = _ins.begin(); for(auto iter = begin; iter != _ins.end(); ++iter) { if(iter != begin) sb << ", "; sb << getOutAttributePrefix(preShaderStage); sb << Strings::capitalizeFirst(iter->_name); } for(const auto& i : _outs) sb << ", " << getOutAttributePrefix(shaderStage) << Strings::capitalizeFirst(i._name); sb << ')'; return sb.str(); } bool ShaderPreprocessor::Function::hasOutAttribute(const String& name) const { for(const auto& i : _outs) if(Strings::capitalizeFirst(i._name) == name) return true; return false; } bool ShaderPreprocessor::Function::hasReturnValue() const { return _return_type != "void"; } ShaderPreprocessor::DeclarationList::DeclarationList(Source& source, const String& descriptor) : _source(source), _descriptor(descriptor) { } void ShaderPreprocessor::DeclarationList::declare(const String& type, const char* prefix, const String& name, int32_t location, const char* qualifier) { if(!_vars.has(name)) { sp<String> declared = sp<String>::make(Strings::sprintf("%s %s %s%s;", qualifier ? qualifier : _descriptor.c_str(), type.c_str(), prefix, name.c_str())); if(location >= 0) _source.push_back(sp<String>::make(Strings::sprintf("layout (location = %d) %s", location, declared->c_str()))); else _source.push_back(declared); _vars.push_back(name, Declaration(name, type, 1, declared)); } else DCHECK(_vars.at(name).type() == type, "Declared type \"\" and variable type \"\" mismatch", _vars.at(name).type().c_str(), type.c_str()); } bool ShaderPreprocessor::DeclarationList::has(const String& name) const { return _vars.has(name); } const Table<String, ShaderPreprocessor::Declaration>& ShaderPreprocessor::DeclarationList::vars() const { return _vars; } Table<String, ShaderPreprocessor::Declaration>& ShaderPreprocessor::DeclarationList::vars() { return _vars; } ShaderPreprocessor::Preprocessed::Preprocessed() : _type(PipelineInput::SHADER_STAGE_NONE) { } ShaderPreprocessor::Preprocessed::Preprocessed(PipelineInput::ShaderStage stage, String source) : _type(stage), _source(std::move(source)) { } PipelineInput::ShaderStage ShaderPreprocessor::Preprocessed::stage() const { return _type; } String ShaderPreprocessor::Preprocessed::toSourceCode(const RenderEngineContext& renderEngineContext) const { DCHECK(renderEngineContext.version() > 0, "Unintialized RenderEngineContext"); static std::regex var_pattern("\\$\\{([\\w.]+)\\}"); const std::map<String, String>& annotations = renderEngineContext.annotations(); return _source.replace(var_pattern, [&annotations] (Array<String>& matches)->String { const String& varName = matches.buf()[1]; const auto iter = annotations.find(varName); DCHECK(iter != annotations.end(), "Cannot find constant \"%s\" in RenderEngineContext", varName.c_str()); return iter->second; }); } ShaderPreprocessor::Source::Source(String code) : _fragments{sp<String>::make(std::move(code))} { } String ShaderPreprocessor::Source::str(char endl) const { StringBuffer sb; for(const auto& i : _fragments) if(i && !i->empty()) { sb << *i; if(endl) sb << endl; } return sb.str(); } void ShaderPreprocessor::Source::push_front(const sp<String>& fragment) { _fragments.push_front(fragment); } void ShaderPreprocessor::Source::push_back(const sp<String>& fragment) { _fragments.push_back(fragment); } bool ShaderPreprocessor::Source::search(const std::regex& pattern, const std::function<bool (const std::smatch&)>& traveller) const { for(const sp<String>& i : _fragments) if(!i->search(pattern, traveller)) return false; return true; } bool ShaderPreprocessor::Source::contains(const String& str) const { for(const sp<String>& i : _fragments) if(i->find(str) != String::npos) return true; return false; } void ShaderPreprocessor::Source::replace(const String& str, const String& replacment) { for(const sp<String>& i : _fragments) *i = i->replace(str, replacment); } void ShaderPreprocessor::Source::replace(const std::regex& regexp, const std::function<sp<String>(const std::smatch&)>& replacer) { for(auto iter = _fragments.begin(); iter != _fragments.end(); ++iter) { const sp<String>& fragment = *iter; std::vector<sp<String>> inserting; fragment->search(regexp, [&inserting, replacer](const std::smatch& match) { sp<String> replacement = replacer(match); if(replacement) inserting.push_back(std::move(replacement)); return true; }, [&inserting](const String& unmatch) { inserting.push_back(sp<String>::make(unmatch)); return true; }); if(inserting.size() > 1) { for(const auto& i : inserting) { iter = _fragments.insert(iter, i); ++iter; } iter = _fragments.erase(iter); if(iter == _fragments.end()) break; } } } void ShaderPreprocessor::Source::insertBefore(const String& statement, const String& str) { for(const sp<String>& i : _fragments) { String& code = *i; String::size_type pos = code.find(statement); if(pos != String::npos) code.insert(pos, str); } } ShaderPreprocessor::Declaration::Declaration(const String& name, const String& type, uint32_t length, const sp<String>& source) : _name(name), _type(type), _length(length), _source(source) { } const String& ShaderPreprocessor::Declaration::name() const { return _name; } const String& ShaderPreprocessor::Declaration::type() const { return _type; } uint32_t ShaderPreprocessor::Declaration::length() const { return _length; } const sp<String>& ShaderPreprocessor::Declaration::source() const { return _source; } ShaderPreprocessor::Parameter::Parameter() : _modifier(PARAMETER_MODIFIER_DEFAULT) { } ShaderPreprocessor::Parameter::Parameter(String type, String name, ShaderPreprocessor::Parameter::Modifier modifier) : _type(std::move(type)), _name(std::move(name)), _modifier(modifier) { } const char* ShaderPreprocessor::Parameter::getQualifierStr() const { const char* qualifiers[] = {"in", "in", "out", "inout"}; DASSERT(_modifier >= PARAMETER_MODIFIER_DEFAULT && _modifier <= PARAMETER_MODIFIER_INOUT); return qualifiers[_modifier]; } }
35.033973
245
0.654102
[ "vector" ]
56c06b9253ec1311d672d9f05799a650e44ff027
3,924
cpp
C++
oi/bzoj/P3757/apple.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
oi/bzoj/P3757/apple.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
oi/bzoj/P3757/apple.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#include <cmath> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> using namespace std; #define NMAX 50000 #define LOGN 16 #define MMAX 100000 struct Query { int u, v; int a, b; int answer; }; static int BLOCKSIZE; static int n, m; static int color[NMAX + 10]; static vector<int> G[NMAX + 10]; static int blockcnt, timestamp; static int stktail; static int stk[NMAX + 10]; static int id[NMAX + 10]; static int dfn[NMAX + 10]; static int depth[NMAX + 10]; static int f[LOGN + 1][NMAX + 10]; static Query que[MMAX + 10]; static Query *ref[MMAX + 10]; static bool cmp(const Query *a, const Query *b) { return id[a->u] < id[b->u] || (id[a->u] == id[b->u] && dfn[a->v] < dfn[b->v]); } inline int evaluate_lca(int u, int v) { if (depth[u] < depth[v]) swap(u, v); int delta = depth[u] - depth[v]; for (int i = LOGN; i >= 0; i--) { if ((delta >> i) & 1) u = f[i][u]; } if (u == v) return u; for (int i = LOGN; i >= 0; i--) { if (f[i][u] != f[i][v]) { u = f[i][u]; v = f[i][v]; } } return f[0][u]; } static void dfs(int x, int fa) { int head = stktail; dfn[x] = ++timestamp; for (size_t i = 0; i < G[x].size(); i++) { int v = G[x][i]; if (v == fa) continue; depth[v] = depth[x] + 1; f[0][v] = x; dfs(v, x); if (stktail - head >= BLOCKSIZE) { blockcnt++; while (stktail > head) { id[stk[--stktail]] = blockcnt; } } } stk[stktail++] = x; } static void initialize() { scanf("%d%d", &n, &m); BLOCKSIZE = max(1, static_cast<int>(sqrt(n))); for (int i = 1; i <= n; i++) { scanf("%d", color + i); } for (int i = 0; i < n; i++) { int u, v; scanf("%d%d", &u, &v); if (u != 0 && v != 0) { G[u].push_back(v); G[v].push_back(u); } } dfs(1, 0); blockcnt++; while (stktail) { id[stk[--stktail]] = blockcnt; } for (int j = 1; j <= LOGN; j++) { for (int i = 1; i <= n; i++) { f[j][i] = f[j - 1][f[j - 1][i]]; } } for (int i = 1; i <= m; i++) { scanf("%d%d%d%d", &que[i].u, &que[i].v, &que[i].a, &que[i].b); ref[i] = que + i; if (que[i].u > que[i].v) swap(que[i].u, que[i].v); } sort(ref + 1, ref + m + 1, cmp); } static int answer; static int cnt[NMAX + 10]; static bool marked[NMAX + 10]; inline void add_color(int c) { cnt[c]++; if (cnt[c] == 1) answer++; } inline void del_color(int c) { cnt[c]--; if (cnt[c] == 0) answer--; } inline void flip(int x) { if (marked[x]) del_color(color[x]); else add_color(color[x]); marked[x] ^= true; } inline void flip(int u, int v) { if (depth[u] < depth[v]) swap(u, v); while (u != v) { if (depth[u] > depth[v]) { flip(u); u = f[0][u]; } else { flip(v); v = f[0][v]; } } } int main() { freopen("apple.in", "r", stdin); freopen("apple.out", "w", stdout); initialize(); int lastu = 1, lastv = 1, lastlca = 1; flip(1); for (int i = 1; i <= m; i++) { Query *current = ref[i]; int lca = evaluate_lca(current->u, current->v); flip(lastu, current->u); flip(lastv, current->v); flip(lastlca); flip(lca); int ans = answer; if (current->a != current->b && cnt[current->a] && cnt[current->b]) ans--; current->answer = ans; lastu = current->u; lastv = current->v; lastlca = lca; } for (int i = 1; i <= m; i++) { printf("%d\n", que[i].answer); } return 0; }
19.048544
70
0.445719
[ "vector" ]
56c50b48ef1dfa6d4ca1bb4d2ec25cb3b9757581
953
cpp
C++
tools/ruleTree/Scores.cpp
riyadhariwal1/Gaming-Engine
96cbebe52979d822828585911f8c1a67a639dc83
[ "MIT" ]
null
null
null
tools/ruleTree/Scores.cpp
riyadhariwal1/Gaming-Engine
96cbebe52979d822828585911f8c1a67a639dc83
[ "MIT" ]
null
null
null
tools/ruleTree/Scores.cpp
riyadhariwal1/Gaming-Engine
96cbebe52979d822828585911f8c1a67a639dc83
[ "MIT" ]
null
null
null
#include "Scores.h" #include <bits/stdc++.h> ScoreRule::ScoreRule (string score, bool ascending) : score(score) , ascending(ascending) { } void ScoreRule::execute (State& gameState) { //TODO: the score should determine what field we should sort by vector<Player> list = gameState.getPlayers(); if (this->ascending) { sort(gameState.getWinners().begin(), gameState.getWinners().end(), [] (Player& player1, Player& player2) { return (player1.getGameWins() < player2.getGameWins()); }); } } void ScoreRule:: print() { cout <<"Score:" << endl; cout << " score == " << score <<endl; cout << " ascending == " << ascending << endl; } void ScoreRule::accept(AstVisitor& visitor, State& gameState) { visitor.visit(*this,gameState); } void ScoreRule::accept(AstVisitor& visitor, State& gameState , List& list, Element& element) { visitor.visit(*this, gameState, list, element); }
30.741935
114
0.640084
[ "vector" ]
56ca46a6793f621b140eb9cc57b44cd205f63336
34,560
cpp
C++
src/ofxNvFlex.cpp
teresuac/ofx_flex_paint
340dbd04ffb356ab24bfb023a6722e50366f6c3c
[ "MIT" ]
1
2021-06-11T10:08:15.000Z
2021-06-11T10:08:15.000Z
src/ofxNvFlex.cpp
teresuac/ofx_flex_paint
340dbd04ffb356ab24bfb023a6722e50366f6c3c
[ "MIT" ]
null
null
null
src/ofxNvFlex.cpp
teresuac/ofx_flex_paint
340dbd04ffb356ab24bfb023a6722e50366f6c3c
[ "MIT" ]
null
null
null
#include "ofxNvFlex.h" #include <stdlib.h> #define DEBUG_MODE false //error namespace m { void ErrorCallback(NvFlexErrorSeverity, const char* msg, const char* file, int line) { printf("Flex: %s - %s:%d\n", msg, file, line); } } void ofx_nvflex::init_flex() { int g_device = -1; g_device = NvFlexDeviceGetSuggestedOrdinal(); bool success = NvFlexDeviceCreateCudaContext(g_device); if (!success) { printf("Error creating CUDA context.\n"); } NvFlexInitDesc desc; desc.deviceIndex = g_device; desc.enableExtensions = true; desc.renderDevice = 0; desc.renderContext = 0; desc.computeType = eNvFlexCUDA; library = NvFlexInit(NV_FLEX_VERSION, m::ErrorCallback, &desc); cursor = 0; buffers = new SimBuffers(library); buffers->MapBuffers(); buffers->InitBuffers(); NvFlexSetSolverDescDefaults(&g_solverDesc); maxParticles = 50000; g_maxDiffuseParticles = 0; g_maxNeighborsPerParticle = 196; g_maxContactsPerParticle = 8; //g_solverDesc.featureMode = eNvFlexFeatureModeSimpleFluids ; // eNvFlexFeatureModeDefault; g_solverDesc.featureMode = eNvFlexFeatureModeSimpleSolids; // eNvFlexFeatureModeDefault; // g_solverDesc.featureMode = eNvFlexFeatureModeDefault; g_solverDesc.maxParticles = maxParticles; g_solverDesc.maxDiffuseParticles = 0; g_solverDesc.maxNeighborsPerParticle = g_maxNeighborsPerParticle; g_solverDesc.maxContactsPerParticle = g_maxContactsPerParticle; solver = NvFlexCreateSolver(library, &g_solverDesc); } Mesh* ImportMeshFromObj(const char* path) { ifstream file(path); if (!file) return NULL; Mesh* m = new Mesh(); vector<Point3> positions; vector<Vector3> normals; vector<Vector2> texcoords; vector<Vector3> colors; vector<uint32_t>& indices = m->m_indices; //typedef unordered_map<VertexKey, uint32_t, MemoryHash<VertexKey> > VertexMap; typedef map<VertexKey, uint32_t> VertexMap; VertexMap vertexLookup; // some scratch memory const uint32_t kMaxLineLength = 1024; char buffer[kMaxLineLength]; //double startTime = GetSeconds(); while (file) { file >> buffer; if (strcmp(buffer, "vn") == 0) { // normals float x, y, z; file >> x >> y >> z; normals.push_back(Vector3(x, y, z)); } else if (strcmp(buffer, "vt") == 0) { // texture coords float u, v; file >> u >> v; texcoords.push_back(Vector2(u, v)); } else if (buffer[0] == 'v') { // positions float x, y, z; file >> x >> y >> z; positions.push_back(Point3(x, y, z)); } else if (buffer[0] == 's' || buffer[0] == 'g' || buffer[0] == 'o') { // ignore smoothing groups, groups and objects char linebuf[256]; file.getline(linebuf, 256); } else if (strcmp(buffer, "mtllib") == 0) { // ignored std::string MaterialFile; file >> MaterialFile; } else if (strcmp(buffer, "usemtl") == 0) { // read Material name std::string materialName; file >> materialName; } else if (buffer[0] == 'f') { // faces uint32_t faceIndices[4]; uint32_t faceIndexCount = 0; for (int i = 0; i < 4; ++i) { VertexKey key; file >> key.v; if (!file.eof()) { // failed to read another index continue on if (file.fail()) { file.clear(); break; } if (file.peek() == '/') { file.ignore(); if (file.peek() != '/') { file >> key.vt; } if (file.peek() == '/') { file.ignore(); file >> key.vn; } } // find / add vertex, index VertexMap::iterator iter = vertexLookup.find(key); if (iter != vertexLookup.end()) { faceIndices[faceIndexCount++] = iter->second; } else { // add vertex uint32_t newIndex = uint32_t(m->m_positions.size()); faceIndices[faceIndexCount++] = newIndex; vertexLookup.insert(make_pair(key, newIndex)); // push back vertex data assert(key.v > 0); m->m_positions.push_back(positions[key.v - 1]); // obj format doesn't support mesh colours so add default value m->m_colours.push_back(Colour(1.0f, 1.0f, 1.0f)); // normal [optional] if (key.vn) { m->m_normals.push_back(normals[key.vn - 1]); } // texcoord [optional] if (key.vt) { m->m_texcoords[0].push_back(texcoords[key.vt - 1]); } } } } if (faceIndexCount == 3) { // a triangle indices.insert(indices.end(), faceIndices, faceIndices + 3); } else if (faceIndexCount == 4) { // a quad, triangulate clockwise indices.insert(indices.end(), faceIndices, faceIndices + 3); indices.push_back(faceIndices[2]); indices.push_back(faceIndices[3]); indices.push_back(faceIndices[0]); } else { cout << "Face with more than 4 vertices are not supported" << endl; } } else if (buffer[0] == '#') { // comment char linebuf[256]; file.getline(linebuf, 256); } } // calculate normals if none specified in file m->m_normals.resize(m->m_positions.size()); const uint32_t numFaces = uint32_t(indices.size()) / 3; for (uint32_t i = 0; i < numFaces; ++i) { uint32_t a = indices[i * 3 + 0]; uint32_t b = indices[i * 3 + 1]; uint32_t c = indices[i * 3 + 2]; Point3& v0 = m->m_positions[a]; Point3& v1 = m->m_positions[b]; Point3& v2 = m->m_positions[c]; Vector3 n = SafeNormalize(Cross(v1 - v0, v2 - v0), Vector3(0.0f, 1.0f, 0.0f)); m->m_normals[a] += n; m->m_normals[b] += n; m->m_normals[c] += n; } for (uint32_t i = 0; i < m->m_normals.size(); ++i) { m->m_normals[i] = SafeNormalize(m->m_normals[i], Vector3(0.0f, 1.0f, 0.0f)); } //cout << "Imported mesh " << path << " in " << (GetSeconds()-startTime)*1000.f << "ms" << endl; return m; } Mesh* mImportMeshFromObj(const char* path) { ifstream file(path); if (!file) { cout << path << endl; return NULL; } Mesh* m = new Mesh(); vector<Point3> positions; vector<Vector3> normals; vector<Vector2> texcoords; vector<Vector3> colors; vector<uint32_t> edge; vector<uint32_t>& indices = m->m_indices; typedef map<VertexKey, uint32_t> VertexMap; VertexMap vertexLookup; const uint32_t kMaxLineLength = 1024; char buffer[kMaxLineLength]; while (file) { file >> buffer; if (strcmp(buffer, "vn") == 0) { // normals float x, y, z; file >> x >> y >> z; normals.push_back(Vector3(x, y, z)); } else if (strcmp(buffer, "vt") == 0) { // texture coords float u, v; file >> u >> v; texcoords.push_back(Vector2(u, v)); } else if (buffer[0] == 'v') { // positions float x, y, z; file >> x >> y >> z; positions.push_back(Point3(x, y, z)); } else if (buffer[0] == 's' || buffer[0] == 'g' || buffer[0] == 'o') { // ignore smoothing groups, groups and objects char linebuf[256]; file.getline(linebuf, 256); } else if (strcmp(buffer, "mtllib") == 0) { // ignored std::string MaterialFile; file >> MaterialFile; } else if (strcmp(buffer, "usemtl") == 0) { // read Material name std::string materialName; file >> materialName; } else if (buffer[0] == 'f') { // faces uint32_t faceIndices[4]; uint32_t faceIndexCount = 0; for (int i = 0; i < 4; ++i) { VertexKey key; file >> key.v; if (!file.eof()) { // failed to read another index continue on if (file.fail()) { file.clear(); break; } if (file.peek() == '/') { file.ignore(); if (file.peek() != '/') { file >> key.vt; } if (file.peek() == '/') { file.ignore(); file >> key.vn; } } // find / add vertex, index VertexMap::iterator iter = vertexLookup.find(key); if (iter != vertexLookup.end()) { faceIndices[faceIndexCount++] = iter->second; } else { // add vertex uint32_t newIndex = uint32_t(m->m_positions.size()); faceIndices[faceIndexCount++] = newIndex; vertexLookup.insert(make_pair(key, newIndex)); // push back vertex data assert(key.v > 0); m->m_positions.push_back(positions[key.v - 1]); // obj format doesn't support mesh colours so add default value m->m_colours.push_back(Colour(1.0f, 1.0f, 1.0f)); // normal [optional] if (key.vn) { m->m_normals.push_back(normals[key.vn - 1]); } // texcoord [optional] if (key.vt) { m->m_texcoords[0].push_back(texcoords[key.vt - 1]); } } } } if (faceIndexCount == 3) { // a triangle indices.insert(indices.end(), faceIndices, faceIndices + 3); edge.push_back(faceIndices[0]); edge.push_back(faceIndices[1]); edge.push_back(faceIndices[1]); edge.push_back(faceIndices[2]); edge.push_back(faceIndices[2]); edge.push_back(faceIndices[0]); } else if (faceIndexCount == 4) { // a triangle indices.insert(indices.end(), faceIndices, faceIndices + 3); edge.push_back(faceIndices[0]); edge.push_back(faceIndices[1]); edge.push_back(faceIndices[1]); edge.push_back(faceIndices[2]); edge.push_back(faceIndices[2]); edge.push_back(faceIndices[3]); edge.push_back(faceIndices[3]); edge.push_back(faceIndices[0]); } } else if (buffer[0] == 'l') { // faces uint32_t faceIndices[4]; uint32_t faceIndexCount = 0; for (int i = 0; i < 4; ++i) { VertexKey key; file >> key.v; if (!file.eof()) { // failed to read another index continue on if (file.fail()) { file.clear(); break; } if (file.peek() == '/') { file.ignore(); if (file.peek() != '/') { file >> key.vt; } if (file.peek() == '/') { file.ignore(); file >> key.vn; } } // find / add vertex, index VertexMap::iterator iter = vertexLookup.find(key); if (iter != vertexLookup.end()) { faceIndices[faceIndexCount++] = iter->second; } else { // add vertex uint32_t newIndex = uint32_t(m->m_positions.size()); faceIndices[faceIndexCount++] = newIndex; vertexLookup.insert(make_pair(key, newIndex)); // push back vertex data assert(key.v > 0); m->m_positions.push_back(positions[key.v - 1]); // obj format doesn't support mesh colours so add default value m->m_colours.push_back(Colour(1.0f, 1.0f, 1.0f)); // normal [optional] if (key.vn) { m->m_normals.push_back(normals[key.vn - 1]); } // texcoord [optional] if (key.vt) { m->m_texcoords[0].push_back(texcoords[key.vt - 1]); } } } } if (faceIndexCount == 2) { // a triangle indices.insert(indices.end(), faceIndices, faceIndices +3); edge.push_back(faceIndices[1]); edge.push_back(faceIndices[0]); edge.push_back(faceIndices[0]); edge.push_back(faceIndices[1]); } else { cout << "Face with more than 4 vertices are not supported" << endl; } } else if (buffer[0] == '#') { // comment char linebuf[256]; file.getline(linebuf, 256); } } cout << "Imported mesh : " << path << endl; cout << "num points : " << m->m_positions.size() << endl; m->m_indices = edge; cout << "edges nums " << edge.size()<<endl; cout << "edges nums " << edge[0] << " "<< edge[1] <<" "<<edge[2] << endl; return m; } inline int GridIndex(int x, int y, int dx) { return y * dx + x; } void ofx_nvflex::CreateSpring(int i, int j, float stiffness, float give ) { buffers->springIndices.push_back(i); buffers->springIndices.push_back(j); buffers->springLengths.push_back((1.0f + give)*Length(Vec3(buffers->positions[i]) - Vec3(buffers->positions[j]))); buffers->springStiffness.push_back(stiffness); } void ofx_nvflex::CreateSpringGrid(Vec3 lower, int dx, int dy, int dz, float radius, int phase, float stretchStiffness, float bendStiffness, float shearStiffness, Vec3 velocity, float invMass) { int baseIndex = int(buffers->positions.size()); for (int z = 0; z < dz; ++z) { for (int y = 0; y < dy; ++y) { for (int x = 0; x < dx; ++x) { Vec3 position = lower + radius * Vec3(float(x), float(z), float(y)); buffers->positions.push_back(Vec4(position.x, position.z, position.y, invMass)); buffers->restPositions.push_back(Vec4(position.x, position.y, position.z, invMass)); buffers->activeIndices.push_back(x+y*dx+z*(dx*dy) ); buffers->velocities.push_back(velocity); buffers->phases.push_back(phase); if (x > 0 && y > 0) { buffers->triangles.push_back(baseIndex + GridIndex(x - 1, y - 1, dx)); buffers->triangles.push_back(baseIndex + GridIndex(x, y - 1, dx)); buffers->triangles.push_back(baseIndex + GridIndex(x, y, dx)); buffers->triangles.push_back(baseIndex + GridIndex(x - 1, y - 1, dx)); buffers->triangles.push_back(baseIndex + GridIndex(x, y, dx)); buffers->triangles.push_back(baseIndex + GridIndex(x - 1, y, dx)); buffers->triangleNormals.push_back(Vec3(0.0f, 1.0f, 0.0f)); buffers->triangleNormals.push_back(Vec3(0.0f, 1.0f, 0.0f)); } } } } // horizontal for (int y = 0; y < dy; ++y) { for (int x = 0; x < dx; ++x) { int index0 = y * dx + x; if (x > 0) { int index1 = y * dx + x - 1; CreateSpring(baseIndex + index0, baseIndex + index1, stretchStiffness); } if (x > 1) { int index2 = y * dx + x - 2; CreateSpring(baseIndex + index0, baseIndex + index2, bendStiffness); } if (y > 0 && x < dx - 1) { int indexDiag = (y - 1)*dx + x + 1; CreateSpring(baseIndex + index0, baseIndex + indexDiag, shearStiffness); } if (y > 0 && x > 0) { int indexDiag = (y - 1)*dx + x - 1; CreateSpring(baseIndex + index0, baseIndex + indexDiag, shearStiffness); } } } // vertical for (int x = 0; x < dx; ++x) { for (int y = 0; y < dy; ++y) { int index0 = y * dx + x; if (y > 0) { int index1 = (y - 1)*dx + x; CreateSpring(baseIndex + index0, baseIndex + index1, stretchStiffness); } if (y > 1) { int index2 = (y - 2)*dx + x; CreateSpring(baseIndex + index0, baseIndex + index2, bendStiffness); } } } } void ofx_nvflex::CreateSpringBrush(Vec3 lower, int dx, int dy, int dz, float radius, int phase, float stretchStiffness, float bendStiffness, float shearStiffness, Vec3 velocity, float invMass) { // create one line int num_points = 35; int num_l = 10; srand(time(NULL) ); for (int k = 0; k < num_l; k++) { for (int j = 0; j < num_l; j++) { int baseIndex = int(buffers->positions.size()); for (int i = 0; i < num_points; i++) { int n = i + j * num_points + k * num_points *num_l; float mix = ((rand() +n) % 100)*0.01; float mixb = ((rand() + n+1000) % 100)*0.01; Vec3 position = Vec3(float(j*0.2f)+mix*0.2f, float(i + 1)*0.3f, float(k*0.2f)+mixb*0.2f); buffers->positions.push_back(Vec4(position.x, position.y, position.z, invMass)); buffers->restPositions.push_back(Vec4(position.x, position.y, position.z, invMass)); buffers->activeIndices.push_back(n); buffers->velocities.push_back(velocity); buffers->phases.push_back(phase); cursor++; if (i > 0 && i < num_points - 1) { buffers->triangles.push_back(baseIndex + i - 1); buffers->triangles.push_back(baseIndex + i); buffers->triangles.push_back(baseIndex + i + 1); buffers->triangleNormals.push_back(Vec3(0.0f, 0.0f, 1.0f)); } if (i > 0) { CreateSpring(baseIndex + i - 1, baseIndex + i, stretchStiffness); } if (i > 1) { CreateSpring(baseIndex + i - 2, baseIndex + i , stretchStiffness); } if (i > 2 ) { CreateSpring(baseIndex + i -3, baseIndex + i , stretchStiffness); } if (i > 4) { CreateSpring(baseIndex + i - 5, baseIndex + i, stretchStiffness); } if (i > 9) { CreateSpring(baseIndex + i - 10, baseIndex + i, stretchStiffness); } } } } } void ofx_nvflex::create_softbody(Instance instance, int group) { CreateSpringBrush(Vec3(0.0f,1.0f,0.0f), 70, 70, 1, 1.6f, NvFlexMakePhase(0, eNvFlexPhaseSelfCollide | eNvFlexPhaseSelfCollideFilter), 1.0f, 1.0f, 1.0f, Vec3(0.0f, 0.0f, 0.0f), 1.0f); } void ofx_nvflex::create_softbody_old(Instance instance, int group) { buffers->springIndices.map(); buffers->springLengths.map(); buffers->springStiffness.map(); Mesh* mesh = ImportMeshFromObj(GetFilePathByPlatform(instance.mFile).c_str()); // print mesh data cout << " create cloth from Mesh ? " << endl; cout << "num faces " << mesh->GetNumFaces() << endl; cout << "num vertices " << mesh->GetNumVertices() << endl; cout << "num indices " << mesh->m_indices.size() << endl; cout << "num pos " << mesh->m_positions.size() << endl; cout << "old importer mode " << endl; NvFlexTriangleMeshId triM = NvFlexCreateTriangleMesh(library); //triM->mesh = NvFlexExtAsset* asset = NvFlexExtCreateClothFromMesh( (float*)&mesh->m_positions[0], mesh->m_positions.size(), (int*)&mesh->m_indices[0], mesh->GetNumFaces(), 1.0f, 1.0f, 0.5f, 0.0f, 0.0f); cout << "asset done " << endl; cout << "asset valid "<< asset->numParticles << endl; cout << "asset valid " << asset->numSprings << endl; cout << "mesh valid " << mesh->m_positions.size() << endl; cout << "mesh valid " << mesh->m_indices.size() << endl; // add particle data to solver /* for (int i = 0; i < mesh->m_positions.size(); ++i) { buffers->positions.push_back(mesh->m_positions[i]); buffers->restPositions.push_back(mesh->m_positions[i]); buffers->velocities.push_back(0.0f); const int phase = NvFlexMakePhase(group, eNvFlexPhaseSelfCollide | eNvFlexPhaseSelfCollideFilter); buffers->phases.push_back(phase); buffers->activeIndices.push_back(cursor); buffers->ids.push_back(cursor); buffers->cols.push_back(Vec3(1.0f, 0.0f, 0.0f));// Vec3(mesh->m_colours[i])); cursor++; } std::cout << endl << "set buffers particles " << mesh->m_positions.size() << endl; // buffers->activeIndices.push_back(0); // add link data to the solver for (int i = 0; i < mesh->m_indices.size(); i += 2) { int num = mesh->m_indices[i + 0]; int numb = mesh->m_indices[i + 1]; buffers->springIndices.push_back(num); buffers->springIndices.push_back(numb); //buffers->activeIndices.push_back(cursor); //cursor++; ofVec3f pos(buffers->positions[num].x, buffers->positions[num].y, buffers->positions[num].z); ofVec3f posb(buffers->positions[numb].x, buffers->positions[numb].y, buffers->positions[numb].z); float len = (pos - posb).length(); buffers->springLengths.push_back(len+0.01f); //len+0.05f buffers->springStiffness.push_back(1.0f); }*/ for (int i = 0; i < asset->numParticles; ++i) { //Vec4 pos(asset->particles[i * 4], asset->particles[i * 4 + 1], asset->particles[i * 4 + 2], 1.0f); buffers->positions.push_back(mesh->m_positions[i]); buffers->restPositions.push_back(mesh->m_positions[i]); buffers->velocities.push_back(0.0f) ; const int phase = NvFlexMakePhase(group, eNvFlexPhaseSelfCollide | eNvFlexPhaseSelfCollideFilter); buffers->phases.push_back(phase); buffers->activeIndices.push_back(cursor); buffers->ids.push_back(cursor); buffers->cols.push_back(Vec3(1.0f, 0.0f, 0.0f)); // Vec3(mesh->m_colours[i])); cursor++; } std::cout << endl << "set buffers particles " << mesh->m_positions.size() << endl; // add link data to the solver for (int i = 0; i <asset->numSprings; i ++) { buffers->springIndices.push_back(asset->springIndices[i*2]); buffers->springIndices.push_back(asset->springIndices[i*2+1]); buffers->springLengths.push_back(asset->springRestLengths[i]); buffers->springStiffness.push_back(asset->springCoefficients[i]); } std::cout << endl << "set spring buffers" << buffers->springIndices.size()*0.5 << " " << buffers->springIndices.size() << endl; std::cout << endl << "set spring buffers" << buffers->springStiffness.size() << endl; std::cout << endl << "set spring buffers" << buffers->springLengths.size() << endl; /* for (int i = 0; i < buffers->springIndices.size(); i+=2) { std::cout<< buffers->springIndices[i] <<" " <<buffers->springIndices[i+0] << endl; }*/ std::cout << "pos size"<< buffers->positions.size() << endl; std::cout << endl << "cloth created from obj"<<endl; } void ofx_nvflex::emit_particles(float x, float y, float dirx, float diry, float odx, float ody, float rate, Vec3 c) { float invMass = 1 / 1.0 ; if (cursor >= maxParticles - 1000) { // shift int num = buffers->positions.size(); for (int i = 5000; i < num ; ++i) { if (i < num - 1000) { buffers->positions[i] = buffers->positions[i + 1000]; buffers->velocities[i] = buffers->velocities[i + 1000]; buffers->phases[i] = buffers->phases[i + 1000]; buffers->ids[i] = buffers->ids[i+1000] ; buffers->cols[i] = buffers->cols[i+1000]; } } buffers->positions.resize(num - 1000); buffers->velocities.resize(num - 1000); buffers->phases.resize(num - 1000); buffers->activeIndices.resize(num - 1000); buffers->ids.resize(num - 1000); buffers->cols.resize(num - 1000); cursor -= 1000; } int phase = NvFlexMakePhase(0, eNvFlexPhaseSelfCollide | eNvFlexPhaseFluid); int nump = 10 * rate; for (int i = 0; i < nump; i++) { srand(time(NULL) + i); float mix = ((rand() + 2000) % 100)*0.01; Vec3 position = Vec3(float(x + 0.05*(rand() % 100 - 50)), float(0.5f), float(y + 0.05*((rand() + 10) % 100 - 50))) - ((Vec3(dirx, 0, diry))*mix * 1); // +RandomUnitVector() * 4; Vec3 velocity = Vec3((dirx*(0.6) + odx * (0.4)) * 5 + 0.002*((rand() + 100) % 100 - 50), 0, (diry*(0.6) + ody * (0.4)) * 5 + 0.002*((rand() + 200) % 100 - 50))*(((rand() + 4000) % 100)*0.01); // +RandomUnitVector() * 4;; if (cursor < maxParticles - 1) { buffers->positions.push_back(Vec4(position.x, position.y, position.z, invMass)); buffers->ids.push_back( (rand() + 2000) % 1000); buffers->cols.push_back(c); buffers->velocities.push_back(velocity); buffers->phases.push_back(phase); buffers->activeIndices.push_back(cursor); cursor++; } } }; void ofx_nvflex::update(int s ) { if (DEBUG_MODE) { cout << "update " << endl; } /* if (s) { // setup spring buffers if (buffers->springIndices.size()) { indicesBuffer = NvFlexAllocBuffer(library, buffers->springIndices.size(), sizeof(int), eNvFlexBufferHost); lengthsBuffer = NvFlexAllocBuffer(library, buffers->springLengths.size(), sizeof(float), eNvFlexBufferHost); coefficientsBuffer = NvFlexAllocBuffer(library, buffers->springStiffness.size(), sizeof(float), eNvFlexBufferHost); int *springIndices = new int[buffers->springIndices.size()]; float *springLengths = new float[buffers->springLengths.size()]; float *springCoefficients = new float[buffers->springStiffness.size()]; for (int i = 0; i < buffers->springIndices.size(); i++) { springIndices[i] = buffers->springIndices[i]; } for (int i = 0; i < buffers->springLengths.size(); i++) { springLengths[i] = buffers->springLengths[i]; springCoefficients[i] = buffers->springStiffness[i]; } memcpy(NvFlexMap(indicesBuffer, eNvFlexMapWait), springIndices, buffers->springIndices.size()); memcpy(NvFlexMap(lengthsBuffer, eNvFlexMapWait), springLengths, buffers->springLengths.size()); memcpy(NvFlexMap(coefficientsBuffer, eNvFlexMapWait), springCoefficients, buffers->springStiffness.size()); } }*/ buffers->UnmapBuffers(); if (DEBUG_MODE) { cout << "unmap " << endl; } NvFlexCopyDesc copyDesc; copyDesc.dstOffset = 0; copyDesc.srcOffset = 0; if (buffers->activeIndices.size()) { copyDesc.elementCount = buffers->activeIndices.size(); NvFlexSetActive( solver, buffers->activeIndices.buffer, &copyDesc); NvFlexSetActiveCount( solver, buffers->activeIndices.size()); } if (DEBUG_MODE) { cout << "set indices " << endl; } if (buffers->positions.size()) { copyDesc.elementCount = buffers->positions.size(); NvFlexSetParticles(solver, buffers->positions.buffer, &copyDesc); NvFlexSetVelocities(solver, buffers->velocities.buffer, &copyDesc); NvFlexSetPhases(solver, buffers->phases.buffer, &copyDesc); } if (DEBUG_MODE) { cout << "set pos " << endl; } if (s) { if (buffers->springIndices.size()) { if (buffers->springIndices.size()) { assert((buffers->springIndices.size() & 1) == 0); assert((buffers->springIndices.size() / 2) == g_buffers->springLengths.size()); NvFlexSetSprings(solver, buffers->springIndices.buffer, buffers->springLengths.buffer, buffers->springStiffness.buffer, buffers->springLengths.size()); } /* if (DEBUG_MODE) { cout << "unmap sping buffers try" << endl; } NvFlexUnmap(indicesBuffer) ; NvFlexUnmap(lengthsBuffer) ; NvFlexUnmap(coefficientsBuffer) ; if (DEBUG_MODE) { cout << "set spring solver" << endl; cout << "solver to set " << buffers->springIndices.size() << endl; cout << "solver to set " << buffers->springStiffness.size() << endl; } NvFlexSetSprings(solver, indicesBuffer, lengthsBuffer, coefficientsBuffer, buffers->springStiffness.size()); if (DEBUG_MODE) { cout << "solver set " << buffers->springStiffness.size() << endl; }*/ } } /* if (buffers->shapeFlags.size()) { NvFlexSetShapes( solver, buffers->shapeGeometry.buffer, buffers->shapePositions.buffer, buffers->shapeRotations.buffer, buffers->shapePrevPositions.buffer, buffers->shapePrevRotations.buffer, buffers->shapeFlags.buffer, buffers->shapeFlags.size()); } */ if (DEBUG_MODE) { cout << "set shapes " << endl; } NvFlexSetParams(solver, &g_params); if (DEBUG_MODE) { cout << "set params " << endl; } NvFlexUpdateSolver(solver, 0.04, numSubsteps, profile); if (DEBUG_MODE) { cout << "update solver " << endl; } if (buffers->positions.size()) { copyDesc.elementCount = buffers->positions.size(); NvFlexGetParticles(solver, buffers->positions.buffer, &copyDesc); NvFlexGetVelocities(solver, buffers->velocities.buffer, &copyDesc); } if (DEBUG_MODE) { cout << "NvFlexGetParticles " << endl; } if (0) { if (buffers->springIndices.size()) { NvFlexGetSprings(solver, indicesBuffer, lengthsBuffer, coefficientsBuffer, buffers->springStiffness.size()); /*buffers->springIndices.map(); buffers->springLengths.map(); buffers->springStiffness.map();*/ if (DEBUG_MODE) { cout << "solver spring get " << endl; } int *springIndices = new int[buffers->springIndices.size()]; float *springLengths = new float[buffers->springLengths.size()]; float *springCoefficients = new float[buffers->springStiffness.size()]; memcpy(springIndices, NvFlexMap(indicesBuffer, eNvFlexMapWait), buffers->springIndices.size()); memcpy(springLengths, NvFlexMap(lengthsBuffer, eNvFlexMapWait), buffers->springLengths.size()); memcpy(springCoefficients, NvFlexMap(coefficientsBuffer, eNvFlexMapWait), buffers->springStiffness.size()); if (DEBUG_MODE) { cout << "copy back spring" << endl; } for (int i = 0; i < buffers->springIndices.size(); i++) { buffers->springIndices[i] = springIndices[i]; } if (DEBUG_MODE) { cout << "indices back to buffer " << endl; } for (int i = 0; i < buffers->springLengths.size(); i++) { buffers->springLengths[i] = springLengths[i]; buffers->springStiffness[i] = springCoefficients[i]; } if (DEBUG_MODE) { cout << "value back to buffer " << endl; } } } } void ofx_nvflex::set_params(float cohesion, float adhesion, float surfaceTension, float vorticityConfinement, float smoothing, float viscosity, float size, float g) { // sim params g_params.gravity[0] = 0.0f; g_params.gravity[1] = g*1.5f; g_params.gravity[2] = 0.0f; g_params.wind[0] = 0.0f; g_params.wind[1] = 0.0f; g_params.wind[2] = 0.0f; g_params.radius = size; g_params.viscosity = viscosity; g_params.dynamicFriction = 0.45f; g_params.staticFriction = 0.45f; g_params.particleFriction = 0.45f; // scale friction between particles by default g_params.freeSurfaceDrag = 0.0f; g_params.drag = 0.05f; g_params.lift = 0.0f; g_params.numIterations = 3; g_params.fluidRestDistance = g_params.radius*0.7; g_params.solidRestDistance = 0.0f; g_params.anisotropyScale = 1.0f; g_params.anisotropyMin = 0.1f; g_params.anisotropyMax = 2.0f; g_params.smoothing = smoothing; g_params.dissipation = 0.0f; g_params.damping = 0.0f; g_params.particleCollisionMargin = 0.015f; g_params.shapeCollisionMargin = 0.01f; g_params.collisionDistance = size*0.5f; g_params.sleepThreshold = 0.0f; g_params.shockPropagation = 0.1f; g_params.restitution = 0.01f; g_params.maxSpeed = FLT_MAX; g_params.maxAcceleration = 500.0f; // approximately 10x gravity g_params.relaxationMode = eNvFlexRelaxationGlobal; g_params.relaxationFactor = 0.25f; g_params.solidPressure = 1.0f; g_params.adhesion = adhesion; g_params.cohesion = cohesion; g_params.surfaceTension = surfaceTension; g_params.vorticityConfinement = vorticityConfinement*150.0f; g_params.buoyancy = 1.0f; g_params.diffuseThreshold = 100.0f; g_params.diffuseBuoyancy = 1.0f; g_params.diffuseDrag = 0.8f; g_params.diffuseBallistic = 16; g_params.diffuseLifetime = 2.0f; g_params.numPlanes = 1; (Vec4&)g_params.planes[0] = Vec4(0.0f, 1.0f, 0.0f, 0.0f); //g_params.collisionDistance = 0.05f; //g_params.shapeCollisionMargin = 0.00001f; } // buffers SimBuffers::SimBuffers(NvFlexLibrary* l) : positions(l), ids(1), cols(1), restPositions(l), velocities(l), phases(l), densities(l), anisotropy1(l), anisotropy2(l), anisotropy3(l), normals(l), smoothPositions(l), diffusePositions(l), diffuseVelocities(l), diffuseIndices(l), activeIndices(l), shapeGeometry(l), shapePositions(l), shapeRotations(l), shapePrevPositions(l), shapePrevRotations(l), shapeFlags(l), rigidOffsets(l), rigidIndices(l), rigidMeshSize(l), rigidCoefficients(l), rigidRotations(l), rigidTranslations(l), rigidLocalPositions(l), rigidLocalNormals(l), inflatableTriOffsets(l), inflatableTriCounts(l), inflatableVolumes(l), inflatableCoefficients(l), inflatablePressures(l), springIndices(l), springLengths(l), springStiffness(l), triangles(l), triangleNormals(l), uvs(l) { } SimBuffers::~SimBuffers() { positions.destroy(); restPositions.destroy(); velocities.destroy(); phases.destroy(); densities.destroy(); anisotropy1.destroy(); anisotropy2.destroy(); anisotropy3.destroy(); normals.destroy(); diffusePositions.destroy(); diffuseVelocities.destroy(); diffuseIndices.destroy(); smoothPositions.destroy(); activeIndices.destroy(); // convexes shapeGeometry.destroy(); shapePositions.destroy(); shapeRotations.destroy(); shapePrevPositions.destroy(); shapePrevRotations.destroy(); shapeFlags.destroy(); // rigids rigidOffsets.destroy(); rigidIndices.destroy(); rigidMeshSize.destroy(); rigidCoefficients.destroy(); rigidRotations.destroy(); rigidTranslations.destroy(); rigidLocalPositions.destroy(); rigidLocalNormals.destroy(); // springs springIndices.destroy(); springLengths.destroy(); springStiffness.destroy(); // inflatables inflatableTriOffsets.destroy(); inflatableTriCounts.destroy(); inflatableVolumes.destroy(); inflatableCoefficients.destroy(); inflatablePressures.destroy(); // triangles triangles.destroy(); triangleNormals.destroy(); uvs.destroy(); } void SimBuffers::MapBuffers() { positions.map(); restPositions.map(); velocities.map(); phases.map(); activeIndices.map(); /*densities.map(); anisotropy1.map(); anisotropy2.map(); anisotropy3.map(); normals.map(); diffusePositions.map(); diffuseVelocities.map(); diffuseIndices.map(); smoothPositions.map();*/ // convexes /*shapeGeometry.map(); shapePositions.map(); shapeRotations.map(); shapePrevPositions.map(); shapePrevRotations.map(); shapeFlags.map();*/ /*rigidOffsets.map(); rigidIndices.map(); rigidMeshSize.map(); rigidCoefficients.map(); rigidRotations.map(); rigidTranslations.map(); rigidLocalPositions.map(); rigidLocalNormals.map();*/ springIndices.map(); springLengths.map(); springStiffness.map(); // inflatables /*inflatableTriOffsets.map(); inflatableTriCounts.map(); inflatableVolumes.map(); inflatableCoefficients.map(); inflatablePressures.map();*/ triangles.map(); triangleNormals.map(); uvs.map(); } void SimBuffers::UnmapBuffers() { // particles positions.unmap(); restPositions.unmap(); velocities.unmap(); phases.unmap(); activeIndices.unmap(); /*densities.unmap(); anisotropy1.unmap(); anisotropy2.unmap(); anisotropy3.unmap(); normals.unmap(); diffusePositions.unmap(); diffuseVelocities.unmap(); diffuseIndices.unmap(); smoothPositions.unmap();*/ // convexes /*shapeGeometry.unmap(); shapePositions.unmap(); shapeRotations.unmap(); shapePrevPositions.unmap(); shapePrevRotations.unmap(); shapeFlags.unmap();*/ // rigids /*rigidOffsets.unmap(); rigidIndices.unmap(); rigidMeshSize.unmap(); rigidCoefficients.unmap(); rigidRotations.unmap(); rigidTranslations.unmap(); rigidLocalPositions.unmap(); rigidLocalNormals.unmap();*/ // springs springIndices.unmap(); springLengths.unmap(); springStiffness.unmap(); // inflatables /*inflatableTriOffsets.unmap(); inflatableTriCounts.unmap(); inflatableVolumes.unmap(); inflatableCoefficients.unmap(); inflatablePressures.unmap();*/ // triangles triangles.unmap(); triangleNormals.unmap(); uvs.unmap(); } void SimBuffers::InitBuffers() { positions.resize(0); velocities.resize(0); phases.resize(0); shapeGeometry.resize(0); shapePositions.resize(0); shapeRotations.resize(0); shapePrevPositions.resize(0); shapePrevRotations.resize(0); shapeFlags.resize(0); // rigids rigidOffsets.resize(0); rigidIndices.resize(0); rigidMeshSize.resize(0); rigidCoefficients.resize(0); rigidRotations.resize(0); rigidTranslations.resize(0); rigidLocalPositions.resize(0); rigidLocalNormals.resize(0); } // constructor/destructor ofx_nvflex::ofx_nvflex() { maxParticles = 100000; g_maxDiffuseParticles = 0; numDiffuse = 0; n = 50; solver = NULL; profile = false; numSubsteps = 8; cursor = 0; } ofx_nvflex::~ofx_nvflex() { if (solver) { if (buffers) delete buffers; NvFlexDestroySolver(solver); NvFlexShutdown(library); } NvFlexDeviceDestroyCudaContext(); }
25.007236
222
0.64673
[ "mesh", "vector" ]
08ce6496e7f618a51fe37f9715d1920f0f732884
16,520
cpp
C++
archived/svdfit.cpp
HiTMonitor/ginan
f348e2683507cfeca65bb58880b3abc2f9c36bcf
[ "Apache-2.0" ]
1
2022-03-31T15:16:19.000Z
2022-03-31T15:16:19.000Z
archived/svdfit.cpp
hqy123-cmyk/ginan
b69593b584f75e03238c1c667796e2030391fbed
[ "Apache-2.0" ]
null
null
null
archived/svdfit.cpp
hqy123-cmyk/ginan
b69593b584f75e03238c1c667796e2030391fbed
[ "Apache-2.0" ]
null
null
null
// /* Slightly modified versions of routines from // * Press, William H., Brian P. Flannery, Saul A Teukolsky and // * William T. Vetterling, 1986, "Numerical Recipes: The Art of // * Scientific Computing" (Fortran), Cambrigde University Press. // * // * svdfit on p. 518. // * svbksb on pp. 57-58. // * svdcmp on pp. 60-64. // * svdvar on p. 519. // */ // // #include <stdio.h> // #include <math.h> // // void funcs( double x, double *afunc, unsigned int ma ); // void svdfit( double *X, double *Y, double *Sig, unsigned int NData, // double *A, unsigned int MA, // double **U, double **V, double *W, unsigned int MP, unsigned int NP, // double *ChiSq, void funcs(double x, double *afunc, unsigned int ma) ); // void svdcmp( double **A, unsigned int M, unsigned int N, // unsigned int MP, unsigned int NP, double *W, double **V ); // void svbksb( double **U, double *W, double **V, unsigned int M, // unsigned int N, unsigned int MP, unsigned int NP, // double *B, double *X ); // void svdvar( double **V, unsigned int MA, unsigned int NP, // double *W, double **CVM, unsigned int NCVM ); // // # define true ((int)1) // # define false ((int)0) // # define nmax ((int)1000) // # define mmax ((int)50) // # define tol ((double)1.0e-15) // // void svdfit( double *X, double *Y, double *Sig, unsigned int NData, // double *A, unsigned int MA, // double **U, double **V, double *W, unsigned int MP, unsigned int NP, // double *ChiSq, void funcs(double x, double *afunc, unsigned int ma) ) // { // /* // Given a set of NData points X[], Y[] with individual standard // deviations of Sig[], use chi-square minimization to determine the // MA coefficients, A[], of the fitting function // y = sum over i Ai * funcsi(x). // Here we solve the fitting equation using singular value decomposition // of the NData by MA matrix. The arrays U, V and W provide workspace // on input. On output they define the singular value decomposition and // can be used to obtaint he covariance matrix. MP and NP are the // physical dimensions of the matrices U, V, and W as indicated below. // It is necessary that MP be greater than or equal to NData and that // NP be greather than or equal to MP. The program returns values for // the MA fit parameters A[] and the chi-square, ChiSq. The user // supplies a subroutine, funcs(), that returns the MA basis functions // evaluated at x in the array afunc[]. // */ // // int i; // int j; // double sum; // double thresh; // double tmp; // double wmax; // double wmin; // // double beta[nmax]; // double afunc[mmax]; // // /* Accumulate coefficients of the fitting matrix. */ // for( i = 0; i < NData; ++i ) { // funcs( X[i], afunc, MA ); // tmp = 1.0 / Sig[i]; // for( j = 0; j < MA; ++j ) { // U[i][j] = afunc[j] * tmp; // } // beta[i] = Y[i] * tmp; // } // // /* Singular value decomposition. */ // svdcmp( U, NData, MA, MP, NP, W, V ); // // /* Edit the singular values, given tol from the parameter statement, // between here ... */ // wmax = 0.0; // wmin = 1.0e99; // for( j = 0; j < MA; ++j ) { // if( W[j] > wmax ) // wmax = W[j]; // if( W[j] < wmin ) // wmin = W[j]; // } // // thresh = tol * wmax; // for( j = 0; j < MA; ++j ) { // if( W[j] < thresh ) { // W[j] = 0.0; // } // } // /* ... and here. */ // // svbksb( U, W, V, NData, MA, MP, NP, beta, A ); // // /* Evaluate chi-square. */ // *ChiSq = 0.0; // for( i = 0; i < NData; ++i ) { // funcs( X[i], afunc, MA ); // sum = 0.0; // for( j = 0; j < MA; ++j ) { // sum = sum + A[j] * afunc[j]; // } // tmp = ((Y[i] - sum) / Sig[i]); // *ChiSq = *ChiSq + tmp*tmp; // } // // return; // } // // void svdvar( double **V, unsigned int MA, unsigned int NP, // double *W, double **CVM, unsigned int NCVM ) // { // /* // To evaluate the covariance matrix CVM of the fit for MA paramaters // obtained by svdfit, call this routine with matrix V and W as returned // from svdfit. NP, NCVM give the physical dimensions of V, W and CVM as // indicated below. // */ // // int i; // int j; // int k; // double sum; // // double wti[mmax]; // // for( i = 0; i < MA; ++i ) { // wti[i] = 0.0; // if( W[i] != 0.0 ) // wti[i] = 1.0 / (W[i] * W[i]); // } // // for( i = 0; i < MA; ++i ) { // for( j = 0; j <= i; ++j ) { // sum = 0.0; // for( k = 0; k < MA; ++k ) { // sum = sum + V[i][k] * V[j][k] * wti[k]; // } // CVM[i][j] = sum; // CVM[j][i] = sum; // } // } // // return; // } // // void svbksb( double **U, double *W, double **V, unsigned int M, // unsigned int N, unsigned int MP, unsigned int NP, // double *B, double *X ) // { // /* // Solves A * X = B for a vector X where A is specified by the arrays // U, W and V as returned by svdcmp. M and N are the logical dimensions // of A and will be equal for a square matrices. MP and NP are the // physical dimensions of A. B is the input right-hand side. X is the // output solution vector. No input quantities are destroyed, so the // routine may be called sequentially with different B's. M must be // greater to N (see svdcmp). // */ // // int i; // int j; // double S; // // double tmp[nmax]; // // /* Calculate transpose U * B */ // for( j = 0; j < N; ++j ) { // S = 0.0; // /* Nonzero result only if W[j] is nonzero. */ // if( W[j] != 0.0 ) { // for( i = 0; i < M; ++i ) { // S = S + U[i][j] * B[i]; // } // S = S / W[j]; // } // tmp[j] = S; // } // // /* Multiply by V to get answer. */ // for( j = 0; j < N; ++j ) { // S = 0.0; // for( i = 0; i < N; ++i ) { // S = S + V[j][i] * tmp[i]; // } // X[j] = S; // } // // return; // } // // void svdcmp( double **A, unsigned int M, unsigned int N, // unsigned int MP, unsigned int NP, double *W, double **V ) // { // /* // Give a matrix A, with logical dimensions M by N and physical // dimensions MP by NP, this routine computes its singular value // decomposition, A = U * W * transpose V. The matrix U replaces // A on output. The diagonal matrix of singular values, W, is output // as a vector W. The matrix V (not the transpose of V) is output as // V. M must be greater or equal to N. If it is smaller then A should // be filled up to square with zero rows. // */ // // double rv1[nmax]; // // /* Householder reduction to bidiagonal form. */ // int NM; // double C; // double F; // double G = 0.0; // double H; // double S; // double X; // double Y; // double Z; // double Scale = 0.0; // double ANorm = 0.0; // double tmp; // int flag; // int i; // int its; // int j; // int jj; // int k; // int l; // // if( M < N ) { // fprintf( stderr, "You must augment A with extra zero rows.\n" ); // return; // } // // for( i = 0; i < N; ++i ) { // l = i + 1; // rv1[i] = Scale * G; // G = 0.0; // S = 0.0; // Scale = 0.0; // if( i < M ) { // for( k = i; k < M; ++k ) { // Scale = Scale + fabs( A[k][i] ); // } // if( Scale != 0.0 ) { // for( k = i; k < M; ++k ) { // A[k][i] = A[k][i] / Scale; // S = S + A[k][i] * A[k][i]; // } // F = A[i][i]; // G = sqrt(S); // if( F > 0.0 ) { // G = -G; // } // H = F * G - S; // A[i][i] = F - G; // if( i != (N-1) ) { // for( j = l; j < N; ++j ) { // S = 0.0; // for( k = i; k < M; ++k ) { // S = S + A[k][i] * A[k][j]; // } // F = S / H; // for( k = i; k < M; ++k ) { // A[k][j] = A[k][j] + F * A[k][i]; // } // } // } // for( k = i; k < M; ++k ) { // A[k][i] = Scale * A[k][i]; // } // } // } // // W[i] = Scale * G; // G = 0.0; // S = 0.0; // Scale = 0.0; // if( (i < M) && (i != (N-1)) ) { // for( k = l; k < N; ++k ) { // Scale = Scale + fabs( A[i][k] ); // } // if( Scale != 0.0 ) { // for( k = l; k < N; ++k ) { // A[i][k] = A[i][k] / Scale; // S = S + A[i][k] * A[i][k]; // } // F = A[i][l]; // G = sqrt(S); // if( F > 0.0 ) { // G = -G; // } // H = F * G - S; // A[i][l] = F - G; // for( k = l; k < N; ++k ) { // rv1[k] = A[i][k] / H; // } // if( i != (M-1) ) { // for( j = l; j < M; ++j ) { // S = 0.0; // for( k = l; k < N; ++k ) { // S = S + A[j][k] * A[i][k]; // } // for( k = l; k < N; ++k ) { // A[j][k] = A[j][k] + S * rv1[k]; // } // } // } // for( k = l; k < N; ++k ) { // A[i][k] = Scale * A[i][k]; // } // } // } // tmp = fabs( W[i] ) + fabs( rv1[i] ); // if( tmp > ANorm ) // ANorm = tmp; // } // // /* Accumulation of right-hand transformations. */ // for( i = N-1; i >= 0; --i ) { // if( i < (N-1) ) { // if( G != 0.0 ) { // for( j = l; j < N; ++j ) { // V[j][i] = (A[i][j] / A[i][l]) / G; // } // for( j = l; j < N; ++j ) { // S = 0.0; // for( k = l; k < N; ++k ) { // S = S + A[i][k] * V[k][j]; // } // for( k = l; k < N; ++k ) { // V[k][j] = V[k][j] + S * V[k][i]; // } // } // } // for( j = l; j < N; ++j ) { // V[i][j] = 0.0; // V[j][i] = 0.0; // } // } // V[i][i] = 1.0; // G = rv1[i]; // l = i; // } // // /* Accumulation of left-hand transformations. */ // for( i = N-1; i >= 0; --i ) { // l = i + 1; // G = W[i]; // if( i < (N-1) ) { // for( j = l; j < N; ++j ) { // A[i][j] = 0.0; // } // } // if( G != 0.0 ) { // G = 1.0 / G; // if( i != (N-1) ) { // for( j = l; j < N; ++j ) { // S = 0.0; // for( k = l; k < M; ++k ) { // S = S + A[k][i] * A[k][j]; // } // F = (S / A[i][i]) * G; // for( k = i; k < M; ++k ) { // A[k][j] = A[k][j] + F * A[k][i]; // } // } // } // for( j = i; j < M; ++j ) { // A[j][i] = A[j][i] * G; // } // } else { // for( j = i; j < M; ++j ) { // A[j][i] = 0.0; // } // } // A[i][i] = A[i][i] + 1.0; // } // // /* Diagonalization of the bidiagonal form. // Loop over singular values. */ // for( k = (N-1); k >= 0; --k ) { // /* Loop over allowed iterations. */ // for( its = 1; its <= 30; ++its ) { // /* Test for splitting. // Note that rv1[0] is always zero. */ // flag = true; // for( l = k; l >= 0; --l ) { // NM = l - 1; // if( (fabs(rv1[l]) + ANorm) == ANorm ) { // flag = false; // break; // } else if( (fabs(W[NM]) + ANorm) == ANorm ) { // break; // } // } // // /* Cancellation of rv1[l], if l > 0; */ // if( flag ) { // C = 0.0; // S = 1.0; // for( i = l; i <= k; ++i ) { // F = S * rv1[i]; // if( (fabs(F) + ANorm) != ANorm ) { // G = W[i]; // H = sqrt( F * F + G * G ); // W[i] = H; // H = 1.0 / H; // C = ( G * H ); // S = -( F * H ); // for( j = 0; j < M; ++j ) { // Y = A[j][NM]; // Z = A[j][i]; // A[j][NM] = (Y * C) + (Z * S); // A[j][i] = -(Y * S) + (Z * C); // } // } // } // } // Z = W[k]; // /* Convergence. */ // if( l == k ) { // /* Singular value is made nonnegative. */ // if( Z < 0.0 ) { // W[k] = -Z; // for( j = 0; j < N; ++j ) { // V[j][k] = -V[j][k]; // } // } // break; // } // // if( its >= 30 ) { // fprintf( stderr, "No convergence in 30 iterations.\n" ); // return; // } // // X = W[l]; // NM = k - 1; // Y = W[NM]; // G = rv1[NM]; // H = rv1[k]; // F = ((Y-Z)*(Y+Z) + (G-H)*(G+H)) / (2.0*H*Y); // G = sqrt( F * F + 1.0 ); // tmp = G; // if( F < 0.0 ) // tmp = -tmp; // F = ((X-Z)*(X+Z) + H*((Y/(F+tmp))-H)) / X; // // /* Next QR transformation. */ // C = 1.0; // S = 1.0; // for( j = l; j <= NM; ++j ) { // i = j + 1; // G = rv1[i]; // Y = W[i]; // H = S * G; // G = C * G; // Z = sqrt( F * F + H * H ); // rv1[j] = Z; // C = F / Z; // S = H / Z; // F = (X * C) + (G * S); // G = -(X * S) + (G * C); // H = Y * S; // Y = Y * C; // for( jj = 0; jj < N; ++jj ) { // X = V[jj][j]; // Z = V[jj][i]; // V[jj][j] = (X * C) + (Z * S); // V[jj][i] = -(X * S) + (Z * C); // } // Z = sqrt( F * F + H * H ); // W[j] = Z; // // /* Rotation can be arbitrary if Z = 0. */ // if( Z != 0.0 ) { // Z = 1.0 / Z; // C = F * Z; // S = H * Z; // } // F = (C * G) + (S * Y); // X = -(S * G) + (C * Y); // for( jj = 0; jj < M; ++jj ) { // Y = A[jj][j]; // Z = A[jj][i]; // A[jj][j] = (Y * C) + (Z * S); // A[jj][i] = -(Y * S) + (Z * C); // } // } // rv1[l] = 0.0; // rv1[k] = F; // W[k] = X; // } // } // // return; // }
32.842942
79
0.322397
[ "vector" ]
08d958590ef521086ed1cb2c7cb5a2fb1b265e9c
2,008
hpp
C++
nvm_engine/NvmEngine.hpp
shink/tair-contest
0b45b7bdb2f7da60904ea141a9a67476e5581a5e
[ "Apache-2.0" ]
null
null
null
nvm_engine/NvmEngine.hpp
shink/tair-contest
0b45b7bdb2f7da60904ea141a9a67476e5581a5e
[ "Apache-2.0" ]
null
null
null
nvm_engine/NvmEngine.hpp
shink/tair-contest
0b45b7bdb2f7da60904ea141a9a67476e5581a5e
[ "Apache-2.0" ]
null
null
null
/* * @author: shenke * @date: 2020/9/7 * @project: tair-contest * @desp: */ #ifndef TAIR_CONTEST_KV_CONTEST_NVM_ENGINE_H_ #define TAIR_CONTEST_KV_CONTEST_NVM_ENGINE_H_ #include "Statement.hpp" struct bucket { char *ptr; uint64_t end_off; }; class NvmEngine : DB { public: /** * @param * name: file in AEP(exist) * dbptr: pointer of db object */ NvmEngine(const std::string &name, FILE *log_file = nullptr); static Status CreateOrOpen(const std::string &name, DB **dbptr, FILE *log_file = nullptr); Status Get(const Slice &key, std::string *value) override; Status Set(const Slice &key, const Slice &value) override; ~NvmEngine() override; private: inline void BuildMapping(const std::string &name, size_t size); inline void InitBucket(); inline uint16_t Hash(const std::string &key); private: char *pmem_base_; size_t mapped_size_; #ifdef USE_LIBPMEM int is_pmem_; #endif #ifndef LOCAL const static size_t MAP_SIZE = 72ull << 30ull; // 72G(77309411328) const static uint64_t DISPLAY_NUM = 100000000; // 1亿 #else const static size_t MAP_SIZE = 960ull << 20ull; // 960M const static uint64_t DISPLAY_NUM = 100000; #endif const static uint64_t KEY_SIZE = 16; const static uint64_t VALUE_SIZE = 80; const static uint64_t PAIR_SIZE = KEY_SIZE + VALUE_SIZE; const static uint64_t PAIR_NUM = MAP_SIZE / PAIR_SIZE; // 键值对数量(805306368,不是素数,805306457是素数) const static uint16_t BUCKET_NUM = 1ull << 10ull; // 1024 个桶 const static uint64_t BUCKET_SIZE = MAP_SIZE / BUCKET_NUM; // 72M(75497472) const static uint16_t FAST_MAP_SIZE = 4ull << 10ull; // fast_map_ 的最大 size (4096) std::hash<std::string> str_hash_; std::mutex log_mut_; std::mutex mut_[BUCKET_NUM]; std::unordered_map<std::string, std::string> fast_map_[BUCKET_NUM]; bucket buckets_[BUCKET_NUM]; uint64_t get_count_; uint64_t set_count_; FILE *log_file_; }; #endif
25.417722
98
0.685757
[ "object" ]
08e6e876f14144bf5aa7f0da8944839538a5e83f
56,401
cpp
C++
src/dft/SxAtomicOrbitals.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
src/dft/SxAtomicOrbitals.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
src/dft/SxAtomicOrbitals.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The ab-initio based multiscale library // // S / P H I / n X // // Copyright: Max-Planck-Institute for Iron Research // 40237 Duesseldorf, Germany // // Contact: https://sxlib.mpie.de // Authors: see sphinx/AUTHORS // License: see sphinx/LICENSE // // --------------------------------------------------------------------------- #include <SxAtomicOrbitals.h> #include <SxNaturalCubicSpline.h> #include <SxCubicSpline.h> #include <SxRegex.h> #include <SxFileIO.h> SxAtomicOrbitals::SxAtomicOrbitals () { // empty } SxAtomicOrbitals::SxAtomicOrbitals ( const SxArray<SxArray<SxRadBasis::TPsi> > &in, const SxConstPtr<SxRadBasis> radBasisPtrIn) : SxPsiSet (PW) { SX_CHECK (radBasisPtrIn.getPtr () != NULL); radBasisPtr = radBasisPtrIn; muSet = in; // --- make sure that basis is set const SxRadBasis *radPtr = radBasisPtr.getPtr (); int iSpecies, nSpecies = (int)in.getSize(); SX_CHECK (nSpecies <= radBasisPtrIn->radFunc.getSize(), nSpecies, radBasisPtrIn->radFunc.getSize()); for (iSpecies=0; iSpecies < nSpecies; iSpecies++) { int nl = (int)in(iSpecies).getSize(); for (int l = 0; l < nl; l++) { // check dimensions SX_CHECK (in(iSpecies)(l).getSize() == radBasisPtrIn->radFunc(iSpecies).getSize(), in(iSpecies)(l).getSize(), radBasisPtrIn->radFunc(iSpecies).getSize()); // check basis if (muSet(iSpecies)(l).getBasisPtr () != radPtr) { muSet(iSpecies)(l) = muSet(iSpecies)(l).getCopy (); muSet(iSpecies)(l).setBasis (radPtr); } } } createFuncLMap (); registerMemoryObservers (); } SxAtomicOrbitals::SxAtomicOrbitals ( const SxArray<SxDiracMat<Double> > &in, const SxConstPtr<SxRadBasis> radBasisPtrIn) : SxPsiSet (PW) { // --- check dimensions int nSpecies = (int)in.getSize(); muSet.resize(nSpecies); SX_CHECK (nSpecies == radBasisPtr->radFunc.getSize(), nSpecies, radBasisPtr->radFunc.getSize()); for (int iSpecies=0; iSpecies < nSpecies; iSpecies++) { int nl = (int)in(iSpecies).row(0).getSize(); muSet(iSpecies).resize(nl); for (int l=0; l < nl; l++) { /*SX_CHECK (in(iSpecies).colRef(l).getSize() == radBasisPtr->radFunc(iSpecies).getSize(), in(iSpecies).colRef(l).getSize(), radBasisPtr->.radFunc(iSpecies).getSize());*/ muSet(iSpecies)(l).copy(in(iSpecies).colRef(l)); } } radBasisPtr = radBasisPtrIn; createFuncLMap (); registerMemoryObservers (); } SxAtomicOrbitals::SxAtomicOrbitals (const SxAtomicOrbitals &in) : SxPsiSet(PW) { (*this) = in; } SxAtomicOrbitals::SxAtomicOrbitals (SxBinIO &io) { radBasisPtr = SxPtr<SxRadBasis>::create(io); try { read(io); } catch (SxException e) { e.print (); SX_EXIT; } createFuncLMap (); } void SxAtomicOrbitals::setup (const SxSymbolTable *table) { SX_CHECK (table); radBasisPtr = SxPtr<SxRadBasis>::create(table); const SxString specName = "species"; const SxString orbitalName = "orbital"; const SxSymbolTable *species, *orbital; int iSpecies=-1; SxDiracVec<Double> newOrbital; try { species = table->getGroup (specName); int nSpecies = species->getNItems (specName); if (nSpecies != radBasisPtr->getNSpecies ()) { cout << endl; cout << "ERROR: Mismatch in number of species" << endl; cout << " Radial basis has " << radBasisPtr->getNSpecies () << " species." << endl; cout << " Orbital setup group '" << table->getName () << "' has " << nSpecies << " species." << endl; SX_QUIT; } } catch (SxException e) { e.print (); SX_EXIT; } try { // get species for(species = table->getGroup (specName); species != NULL; species = species->nextSibling (specName)) { int iOrbital = -1; iSpecies++; for(orbital = species->getGroup (orbitalName); orbital != NULL; orbital = orbital->nextSibling (orbitalName)) { iOrbital++; if (orbital->containsGroup("fromPotential")) { const SxSymbolTable *mode = orbital->getGroup ("fromPotential"); try { SxParser parser; SxString potFile = mode->get("file")->toString(); SxConstPtr<SxSymbolTable> potTable = parser.read (potFile); SxAtomicOrbitals fromPot; if (potTable->containsGroup("pseudoPot")) { SxPseudoPot pot = SxPseudoPot(&*potTable); SxPtr<SxRadBasis> radBasisPotPtr = SxPtr<SxRadBasis>::create(pot.rad, pot.logDr); fromPot = SxAtomicOrbitals(pot.getPseudoPsi (), radBasisPotPtr); } else if (potTable->containsGroup("pawPot")) { SxPAWPot pot = SxPAWPot(&*potTable); SxPtr<SxRadBasis> radBasisPotPtr = SxPtr<SxRadBasis>::create(pot.rad,pot.logDr); fromPot = SxAtomicOrbitals(pot.getPhiPS (),radBasisPotPtr); } else { cout << "No known potential group found!" << endl; SX_QUIT; } int l = mode->get("l")->toInt(); int iot = mode->get("iot")->toInt(); int is = mode->get("is")->toInt(); newOrbital = fromPot(is,iot).getCopy (); // Check Basis if (fromPot.getBasis().getPtr() != radBasisPtr.getPtr()) { newOrbital = fromPot.getBasis() ->changeRadBasis(radBasisPtr.getPtr (),newOrbital); } if (l != newOrbital.handle->auxData.l) { cout << "Inconsistent iot/l combination in fromPotential!" << endl; cout << "l is " << l <<", should be " << newOrbital.handle->auxData.l << endl; SX_QUIT; } newOrbital.handle->auxData.is = iSpecies; if (mode->contains("scale")) { double scale = mode->get("scale")->toReal(); SX_CHECK(scale > 1.0); SxDiracVec<Double> scaledRad = scale * radBasisPtr->radFunc(iSpecies); scaledRad(0) = 0.0; SxCubicSpline<SxDiracVec<Double> > spline; if (l < 2) spline = SxCubicSpline<SxDiracVec<Double> > (scaledRad, newOrbital, SxCubicSpline<SxDiracVec<Double> >::NaturalHermite); else spline = SxCubicSpline<SxDiracVec<Double> > (scaledRad, newOrbital, SxCubicSpline<SxDiracVec<Double> >::Hermite); newOrbital = spline.getY (radBasisPtr->radFunc(iSpecies)); if (l > 0) newOrbital(0) = 0; newOrbital.handle->auxData.is = iSpecies; newOrbital.handle->auxData.ia = -1; newOrbital.handle->auxData.n = -1; newOrbital.handle->auxData.l = l; newOrbital.handle->auxData.m = NONE_M; } cout << "Add Orbital from Potential: is iot l " << is << " " << iot << " " << l; addOrbital(newOrbital); } catch (SxException e) { e.print (); SX_EXIT; } } else if(orbital->containsGroup("fromFile")) { const SxSymbolTable *mode = orbital->getGroup ("fromFile"); try { SxString fileName = mode->get("file")->toString(); int l = mode->get("l")->toInt(); int iot = mode->get("iot")->toInt(); int is = mode->get("is")->toInt(); // read Orbitalfile & check Basis SxAtomicOrbitals fileOrbitals; if (mode->contains("Siesta")) { fileOrbitals.readSiesta(fileName,radBasisPtr->radFunc(is)); newOrbital = fileOrbitals(is,iot).getCopy (); newOrbital.setBasis(&*radBasisPtr); } else { SxRadBasis vecBasis; vecBasis.read(fileName); fileOrbitals.read(fileName); int nSpeciesFile = fileOrbitals.getNSpecies (); if (is >= nSpeciesFile) { cout << "Did not find species " << is << " in quamol file " << fileName << " with " << nSpeciesFile << " species." << endl; SX_QUIT; } int nOrbTypesFile = fileOrbitals.getNOrbTypes(is); if (iot >= nOrbTypesFile) { cout << "Did not find orbitaltype iot=" << iot << " in quamol file " << fileName << " with " << nOrbTypesFile << " orbital types." << endl; SX_QUIT; } if (mode->contains("rCut")) { double rCut = mode->get("rCut")->toReal(); double rMin = vecBasis.getRMin(is); double rMax = vecBasis.getRMax(is); int nPoints = int ((double)vecBasis.getNPoints (is) * rCut / rMax); SxRadRBasis cutRad (rMin,rCut,nPoints); newOrbital = fileOrbitals(is,iot).getCopy (); newOrbital = vecBasis.toRadRBasis (&cutRad, newOrbital); newOrbital = cutRad.toRadBasis (&vecBasis, newOrbital); newOrbital.setBasis(vecBasis); } else { newOrbital = fileOrbitals(is,iot).getCopy (); newOrbital.setBasis(vecBasis); } if (fabs (vecBasis.radFunc(is)(0) - radBasisPtr->radFunc(iSpecies)(0)) > 1e-6 || fabs (vecBasis.logDr(is) - radBasisPtr->logDr(iSpecies)) > 1e-6) newOrbital = vecBasis.changeRadBasis( radBasisPtr.getPtr (), newOrbital); } if (l != newOrbital.handle->auxData.l) { cout << "Inconsistent iot/l combination in fromFile!" << endl; cout << "l is " << l <<", should be " << newOrbital.handle->auxData.l << endl; SX_QUIT; } newOrbital.handle->auxData.is = iSpecies; if (mode->contains("scale")) { double scale = mode->get("scale")->toReal(); SX_CHECK(scale > 1.0); SxDiracVec<Double> scaledRad = scale * radBasisPtr->radFunc(iSpecies); scaledRad(0) = 0.0; SxCubicSpline<SxDiracVec<Double> > spline; if (l < 2) spline = SxCubicSpline<SxDiracVec<Double> > (scaledRad, newOrbital, SxCubicSpline<SxDiracVec<Double> >::NaturalHermite); else spline = SxCubicSpline<SxDiracVec<Double> > (scaledRad, newOrbital, SxCubicSpline<SxDiracVec<Double> >::Hermite); newOrbital = spline.getY (radBasisPtr->radFunc(iSpecies)); if (l > 0) newOrbital(0) = 0; newOrbital.handle->auxData.is = iSpecies; newOrbital.handle->auxData.ia = -1; newOrbital.handle->auxData.n = -1; newOrbital.handle->auxData.l = l; newOrbital.handle->auxData.m = NONE_M; } cout << "Add Orbital from File: is iot l " << is << " " << iot << " " << l; addOrbital(newOrbital); } catch (SxException e) { e.print (); SX_EXIT; } } else if(orbital->containsGroup("fromWaves")) { const SxSymbolTable *mode = orbital->getGroup ("fromWaves"); try { SxString fileName = mode->get("file")->toString(); int l = mode->get("l")->toInt(); int iState = mode->get("iState")->toInt(); newOrbital = compressWave(fileName,iState,iSpecies,l); newOrbital.handle->auxData.is = iSpecies; newOrbital.handle->auxData.ia = -1; newOrbital.handle->auxData.n = -1; newOrbital.handle->auxData.l = l; newOrbital.handle->auxData.m = NONE_M; cout << "Add Orbital from wavestate: iState l " << iState << " " << l; addOrbital(newOrbital); } catch (SxException e) { e.print (); SX_EXIT; } } else if(orbital->containsGroup("generateGaussian")) { const SxSymbolTable *mode = orbital->getGroup ("generateGaussian"); try { double beta = mode->get("beta")->toReal(); int l = mode->get("l")->toInt(); if (l > 0) beta = beta * sqrt(2./(1.* l)); const SxDiracVec<Double> &r = radBasisPtr->radFunc(iSpecies); SxDiracVec<Double> rPowL = 1.0 * r; if (l == 0) rPowL.set(1.0); for (int il = 2; il <= l; il++) rPowL *= r; newOrbital = rPowL * exp(-beta * r.sqr ()); newOrbital.handle->auxData.is = iSpecies; newOrbital.handle->auxData.ia = -1; newOrbital.handle->auxData.n = -1; newOrbital.handle->auxData.l = l; newOrbital.handle->auxData.m = NONE_M; newOrbital.setBasis(radBasisPtr.getConstPtr()); if (l == 0) { cout << "Generate Gaussian Orbital: is l beta "; cout << iSpecies; cout << " " << l; cout << " " << beta; } else { cout << "Generate Gaussian Orbital: is l rMax "; cout << iSpecies; cout << " " << l; cout << " " << beta / sqrt(2./(1.* l)); } addOrbital(newOrbital); } catch (SxException e) { e.print (); SX_EXIT; } } else if(orbital->containsGroup("gaussianBasis")) { const SxSymbolTable *mode = orbital->getGroup ("gaussianBasis"); try { SxVector<Double> exps (mode->get("exponents")->toList()); int nGauss = (int)exps.getSize (); SxVector<Double> coeffs (mode->get("coefficients")->toList()); int l = mode->get("l")->toInt(); if (nGauss != coeffs.getSize()) { cout << "Wrong Number of coefficients: nGaussians is " << nGauss << ", but have " << coeffs.getSize () << "coefficients!" << endl; SX_QUIT; } const SxDiracVec<Double> &r = radBasisPtr->radFunc(iSpecies); int dim = (int)r.getSize(); newOrbital.resize (dim); newOrbital.set(0.0); for (int iGauss = 0; iGauss < nGauss; iGauss++) { newOrbital += coeffs(iGauss) * exp(-r.sqr () * exps(iGauss)); } newOrbital *= pow(r, double(l)); newOrbital.handle->auxData.is = iSpecies; newOrbital.handle->auxData.ia = -1; newOrbital.handle->auxData.n = -1; newOrbital.handle->auxData.l = l; newOrbital.handle->auxData.m = NONE_M; newOrbital.setBasis(radBasisPtr.getConstPtr()); cout << "Generate orbital via gaussian basis: is l nGauss "; cout << iSpecies; cout << " " << l; cout << " " << nGauss; addOrbital(newOrbital); } catch (SxException e) { e.print (); SX_EXIT; } } else { cout << "No known Initialization shema found!" << endl; cout << "SPHInX quits here!" << endl; SX_QUIT; } } } } catch (SxException e) { e.print (); SX_EXIT; } createFuncLMap (); } void SxAtomicOrbitals::addOrbital (const SxDiracVec<Double> &orbitalIN) { SX_CHECK(radBasisPtr.getPtr () != NULL); int nSpeciesOld = getNSpecies (); int nSpeciesNew = nSpeciesOld; int SpeciesIN = orbitalIN.handle->auxData.is; if (nSpeciesOld <= SpeciesIN) nSpeciesNew = nSpeciesOld+1; int lIN = orbitalIN.handle->auxData.l; SxArray<SxArray<SxDiracVec<Double> > > muSetNew(nSpeciesNew); bool insert = false; for (int iSpecies = 0; iSpecies < nSpeciesOld; iSpecies++) { int nOrbTypes = getNOrbTypes(iSpecies); if (iSpecies == SpeciesIN) muSetNew(iSpecies).resize(nOrbTypes + 1); else muSetNew(iSpecies).resize(nOrbTypes); int iot = 0; for (int iotOrig = 0; iotOrig < nOrbTypes; iotOrig++) { int l = muSet(iSpecies)(iotOrig).handle->auxData.l; // insert new Orbital if l < lMax if (!insert && iSpecies == SpeciesIN && l > lIN ) { muSetNew(iSpecies)(iot) = 1.0 * orbitalIN; muSetNew(iSpecies)(iot).handle->auxData.is = iSpecies; muSetNew(iSpecies)(iot).handle->auxData.ia = -1; muSetNew(iSpecies)(iot).handle->auxData.n = iot; muSetNew(iSpecies)(iot).handle->auxData.l = lIN; muSetNew(iSpecies)(iot).handle->auxData.m = NONE_M; muSetNew(iSpecies)(iot).setBasis(radBasisPtr.getConstPtr ()); cout << " as " << muSetNew(iSpecies)(iot).handle->auxData.is << " " << muSetNew(iSpecies)(iot).handle->auxData.n << " " << muSetNew(iSpecies)(iot).handle->auxData.l << endl; iot++; insert = true; } muSetNew(iSpecies)(iot) = 1.0 * muSet(iSpecies)(iotOrig); muSetNew(iSpecies)(iot).handle->auxData.n = iot; iot++; } // or append it if l = lMax if (iSpecies == SpeciesIN && !insert) { muSetNew(iSpecies)(iot) = 1.0 * orbitalIN; muSetNew(iSpecies)(iot).handle->auxData.is = iSpecies; muSetNew(iSpecies)(iot).handle->auxData.ia = -1; muSetNew(iSpecies)(iot).handle->auxData.n = iot; muSetNew(iSpecies)(iot).handle->auxData.l = lIN; muSetNew(iSpecies)(iot).handle->auxData.m = NONE_M; muSetNew(iSpecies)(iot).setBasis(radBasisPtr.getConstPtr()); cout << " as " << muSetNew(iSpecies)(iot).handle->auxData.is << " " << muSetNew(iSpecies)(iot).handle->auxData.n << " " << muSetNew(iSpecies)(iot).handle->auxData.l << endl; insert = true; iot++; } } if (!insert) { muSetNew(nSpeciesNew-1).resize(1); muSetNew(nSpeciesNew-1)(0) = 1.0 * orbitalIN; muSetNew(nSpeciesNew-1)(0).handle->auxData.is = nSpeciesNew-1; muSetNew(nSpeciesNew-1)(0).handle->auxData.ia = -1; muSetNew(nSpeciesNew-1)(0).handle->auxData.n = 0; muSetNew(nSpeciesNew-1)(0).handle->auxData.l = lIN; muSetNew(nSpeciesNew-1)(0).handle->auxData.m = NONE_M; muSetNew(nSpeciesNew-1)(0).setBasis(radBasisPtr.getConstPtr()); cout << " as " << muSetNew(nSpeciesNew-1)(0).handle->auxData.is << " " << muSetNew(nSpeciesNew-1)(0).handle->auxData.n << " " << muSetNew(nSpeciesNew-1)(0).handle->auxData.l << endl; insert = true; } *this = SxAtomicOrbitals(muSetNew,radBasisPtr); } SxAtomicOrbitals::~SxAtomicOrbitals () { // empty } void SxAtomicOrbitals::operator= (const SxAtomicOrbitals &in) { if (&in == this) { cout << "a = a Error" << endl; SX_EXIT; } radBasisPtr = in.radBasisPtr; muSet = in.muSet; funcLMap = in.funcLMap; } void SxAtomicOrbitals::operator+= (const SxAtomicOrbitals &in) { SX_CHECK(radBasisPtr.getPtr() != NULL); SX_CHECK(radBasisPtr == in.getRadBasisPtr()); SX_CHECK(muSet.getSize() == in.muSet.getSize(), muSet.getSize(), in.muSet.getSize()); for (int is = 0; is < in.muSet.getSize (); is++) { SX_CHECK(muSet(is).getSize() == in.muSet(is).getSize(), muSet(is).getSize(), in.muSet(is).getSize()); for (int l = 0; l < in.muSet(is).getSize (); l++) { muSet(is)(l) += in.muSet(is)(l); } } } SxAtomicOrbitals SxAtomicOrbitals::operator+ (const SxAtomicOrbitals &in) const { SX_CHECK(radBasisPtr.getPtr() != NULL); SX_CHECK(radBasisPtr == in.getRadBasisPtr()); int nSpecies = (int)muSet.getSize(); SX_CHECK(nSpecies == in.getNSpecies(), nSpecies, in.getNSpecies()); SxArray<SxArray<SxRadBasis::TPsi> > resMuSet(nSpecies); for (int is = 0; is < nSpecies; is++) { int nOrbTypes = getNOrbTypes (is); SX_CHECK(nOrbTypes == in.getNOrbTypes(is), nOrbTypes, in.getNOrbTypes(is)); resMuSet(is).resize(nOrbTypes); for (int iot = 0; iot < nOrbTypes; iot++) { resMuSet(is)(iot) = in.muSet(is)(iot) + muSet(is)(iot); } } SxAtomicOrbitals result = SxAtomicOrbitals(resMuSet, radBasisPtr); return result; } SxAtomicOrbitals SxAtomicOrbitals::operator- (const SxAtomicOrbitals &in) const { SX_CHECK(radBasisPtr.getPtr() != NULL); SX_CHECK(radBasisPtr == in.getRadBasisPtr()); int nSpecies = (int)muSet.getSize(); SX_CHECK(nSpecies == in.getNSpecies(), nSpecies, in.getNSpecies()); SxArray<SxArray<SxRadBasis::TPsi> > resMuSet(nSpecies); for (int is = 0; is < nSpecies; is++) { int nOrbTypes = getNOrbTypes (is); SX_CHECK(nOrbTypes == in.getNOrbTypes(is), nOrbTypes, in.getNOrbTypes(is)); resMuSet(is).resize(nOrbTypes); for (int iot = 0; iot < nOrbTypes; iot++) { resMuSet(is)(iot) = muSet(is)(iot) - in.muSet(is)(iot); } } SxAtomicOrbitals result = SxAtomicOrbitals(resMuSet, radBasisPtr); return result; } SxAtomicOrbitals SxAtomicOrbitals::operator* (double skalar) const { SX_CHECK(radBasisPtr.getPtr() != NULL); int nSpecies = (int)muSet.getSize(); SxArray<SxArray<SxRadBasis::TPsi> > resMuSet(nSpecies); for (int is = 0; is < nSpecies; is++) { int nOrbTypes = getNOrbTypes(is); resMuSet(is).resize(nOrbTypes); for (int iot = 0; iot < nOrbTypes; iot++) { resMuSet(is)(iot) = skalar * muSet(is)(iot); } } SxAtomicOrbitals result = SxAtomicOrbitals(resMuSet, radBasisPtr); return result; } SxAtomicOrbitals SxAtomicOrbitals::operator* (const SxArray<SxArray<double> > &skalar) const { SX_CHECK(radBasisPtr.getPtr() != NULL); int nSpecies = (int)muSet.getSize(); SxArray<SxArray<SxRadBasis::TPsi> > resMuSet(nSpecies); for (int is = 0; is < nSpecies; is++) { int nOrbTypes = getNOrbTypes(is); resMuSet(is).resize(nOrbTypes); for (int iot = 0; iot < nOrbTypes; iot++) { resMuSet(is)(iot) = skalar(is)(iot) * muSet(is)(iot); } } SxAtomicOrbitals result = SxAtomicOrbitals(resMuSet, radBasisPtr); return result; } SxAtomicOrbitals SxAtomicOrbitals::operator* (const SxAtomicOrbitals &in) const { SX_CHECK(radBasisPtr.getPtr () != NULL); SX_CHECK(radBasisPtr == in.radBasisPtr); int nSpecies = getNSpecies (); SX_CHECK (nSpecies == in.getNSpecies ()); SxArray<SxArray<SxRadBasis::TPsi> > resMuSet(nSpecies); for (int is = 0; is < nSpecies; is++) { int nOrbTypes = getNOrbTypes(is); SX_CHECK (nOrbTypes == in.getNOrbTypes(is)); resMuSet(is).resize(nOrbTypes); for (int iot = 0; iot < nOrbTypes; iot++) { resMuSet(is)(iot) = in.muSet(is)(iot) * muSet(is)(iot); } } SxAtomicOrbitals result = SxAtomicOrbitals(resMuSet, radBasisPtr); return result; } SxRadBasis::TPsi & SxAtomicOrbitals::operator() (int is, int iot) { return muSet(is)(iot); } const SxRadBasis::TPsi & SxAtomicOrbitals::operator() (int is, int iot) const { return muSet(is)(iot); } int SxAtomicOrbitals::getIOT (int is, int n, int l) const { int iot = 0; while ((muSet(is)(iot).handle->auxData.n != n) || (muSet(is)(iot).handle->auxData.l != l)) { iot++; if (iot >= muSet(is).getSize()) SX_EXIT; } return iot; } SxRadBasis::TPsi SxAtomicOrbitals::operator() (int is, int ia, int n, int l, int m) const { int iot = getIOT (is,n,l); SxRadBasis::TPsi vec ( muSet(is)(iot) ); vec.setBasis (radBasisPtr.getConstPtr ()); vec.handle->auxData.is = is; vec.handle->auxData.ia = ia; vec.handle->auxData.n = n; vec.handle->auxData.l = l; vec.handle->auxData.m = m; return vec; } int SxAtomicOrbitals::getNSpecies () const { return (int)muSet.getSize (); } int SxAtomicOrbitals::getNOrbTypes (int iSpecies) const { return (int)muSet(iSpecies).getSize (); } int SxAtomicOrbitals::getNOrbTypes () const { int result = 0; for (int is = 0; is < getNSpecies (); is++) result += getNOrbTypes(is); return result; } void SxAtomicOrbitals::set(double val) { for (int iSpecies = 0; iSpecies < muSet.getSize(); iSpecies++) { for (int iot = 0; iot < muSet(iSpecies).getSize(); iot++) { muSet(iSpecies)(iot).set(val); } } } SxQuantumNumbers SxAtomicOrbitals::getQuantumNumbers (int iSpecies, int idx) const { SX_CHECK(iSpecies < muSet.getSize(), iSpecies, muSet.getSize()); SX_CHECK(idx < muSet(iSpecies).getSize(), idx, muSet(iSpecies).getSize()); int n = muSet(iSpecies)(idx).handle->auxData.n; int l = muSet(iSpecies)(idx).handle->auxData.l; SxQuantumNumbers result (iSpecies,n,l,0); return result; } SxArray<SxQuantumNumbers> SxAtomicOrbitals::getReducedOrbitalMap () const { SX_CHECK(&muSet); int nSpecies = (int)muSet.getSize (); SxList<SxQuantumNumbers> list; for(int is = 0; is < nSpecies; is++) { int nOrbLocal = (int)muSet(is).getSize(); for(int iot = 0; iot < nOrbLocal; iot++) { int l = muSet(is)(iot).handle->auxData.l; // SxQuantumNumberConstructor forbids uninitialized ia and m SxQuantumNumbers qNumbers (is,0,iot,l,0); // Therefore unset it here qNumbers.iAtom = -1; qNumbers.m = NONE_M; list.append(qNumbers); } } SxArray<SxQuantumNumbers> result = SxArray<SxQuantumNumbers>(list); return result; } SxArray<SxQuantumNumbers> SxAtomicOrbitals::getOrbitalMap ( SxAtomicStructure structure) const { SX_CHECK(&muSet); int nSpecies = (int)muSet.getSize (); SxList<SxQuantumNumbers> list; for(int is = 0; is < nSpecies; is++) { int nAtoms = structure.getNAtoms(is); int nOrbLocal = (int)muSet(is).getSize(); for(int ia = 0; ia < nAtoms; ia++) { for(int iot = 0; iot < nOrbLocal; iot++) { int l = muSet(is)(iot).handle->auxData.l; for(int m = -l; m <= l; m++) { list.append(SxQuantumNumbers(is,ia,iot,l,m)); } } } } SxArray<SxQuantumNumbers> result = SxArray<SxQuantumNumbers>(list); return result; } int SxAtomicOrbitals::getNOrbitals ( SxAtomicStructure structure) const { SX_CHECK(muSet.getSize() > 0); int nSpecies = (int)muSet.getSize (); int result = 0; for(int is = 0; is < nSpecies; is++) { int nAtoms = structure.getNAtoms(is); int nOrbLocal = (int)muSet(is).getSize(); for(int ia = 0; ia < nAtoms; ia++) { for(int iot = 0; iot < nOrbLocal; iot++) { int l = muSet(is)(iot).handle->auxData.l; result += 2*l+1; } } } return result; } int SxAtomicOrbitals::getOrbitalIdx (int is, int ia, int iot, int l, int m, SxArray<SxQuantumNumbers> map) const { for (int iOrbital = 0; iOrbital < map.getSize(); iOrbital++) { if (map(iOrbital).iSpecies == is && map(iOrbital).iAtom == ia && map(iOrbital).n == iot && map(iOrbital).l == l && map(iOrbital).m == m) return iOrbital; } cout << "OrbitalIdx with is = " << is << ", ia = " << ia << ", n = " << iot << ", l = " << l << ", m = " << m << " not found!" << endl; SX_EXIT; } void SxAtomicOrbitals::createFuncLMap () { int nSpecies = (int)muSet.getSize (); funcLMap.resize(nSpecies); for(int iSpecies = 0; iSpecies < nSpecies; iSpecies++) { int lMax = getLMax (iSpecies); funcLMap(iSpecies).resize(lMax + 1); SxArray<int> funcPerL(lMax + 1); funcPerL.set(0); int nOrbTypes = (int)muSet(iSpecies).getSize (); for(int iot = 0; iot < nOrbTypes; iot++) { int l = muSet(iSpecies)(iot).handle->auxData.l; funcPerL(l)++; } SxArray<int> currentIFL(lMax + 1); currentIFL.set(0); for (int l = 0; l <= lMax; l++) { funcLMap(iSpecies)(l).resize(funcPerL(l)); } for (int iot = 0; iot < nOrbTypes; iot++) { int l = muSet(iSpecies)(iot).handle->auxData.l; funcLMap(iSpecies)(l)(currentIFL(l)) = iot; currentIFL(l)++; } } } SxRadBasis::TPsi SxAtomicOrbitals::getFuncL (int is, int l, int ifl) { int iot = funcLMap(is)(l)(ifl); return muSet(is)(iot); } const SxRadBasis::TPsi SxAtomicOrbitals::getFuncL (int is, int l, int ifl) const { int iot = funcLMap(is)(l)(ifl); return muSet(is)(iot); } int SxAtomicOrbitals::getLMax () const { int nSpecies = (int)muSet.getSize (); int result = 0; for (int is = 0; is < nSpecies; is++) { int nOrbTypes = (int)muSet(is).getSize (); for (int iot = 0; iot < nOrbTypes; iot++) { if (result < muSet(is)(iot).handle->auxData.l) result = muSet(is)(iot).handle->auxData.l; } } return result; } int SxAtomicOrbitals::getLMax (const int iSpecies) const { int nOrbTypes = (int)muSet(iSpecies).getSize (); int result = 0; for (int iot = 0; iot < nOrbTypes; iot++) { if (result < muSet(iSpecies)(iot).handle->auxData.l) result = muSet(iSpecies)(iot).handle->auxData.l; } return result; } SxArray<SxArray<int> > SxAtomicOrbitals::getFuncPerL () const { int nSpecies = (int)muSet.getSize (); SxArray<SxArray<int> > result(nSpecies); for(int iSpecies = 0; iSpecies < nSpecies; iSpecies++) { int lMax = getLMax (iSpecies); result(iSpecies).resize(lMax + 1); for(int l = 0; l <= lMax; l++) { result(iSpecies)(l) = getFuncPerL(iSpecies,l); } } return result; } int SxAtomicOrbitals::getFuncPerL (int is, int l) const { return (int)funcLMap(is)(l).getSize(); } void SxAtomicOrbitals::registerMemoryObservers () { TRACK_MEMORY (muSet); } void SxAtomicOrbitals::write (SxBinIO &io) const { SX_CHECK(radBasisPtr.getPtr () != NULL); const SxRadBasis &radBasis = *radBasisPtr; int nSpecies = getNSpecies(); try { //create dimensions io.addDimension ("nSpecies", nSpecies); for (int is = 0; is < nSpecies; is++) { io.addDimension ("dimOrbTypes-"+SxString(is), getNOrbTypes(is)); io.addDimension ("dimRad-"+SxString(is), (int)radBasis.radFunc(is).getSize()); } //write data SxArray<SxVector<Int> > lNumbers (nSpecies); for (int is = 0; is < nSpecies; is++) { SxString radialName= "radFunc-" + SxString(is); SxString dimRadName = "dimRad-" + SxString(is); io.write(radialName, radBasis.radFunc(is), dimRadName); SxString logDrName= "logDr-" + SxString(is); io.write(logDrName, radBasis.logDr(is)); lNumbers(is).resize(getNOrbTypes(is)); for (int iot=0; iot < getNOrbTypes(is); iot++) { radialName= "radial-" + SxString(is) + "-" + SxString(iot); io.write(radialName, muSet(is)(iot), dimRadName); lNumbers(is)(iot) = muSet(is)(iot).handle->auxData.l; } SxString lName= "lNumbers-" + SxString(is); io.write(lName, lNumbers(is),"dimOrbTypes-"+SxString(is)); } } catch (SxException e) { e.print (); SX_EXIT; } } void SxAtomicOrbitals::write (SxString filename) const { SxBinIO io(filename, SxBinIO::BINARY_WRITE_ONLY); write(io); io.setMode (SxBinIO::WRITE_DATA); write(io); io.close(); } void SxAtomicOrbitals::read (SxBinIO &io) { try { SxPtr<SxRadBasis> basisPtr = SxPtr<SxRadBasis>::create(io); radBasisPtr = basisPtr; //get dimensions int nSpecies = io.getDimension ("nSpecies"); muSet.resize(nSpecies); for (int is = 0; is < nSpecies; is++) { int nOrbTypes = io.getDimension ("dimOrbTypes-"+SxString(is)); muSet(is).resize(nOrbTypes); int dimRad = io.getDimension ("dimRad-"+SxString(is)); SxDiracVec<Int> lVec (nOrbTypes); SxString lName= "lNumbers-" + SxString(is); io.read(lName,&lVec,nOrbTypes); // TODO further check of SxRadBasis for (int iot=0; iot < nOrbTypes; iot++) { muSet(is)(iot).resize(dimRad); SxString radialName= "radial-" + SxString(is) + "-" + SxString(iot); SxDiracVec<Double> &readVec = muSet(is)(iot); io.read(radialName,&readVec,dimRad); muSet(is)(iot).setBasis (radBasisPtr.getConstPtr()); muSet(is)(iot).handle->auxData.is = is; muSet(is)(iot).handle->auxData.n = iot; muSet(is)(iot).handle->auxData.l = lVec(iot); muSet(is)(iot).handle->auxData.m = 0; } // TODO Inconsistent check --- is in file and is in RadBasis might differ /* if (dimRad != rBasis.radFunc(is).getSize()) { cout << "WARNING: Incompatible grid size in readAtomicOrbitals !" << endl; cout << "Grid size in File is " << dimRad << endl; cout << "Grid size in rad Basis is " << rBasis.radFunc(is).getSize() << endl; cout << "Interpolate now!" << endl; SxRadBasis fileBasis; fileBasis.read(io); for (int iot=0; iot < nOrbTypes; iot++) { SxNaturalCubicSpline interpol (toVector(fileBasis.radFunc(is)), toVector(muSet(is)(iot))); muSet(is)(iot).resize(rBasis.radFunc(is).getSize ()); for (int i = 0; i < rBasis.radFunc(is).getSize (); i++) { int last = fileBasis.radFunc(is).getSize() - 1; if (fileBasis.radFunc(is)(last) > rBasis.radFunc(is)(i)) muSet(is)(iot)(i) = interpol.getVal(rBasis.radFunc(is)(i)); else muSet(is)(iot)(i) = 0.0; } } } */ } } catch (SxException e) { e.print (); SX_EXIT; } createFuncLMap (); } void SxAtomicOrbitals::read (const SxString &file) { try { SxBinIO io (file, SxBinIO::BINARY_READ_ONLY); read (io); io.close (); } catch (SxException e) { e.print (); SX_EXIT; } } void SxAtomicOrbitals::writeSiesta (const SxArray<SxString> &file, const SxArray<SxDiracVec<Double> > &basis) { int nSpecies = getNSpecies (); SX_CHECK (basis.getSize () == nSpecies); SX_CHECK (file.getSize () == nSpecies); for (int iSpecies = 0; iSpecies < nSpecies; iSpecies++) { SxBinIO io; io.open(file(iSpecies), SxBinIO::ASCII_WRITE_ONLY); int oldL = -1; int z = 0; for (int iot = 0; iot < getNOrbTypes (iSpecies); iot++) { // orbital header int l = muSet(iSpecies)(iot).handle->auxData.l; if (l == oldL) z++; else { z = 0; oldL = l; } fprintf(io.fp,"%i ? %i ? 0.000000 #orbital l, n, z, is_polarized, population\n",l,z); int npts = (int)basis(iSpecies).getSize (); double delta = basis(iSpecies)(1) - basis(iSpecies)(0); double cutoff = basis(iSpecies)(npts-1); fprintf(io.fp,"%i %.12e %.12f # npts, delta, cutoff\n",npts, delta, cutoff); SxCubicSpline<SxDiracVec<Double> > spline ( radBasisPtr->radFunc(iSpecies), muSet(iSpecies)(iot), SxCubicSpline<SxDiracVec<Double> >::Natural); SxDiracVec<Double> orbital = spline.getY(basis(iSpecies)); orbital(npts-1) = 0.0; if (l != 0) orbital(0) = 0.0; // data io.writeXYPlot (basis(iSpecies), orbital); } io.close (); } } void SxAtomicOrbitals::readSiesta (const SxString &file, const SxDiracVec<Double> &radFunc) { SxString ionFile; SxList<SxString> cLine; SxString data; muSet.resize(1); try { ionFile = SxFileIO::readBinary (file,-1); } catch (SxException e) { e.print (); SX_EXIT; } SxList<SxString> ionFileTok = ionFile.tokenize ('\n'); int line = 0; while (ionFileTok(line).contains("# Lmax for basis, no. of nl orbitals") == 0) if (line >= ionFileTok.getSize()) { cout << "Expression not found" << endl; SX_EXIT; } data = ionFileTok(line).left("#").stripWhiteSpace (); //int lMax = (data.left(" ").stripWhiteSpace ()).toInt (); int nOrbTypes = (data.right(" ").stripWhiteSpace ()).toInt (); muSet(0).resize(nOrbTypes); for (int iot = 0; iot < nOrbTypes; iot++) { while (ionFileTok(line).contains("#orbital") == 0) { line++; if (line >= ionFileTok.getSize()) { cout << "Expression not found" << endl; SX_EXIT; } } cLine = ionFileTok(line).left('#').stripWhiteSpace ().tokenize(' '); int l = cLine.first ().toInt (); line++; cLine = ionFileTok(line).left('#').stripWhiteSpace ().tokenize(' '); int nPoints = cLine.first ().toInt (); //int cutoff = cLine.last ().toInt (); SxDiracVec<Double> x (nPoints); SxDiracVec<Double> y (nPoints); line++; for (int iPoint = 0; iPoint < nPoints; iPoint++,line++) { x(iPoint) = ionFileTok(line).stripWhiteSpace ().left (' ') .stripWhiteSpace ().toDouble(); y(iPoint) = ionFileTok(line).stripWhiteSpace ().right(' ') .stripWhiteSpace ().toDouble(); } SxCubicSpline<SxDiracVec<Double> > spline(x,y, SxCubicSpline<SxDiracVec<Double> >::Natural); muSet(0)(iot) = spline.getY(radFunc); // Set auxdata SxRadBasis::TPsi &mu = muSet(0)(iot); mu.handle->auxData.is = -1; mu.handle->auxData.ia = -1; mu.handle->auxData.n = iot; mu.handle->auxData.l = l; mu.handle->auxData.m = NONE_M; } createFuncLMap (); registerMemoryObservers (); } void SxAtomicOrbitals::print (SxString file) const { int nSpecies = getNSpecies(); const SxRadBasis &rad = *radBasisPtr; for (int is = 0; is < nSpecies; is++) { int nOrbTypes = getNOrbTypes(is); for (int iot = 0; iot < nOrbTypes; iot++) { try { SxString outFile = file + SxString(is) + SxString(iot) + ".dat"; SxBinIO out; out.open(outFile, SxBinIO::ASCII_WRITE_ONLY); out.writeXYPlot(toVector(rad.radFunc(is)),toVector(muSet(is)(iot))); out.close(); } catch (SxException e) { e.print (); SX_QUIT; } } } } void SxAtomicOrbitals::print () const { SxString file = "AtomicOrbitals"; print (file); } void SxAtomicOrbitals::setBasis (SxConstPtr<SxRadBasis> radBasisPtrIn) { radBasisPtr = radBasisPtrIn; for (int is = 0; is < muSet.getSize (); ++is) { for (int iot = 0; iot < muSet(is).getSize (); ++iot) { muSet(is)(iot).setBasis (radBasisPtr.getConstPtr ()); } } } void SxAtomicOrbitals::readOrbital (FILE *fp, int is, int n, int l, int iot, bool ignoreComments) { SX_CHECK (fp); SX_CHECK (is >= 0 && ( (is <= getNSpecies () && iot == -1) || (is < getNSpecies ())), is, getNSpecies (), iot); SX_CHECK (l >= 0, l); SX_CHECK ((iot >= 0 && iot < muSet(is).getSize ()) || (iot == -1), iot, muSet(is).getSize ()); // --- read the file int N = 0; char c; SxStack<double> rFile, psiFile; while (!feof(fp)) { if (ignoreComments) { while (fscanf (fp, " #%c", &c) == 1) { // comment line while (c != '\n') { if (feof(fp)) break; c = (char)fgetc (fp); } } } double r, f; if (fscanf(fp, "%lf %lf", &r, &f) == 2) { rFile << r; psiFile << f; N++; } else { break; } } if (N == 0) { cout << "Could not read orbital from text file!" << endl; SX_EXIT; } // --- transform data to vectors SxDiracVec<Double> r(rFile), psi(psiFile); // --- change radial grid? if (radBasisPtr) { if (N != radBasisPtr->radFunc(is).getSize () || (radBasisPtr->radFunc(is) - r).normSqr () > 1e-10) { // --- spline interpolation SxNaturalCubicSpline spline; if (l == 0) spline = SxNaturalCubicSpline (toVector(r), toVector(r * r * psi)); else spline = SxNaturalCubicSpline (toVector(r), toVector(psi)); // linear extrapolation below r0 double rmax = r(r.getSize () - 1), rmin = r(0); double dpsi0 = (psi(1) - psi(0)) / (r(1) - r(0)), psi0 = psi(0); // --- get psi on rBasis radial grid psi = SxDiracVec<Double>((*radBasisPtr)(is)); for (int ir = 0; ir < radBasisPtr->radFunc(is).getSize (); ++ir) { double rr = radBasisPtr->radFunc(is)(ir); if (rr > rmax) { psi(ir) = 0.; } else if (rr < rmin) { psi(ir) = psi0 + (rr - rmin) * dpsi0; } else { psi(ir) = spline.getVal (rr); if (l == 0) psi(ir) /= rr * rr; } } VALIDATE_VECTOR (psi); } } // --- metadata if (iot != -1 && muSet(is)(iot).getSize () > 0) psi.handle->auxData = muSet(is)(iot).handle->auxData; psi.handle->auxData.is = is; psi.handle->auxData.n = n; psi.handle->auxData.l = l; // --- store away data in right place if (iot == -1) addOrbital (psi); else muSet(is)(iot) = psi; } void SxAtomicOrbitals::readOrbitals (FILE *fp, int is) { char buffer[10240]; int n, l; SxRegex lMatch("l *= *([0-9]+)"); SxRegex nMatch("n *= *([0-9]+)"); for ( ; !feof(fp); ) { buffer[0] = 0; fgets (buffer, 10240, fp); SxString line(buffer); line = line.stripWhiteSpace (); if (line.getSize () <= 1) continue; SxList<SxString> match; n = muSet.getSize () >= is ? 0 : (int)muSet(is).getSize (); try { match = lMatch.match (line); if (match.getSize () == 2) { cout << line; cout << match(0) << endl; l = match(1).toInt (); } else { cout << match << endl; cout << "Missing l in '" << line << "'." << endl; SX_EXIT; } match = nMatch.match (line); if (match.getSize () == 2) n = match(1).toInt (); } catch (SxException e) { e.print (); SX_EXIT; } readOrbital (fp, is, n, l, -1, false); } } double SxAtomicOrbitals::getNormSqr(int is, int iot) const { const SxDiracVec<Double> &vec = muSet(is)(iot); double logDr = radBasisPtr->logDr(is); const SxDiracVec<Double> &r = radBasisPtr->radFunc(is); double result = (vec * vec * r * r * r).integrate(logDr); return result; } double SxAtomicOrbitals::getNormSqrSum() const { double result = 0.0; int nSpecies = (int)muSet.getSize(); for (int is = 0; is < nSpecies; is++) { int nOrbTypes = (int)muSet(is).getSize (); for (int iot = 0; iot < nOrbTypes; iot++) { result += getNormSqr(is,iot); } } return result; } double SxAtomicOrbitals::dot(const SxAtomicOrbitals &in) const { double result = 0.0; int nSpecies = getNSpecies (); SX_CHECK(nSpecies == in.getNSpecies()); for (int is = 0; is < nSpecies; is++) { SX_CHECK (getNOrbTypes(is) == in.getNOrbTypes (is)); int nOrbTypes = (int)muSet(is).getSize (); for (int iot = 0; iot < nOrbTypes; iot++) { result += dot(in,is,iot,is,iot); } } return result; } double SxAtomicOrbitals::dot(const SxAtomicOrbitals &in, int is, int iot, int js, int jot) const { const SxDiracVec<Double> &vec1 = muSet(is)(iot); const SxDiracVec<Double> &vec2 = in.muSet(js)(jot); double logDr = radBasisPtr->logDr(is); const SxDiracVec<Double> &r = radBasisPtr->radFunc(is); SX_CHECK (logDr == in.radBasisPtr->logDr(is)); SX_CHECK ((r(0) - in.radBasisPtr->radFunc(is)(0)) < 1e-6); double result = (vec1 * vec2 * r * r * r).integrate(logDr); return result; } void SxAtomicOrbitals::normalize () { int nSpecies = (int)muSet.getSize(); for (int is = 0; is < nSpecies; is++) { int nOrbTypes = (int)muSet(is).getSize (); for (int iot = 0; iot < nOrbTypes; iot++) { double norm = getNormSqr(is,iot); if (norm > 1e-6) muSet(is)(iot) /= sqrt(norm); else { cout << "WARNING: Try to normalize zero norm orbital." << endl; cout << "Norm is " << norm << endl; muSet(is)(iot).set(0.0); } } } } SxArray<SxArray<SxMatrix<Double> > > SxAtomicOrbitals::orthogonalize () { SX_CHECK(muSet.getSize() == funcLMap.getSize(), muSet.getSize(), funcLMap.getSize()); // Gram-Schmidt via Cholesky SxAtomicOrbitals org = 1.0 * *this; int nSpecies = (int)muSet.getSize (); SxArray<SxArray<SxMatrix<Double> > > result(nSpecies); for (int is = 0; is < nSpecies; is++) { int lMax = getLMax(is); result(is).resize(lMax + 1); for (int l = 0; l <= lMax; l++) { int nFL = getFuncPerL (is,l); if (nFL == 0) continue; SxMatrix<Double> S = getOverlap(is,l); result(is)(l) = S.choleskyDecomposition ().adjoint (). inverse (); for (int ifl = 0; ifl < nFL; ifl++) { int iot = funcLMap(is)(l)(ifl); muSet(is)(iot).set(0.0); for (int jfl = 0; jfl < nFL; jfl++) { muSet(is)(iot) += result(is)(l)(jfl,ifl) * org.getFuncL(is,l,jfl); } } } } return result; } SxArray<SxArray<SxMatrix<Double> > > SxAtomicOrbitals::getOverlap () const { int nSpecies = getNSpecies (); SxArray<SxArray<SxMatrix<Double> > > result(nSpecies); for (int is = 0; is < nSpecies; is++) { int lMax = getLMax(is); result(is).resize(lMax + 1); for (int l = 0; l <= lMax; l++) { result(is)(l) = getOverlap (is, l); } } return result; } SxMatrix<Double> SxAtomicOrbitals::getOverlap (int is, int l) const { const SxDiracVec<Double> &r = radBasisPtr->radFunc(is); double logDr = radBasisPtr->logDr(is); int nFL = getFuncPerL (is,l); SxMatrix<Double> result(nFL,nFL); for (int ifl = 0; ifl < nFL; ifl++) { for (int jfl = ifl; jfl < nFL; jfl++) { result(ifl,jfl) = result(jfl,ifl) = (getFuncL(is,l,ifl) * getFuncL(is,l,jfl)*r*r*r).integrate(logDr); } } return result; } void SxAtomicOrbitals::refine (SxArray<int> &factor) { SX_CHECK(radBasisPtr.getPtr () != NULL); const SxRadBasis &radBasis = *radBasisPtr; int nSpecies = getNSpecies (); SX_CHECK(factor.getSize() == nSpecies, factor.getSize(), nSpecies); SxArray<SxDiracVec<Double> > rad(nSpecies); SxArray<double> logDr(nSpecies); for (int iSpecies = 0; iSpecies < nSpecies; iSpecies++) { SX_CHECK(factor(iSpecies) > 0, factor(iSpecies)); if (factor(iSpecies) == 1) { cout << "Mesh for species " << (iSpecies + 1) << " not refined." << endl; rad(iSpecies) = radBasis.radFunc(iSpecies).getCopy(); logDr(iSpecies) = radBasis.logDr(iSpecies); } else { // --- interpolate phi on finer mesh cout << "Refining mesh for species " << (iSpecies + 1) << " by factor " << factor(iSpecies) << "." << endl; double logDrOrig = radBasis.logDr(iSpecies); double r0 = radBasis.radFunc(iSpecies)(0); double r0New = r0; // --- define finer mesh int nrOrig = (int)radBasis.radFunc(iSpecies).getSize (); logDr(iSpecies) = logDrOrig / factor(iSpecies); int nExtra = (r0New < 0.) ? 0 : (int)(log(r0/r0New) / logDr(iSpecies)); int nFine = (nrOrig-1)*factor(iSpecies) + 1 + nExtra; rad(iSpecies).resize(nFine); for (int i = 0; i < nFine; ++i) { rad(iSpecies)(i) = r0 * exp(i * logDr(iSpecies)); } // interpolate for (int iot = 0; iot < getNOrbTypes (iSpecies); iot++) { // update rad,psi,logDr in psPot muSet(iSpecies)(iot) = interpolateRad (muSet(iSpecies)(iot), radBasis.radFunc(iSpecies)(0), radBasis.logDr(iSpecies), rad(iSpecies)); } } } radBasisPtr = SxConstPtr<SxRadBasis>::create(rad,logDr); setBasis (radBasisPtr); } SxDiracVec<Double> SxAtomicOrbitals::compressWave(SxString &file, int iState, int iSpecies, int l) { SxPW waves; SxAtomicStructure structure; try { SxBinIO io (file, SxBinIO::BINARY_READ_ONLY); waves = SxPW (file, SxPW::InMemory); structure.read (io); io.close (); } catch (SxException e) { e.print (); SX_QUIT; } SxStack<double> xData; SxStack<double> yData; SxDiracVec<Double> yRad; SxDiracVec<Double> result; SxGkBasis &GkBasis = *waves.getGkBasisPtr (); GkBasis.changeTau(structure); double naNorm = 1.0/(structure.getNAtoms(iSpecies)); double mNorm = 1.0/(2.0*l+1.0); double spinNorm = 1.0/(1.0 * waves.getNSpin ()); for (int ik = 0; ik < waves.getNk(); ik++) { yRad.resize(GkBasis(ik).g2.getSize()); yRad.set(0.0); for (int iSpin = 0; iSpin < waves.getNSpin (); iSpin++) { for (int iAtom = 0; iAtom < structure.getNAtoms(iSpecies); iAtom++) { for (int m = -l; m <= l; m++) { SxDiracVec<Double> wave = sqrt(waves(iState,iSpin,ik).absSqr ()); SxDiracVec<Complex16> radial = wave * GkBasis(ik).getPhaseFactors(iSpecies,iAtom).conj () //shift * GkBasis(ik).getYlm(l,m) // project l * SxYlm::getYlmNormFactor(l,m) * sqrt(2.0 * structure.cell.volume/PI) * spinNorm * naNorm * mNorm; yRad += 0.5 * (radial + radial.conj ()); } } } for (int i = 0; i < GkBasis(ik).g2.getSize(); i++) { xData.push(sqrt(GkBasis(ik).g2(i))); yData.push(yRad(i)); } } SxDiracVec<Double> xToFit(xData); SxDiracVec<Double> yToFit(yData); SxCubicSpline<SxDiracVec<Double> > fit; SxRadGBasis radGBasis = SxRadGBasis(0.0, GkBasis.getMaxGk(), 100, SxRadGBasis::Linear); if (l == 0) // ?(May have CUSP, no Mirror)? fit = SxCubicSpline<SxDiracVec<Double> > ( xToFit, yToFit, radGBasis.getRadGFunc(), SxCubicSpline<SxDiracVec<Double> >::Natural, SxCubicSpline<SxDiracVec<Double> >::MirrorPlane); else if (l & 1) // (l odd) fit = SxCubicSpline<SxDiracVec<Double> > ( xToFit, yToFit, radGBasis.getRadGFunc(), SxCubicSpline<SxDiracVec<Double> >::Natural, SxCubicSpline<SxDiracVec<Double> >::MirrorPoint); else // (l even and not zero) fit = SxCubicSpline<SxDiracVec<Double> > ( xToFit, yToFit, radGBasis.getRadGFunc(), SxCubicSpline<SxDiracVec<Double> >::Natural, SxCubicSpline<SxDiracVec<Double> >::MirrorPlane); SxDiracVec<Double> resultG = fit.getYFit (); resultG.setBasis(&radGBasis); resultG.handle->auxData.is = iSpecies; resultG.handle->auxData.ia = -1; resultG.handle->auxData.n = -1; resultG.handle->auxData.l = l; resultG.handle->auxData.m = NONE_M; //const SxRadBasis &radBasis = *radBasisPtr; //result = (radBasis | resultG); result = radGBasis.toRadBasis(&*radBasisPtr,resultG); result.setBasis(&*radBasisPtr); result.handle->auxData.is = iSpecies; result.handle->auxData.ia = -1; result.handle->auxData.n = -1; result.handle->auxData.l = l; result.handle->auxData.m = NONE_M; // ensure localization SxDiracVec<Double> rCut (radBasisPtr->radFunc(iSpecies).getSize ()); rCut.set(10.0); result *= 1.0 / (1.0 + exp((radBasisPtr->radFunc(iSpecies) - rCut) / 1.0)); result.normalize (); return result; } #ifdef USE_HDF5 void SxAtomicOrbitals::writeHDF5(const SxString &name) { SxHDF5 file (name, SxHDF5::BINARY_CREATE); SxArray<SxArray<int> > funcPerL = getFuncPerL (); for (int is = 0; is < funcPerL.getSize (); is++) { SxString isName = "Species-" + SxString(is); file.createGroup(isName); file.enterGroup(isName); SxString basisName = "radBasis"; SxVector<Double> radBasis = toVector(radBasisPtr->radFunc(is)); file.writeVector(basisName, radBasis); for (int l = 0; l < funcPerL(is).getSize(); l++) { SxString lName = "Angularmomentum-" + SxString(l); file.createGroup(lName); file.enterGroup(lName); for (int il = 0; il < funcPerL(is)(l); il++) { SxString radName = "Radial-" + SxString(il); SxVector<Double> radial = toVector(getFuncL(is,l,il)); file.writeVector(radName, radial); } file.leaveGroup(); } file.leaveGroup(); } } #endif
35.472327
112
0.528572
[ "mesh", "transform" ]
08ee7097b6fec7c37881a8eec2962ca3838f98db
3,550
cpp
C++
test/ObstacleDetectorTest.cpp
bshantam97/enpm808x_turtlebot_navigator
3a0d315f9f5358487e293c7a4c519359b54dedd2
[ "MIT" ]
1
2020-06-01T19:39:23.000Z
2020-06-01T19:39:23.000Z
test/ObstacleDetectorTest.cpp
bshantam97/enpm808x_turtlebot_navigator
3a0d315f9f5358487e293c7a4c519359b54dedd2
[ "MIT" ]
13
2019-11-29T22:47:20.000Z
2019-12-08T21:06:00.000Z
test/ObstacleDetectorTest.cpp
arp95/enpm808x_turtlebot_navigator
94e6b46d9b44a82c904e7aaec266ff65220e1c01
[ "MIT" ]
2
2019-12-09T03:33:11.000Z
2021-12-12T23:24:46.000Z
/** * MIT License * * Copyright (c) 2019 Arpit Aggarwal Shantam Bajpai * * 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. */ /** *@file ObstacleDetectorTest.cpp *@copyright MIT License *@brief Test cases for ObstacleDetector.cpp file. */ #include <ros/ros.h> #include <gtest/gtest.h> #include <std_msgs/Float64.h> #include <sensor_msgs/LaserScan.h> #include <ObstacleDetector.h> #include <iostream> /** * @brief Tests the object creation of the class ObstacleDetector * @param ObstacleDetectorTest gtest framework * @param ObstacleDetectorTest Name of the test * @return none */ TEST(ObstacleDetectorTest, ObstacleDetectorTest) { // Object of type ObstacleDetector created EXPECT_NO_FATAL_FAILURE(ObstacleDetector obstacleDetector); } /** * @brief Tests the getIsCollision method of the class ObstacleDetector * @param ObstacleDetectorTest gtest framework * @param CollisionMethodTest Name of the test * @return none */ TEST(ObstacleDetectorTest, CollisionMethodTest) { // Object of type ObstacleDetector created ObstacleDetector obstacleDetector; obstacleDetector.setIsCollision(false); EXPECT_FALSE(obstacleDetector.getIsCollision()); } /** * @brief Tests the laserCallback method of the class ObstacleDetector * @param ObstacleDetectorTest gtest framework * @param LaserCallbackMethodTest Name of the test * @return none */ TEST(ObstacleDetectorTest, LaserCallbackMethodTest) { // Object of type ObstacleDetector created ObstacleDetector obstacleDetector; // Create ros node ros::NodeHandle node; // Create a ros publisher ros::Publisher pub = node.advertise<sensor_msgs::LaserScan>("/scan", 50); ros::WallDuration(25).sleep(); ros::spinOnce(); // Expect the collision flag to be false EXPECT_EQ(pub.getNumSubscribers(), 2); } /** * @brief Tests the distCallback method of the class ObstacleDetector * @param ObstacleDetectorTest gtest framework * @param DistCallbackMethodTest Name of the test * @return none */ TEST(ObstacleDetectorTest, DistCallbackMethodTest) { // Object of type ObstacleDetector created ObstacleDetector obstacleDetector; // Create ros node ros::NodeHandle node; ros::Publisher pub = node.advertise<std_msgs::Float64>("/dist", 50); ros::WallDuration(25).sleep(); ros::spinOnce(); // Expect the collision flag to be false EXPECT_EQ(pub.getNumSubscribers(), 2); }
35.148515
78
0.727042
[ "object" ]
08f08fc080b56e8a33d814525cca5c3420c8aca2
725
hpp
C++
src/kc/core/Countable.hpp
nekoffski/libkc
f72cc40d2780747a707eaf6b822ba98848d92237
[ "MIT" ]
null
null
null
src/kc/core/Countable.hpp
nekoffski/libkc
f72cc40d2780747a707eaf6b822ba98848d92237
[ "MIT" ]
null
null
null
src/kc/core/Countable.hpp
nekoffski/libkc
f72cc40d2780747a707eaf6b822ba98848d92237
[ "MIT" ]
null
null
null
#pragma once #include <vector> namespace kc::core { template <typename T> class Countable { public: Countable() : m_id(generateId()) { } ~Countable() { freeIds.push_back(m_id); } Countable(const Countable&) = delete; Countable& operator=(const Countable&) = delete; unsigned int getId() { return m_id; } private: unsigned int generateId() const { if (not freeIds.empty()) { auto freeId = freeIds.back(); freeIds.pop_back(); return freeId; } return currentId++; } unsigned int m_id; inline static std::vector<unsigned int> freeIds; inline static unsigned int currentId = 0; }; }
16.860465
52
0.577931
[ "vector" ]
08f291b894cbaff1fa54468fbd10eb5a1bc6c452
3,187
cpp
C++
src/services/extension_server/extension_server.cpp
tinganho/lya
d956220da76d5658e8e2c0654db2068427463c60
[ "Apache-2.0" ]
1
2020-06-04T06:57:31.000Z
2020-06-04T06:57:31.000Z
src/services/extension_server/extension_server.cpp
tinganho/lya
d956220da76d5658e8e2c0654db2068427463c60
[ "Apache-2.0" ]
6
2018-01-05T02:55:59.000Z
2018-01-09T03:29:55.000Z
src/services/extension_server/extension_server.cpp
tinganho/lya
d956220da76d5658e8e2c0654db2068427463c60
[ "Apache-2.0" ]
null
null
null
#include "extension_server.h" #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <libxml++/libxml++.h> #include "utils.h" using namespace std; using namespace grpc; using namespace xmlpp; using namespace Lya::lib::utils; using namespace Lya::lib::types; namespace Lya::services { ExtensionServer::ExtensionServer( string _server_address, ExtractCallback _extract_callback, CompileCallback _compile_callback): server_address(move(_server_address)), extract_callback(move(_extract_callback)), compile_callback(move(_compile_callback)) { } void ExtensionServer::start_server(bool quiet = false) { ServerBuilder builder; builder.AddListeningPort(server_address, InsecureServerCredentials()); builder.RegisterService(this); unique_ptr<Server> s(builder.BuildAndStart()); if (!quiet) { cout << "Extension server listening on " << server_address << endl; } s->Wait(); } Status ExtensionServer::extract(ServerContext *context, const PBExtractRequest *request, PBExtractResponse *response) { PBFileToLocalizations* file_to_localization = response->add_file_to_localizations(); std::vector<Glib::ustring> function_names; for (const auto& f : request->functions()) { function_names.push_back(f); } for (const auto& f : request->files()) { file_to_localization->set_file(f); const auto& result = extract_callback(f, function_names, request->start_line()); for (const auto& l : get<vector<LocalizationLocation>>(result)) { auto localization = file_to_localization->add_localizations(); localization->set_id(l.id); auto location = localization->mutable_location(); location->set_line(l.location.line); location->set_column(l.location.column); location->set_length(l.location.length); for (const auto& p : l.params) { auto param = localization->add_parameters(); param->set_name(p.name); if (p.type != nullptr) { param->set_type(*p.type); } } } for (const auto d : get<vector<Diagnostic>>(result)) { PBDiagnostic* diagnostic = response->add_diagnostics(); diagnostic->set_message(d.message); PBLocation* location = diagnostic->mutable_location(); SpanLocation l = d.location; location->set_line(l.line); location->set_column(l.column); location->set_length(l.length); } } return Status::OK; } Status ExtensionServer::compile(ServerContext *context, const PBCompileRequest *request, PBCompileResponse *response) { const auto& pb_localization_files = request->localization_files(); vector<string> localization_files; for (const auto& l : pb_localization_files) { localization_files.push_back(l); } compile_callback(localization_files); return Status::OK; } Status ExtensionServer::check_availability(ServerContext *context, const PBAvailabilityRequest *request, PBAvailabilityResponse *response) { return Status::OK; } } // Lya::Extension
35.808989
141
0.673047
[ "vector" ]
08f3e610c2d967e68ed8efb7cf6793936f18bdfe
18,144
cpp
C++
code/c/configs/test/master.cpp
leomeyer/opdi_core
29fcb1c1c8ecd7d3d3da251333ebefb731075813
[ "BSD-2-Clause" ]
null
null
null
code/c/configs/test/master.cpp
leomeyer/opdi_core
29fcb1c1c8ecd7d3d3da251333ebefb731075813
[ "BSD-2-Clause" ]
null
null
null
code/c/configs/test/master.cpp
leomeyer/opdi_core
29fcb1c1c8ecd7d3d3da251333ebefb731075813
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2016, Leo Meyer, leo@leomeyer.de // 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. #ifdef windows #include <winsock2.h> #include <windows.h> #endif #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <stdio.h> #include <algorithm> #include "Poco/Net/SocketReactor.h" #include "Poco/Net/SocketAcceptor.h" #include "Poco/Net/SocketNotification.h" #include "Poco/Net/StreamSocket.h" #include "Poco/Net/ServerSocket.h" #include "Poco/NObserver.h" #include "Poco/Exception.h" #include "Poco/Thread.h" #include "Poco/Util/ServerApplication.h" #include "Poco/Util/Option.h" #include "Poco/Util/OptionSet.h" #include "Poco/Util/HelpFormatter.h" #include "Poco/URI.h" #include <iostream> #include "opdi_constants.h" #include "opdi_port.h" #include "opdi_protocol_constants.h" #include "master.h" #include "opdi_main_io.h" #include "opdi_AbstractProtocol.h" #include "opdi_IDevice.h" #include "opdi_TCPIPDevice.h" #include "opdi_SerialDevice.h" using Poco::Net::SocketReactor; using Poco::Net::SocketAcceptor; using Poco::Net::ReadableNotification; using Poco::Net::ShutdownNotification; using Poco::Net::ServerSocket; using Poco::Net::StreamSocket; using Poco::NObserver; using Poco::AutoPtr; using Poco::Thread; using Poco::Util::ServerApplication; using Poco::Util::Application; using Poco::Util::Option; using Poco::Util::OptionSet; using Poco::Util::HelpFormatter; // global output stream OUTPUT_TYPE output; // debug flag (for verbose logging) bool var_debug = false; void show_device_info(IDevice* device) { output << "Device " << device->getID() << " (" << device->getStatusText() << "): " << device->getLabel() << (device->getStatus() == DS_CONNECTED ? " (" + device->getDeviceName() + ")" : "") << std::endl; } class DeviceListener : public IDeviceListener { public: void connectionOpened(IDevice* aDevice) override { output << "Device " << aDevice->getID() << ": Connection opened to " << aDevice->getDeviceName() << std::endl; } void connectionInitiated(IDevice* aDevice) override { output << "Device " << aDevice->getID() << ": Connection initiated" << std::endl; } void connectionAborted(IDevice* aDevice) override { output << "Device " << aDevice->getID() << ": Connection aborted" << std::endl; } void connectionFailed(IDevice* aDevice, std::string message) override { output << "Device " << aDevice->getID() << ": Connection failed: " << message << std::endl; } void connectionTerminating(IDevice* aDevice) override { output << "Device " << aDevice->getID() << ": Connection terminating" << std::endl; } void connectionClosed(IDevice* aDevice) override { output << "Device " << aDevice->getID() << ": Connection closed" << std::endl; } void connectionError(IDevice* aDevice, std::string message) override { output << "Device " << aDevice->getID() << ": Connection error" << (message != "" ? ": " + message : "") << std::endl; } bool getCredentials(IDevice* device, std::string* user, std::string* password, bool* save) override { output << "Authentication required for "; show_device_info(device); *user = getLine("User: "); *password = getLine("Password: "); *save = true; /* user = new std::string(); password = new std::string(); save = false; */ return true; } void receivedDebug(IDevice* device, std::string message) override { output << "Device " << device->getID() << " says: " << message << std::endl; } void receivedReconfigure(IDevice* device) override { output << "Received Reconfigure for device " << device->getID() << std::endl; } void receivedRefresh(IDevice* device, std::vector<std::string> portIDs) override { output << "Received Refresh for device " << device->getID() << std::endl; } void receivedError(IDevice* device, std::string text) override { output << "Error on device " << device->getID() << ": " << text << std::endl; } }; std::string opdiMasterName = "WinOPDI Master"; // device list typedef std::vector<IDevice*> DeviceList; DeviceList devices; void show_help() { output << "Interactive OPDI master commands:" << std::endl; output << "? - show help" << std::endl; output << "quit - exit" << std::endl; output << "create_device <id> <address> - create a device; address must start with opdi_tcp://" << std::endl; output << "list - show the list of created devices" << std::endl; output << "connect <id> - connect to the specified device" << std::endl; output << "disconnect <id> - disconnect from the specified device" << std::endl; output << "set [<variable>] [<value>] - display or set control variable values" << std::endl; output << "" << std::endl; output << "Get started: Run slave and try 'create_device 1 opdi_tcp://localhost:13110'" << std::endl; output << "Next, connect the device: 'connect 1'" << std::endl; output << "Query device capabilities: 'gDC 1'" << std::endl; } IDevice* create_device(const std::string id, const std::string address) { // parse address Poco::URI uri; try { uri = Poco::URI(address); } catch (Poco::Exception& e) { throw Poco::InvalidArgumentException("Address parse error", e, 0); } if (strcmp(uri.getScheme().c_str(), "opdi_tcp") == 0) { return new TCPIPDevice(id, uri, &var_debug); } else if (strcmp(uri.getScheme().c_str(), "opdi_com") == 0) { return new SerialDevice(id, uri, &var_debug); } else { throw Poco::UnknownURISchemeException("Address schema not recognized", uri.getScheme(), 0); return NULL; } } void print_exception(const Poco::Exception* e, bool inner = false) { output << (inner ? "Caused by: " : "") << e->displayText() << std::endl; if (e->nested() != NULL) print_exception(e->nested(), true); } IDevice* find_device(std::string devID, bool throwIfNotFound) { IDevice* result = NULL; // check whether it's already contained DeviceList::iterator iter; for (iter = devices.begin(); iter != devices.end(); ++iter) { if ((*iter)->getID() == devID) result = *iter; } if (result == NULL && throwIfNotFound) { throw Poco::InvalidArgumentException("Unknown device ID: " + devID); } return result; } void add_device(IDevice* device) { // check whether it's already contained DeviceList::iterator iter; for (iter = devices.begin(); iter != devices.end(); ++iter) { if (*device == *iter) break; } // found it? if (iter != devices.end()) { output << "Cannot add device: A device with ID " << device->getID() << " already exists" << std::endl; } else { // add the device devices.push_back(device); output << "Device " << device->getID() << " added: " << device->getLabel() << std::endl; } } void list_devices() { if (devices.size() == 0) { output << "No devices" << std::endl; return; } DeviceList::iterator iter; for (iter = devices.begin(); iter != devices.end(); ++iter) { IDevice* device = *iter; show_device_info(device); } } void show_variable(std::string variable) { if (variable == "debug") { output << "debug " << var_debug << std::endl; } else output << "Unknown variable: " << variable << std::endl; } void show_variables() { // show all variables show_variable("debug"); } bool get_bool_value(std::string variable, std::string value, bool* var) { if (value == "0") *var = false; else if (value == "1") *var = true; else { output << "Invalid value for boolean variable " << variable << "; try 0 or 1" << std::endl; return false; } return true; } void set_variable(std::string variable, std::string value) { bool ok; if (variable == "debug") { ok = get_bool_value(variable, value, &var_debug); } if (ok) show_variable(variable); } void cleanup() { // disconnect all connected devices DeviceList::iterator iter; for (iter = devices.begin(); iter != devices.end(); ++iter) { IDevice* device = *iter; if (device->isConnected()) device->disconnect(false); } } void print_devicecaps(BasicDeviceCapabilities* bdc) { for (std::vector<OPDIPort*>::iterator iter = bdc->getPorts().begin(); iter != bdc->getPorts().end(); iter++) { output << (*iter)->toString() << std::endl; } } DigitalPort* checkDigitalPort(std::string cmd, OPDIPort* port) { if (port->getType() != PORTTYPE_DIGITAL) { output << "Expected digital port for command: " << cmd << std::endl; return NULL; } return (DigitalPort*)port; } SelectPort* checkSelectPort(std::string cmd, OPDIPort* port) { if (port->getType() != PORTTYPE_SELECT) { output << "Expected select port for command: " << cmd << std::endl; return NULL; } return (SelectPort*)port; } bool digital_port_command(std::string cmd, OPDIPort* port) { const char* part; if (cmd == OPDI_setDigitalPortMode) { part = strtok(NULL, " "); if (part == NULL) { output << "Error: Digital port mode expected" << std::endl; return false; } int8_t dpm = OPDI_DIGITAL_MODE_UNKNOWN; if (strcmp(part, OPDI_QUOTE(OPDI_DIGITAL_MODE_INPUT_FLOATING)) == 0) dpm = OPDI_DIGITAL_MODE_INPUT_FLOATING; else if (strcmp(part, OPDI_QUOTE(OPDI_DIGITAL_MODE_INPUT_PULLUP)) == 0) dpm = OPDI_DIGITAL_MODE_INPUT_PULLUP; else if (strcmp(part, OPDI_QUOTE(OPDI_DIGITAL_MODE_INPUT_PULLDOWN)) == 0) dpm = OPDI_DIGITAL_MODE_INPUT_PULLDOWN; else if (strcmp(part, OPDI_QUOTE(OPDI_DIGITAL_MODE_OUTPUT)) == 0) dpm = OPDI_DIGITAL_MODE_OUTPUT; DigitalPort* thePort = checkDigitalPort(cmd, port); if (thePort == NULL) return false; thePort->setMode(dpm); return true; } else if (cmd == OPDI_setDigitalPortLine) { part = strtok(NULL, " "); if (part == NULL) { output << "Error: Digital port line expected" << std::endl; return false; } int8_t dpl = OPDI_DIGITAL_LINE_UNKNOWN; if (strcmp(part, OPDI_QUOTE(OPDI_DIGITAL_LINE_LOW)) == 0) dpl = OPDI_DIGITAL_LINE_LOW; else if (strcmp(part, OPDI_QUOTE(OPDI_DIGITAL_LINE_HIGH)) == 0) dpl = OPDI_DIGITAL_LINE_HIGH; DigitalPort* thePort = checkDigitalPort(cmd, port); if (thePort == NULL) return false; thePort->setLine(dpl); return true; } else if (cmd == OPDI_getDigitalPortState) { DigitalPort* thePort = checkDigitalPort(cmd, port); if (thePort == NULL) return false; thePort->getPortState(); return true; } output << "Command not implemented: " << cmd << std::endl; return false; } bool select_port_command(std::string cmd, OPDIPort* port) { const char* part; if (cmd == OPDI_getSelectPortState) { SelectPort* thePort = checkSelectPort(cmd, port); if (thePort == NULL) return false; thePort->getPortState(); } else if (cmd == OPDI_setSelectPortPosition) { part = strtok(NULL, " "); if (part == NULL) { output << "Error: Select port position expected" << std::endl; return false; } uint16_t pos = atoi(part); SelectPort* thePort = checkSelectPort(cmd, port); if (thePort == NULL) return false; thePort->setPosition(pos); return true; } output << "Command not implemented: " << cmd << std::endl; return false; } // commands that operate on ports // find device, find port, execute command bool port_command(const char* part) { std::string cmd = part; // expect second token: device ID part = strtok(NULL, " "); if (part == NULL) { output << "Error: Device ID expected" << std::endl; return false; } std::string devID = part; // find device // throw exception if not found IDevice* device = find_device(devID, true); if (device->getStatus() != DS_CONNECTED) { output << "Device " << device->getID() << " is not connected" << std::endl; return false; } // expect third token: port ID part = strtok(NULL, " "); if (part == NULL) { output << "Error: Port ID expected" << std::endl; return false; } std::string portID = part; // find port OPDIPort* port = device->getCapabilities()->findPortByID(portID); if (port == NULL) { output << "Error: Port not found: " << portID << std::endl; return false; } // check command if (cmd == OPDI_setDigitalPortMode || cmd == OPDI_setDigitalPortLine || cmd == OPDI_getDigitalPortState) { if (digital_port_command(cmd, port)) { output << port->toString() << std::endl; return true; } } else if (cmd == OPDI_getSelectPortState || cmd == OPDI_setSelectPortPosition) { if (select_port_command(cmd, port)) { output << port->toString() << std::endl; return true; } } else { output << "Command not implemented: " << cmd << std::endl; } return false; } int start_master() { #define PROMPT "$ " const char* part; printf("Interactive OPDI master started. Type '?' for help.\n"); add_device(create_device("1", "opdi_tcp://admin:admin@localhost:13110")); add_device(create_device("2", "opdi_tcp://admin:admin@192.168.56.101")); std::string cmd; while (true) { cmd = getLine(PROMPT); // evaluate command try { // tokenize the input part = strtok((char*)cmd.c_str(), " "); if (part == NULL) continue; // evaluate command if (strcmp(part, "?") == 0) { show_help(); } else if ((strcmp(part, "quit") == 0) || (strcmp(part, "exit") == 0)) { cleanup(); break; } else if (strcmp(part, "list") == 0) { list_devices(); } else if (strcmp(part, "create_device") == 0) { // expect second token: device ID part = strtok(NULL, " "); if (part == NULL) { output << "Error: Device ID expected" << std::endl; continue; } std::string devID = part; // expect third token: slave address part = strtok(NULL, " "); if (part == NULL) { output << "Error: Slave address expected" << std::endl; continue; } std::string address = part; // create the device IDevice* device = create_device(devID, address); add_device(device); } else if (strcmp(part, "connect") == 0) { // expect second token: device ID part = strtok(NULL, " "); if (part == NULL) { output << "Error: Device ID expected" << std::endl; continue; } std::string devID = part; // throw exception if not found IDevice* device = find_device(devID, true); if (!device->prepare()) continue; // prepare the device for connection if (device->getStatus() == DS_CONNECTED) { output << "Device " << device->getID() << " is already connected" << std::endl; continue; } else if (device->getStatus() == DS_CONNECTING) { output << "Device " << device->getID() << " is already connecting" << std::endl; continue; } else { device->connect(new DeviceListener()); } } else if (strcmp(part, OPDI_getDeviceCaps) == 0) { // expect second token: device ID part = strtok(NULL, " "); if (part == NULL) { output << "Error: Device ID expected" << std::endl; continue; } std::string devID = part; // throw exception if not found IDevice* device = find_device(devID, true); if (device->getStatus() != DS_CONNECTED) { output << "Device " << device->getID() << " is not connected" << std::endl; continue; } // query device capabilities print_devicecaps(device->getCapabilities()); } else if (strcmp(part, OPDI_setDigitalPortMode) == 0) { port_command(part); } else if (strcmp(part, OPDI_setDigitalPortLine) == 0) { port_command(part); } else if (strcmp(part, OPDI_getDigitalPortState) == 0) { port_command(part); } else if (strcmp(part, OPDI_getSelectPortState) == 0) { port_command(part); } else if (strcmp(part, OPDI_setSelectPortPosition) == 0) { port_command(part); } else if (strcmp(part, "disconnect") == 0) { // expect second token: device ID part = strtok(NULL, " "); if (part == NULL) { output << "Error: Device ID expected" << std::endl; continue; } std::string devID = part; // throw exception if not found IDevice* device = find_device(devID, true); if (device->getStatus() == DS_DISCONNECTED) { output << "Device " << device->getID() << " is already disconnected" << std::endl; continue; } // disconnect the device device->disconnect(false); } else if (strcmp(part, "set") == 0) { // expect second token: variable part = strtok(NULL, " "); if (part == NULL) { show_variables(); continue; } std::string variable = part; // optional third token: variable value part = strtok(NULL, " "); if (part == NULL) { show_variable(variable); continue; } // set the value set_variable(variable, part); } else { output << "Command unknown" << std::endl; } } catch (const ProtocolException& pe) { output << "Protocol exception: "; print_exception(&pe); } catch (const Poco::Exception& e) { print_exception(&e); } catch (const std::exception&) { output << "Unknown exception\n"; } catch (...) { output << "Unknown error\n"; } } // while return 0; }
26.800591
205
0.652502
[ "vector" ]