hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
c6ceaa6dffd92a6e6e6872fa7f65eff67f214a42
2,387
cpp
C++
examples/ofxEasingAnimation/src/ofApp.cpp
davidbeermann/timely-matter
fca86fb5b48766c5371677a90ac5149c1b071149
[ "MIT" ]
2
2016-09-03T17:49:30.000Z
2016-12-20T18:12:58.000Z
examples/ofxEasingAnimation/src/ofApp.cpp
davidbeermann/timely-matter
fca86fb5b48766c5371677a90ac5149c1b071149
[ "MIT" ]
null
null
null
examples/ofxEasingAnimation/src/ofApp.cpp
davidbeermann/timely-matter
fca86fb5b48766c5371677a90ac5149c1b071149
[ "MIT" ]
null
null
null
#include "ofApp.h" #define PADDING 30 void ofApp::reset() { m_rect.set(PADDING, PADDING, 0, 0); m_color.set(0, ofRandom(255.f), ofRandom(255.f)); m_start = 0.f; m_end = 0.f; m_progress = 0.f; m_animating = false; m_running = false; } void ofApp::setup() { ofBackground(33); func_w = ofxeasing::exp::easeInOut; func_h = ofxeasing::circ::easeInOut; func_r = ofxeasing::sine::easeOut; reset(); } void ofApp::update() { if (m_animating) { float t = ofGetElapsedTimef(); if (t > m_start && !m_running) { m_running = true; ofLog() << "animation started: " << ofGetElapsedTimef(); } if (m_running) { m_progress = (t - m_start) / (m_end - m_start); if (m_progress > 1.f) { m_progress = 1.f; m_animating = false; m_running = false; ofLog() << "animation complete: " << ofGetElapsedTimef(); } float mw = (float) ofGetWidth() - PADDING * 2.f; float w = ofxeasing::map(m_progress, 0.f, 1.f, 0.f, mw, func_w); m_rect.setWidth(w); float mh = (float) ofGetHeight() - PADDING * 2.f; float h = ofxeasing::map(m_progress, 0.f, 1.f, 0.f, mh, func_h); m_rect.setHeight(h); float r = ofxeasing::map(m_progress, 0.f, 1.f, 0.f, 255.f, func_r); m_color.r = r; } } } void ofApp::draw() { string msg = "Duration in s: " + to_string(m_duration); msg += " - Delay in s: " + to_string(m_delay); msg += " - animating: " + to_string(m_animating); msg += " - running: " + to_string(m_running); msg += " - Click anywhere to start animation"; ofSetColor(255); ofDrawBitmapString(msg, PADDING, 21); ofSetColor(m_color); ofDrawRectangle(m_rect); } void ofApp::mouseMoved(int x, int y ) { m_duration = ofMap(x, 0.f, ofGetWidth(), 0.f, 5.f); m_delay = ofMap(y, 0.f, ofGetHeight(), 0.f, 2.f); } void ofApp::mousePressed(int x, int y, int button) { reset(); m_start = ofGetElapsedTimef() + m_delay; m_end = m_start + m_duration; m_progress = 0.f; m_animating = true; }
21.899083
79
0.513615
davidbeermann
c6d01cab0dc1f3d4b29f9eee79ae02505f45e945
54,590
cpp
C++
PrecompiledExp.cpp
BalazsJako/LSystem
571aeec8e00c50cffead24caaafe9c6d2f798547
[ "MIT" ]
null
null
null
PrecompiledExp.cpp
BalazsJako/LSystem
571aeec8e00c50cffead24caaafe9c6d2f798547
[ "MIT" ]
null
null
null
PrecompiledExp.cpp
BalazsJako/LSystem
571aeec8e00c50cffead24caaafe9c6d2f798547
[ "MIT" ]
1
2020-12-11T05:13:17.000Z
2020-12-11T05:13:17.000Z
#include <assert.h> #include <iostream> #include <sstream> #include <algorithm> #define GLM_ENABLE_EXPERIMENTAL 1 #include "GLM/gtx/norm.hpp" #include "PrecompiledExp.h" #include "LSystem.h" using namespace std; namespace LSystem { PrecompiledExp::PrecompiledExp(LSystem &aLSystem) : mLSystem(aLSystem) , mResultType(ArgumentType::Unspecified) { } PrecompiledExp::PrecompiledExp(const PrecompiledExp &o) : mLSystem(o.mLSystem) , mCode(o.mCode) , mResultType(o.mResultType) { } PrecompiledExp& PrecompiledExp::operator =(const PrecompiledExp& o) { mCode = o.mCode; mResultType = o.mResultType; return *this; } const Location& PrecompiledExp::GetLocation(int ip) const { ASSERT(!mDebugInfo.empty()); auto it = mDebugInfo.lower_bound(ip); return it->second; } void PrecompiledExp::AddLocation(const Location& aLocation) { const int ip = (int)mCode.Size(); auto it = mDebugInfo.find(ip); if (it == mDebugInfo.end()) mDebugInfo.insert(std::make_pair(ip, aLocation)); } void PrecompiledExp::DebugDump() const { Location coord; for (int i = 0; i < (int)mCode.Size(); ) { const Opcode o = mCode.Get<Opcode>(i); const Location& loc = GetLocation(i); if (loc.GetFirstLine() != coord.GetFirstLine()) { coord = loc; cerr << "; " << coord.ToShortString() << ":" << endl; } cerr << i << ".:\t" << o << "\t"; i += sizeof(Opcode); switch (o) { case IPUSH: cerr << ToString(o) << " " << mCode.Get<int>(i) << endl; i += sizeof(int); break; case FPUSH: cerr << ToString(o) << " " << mCode.Get<float>(i) << endl; i += sizeof(float); break; case BPUSH: cerr << ToString(o) << " " << mCode.Get<bool>(i) << endl; i += sizeof(bool); break; case V2PUSH: cerr << ToString(o) << endl; break; case V3PUSH: cerr << ToString(o) << endl; break; case V4PUSH: cerr << ToString(o) << endl; break; case ILOAD: case FLOAD: case BLOAD: case V2LOAD: case V3LOAD: case V4LOAD: cerr << ToString(o) << " [" << mCode.Get<Token>(i) << "]" << "\t; " << mLSystem.GetTokenName(mCode.Get<Token>(i)) << endl; i += sizeof(int); break; default: cerr << ToString(o) << endl; break; } } } ArgumentType::Type PrecompiledExp::CompileTypeCast(const AST::Expression* aExpression, const FormalArgumentMap& aArgs) { const AST::Expressions& operands = aExpression->GetOperands(); ASSERT(operands.size() == 2); const AST::Expression* l = operands[0]; const AST::Expression* r = operands[1]; ASSERT(l != NULL); ASSERT(r != NULL); ArgumentType::Type rt = Compile(r, aArgs); switch (l->GetOpCode()) { case AST::Expression::IntType: switch (rt) { case ArgumentType::Bool: Emit(BTOI, aExpression->GetLocation()); break; case ArgumentType::Float: Emit(FTOI, aExpression->GetLocation()); break; } mResultType = ArgumentType::Int; break; case AST::Expression::FloatType: switch (rt) { case ArgumentType::Bool: Emit(BTOF, aExpression->GetLocation()); break; case ArgumentType::Int: Emit(ITOF, aExpression->GetLocation()); break; } mResultType = ArgumentType::Float; break; case AST::Expression::BoolType: switch (rt) { case ArgumentType::Int: Emit(ITOB, aExpression->GetLocation()); break; case ArgumentType::Float: Emit(FTOB, aExpression->GetLocation()); break; } mResultType = ArgumentType::Bool; break; default: ASSERT(!"Cast to invalid type."); mResultType = ArgumentType::Unspecified; break; } return mResultType; } ArgumentType::Type PrecompiledExp::Compile(const AST::Expression *aExpression, const FormalArgumentMap& aArgs) { if (aExpression == NULL) return ArgumentType::Unspecified; const AST::Expression::Type astOp = aExpression->GetOpCode(); if (astOp == AST::Expression::FuncCall) mResultType = CompileFuncCall(aExpression, aArgs); else if (astOp == AST::Expression::TypeCast) mResultType = CompileTypeCast(aExpression, aArgs); else if (astOp == AST::Expression::ExpressionList) { const AST::Expressions& operands = aExpression->GetOperands(); ArgumentTypes argTypes; CompileAllOperands(aExpression, argTypes, aArgs); mResultType = ArgumentType::Unspecified; } else mResultType = CompileOperator(aExpression, aArgs); return mResultType; } ArgumentType::Type PrecompiledExp::CompileFuncCall(const AST::Expression* aExpression, const FormalArgumentMap& aArgs) { const AST::Expressions& operands = aExpression->GetOperands(); ASSERT(operands.size() == 2); const AST::Expression* left = operands[0]; const AST::Expression* right = operands[1]; ASSERT(left->GetOpCode() == AST::Expression::QualifiedName); ArgumentTypes types; CompileAllOperands(right, types, aArgs); static const struct FunctionDescr { const char* mName; int mNumArgs; Opcode mOpcode; ArgumentType::Type mReturnType; ArgumentType::Type mArg0Type; ArgumentType::Type mArg1Type; } funcs[] = { { "sin", 1, FSIN, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "cos", 1, FCOS, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "tan", 1, FTAN, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "asin", 1, FASIN, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "acos", 1, FACOS, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "atan", 1, FATAN, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "atan2", 2, FATAN2, ArgumentType::Float, ArgumentType::Float, ArgumentType::Float }, { "log", 1, FLOG, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "log10", 1, FLOG10, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "pow", 2, FPOW, ArgumentType::Float, ArgumentType::Float, ArgumentType::Float }, { "mod", 2, FMOD, ArgumentType::Float, ArgumentType::Float, ArgumentType::Float }, { "exp", 1, FEXP, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "sqrt", 1, FSQRT, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "ceil", 1, FCEIL, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "floor", 1, FFLOOR, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "round", 1, FROUND, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "abs", 1, FABS, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, { "min", 2, FMIN, ArgumentType::Float, ArgumentType::Float, ArgumentType::Float }, { "max", 2, FMAX, ArgumentType::Float, ArgumentType::Float, ArgumentType::Float }, { "dot", 2, V2DOT, ArgumentType::Float, ArgumentType::Vec2, ArgumentType::Vec2 }, { "dot", 2, V3DOT, ArgumentType::Float, ArgumentType::Vec3, ArgumentType::Vec3 }, { "dot", 2, V4DOT, ArgumentType::Float, ArgumentType::Vec4, ArgumentType::Vec4 }, { "cross", 2, V3CROSS, ArgumentType::Float, ArgumentType::Vec3, ArgumentType::Vec3 }, { "length", 1, V2LEN, ArgumentType::Float, ArgumentType::Vec2, ArgumentType::Unspecified }, { "length", 1, V3LEN, ArgumentType::Float, ArgumentType::Vec3, ArgumentType::Unspecified }, { "length", 1, V4LEN, ArgumentType::Float, ArgumentType::Vec4, ArgumentType::Unspecified }, { "length2", 1, V2LEN2, ArgumentType::Float, ArgumentType::Vec2, ArgumentType::Unspecified }, { "length2", 1, V3LEN2, ArgumentType::Float, ArgumentType::Vec3, ArgumentType::Unspecified }, { "length2", 1, V4LEN2, ArgumentType::Float, ArgumentType::Vec4, ArgumentType::Unspecified }, { "normalize", 1, V2NORM, ArgumentType::Vec2, ArgumentType::Vec2, ArgumentType::Unspecified }, { "normalize", 1, V3NORM, ArgumentType::Vec3, ArgumentType::Vec3, ArgumentType::Unspecified }, { "normalize", 1, V4NORM, ArgumentType::Vec4, ArgumentType::Vec4, ArgumentType::Unspecified }, { "reflect", 2, V3REFL, ArgumentType::Vec3, ArgumentType::Vec3, ArgumentType::Vec3 }, { "rand", 1, RAND, ArgumentType::Int, ArgumentType::Int, ArgumentType::Unspecified }, { "frand", 1, FRAND, ArgumentType::Float, ArgumentType::Float, ArgumentType::Unspecified }, }; static const int size = sizeof(funcs) / sizeof(funcs[0]); const std::string f = left->GetName(); const AST::Expressions& arguments = operands[1]->GetOperands(); std::vector<int> matchingIndices; int i; for (i = 0; i < size; ++i) { const FunctionDescr& d = funcs[i]; if (f == d.mName) { ASSERT(arguments.size() <= 2); if (arguments.size() != d.mNumArgs || types[0] != d.mArg0Type || (arguments.size() == 2 && types[1] != d.mArg1Type)) { matchingIndices.push_back(i); continue; } break; } } if (i < size) { const FunctionDescr& d = funcs[i]; mResultType = d.mReturnType; Emit(d.mOpcode, aExpression->GetLocation()); } else { if (matchingIndices.empty()) { mLSystem.Error(left->GetLocation(), "uknown function: " + left->GetName()); mResultType = ArgumentType::Unspecified; } else { mLSystem.Error(left->GetLocation(), "argument signature does not match to any function: " + left->GetName()); mResultType = ArgumentType::Unspecified; } } return mResultType; } ArgumentType::Type PrecompiledExp::CompileOperator(const AST::Expression* aExpression, const FormalArgumentMap& aArgs) { struct CodeEntry { struct OperandPair { ArgumentType::Type mResultType; Opcode mOpCode; OperandPair() : mResultType(ArgumentType::Unspecified), mOpCode(NOP) {} }; const char * mName; // name of the operator (for error reporting) int mNumArguments; // number of arguments [0..3] OperandPair mValidPairs[ArgumentType::MaxArgumentTypes][ArgumentType::MaxArgumentTypes]; CodeEntry(const char* aName, int aNumArguments) : mName(aName), mNumArguments(aNumArguments) { } CodeEntry& AddValidPair(ArgumentType::Type aLeftType, ArgumentType::Type aRightType, ArgumentType::Type aResultType, Opcode aOpcode) { //ASSERT(op.mResultType == ArgumentType::Unspecified); //ASSERT(op.mOpCode == NOP); mValidPairs[aLeftType][aRightType].mResultType = aResultType; mValidPairs[aLeftType][aRightType].mOpCode = aOpcode; return *this; } }; static const CodeEntry table[AST::Expression::MaxOpCode] = { CodeEntry("call", 0) , CodeEntry("list", 2) , CodeEntry("+", 1) .AddValidPair(ArgumentType::Int, ArgumentType::Unspecified, ArgumentType::Int, IADD) .AddValidPair(ArgumentType::Float, ArgumentType::Unspecified, ArgumentType::Float, FADD) .AddValidPair(ArgumentType::Vec2, ArgumentType::Unspecified, ArgumentType::Vec2, V2ADD) .AddValidPair(ArgumentType::Vec3, ArgumentType::Unspecified, ArgumentType::Vec3, V3ADD) .AddValidPair(ArgumentType::Vec4, ArgumentType::Unspecified, ArgumentType::Vec4, V4ADD) , CodeEntry("-", 1) .AddValidPair(ArgumentType::Int, ArgumentType::Unspecified, ArgumentType::Int, INEG) .AddValidPair(ArgumentType::Float, ArgumentType::Unspecified, ArgumentType::Float, FNEG) .AddValidPair(ArgumentType::Vec2, ArgumentType::Unspecified, ArgumentType::Vec2, V2NEG) .AddValidPair(ArgumentType::Vec3, ArgumentType::Unspecified, ArgumentType::Vec3, V3NEG) .AddValidPair(ArgumentType::Vec4, ArgumentType::Unspecified, ArgumentType::Vec4, V4NEG) , CodeEntry("~", 1) .AddValidPair(ArgumentType::Int, ArgumentType::Unspecified, ArgumentType::Int, INEG) , CodeEntry("!", 1) .AddValidPair(ArgumentType::Bool, ArgumentType::Unspecified, ArgumentType::Bool, IADD) , CodeEntry("*", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Int, IMUL) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Float, FMUL) .AddValidPair(ArgumentType::Vec2, ArgumentType::Vec2, ArgumentType::Vec2, V2MUL) .AddValidPair(ArgumentType::Vec3, ArgumentType::Vec3, ArgumentType::Vec3, V3MUL) .AddValidPair(ArgumentType::Vec4, ArgumentType::Vec4, ArgumentType::Vec4, V4MUL) .AddValidPair(ArgumentType::Vec2, ArgumentType::Float, ArgumentType::Vec2, V2SMUL) .AddValidPair(ArgumentType::Vec3, ArgumentType::Float, ArgumentType::Vec3, V3SMUL) .AddValidPair(ArgumentType::Vec4, ArgumentType::Float, ArgumentType::Vec4, V4SMUL) .AddValidPair(ArgumentType::Float, ArgumentType::Vec2, ArgumentType::Vec2, SV2MUL) .AddValidPair(ArgumentType::Float, ArgumentType::Vec3, ArgumentType::Vec3, SV3MUL) .AddValidPair(ArgumentType::Float, ArgumentType::Vec4, ArgumentType::Vec4, SV4MUL) , CodeEntry("/", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Int, IDIV) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Float, FDIV) .AddValidPair(ArgumentType::Vec2, ArgumentType::Float, ArgumentType::Vec2, V2SDIV) .AddValidPair(ArgumentType::Vec3, ArgumentType::Float, ArgumentType::Vec3, V3SDIV) .AddValidPair(ArgumentType::Vec4, ArgumentType::Float, ArgumentType::Vec4, V4SDIV) .AddValidPair(ArgumentType::Float, ArgumentType::Vec2, ArgumentType::Vec2, SV2DIV) .AddValidPair(ArgumentType::Float, ArgumentType::Vec3, ArgumentType::Vec3, SV3DIV) .AddValidPair(ArgumentType::Float, ArgumentType::Vec4, ArgumentType::Vec4, SV4DIV) , CodeEntry("%", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Int, IMOD) , CodeEntry("+", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Int, IADD) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Float, FADD) .AddValidPair(ArgumentType::Vec2, ArgumentType::Vec2, ArgumentType::Vec2, V2ADD) .AddValidPair(ArgumentType::Vec3, ArgumentType::Vec3, ArgumentType::Vec3, V3ADD) .AddValidPair(ArgumentType::Vec4, ArgumentType::Vec4, ArgumentType::Vec4, V4ADD) .AddValidPair(ArgumentType::Vec2, ArgumentType::Float, ArgumentType::Vec2, V2SADD) .AddValidPair(ArgumentType::Vec3, ArgumentType::Float, ArgumentType::Vec3, V3SADD) .AddValidPair(ArgumentType::Vec4, ArgumentType::Float, ArgumentType::Vec4, V4SADD) .AddValidPair(ArgumentType::Float, ArgumentType::Vec2, ArgumentType::Vec2, SV2ADD) .AddValidPair(ArgumentType::Float, ArgumentType::Vec3, ArgumentType::Vec3, SV3ADD) .AddValidPair(ArgumentType::Float, ArgumentType::Vec4, ArgumentType::Vec4, SV4ADD) , CodeEntry("-", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Int, ISUB) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Float, FSUB) .AddValidPair(ArgumentType::Vec2, ArgumentType::Vec2, ArgumentType::Vec2, V2SUB) .AddValidPair(ArgumentType::Vec3, ArgumentType::Vec3, ArgumentType::Vec3, V3SUB) .AddValidPair(ArgumentType::Vec4, ArgumentType::Vec4, ArgumentType::Vec4, V4SUB) .AddValidPair(ArgumentType::Vec2, ArgumentType::Float, ArgumentType::Vec2, V2SSUB) .AddValidPair(ArgumentType::Vec3, ArgumentType::Float, ArgumentType::Vec3, V3SSUB) .AddValidPair(ArgumentType::Vec4, ArgumentType::Float, ArgumentType::Vec4, V4SSUB) .AddValidPair(ArgumentType::Float, ArgumentType::Vec2, ArgumentType::Vec2, SV2SUB) .AddValidPair(ArgumentType::Float, ArgumentType::Vec3, ArgumentType::Vec3, SV3SUB) .AddValidPair(ArgumentType::Float, ArgumentType::Vec4, ArgumentType::Vec4, SV4SUB) , CodeEntry("<<", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Int, SHL) , CodeEntry(">>", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Int, SHR) , CodeEntry("<", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Bool, ILT) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Bool, FLT) , CodeEntry(">", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Bool, IGT) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Bool, FGT) , CodeEntry("<=", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Bool, ILE) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Bool, FLE) , CodeEntry(">=", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Bool, IGE) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Bool, FGE) , CodeEntry("==", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Bool, IEQ) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Bool, FEQ) .AddValidPair(ArgumentType::Bool, ArgumentType::Bool, ArgumentType::Bool, BEQ) .AddValidPair(ArgumentType::Vec2, ArgumentType::Vec2, ArgumentType::Bool, V2EQ) .AddValidPair(ArgumentType::Vec3, ArgumentType::Vec3, ArgumentType::Bool, V3EQ) .AddValidPair(ArgumentType::Vec4, ArgumentType::Vec4, ArgumentType::Bool, V4EQ) , CodeEntry("!=", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Bool, INE) .AddValidPair(ArgumentType::Float, ArgumentType::Float, ArgumentType::Bool, FNE) .AddValidPair(ArgumentType::Bool, ArgumentType::Bool, ArgumentType::Bool, BNE) .AddValidPair(ArgumentType::Vec2, ArgumentType::Vec2, ArgumentType::Bool, V2NE) .AddValidPair(ArgumentType::Vec3, ArgumentType::Vec3, ArgumentType::Bool, V3NE) .AddValidPair(ArgumentType::Vec4, ArgumentType::Vec4, ArgumentType::Bool, V4NE) , CodeEntry("&", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Int, BWAND) , CodeEntry("|", 2) .AddValidPair(ArgumentType::Int, ArgumentType::Int, ArgumentType::Int, BWOR) , CodeEntry("&&", 2) .AddValidPair(ArgumentType::Bool, ArgumentType::Bool, ArgumentType::Bool, AND) , CodeEntry("||", 2) .AddValidPair(ArgumentType::Bool, ArgumentType::Bool, ArgumentType::Bool, OR) , CodeEntry("^", 2) .AddValidPair(ArgumentType::Bool, ArgumentType::Bool, ArgumentType::Bool, XOR) , CodeEntry("?", 3) , CodeEntry("integer constant", 0) , CodeEntry("floating constant", 0) , CodeEntry("boolean constant", 0) , CodeEntry("vec2 constant", 0) , CodeEntry("vec3 constant", 0) , CodeEntry("vec4 constant", 0) , CodeEntry("name reference", 0) .AddValidPair(ArgumentType::Int, ArgumentType::Unspecified, ArgumentType::Int, ILOAD) .AddValidPair(ArgumentType::Float, ArgumentType::Unspecified, ArgumentType::Float, FLOAD) .AddValidPair(ArgumentType::Bool, ArgumentType::Unspecified, ArgumentType::Bool, BLOAD) .AddValidPair(ArgumentType::Vec2, ArgumentType::Unspecified, ArgumentType::Vec2, V2LOAD) .AddValidPair(ArgumentType::Vec3, ArgumentType::Unspecified, ArgumentType::Vec3, V3LOAD) .AddValidPair(ArgumentType::Vec4, ArgumentType::Unspecified, ArgumentType::Vec4, V4LOAD) , CodeEntry("int type", 0) , CodeEntry("float type", 0) , CodeEntry("bool type", 0) , CodeEntry("vec2 type", 0) , CodeEntry("vec3 type", 0) , CodeEntry("vec4 type", 0) , CodeEntry("type cast", 2) , CodeEntry(".", 1) }; const AST::Expression::Type astOp = aExpression->GetOpCode(); const CodeEntry &e = table[astOp]; static const char * typeNames[] = { "<invalid>", "int", "float", "bool", "vec2", "vec3", "vec4" }; ArgumentTypes argumentTypes; CompileAllOperands(aExpression, argumentTypes, aArgs); const AST::Expressions& operands = aExpression->GetOperands(); switch (astOp) { case AST::Expression::Integer: Emit(IPUSH, aExpression->GetLocation()); Emit(aExpression->GetIntegerValue(), aExpression->GetLocation()); mResultType = ArgumentType::Int; break; case AST::Expression::Float: Emit(FPUSH, aExpression->GetLocation()); Emit(aExpression->GetFloatValue(), aExpression->GetLocation()); mResultType = ArgumentType::Float; break; case AST::Expression::Boolean: Emit(BPUSH, aExpression->GetLocation()); Emit(aExpression->GetBoolValue(), aExpression->GetLocation()); mResultType = ArgumentType::Bool; break; case AST::Expression::Vec2: ASSERT(argumentTypes.size() == 2); for (int i = 0; i < (int)argumentTypes.size(); ++i) if (argumentTypes[i] != ArgumentType::Float) mLSystem.Error(aExpression->GetOperands()[i]->GetLocation(), "vec2: constructor arguments must be floating type"); Emit(V2PUSH, aExpression->GetLocation()); mResultType = ArgumentType::Vec2; break; case AST::Expression::Vec3: ASSERT(argumentTypes.size() == 3); for (int i = 0; i < (int)argumentTypes.size(); ++i) if (argumentTypes[i] != ArgumentType::Float) mLSystem.Error(aExpression->GetOperands()[i]->GetLocation(), "vec3: constructor arguments must be floating type"); Emit(V3PUSH, aExpression->GetLocation()); mResultType = ArgumentType::Vec3; break; case AST::Expression::Vec4: ASSERT(argumentTypes.size() == 4); for (int i = 0; i < (int)argumentTypes.size(); ++i) if (argumentTypes[i] != ArgumentType::Float) mLSystem.Error(aExpression->GetOperands()[i]->GetLocation(), "vec4: constructor arguments must be floating type"); Emit(V4PUSH, aExpression->GetLocation()); mResultType = ArgumentType::Vec4; break; case AST::Expression::QualifiedName: { const Token t = mLSystem.GetToken(aExpression->GetName()); auto it = aArgs.find(t); if (it == aArgs.end()) { mLSystem.Error(aExpression->GetLocation(), std::string("unknown identifier: ") + aExpression->GetName()); mResultType = ArgumentType::Unspecified; return mResultType; } else { mResultType = it->second.mType; Emit(e.mValidPairs[it->second.mType][ArgumentType::Unspecified].mOpCode, aExpression->GetLocation()); Emit(t, aExpression->GetLocation()); } } break; case AST::Expression::FuncCall: case AST::Expression::TypeCast: ASSERT(!"internal error"); break; case AST::Expression::MemberSelect: { ASSERT(e.mNumArguments == 1); ASSERT(operands.size() == 2); ASSERT(operands[1]->GetOpCode() == AST::Expression::QualifiedName); CompileAllOperands(operands[0], argumentTypes, aArgs); const std::string fieldName = operands[1]->GetName(); switch (argumentTypes[0]) { case ArgumentType::Vec2: { static const struct Swizzle { std::string mName; PrecompiledExp::Opcode mOpCode; ArgumentType::Type mResultType; } swizzles[] = { { "x", V2X, ArgumentType::Float }, { "y", V2Y, ArgumentType::Float }, { "yx", V2YX, ArgumentType::Vec2 }, }; for (int i = 0; i < sizeof(swizzles) / sizeof(swizzles[0]); ++i) { const Swizzle& s = swizzles[i]; if (s.mName == fieldName) { Emit(s.mOpCode, aExpression->GetLocation()); mResultType = s.mResultType; goto done; } } mLSystem.Error(operands[1]->GetLocation(), fieldName + ": invalid field selector"); mResultType = ArgumentType::Unspecified; } done: break; case ArgumentType::Vec3: { static const struct Swizzle { std::string mName; PrecompiledExp::Opcode mOpCode; ArgumentType::Type mResultType; } swizzles[] = { { "x", V3X, ArgumentType::Float }, { "y", V3Y, ArgumentType::Float }, { "z", V3Z, ArgumentType::Float }, { "xy", V3XY, ArgumentType::Vec2 }, { "xz", V3XZ, ArgumentType::Vec2 }, { "yx", V3YX, ArgumentType::Vec2 }, { "yz", V3YZ, ArgumentType::Vec2 }, { "zy", V3ZY, ArgumentType::Vec2 }, { "zx", V3ZX, ArgumentType::Vec2 }, { "xyz", V3XYZ, ArgumentType::Vec3 }, { "xzy", V3XZY, ArgumentType::Vec3 }, { "yxz", V3YXZ, ArgumentType::Vec3 }, { "yzx", V3YZX, ArgumentType::Vec3 }, { "zxy", V3ZXY, ArgumentType::Vec3 }, { "zyx", V3ZYX, ArgumentType::Vec3 }, }; for (int i = 0; i < sizeof(swizzles) / sizeof(swizzles[0]); ++i) { const Swizzle& s = swizzles[i]; if (s.mName == fieldName) { Emit(s.mOpCode, aExpression->GetLocation()); mResultType = s.mResultType; goto done; } } mLSystem.Error(operands[1]->GetLocation(), fieldName + ": invalid field selector"); mResultType = ArgumentType::Unspecified; } break; case ArgumentType::Vec4: { static const struct Swizzle { std::string mName; PrecompiledExp::Opcode mOpCode; ArgumentType::Type mResultType; } swizzles[] = { { "x", V4X, ArgumentType::Float }, { "y", V4Y, ArgumentType::Float }, { "z", V4Z, ArgumentType::Float }, { "w", V4W, ArgumentType::Float }, { "xy", V4XY, ArgumentType::Vec2 }, { "yx", V4YX, ArgumentType::Vec2 }, { "xz", V4XZ, ArgumentType::Vec2 }, { "zx", V4ZX, ArgumentType::Vec2 }, { "xw", V4XW, ArgumentType::Vec2 }, { "wx", V4WX, ArgumentType::Vec2 }, { "yz", V4YZ, ArgumentType::Vec2 }, { "zy", V4ZY, ArgumentType::Vec2 }, { "yw", V4YW, ArgumentType::Vec2 }, { "wy", V4WY, ArgumentType::Vec2 }, { "xyz", V4XYZ, ArgumentType::Vec3 }, { "xyw", V4XYW, ArgumentType::Vec3 }, { "xzy", V4XZY, ArgumentType::Vec3 }, { "xzw", V4XZW, ArgumentType::Vec3 }, { "xwy", V4XWY, ArgumentType::Vec3 }, { "xwz", V4XWZ, ArgumentType::Vec3 }, { "yxz", V4YXZ, ArgumentType::Vec3 }, { "yxw", V4YXW, ArgumentType::Vec3 }, { "yzx", V4YZX, ArgumentType::Vec3 }, { "yzw", V4YZW, ArgumentType::Vec3 }, { "ywx", V4YWX, ArgumentType::Vec3 }, { "ywz", V4YWZ, ArgumentType::Vec3 }, { "zxy", V4ZXY, ArgumentType::Vec3 }, { "zxw", V4ZXW, ArgumentType::Vec3 }, { "zyx", V4ZYX, ArgumentType::Vec3 }, { "zyw", V4ZYW, ArgumentType::Vec3 }, { "zwx", V4ZWX, ArgumentType::Vec3 }, { "zwy", V4ZWY, ArgumentType::Vec3 }, { "wxy", V4WXY, ArgumentType::Vec3 }, { "wxz", V4WXZ, ArgumentType::Vec3 }, { "wyx", V4WYX, ArgumentType::Vec3 }, { "wyz", V4WYZ, ArgumentType::Vec3 }, { "wzx", V4WZX, ArgumentType::Vec3 }, { "wzy", V4WZY, ArgumentType::Vec3 }, { "xyzw", V4XYZW, ArgumentType::Vec4 }, { "xywz", V4XYWZ, ArgumentType::Vec4 }, { "xzyw", V4XZYW, ArgumentType::Vec4 }, { "xzwy", V4XZWY, ArgumentType::Vec4 }, { "xwyz", V4XWYZ, ArgumentType::Vec4 }, { "xwzy", V4XWZY, ArgumentType::Vec4 }, { "yxzw", V4YXZW, ArgumentType::Vec4 }, { "yxwz", V4YXWZ, ArgumentType::Vec4 }, { "yzxw", V4YZXW, ArgumentType::Vec4 }, { "yzwx", V4YZWX, ArgumentType::Vec4 }, { "ywxz", V4YWXZ, ArgumentType::Vec4 }, { "ywzx", V4YWZX, ArgumentType::Vec4 }, { "zxyw", V4ZXYW, ArgumentType::Vec4 }, { "zxwy", V4ZXWY, ArgumentType::Vec4 }, { "zyxw", V4ZYXW, ArgumentType::Vec4 }, { "zywx", V4ZYWX, ArgumentType::Vec4 }, { "zwxy", V4ZWXY, ArgumentType::Vec4 }, { "zwyx", V4ZWYX, ArgumentType::Vec4 }, { "wxyz", V4WXYZ, ArgumentType::Vec4 }, { "wxzy", V4WXZY, ArgumentType::Vec4 }, { "wyxz", V4WYXZ, ArgumentType::Vec4 }, { "wyzx", V4WYZX, ArgumentType::Vec4 }, { "wzxy", V4WZXY, ArgumentType::Vec4 }, { "wzyx", V4WZYX, ArgumentType::Vec4 }, }; for (int i = 0; i < sizeof(swizzles) / sizeof(swizzles[0]); ++i) { const Swizzle& s = swizzles[i]; if (s.mName == fieldName) { Emit(s.mOpCode, aExpression->GetLocation()); mResultType = s.mResultType; goto done; } } mLSystem.Error(operands[1]->GetLocation(), fieldName + ": invalid field selector"); mResultType = ArgumentType::Unspecified; } break; default: ASSERT(!"Internal error: unknown left-hand side type for swizzle/member select operator"); } } break; default: if (e.mNumArguments == 1) { const CodeEntry::OperandPair& op = e.mValidPairs[argumentTypes[0]][ArgumentType::Unspecified]; if (op.mOpCode == NOP) { mLSystem.Error(operands[0]->GetLocation(), std::string(e.mName) + " operator is not allowed on type " + typeNames[argumentTypes[0]]); mResultType = ArgumentType::Unspecified; } else { Emit(op.mOpCode, aExpression->GetLocation()); mResultType = op.mResultType; } } else if (e.mNumArguments == 2) { const CodeEntry::OperandPair& op = e.mValidPairs[argumentTypes[0]][argumentTypes[1]]; if (op.mOpCode == NOP) { mLSystem.Error(aExpression->GetLocation(), std::string("operand types do not match: ") + typeNames[argumentTypes[0]] + " '" + e.mName + "' " + typeNames[argumentTypes[1]]); mResultType = ArgumentType::Unspecified; } else { Emit(op.mOpCode, aExpression->GetLocation()); mResultType = op.mResultType; } } else ASSERT(!"internal error"); break; } return mResultType; } void PrecompiledExp::Emit(PrecompiledExp::Opcode aOpcode, const Location &aLocation) { ASSERT(aOpcode != NOP); AddLocation(aLocation); mCode.Push(aOpcode); } void PrecompiledExp::Emit(int aInteger, const Location &aLocation) { AddLocation(aLocation); mCode.Push(aInteger); } void PrecompiledExp::Emit(float aFloat, const Location &aLocation) { AddLocation(aLocation); mCode.Push(aFloat); } void PrecompiledExp::EmitName(Token aName, const Location &aLocation) { AddLocation(aLocation); mCode.Push(aName); } void PrecompiledExp::Emit(glm::vec2 aVec2, const Location &aLocation) { AddLocation(aLocation); mCode.Push(aVec2); } void PrecompiledExp::Emit(glm::vec3 aVec3, const Location &aLocation) { AddLocation(aLocation); mCode.Push(aVec3); } void PrecompiledExp::Emit(glm::vec4 aVec4, const Location &aLocation) { AddLocation(aLocation); mCode.Push(aVec4); } const char* PrecompiledExp::ToString(Opcode o) { static const char * names[] = { #define T(C,M,D) M, SCOPE_OPCODES() #undef T }; return names[o]; } std::string PrecompiledExp::ToString(const glm::vec2& v) { std::ostringstream s; s << "vec2(" << v[0] << ", " << v[1] << "," << ")"; return s.str(); } std::string PrecompiledExp::ToString(const glm::vec3& v) { std::ostringstream s; s << "vec3(" << v[0] << ", " << v[1] << "," << v[2] << ")"; return s.str(); } std::string PrecompiledExp::ToString(const glm::vec4& v) { std::ostringstream s; s << "vec4(" << v[0] << ", " << v[1] << "," << v[2] << "," << v[3] << ")"; return s.str(); } void PrecompiledExp::Evaluate(const ArgumentValueMap& aArgs, State& aState) const { ASSERT(!mCode.IsEmpty()); for (int ip = 0; ip < (int)mCode.Size(); ) { const Opcode o = mCode.Get<Opcode>(ip); ip += sizeof(Opcode); const int sp = aState.ElementCount(); // (cerr << ToString(o) << " "); switch (o) { case NOP: break; case IPUSH: aState.Push(mCode.Get<int>(ip)); ip += sizeof(int); break; case FPUSH: aState.Push(mCode.Get<float>(ip)); ip += sizeof(float); break; case BPUSH: aState.Push(mCode.Get<bool>(ip)); ip += sizeof(bool); break; case V2PUSH: { auto y = aState.Pop<float>(); auto x = aState.Pop<float>(); aState.Push(glm::vec2(x, y)); break; } case V3PUSH: { auto z = aState.Pop<float>(); auto y = aState.Pop<float>(); auto x = aState.Pop<float>(); aState.Push(glm::vec3(x, y, z)); break; } case V4PUSH: { auto w = aState.Pop<float>(); auto z = aState.Pop<float>(); auto y = aState.Pop<float>(); auto x = aState.Pop<float>(); aState.Push(glm::vec4(x, y, z, w)); break; } case ILOAD: aState.Push(aArgs.Get<int>(mCode.Get<int>(ip))); ip += sizeof(int); break; case FLOAD: aState.Push(aArgs.Get<float>(mCode.Get<int>(ip))); ip += sizeof(int); break; case BLOAD: aState.Push(aArgs.Get<bool>(mCode.Get<int>(ip))); ip += sizeof(int); break; case V2LOAD: aState.Push(aArgs.Get<glm::vec2>(mCode.Get<int>(ip))); ip += sizeof(int); break; case V3LOAD: aState.Push(aArgs.Get<glm::vec3>(mCode.Get<int>(ip))); ip += sizeof(int); break; case V4LOAD: aState.Push(aArgs.Get<glm::vec4>(mCode.Get<int>(ip))); ip += sizeof(int); break; case INEG: aState.Top<int>() = -aState.Top<int>(); break; case FNEG: aState.Top<float>() = -aState.Top<float>(); break; case V2NEG: aState.Top<glm::vec2>() = -aState.Top<glm::vec2>(); break; case V3NEG: aState.Top<glm::vec3>() = -aState.Top<glm::vec3>(); break; case V4NEG: aState.Top<glm::vec4>() = -aState.Top<glm::vec4>(); break; case BWNEG: aState.Top<int>() = ~aState.Top<int>(); break; case NOT: aState.Top<bool>() = !aState.Top<bool>(); break; case IMUL: aState.Top<int>(-2) = aState.Top<int>(-2) * aState.Top<int>(-1); aState.Pop<int>(); break; case FMUL: aState.Top<float>(-2) = aState.Top<float>(-2) * aState.Top<float>(-1); aState.Pop<float>(); break; case V2MUL: aState.Top<glm::vec2>(-2) = aState.Top<glm::vec2>(-2) * aState.Top<glm::vec2>(-1); aState.Pop<glm::vec2>(); break; case V3MUL: aState.Top<glm::vec3>(-2) = aState.Top<glm::vec3>(-2) * aState.Top<glm::vec3>(-1); aState.Pop<glm::vec3>(); break; case V4MUL: aState.Top<glm::vec4>(-2) = aState.Top<glm::vec4>(-2) * aState.Top<glm::vec4>(-1); aState.Pop<glm::vec4>(); break; case V2SMUL: { const float s = aState.Pop<float>(); const glm::vec2 v = aState.Pop<glm::vec2>(); const glm::vec2 r = v * s; aState.Push(r); } break; case V3SMUL: { const float s = aState.Pop<float>(); const glm::vec3 v = aState.Pop<glm::vec3>(); const glm::vec3 r = v * s; aState.Push(r); } break; case V4SMUL: { const float s = aState.Pop<float>(); const glm::vec4 v = aState.Pop<glm::vec4>(); const glm::vec4 r = v * s; aState.Push(r); } break; case SV2MUL: { const glm::vec2 v = aState.Pop<glm::vec2>(); const float s = aState.Pop<float>(); const glm::vec2 r = v * s; aState.Push(r); } break; case SV3MUL: { const glm::vec3 v = aState.Pop<glm::vec3>(); const float s = aState.Pop<float>(); const glm::vec3 r = v * s; aState.Push(r); } break; case SV4MUL: { const glm::vec4 v = aState.Pop<glm::vec4>(); const float s = aState.Pop<float>(); const glm::vec4 r = v * s; aState.Push(r); } break; case IDIV: aState.Top<int>(-2) = aState.Top<int>(-2) / aState.Top<int>(-1); aState.Pop<int>(); break; case FDIV: aState.Top<float>(-2) = aState.Top<float>(-2) / aState.Top<float>(-1); aState.Pop<float>(); break; case V2SDIV: { const float s = aState.Pop<float>(); const glm::vec2 v = aState.Pop<glm::vec2>(); const glm::vec2 r = v / s; aState.Push(r); } break; case V3SDIV: { const float s = aState.Pop<float>(); const glm::vec3 v = aState.Pop<glm::vec3>(); const glm::vec3 r = v / s; aState.Push(r); } break; case V4SDIV: { const float s = aState.Pop<float>(); const glm::vec4 v = aState.Pop<glm::vec4>(); const glm::vec4 r = v / s; aState.Push(r); } break; case SV2DIV: { const glm::vec2 v = aState.Pop<glm::vec2>(); const float s = aState.Pop<float>(); const glm::vec2 r = v / s; aState.Push(r); } break; case SV3DIV: { const glm::vec3 v = aState.Pop<glm::vec3>(); const float s = aState.Pop<float>(); const glm::vec3 r = v / s; aState.Push(r); } break; case SV4DIV: { const glm::vec4 v = aState.Pop<glm::vec4>(); const float s = aState.Pop<float>(); const glm::vec4 r = v / s; aState.Push(r); } break; case IMOD: aState.Top<int>(-2) = aState.Top<int>(-2) % aState.Top<int>(-1); aState.Pop<int>(); break; case IADD: aState.Top<int>(-2) = aState.Top<int>(-2) + aState.Top<int>(-1); aState.Pop<int>(); break; case FADD: aState.Top<float>(-2) = aState.Top<float>(-2) + aState.Top<float>(-1); aState.Pop<float>(); break; case V2ADD: aState.Top<glm::vec2>(-2) = aState.Top<glm::vec2>(-2) + aState.Top<glm::vec2>(-1); aState.Pop<glm::vec2>(); break; case V3ADD: aState.Top<glm::vec3>(-2) = aState.Top<glm::vec3>(-2) + aState.Top<glm::vec3>(-1); aState.Pop<glm::vec3>(); break; case V4ADD: aState.Top<glm::vec4>(-2) = aState.Top<glm::vec4>(-2) + aState.Top<glm::vec4>(-1); aState.Pop<glm::vec4>(); break; case V2SADD: { const float s = aState.Pop<float>(); const glm::vec2 v = aState.Pop<glm::vec2>(); const glm::vec2 r = v + s; aState.Push(r); } break; case V3SADD: { const float s = aState.Pop<float>(); const glm::vec3 v = aState.Pop<glm::vec3>(); const glm::vec3 r = v + s; aState.Push(r); } break; case V4SADD: { const float s = aState.Pop<float>(); const glm::vec4 v = aState.Pop<glm::vec4>(); const glm::vec4 r = v + s; aState.Push(r); } break; case SV2ADD: { const glm::vec2 v = aState.Pop<glm::vec2>(); const float s = aState.Pop<float>(); const glm::vec2 r = v + s; aState.Push(r); } break; case SV3ADD: { const glm::vec3 v = aState.Pop<glm::vec3>(); const float s = aState.Pop<float>(); const glm::vec3 r = v + s; aState.Push(r); } break; case SV4ADD: { const glm::vec4 v = aState.Pop<glm::vec4>(); const float s = aState.Pop<float>(); const glm::vec4 r = v + s; aState.Push(r); } break; case ISUB: aState.Top<int>(-2) = aState.Top<int>(-2) - aState.Top<int>(-1); aState.Pop<int>(); break; case FSUB: aState.Top<float>(-2) = aState.Top<float>(-2) - aState.Top<float>(-1); aState.Pop<float>(); break; case V2SUB: aState.Top<glm::vec2>(-2) = aState.Top<glm::vec2>(-2) - aState.Top<glm::vec2>(-1); aState.Pop<glm::vec2>(); break; case V3SUB: aState.Top<glm::vec3>(-2) = aState.Top<glm::vec3>(-2) - aState.Top<glm::vec3>(-1); aState.Pop<glm::vec3>(); break; case V4SUB: aState.Top<glm::vec4>(-2) = aState.Top<glm::vec4>(-2) - aState.Top<glm::vec4>(-1); aState.Pop<glm::vec4>(); break; case V2SSUB: { const float s = aState.Pop<float>(); const glm::vec2 v = aState.Pop<glm::vec2>(); const glm::vec2 r = v - s; aState.Push(r); } break; case V3SSUB: { const float s = aState.Pop<float>(); const glm::vec3 v = aState.Pop<glm::vec3>(); const glm::vec3 r = v - s; aState.Push(r); } break; case V4SSUB: { const float s = aState.Pop<float>(); const glm::vec4 v = aState.Pop<glm::vec4>(); const glm::vec4 r = v - s; aState.Push(r); } break; case SV2SUB: { const glm::vec2 v = aState.Pop<glm::vec2>(); const float s = aState.Pop<float>(); const glm::vec2 r = v - s; aState.Push(r); } break; case SV3SUB: { const glm::vec3 v = aState.Pop<glm::vec3>(); const float s = aState.Pop<float>(); const glm::vec3 r = v - s; aState.Push(r); } break; case SV4SUB: { const glm::vec4 v = aState.Pop<glm::vec4>(); const float s = aState.Pop<float>(); const glm::vec4 r = v - s; aState.Push(r); } break; case SHR: aState.Top<int>(-2) = aState.Top<int>(-2) >> aState.Top<int>(-1); aState.Pop<int>(); break; case SHL: aState.Top<int>(-2) = aState.Top<int>(-2) << aState.Top<int>(-1); aState.Pop<int>(); break; case ILT: aState.Push<bool>(aState.Pop<int>() > aState.Pop<int>()); break; case FLT: aState.Push<bool>(aState.Pop<float>() > aState.Pop<float>()); break; case IGT: aState.Push<bool>(aState.Pop<int>() < aState.Pop<int>()); break; case FGT: aState.Push<bool>(aState.Pop<float>() < aState.Pop<float>()); break; case ILE: aState.Push<bool>(aState.Pop<int>() >= aState.Pop<int>()); break; case FLE: aState.Push<bool>(aState.Pop<float>() >= aState.Pop<float>()); break; case IGE: aState.Push<bool>(aState.Pop<int>() <= aState.Pop<int>()); break; case FGE: aState.Push<bool>(aState.Pop<float>() <= aState.Pop<float>()); break; case IEQ: aState.Push<bool>(aState.Pop<int>() == aState.Pop<int>()); break; case FEQ: aState.Push<bool>(aState.Pop<float>() == aState.Pop<float>()); break; case BEQ: aState.Push<bool>(aState.Pop<bool>() == aState.Pop<bool>()); break; case V2EQ: aState.Push<bool>(aState.Pop<glm::vec2>() == aState.Pop<glm::vec2>()); break; case V3EQ: aState.Push<bool>(aState.Pop<glm::vec3>() == aState.Pop<glm::vec3>()); break; case V4EQ: aState.Push<bool>(aState.Pop<glm::vec4>() == aState.Pop<glm::vec4>()); break; case INE: aState.Push<bool>(aState.Pop<int>() != aState.Pop<int>()); break; case FNE: aState.Push<bool>(aState.Pop<float>() != aState.Pop<float>()); break; case BNE: aState.Push<bool>(aState.Pop<bool>() != aState.Pop<bool>()); break; case V2NE: aState.Push<bool>(aState.Pop<glm::vec2>() != aState.Pop<glm::vec2>()); break; case V3NE: aState.Push<bool>(aState.Pop<glm::vec3>() != aState.Pop<glm::vec3>()); break; case V4NE: aState.Push<bool>(aState.Pop<glm::vec4>() != aState.Pop<glm::vec4>()); break; case BWAND: aState.Top<int>(-2) = aState.Top<int>(-2) & aState.Top<int>(-1); aState.Pop<int>(); break; case BWOR: aState.Top<int>(-2) = aState.Top<int>(-2) | aState.Top<int>(-1); aState.Pop<int>(); break; case AND: aState.Top<bool>(-2) = aState.Top<bool>(-2) && aState.Top<bool>(-1); aState.Pop<bool>(); break; case OR: aState.Top<bool>(-2) = aState.Top<bool>(-2) || aState.Top<bool>(-1); aState.Pop<bool>(); break; case XOR: aState.Top<bool>(-2) = aState.Top<bool>(-2) ^ aState.Top<bool>(-1); aState.Pop<bool>(); break; case JP: ip = mCode.Get<int>(++ip); break; case JPT: if (aState.Pop<bool>()) ip = mCode.Get<int>(++ip); break; case JPF: if (!aState.Pop<bool>()) ip = mCode.Get<int>(++ip); break; case CBN: ip = mCode.Get<int>(++ip); break; case FSIN: aState.Top<float>(-1) = sinf(aState.Top<float>(-1)); break; case FCOS: aState.Top<float>(-1) = cosf(aState.Top<float>(-1)); break; case FTAN: aState.Top<float>(-1) = tanf(aState.Top<float>(-1)); break; case FASIN: aState.Top<float>(-1) = asinf(aState.Top<float>(-1)); break; case FACOS: aState.Top<float>(-1) = acosf(aState.Top<float>(-1)); break; case FATAN: aState.Top<float>(-1) = acosf(aState.Top<float>(-1)); break; case FLOG: aState.Top<float>(-1) = logf(aState.Top<float>(-1)); break; case FEXP: aState.Top<float>(-1) = expf(aState.Top<float>(-1)); break; case FSQRT: aState.Top<float>(-1) = sqrtf(aState.Top<float>(-1)); break; case FCEIL: aState.Top<float>(-1) = ceilf(aState.Top<float>(-1)); break; case FABS: aState.Top<float>(-1) = abs(aState.Top<float>(-1)); break; case ITOF: aState.Top<float>(-1) = float(aState.Top<int>(-1)); break; case BTOF: aState.Top<float>(-1) = float(aState.Top<bool>(-1)); break; case BTOI: aState.Top<int>(-1) = int(aState.Top<bool>(-1)); break; case ITOB: aState.Top<bool>(-1) = !!(aState.Top<int>(-1)); break; case FLOG10: aState.Top<float>(-1) = log10f(aState.Top<float>(-1)); break; case FFLOOR: aState.Top<float>(-1) = floorf(aState.Top<float>(-1)); break; case FROUND: aState.Top<float>(-1) = floorf(aState.Top<float>(-1) + 0.5f); break; case FMOD: aState.Top<float>(-2) = fmod(aState.Top<float>(-2), aState.Top<float>(-1)); aState.Pop<float>(); break; case FPOW: aState.Top<float>(-2) = powf(aState.Top<float>(-2), aState.Top<float>(-1)); aState.Pop<float>(); break; case FMIN: aState.Top<float>(-2) = min(aState.Top<float>(-2), aState.Top<float>(-1)); aState.Pop<float>(); break; case FMAX: aState.Top<float>(-2) = max(aState.Top<float>(-2), aState.Top<float>(-1)); aState.Pop<float>(); break; case FATAN2: aState.Top<float>(-2) = atan2f(aState.Top<float>(-2), aState.Top<float>(-1)); aState.Pop<float>(); break; case V2X: aState.Push(aState.Pop<glm::vec2>()[0]); break; case V2Y: aState.Push(aState.Pop<glm::vec2>()[1]); break; case V2YX: { const glm::vec2 v = aState.Pop<glm::vec2>(); aState.Push(glm::vec2(v[1], v[0])); break; } case V3X: aState.Push(aState.Pop<glm::vec3>()[0]); break; case V3Y: aState.Push(aState.Pop<glm::vec3>()[1]); break; case V3Z: aState.Push(aState.Pop<glm::vec3>()[2]); break; case V3XY: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec2(v[0], v[1])); break; } case V3XZ: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec2(v[0], v[2])); break; } case V3YX: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec2(v[1], v[0])); break; } case V3YZ: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec2(v[1], v[2])); break; } case V3ZX: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec2(v[2], v[0])); break; } case V3ZY: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec2(v[2], v[1])); break; } case V3XYZ: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec3(v[0], v[1], v[2])); break; } case V3XZY: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec3(v[0], v[2], v[1])); break; } case V3YXZ: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec3(v[1], v[0], v[2])); break; } case V3YZX: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec3(v[1], v[2], v[0])); break; } case V3ZXY: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec3(v[2], v[0], v[1])); break; } case V3ZYX: { const glm::vec3 v = aState.Pop<glm::vec3>(); aState.Push(glm::vec3(v[2], v[1], v[0])); break; } case V4X: aState.Push(aState.Pop<glm::vec4>()[0]); break; case V4Y: aState.Push(aState.Pop<glm::vec4>()[1]); break; case V4Z: aState.Push(aState.Pop<glm::vec4>()[2]); break; case V4W: aState.Push(aState.Pop<glm::vec4>()[3]); break; case V4XY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[0], v[1])); break; } case V4YX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[2], v[0])); break; } case V4XZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[0], v[2])); break; } case V4ZX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[2], v[0])); break; } case V4YZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[1], v[2])); break; } case V4ZY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[2], v[1])); break; } case V4YW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[1], v[3])); break; } case V4WY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[3], v[1])); break; } case V4XW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[0], v[3])); break; } case V4WX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec2(v[3], v[0])); break; } case V4XYZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[0], v[1], v[2])); break; } case V4XYW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[0], v[1], v[3])); break; } case V4XZY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[0], v[2], v[1])); break; } case V4XZW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[0], v[2], v[3])); break; } case V4XWY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[0], v[3], v[1])); break; } case V4XWZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[0], v[3], v[2])); break; } case V4YXZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[1], v[0], v[2])); break; } case V4YXW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[1], v[0], v[3])); break; } case V4YZX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[1], v[2], v[0])); break; } case V4YZW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[1], v[2], v[3])); break; } case V4YWX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[1], v[3], v[0])); break; } case V4YWZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[1], v[3], v[2])); break; } case V4ZXY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[2], v[0], v[1])); break; } case V4ZXW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[2], v[0], v[2])); break; } case V4ZYX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[2], v[1], v[0])); break; } case V4ZYW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[2], v[1], v[3])); break; } case V4ZWX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[2], v[3], v[0])); break; } case V4ZWY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[2], v[3], v[1])); break; } case V4WXY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[3], v[0], v[1])); break; } case V4WXZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[3], v[0], v[2])); break; } case V4WYX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[3], v[1], v[0])); break; } case V4WYZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[3], v[1], v[2])); break; } case V4WZX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[3], v[2], v[0])); break; } case V4WZY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec3(v[3], v[2], v[1])); break; } case V4XYZW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[0], v[1], v[2], v[3])); break; } case V4XYWZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[0], v[1], v[3], v[2])); break; } case V4XZYW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[0], v[2], v[1], v[3])); break; } case V4XZWY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[0], v[2], v[3], v[1])); break; } case V4XWYZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[0], v[3], v[1], v[2])); break; } case V4XWZY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[0], v[3], v[2], v[1])); break; } case V4YXZW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[1], v[0], v[2], v[3])); break; } case V4YXWZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[1], v[0], v[3], v[2])); break; } case V4YZXW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[1], v[2], v[0], v[3])); break; } case V4YZWX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[1], v[2], v[3], v[0])); break; } case V4YWXZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[1], v[3], v[0], v[2])); break; } case V4YWZX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[1], v[3], v[2], v[0])); break; } case V4ZXYW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[2], v[0], v[1], v[3])); break; } case V4ZXWY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[2], v[0], v[3], v[1])); break; } case V4ZYXW: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[2], v[1], v[0], v[3])); break; } case V4ZYWX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[2], v[1], v[3], v[0])); break; } case V4ZWXY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[2], v[3], v[0], v[1])); break; } case V4ZWYX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[2], v[3], v[1], v[0])); break; } case V4WXYZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[3], v[0], v[1], v[2])); break; } case V4WXZY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[3], v[0], v[2], v[1])); break; } case V4WYXZ: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[3], v[1], v[0], v[2])); break; } case V4WYZX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[3], v[1], v[2], v[0])); break; } case V4WZXY: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[3], v[2], v[0], v[1])); break; } case V4WZYX: { const glm::vec4 v = aState.Pop<glm::vec4>(); aState.Push(glm::vec4(v[3], v[2], v[1], v[0])); break; } case V2DOT: { const glm::vec2 v0 = aState.Pop<glm::vec2>(); const glm::vec2 v1 = aState.Pop<glm::vec2>(); aState.Push<float>(glm::dot(v1, v0)); break; } case V3DOT: { const glm::vec3 v0 = aState.Pop<glm::vec3>(); const glm::vec3 v1 = aState.Pop<glm::vec3>(); aState.Push<float>(glm::dot(v1, v0)); break; } case V4DOT: { const glm::vec4 v0 = aState.Pop<glm::vec4>(); const glm::vec4 v1 = aState.Pop<glm::vec4>(); aState.Push<float>(glm::dot(v1, v0)); break; } case V3CROSS: { const glm::vec3 v0 = aState.Pop<glm::vec3>(); const glm::vec3 v1 = aState.Pop<glm::vec3>(); aState.Push(glm::cross(v1, v0)); break; } case V2LEN: { aState.Push(glm::length(aState.Pop<glm::vec2>())); break; } case V3LEN: { aState.Push(glm::length(aState.Pop<glm::vec3>())); break; } case V4LEN: { aState.Push(glm::length(aState.Pop<glm::vec4>())); break; } case V2LEN2: { aState.Push(glm::length2(aState.Pop<glm::vec2>())); break; } case V3LEN2: { aState.Push(glm::length2(aState.Pop<glm::vec3>())); break; } case V4LEN2: { aState.Push(glm::length2(aState.Pop<glm::vec4>())); break; } case V2NORM: { aState.Push(glm::normalize(aState.Pop<glm::vec2>())); break; } case V3NORM: { aState.Push(glm::normalize(aState.Pop<glm::vec3>())); break; } case V4NORM: { aState.Push(glm::normalize(aState.Pop<glm::vec4>())); break; } case V2REFL: { const glm::vec2 v0 = aState.Pop<glm::vec2>(); const glm::vec2 v1 = aState.Pop<glm::vec2>(); aState.Push(glm::reflect(v1, v0)); break; } case V3REFL: { const glm::vec3 v0 = aState.Pop<glm::vec3>(); const glm::vec3 v1 = aState.Pop<glm::vec3>(); aState.Push(glm::reflect(v1, v0)); break; } case V4REFL: { const glm::vec4 v0 = aState.Pop<glm::vec4>(); const glm::vec4 v1 = aState.Pop<glm::vec4>(); aState.Push(glm::reflect(v1, v0)); break; } case RAND: { aState.Push(rand() % aState.Pop<int>()); break; } case FRAND: { aState.Push(static_cast<float>(rand()) / (static_cast <float>(RAND_MAX) / aState.Pop<float>())); break; } default: ASSERT(!"Invalid opcode"); } } } void PrecompiledExp::CompileAllOperands(const AST::Expression* aExpression, ArgumentTypes& aTypes, const FormalArgumentMap& aFormalArguments) { ASSERT(aExpression != NULL); const AST::Expressions& operands = aExpression->GetOperands(); if (aExpression->GetOpCode() == AST::Expression::MemberSelect) { // special case: member selector/swizzle operators are compiled as if the the left operand is a namespace // so we don't try to compile the right operand (name node) here const AST::Expressions& operands = aExpression->GetOperands(); ASSERT(operands.size() == 2); ArgumentType::Type type = Compile(operands[0], aFormalArguments); aTypes.push_back(type); aTypes.push_back(ArgumentType::Unspecified); } else { for (const auto expression : operands) { ArgumentType::Type type = Compile(expression, aFormalArguments); aTypes.push_back(type); } } } }
48.012313
177
0.643341
BalazsJako
c6d0ee41acd735f39f88bce469b9b7ba6379e18d
1,107
cpp
C++
aat/cpp/src/core/models/trade.cpp
ryuuni/aat
1a46d21463f8e080c389d1011b35d6a3fd036545
[ "Apache-2.0" ]
null
null
null
aat/cpp/src/core/models/trade.cpp
ryuuni/aat
1a46d21463f8e080c389d1011b35d6a3fd036545
[ "Apache-2.0" ]
null
null
null
aat/cpp/src/core/models/trade.cpp
ryuuni/aat
1a46d21463f8e080c389d1011b35d6a3fd036545
[ "Apache-2.0" ]
null
null
null
#include <sstream> #include <aat/common.hpp> #include <aat/config/enums.hpp> #include <aat/core/models/trade.hpp> using namespace aat::common; namespace aat { namespace core { str_t Trade::toString() const { sstream_t ss; ss << "Trade+( id=" << id << ", timestamp=" << format_timestamp(timestamp) << volume << "@" << price << ", maker_orders=" << maker_orders.size() << ", taker_order=" << taker_order->toString() << ")"; return ss.str(); } json Trade::toJson() const { json ret; ret["id"] = id; ret["timestamp"] = format_timestamp(timestamp); ret["volume"] = volume; ret["price"] = price; ret["taker_order"] = taker_order->toJson(); std::vector<json> orders; for (auto order : maker_orders) { orders.push_back(order->toJson()); } ret["maker_orders"] = orders; return ret; } json Trade::perspectiveSchema() const { json ret; ret["id"] = "int"; ret["timestamp"] = "int"; ret["volume"] = "float"; ret["price"] = "float"; // FIXME return ret; } } // namespace core } // namespace aat
21.705882
105
0.585366
ryuuni
c6d0f559171397e1543ba799dcca7fb25ce0b662
7,601
hpp
C++
src/pnp2/include/pnp2/receiver.hpp
rosmod/lib-pnp2
e4087177952a4ddb5413b95efbd65821e725e083
[ "MIT" ]
null
null
null
src/pnp2/include/pnp2/receiver.hpp
rosmod/lib-pnp2
e4087177952a4ddb5413b95efbd65821e725e083
[ "MIT" ]
null
null
null
src/pnp2/include/pnp2/receiver.hpp
rosmod/lib-pnp2
e4087177952a4ddb5413b95efbd65821e725e083
[ "MIT" ]
null
null
null
/** \file receiver.hpp * * This file declares the Network::receiver class */ #ifndef NETWORK_RECEIVER_HPP #define NETWORK_RECEIVER_HPP #include "ros/ros.h" #include <boost/thread/thread.hpp> #include <boost/asio.hpp> #include <boost/bind.hpp> #include "network/NetworkProfile.hpp" #include "network/buffer.hpp" #include "network/oob.hpp" namespace Network { /** Allows for the reception of data through a (possibly fixed-size) buffer at a configurable rate that can vary as a function of time. Optionally enables out-of-band (oob) communication to senders to shut them off if the buffer is filling up too fast. The receiver also records the reception of data (size, time) into memory for later dump to disk. */ class receiver { public: receiver() : enable_sendback(false), received_data(false) { } int init(int argc, char ** argv, std::string prof_str, uint64_t buff_capacity_bits = 0, bool enable_oob = false) { this->buffer_capacity_bits = buff_capacity_bits; profile.initializeFromString((char *)prof_str.c_str()); buffer.set_capacityBits(this->buffer_capacity_bits); set_enable_sendback(enable_oob); if (enable_sendback) init_oob(); boost::thread *tmr_thread = new boost::thread( boost::bind(&receiver::buffer_recv_threadfunc, this) ); return 0; } void add_sender(uint64_t id, std::string profile) { Network::NetworkProfile p; p.initializeFromString((char *)profile.c_str()); uuids.push_back(id); profile_map[id] = p; receive_map[id] = std::map<ros::Time, uint64_t>(); printf("added uuid: %lu\n",id); } void add_sender(std::string profileName) { Network::NetworkProfile p; p.initializeFromFile(profileName.c_str()); uuids.push_back(p.uuid); profile_map[p.uuid] = p; receive_map[p.uuid] = std::map<ros::Time, uint64_t>(); printf("added uuid: %lu\n",p.uuid); } void set_duration(double dur) { duration = ros::Duration(dur); } void set_output_filename(std::string filename) { output_filename = filename; } void set_recv_done_callback(boost::function<void()> func) { callback_func = func; } void set_enable_sendback(bool sendback) { enable_sendback = sendback; } void update_sender_stream(uint64_t uuid, ros::Time t, uint64_t new_size) { uint64_t prevData = 0; if ( receive_map[uuid].size() ) prevData = receive_map[uuid].end()->second; receive_map[uuid][t] = new_size + prevData; } ros::Time get_end_time() const { return ros::Time(endTime); } int init_oob() { sd = socket(AF_INET, SOCK_DGRAM, 0); if(sd < 0) { perror("Opening datagram socket error"); exit(1); } else printf("Opening the datagram socket...OK.\n"); /* Initialize the group sockaddr structure with a */ /* group address of 225.1.1.1 and port 5555. */ memset((char *) &groupSock, 0, sizeof(groupSock)); groupSock.sin_family = AF_INET; groupSock.sin_addr.s_addr = inet_addr(oob_mc_group.c_str()); groupSock.sin_port = htons(oob_mc_port); /* Set local interface for outbound multicast datagrams. */ /* The IP address specified must be associated with a local, */ /* multicast capable interface. */ struct in_addr localInterface; localInterface.s_addr = inet_addr("0.0.0.0"); if(setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localInterface, sizeof(localInterface)) < 0) { perror("Setting local interface error"); exit(1); } else printf("Setting the local interface...OK\n"); } int oob_send(std::vector<uint64_t>& send_uuids, bool val) { int num_disabled = send_uuids.size(); if (!num_disabled) return 0; // FORMAT DATA char msg[(num_disabled+2) * 16]; memset(msg,0,(num_disabled+2)*16); for (auto it = send_uuids.begin(); it != send_uuids.end(); ++it) { sprintf(msg,"%s%lu,%d;", msg, *it, (int)val); } int len = sendto(sd, msg, strlen(msg)+1, 0, (struct sockaddr*)&groupSock, sizeof(groupSock)); return 0; } void buffer_recv_threadfunc(void) { while ( true ) { // UPDATE SENDERS IF BUFFER IS CLEARING: uint64_t currentSize = buffer.bits(); uint64_t currentCapacity = buffer.capacityBits(); if ( currentCapacity > 0 and enable_sendback ) { double utilization = (double)currentSize/(double)currentCapacity; ros::Time now = ros::Time::now(); if ( utilization < 0.75 ) unlimit_ddos(); else if (utilization > 0.9) limit_ddos(now, 1.0); } // READ FROM THE BUFFER double timerDelay = -1; try { Network::Message msg = buffer.receive(1000); if (!received_data) { ros::Time now = ros::Time::now(); endTime = now + duration; received_data = true; } msg.TimeStamp(); messages.push_back(msg); // CHECK AGAINST RECEIVER PROFILE: LOOK UP WHEN I CAN READ NEXT timerDelay = profile.Delay(msg.Bits(), msg.LastEpochTime()); } catch ( Network::Buffer_Empty& ex ) { } if ( received_data and ros::Time::now() >= endTime ) { if (this->callback_func) this->callback_func(); break; } else { // SLEEP UNTIL NEXT TIME BUFFER CAN BE SERVICED if (timerDelay > 0) ros::Duration(timerDelay).sleep(); } } } void record() { printf("writing output\n"); printf("max buffer: %lu\n", buffer.maxBits()); printf("received msgs: %lu\n", messages.size()); Network::write_data(output_filename.c_str(),messages); } int unlimit_ddos(void) { if ( oob_send(disabled_uuids, false) < 0 ) return -1; disabled_uuids.clear(); return 0; } int limit_ddos(ros::Time now, double timeWindow) { std::vector<uint64_t> bad_uuids; ros::Time prevTime = now - ros::Duration(timeWindow); for (auto uuid_it = uuids.begin(); uuid_it != uuids.end(); ++uuid_it) { uint64_t d1 = receive_map[*uuid_it].lower_bound(prevTime)->second; ros::Time t1 = receive_map[*uuid_it].lower_bound(prevTime)->first; uint64_t d2 = receive_map[*uuid_it].end()->second; ros::Time t2 = receive_map[*uuid_it].end()->first; // get data @ t1 from profile, get data @ t2 from profile uint64_t pd1 = profile_map[*uuid_it].getDataAtTime({t1.sec, t1.nsec}); uint64_t pd2 = profile_map[*uuid_it].getDataAtTime({t2.sec, t2.nsec}); // if profile difference < (d2-d1) : they are sending too much uint64_t pDiff = pd2 - pd1; uint64_t diff = d2 - d1; if (diff > pDiff) { bad_uuids.push_back(*uuid_it); if ( std::find(disabled_uuids.begin(), disabled_uuids.end(), *uuid_it) == disabled_uuids.end() ) disabled_uuids.push_back(*uuid_it); } } return oob_send(bad_uuids, true); } public: message_buffer<Network::Message> buffer; Network::NetworkProfile profile; private: std::vector<Network::Message> messages; ros::Duration duration; ros::Time endTime; bool received_data; bool enable_sendback; uint64_t buffer_capacity_bits; int sd; struct sockaddr_in groupSock; boost::function<void()> callback_func; std::string output_filename; std::vector<uint64_t> uuids; std::vector<uint64_t> disabled_uuids; std::map<uint64_t, Network::NetworkProfile> profile_map; std::map<uint64_t, std::map<ros::Time, uint64_t>> receive_map; // uuid - > <time, data> }; }; #endif
29.122605
116
0.641363
rosmod
c6d0fd6c55045844b6e757d3a9bb3720660312f6
1,832
cpp
C++
Plugins/ShowtimeUnreal/Source/ShowtimeRuntime/Private/Tests/ShowtimeClientTest.cpp
straycatss/NectoXR
c7d00fe5070cfd1d94aa9401bb7ef66238d4cae7
[ "MIT" ]
null
null
null
Plugins/ShowtimeUnreal/Source/ShowtimeRuntime/Private/Tests/ShowtimeClientTest.cpp
straycatss/NectoXR
c7d00fe5070cfd1d94aa9401bb7ef66238d4cae7
[ "MIT" ]
null
null
null
Plugins/ShowtimeUnreal/Source/ShowtimeRuntime/Private/Tests/ShowtimeClientTest.cpp
straycatss/NectoXR
c7d00fe5070cfd1d94aa9401bb7ef66238d4cae7
[ "MIT" ]
null
null
null
#include "Misc/AutomationTest.h" #include "ShowtimeClient.h" #include "ShowtimeServer.h" using namespace showtime; BEGIN_DEFINE_SPEC(ShowtimeClientSpec, "ShowtimeRuntimeModule.UShowtimeClient", EAutomationTestFlags::ProductFilter | EAutomationTestFlags::ApplicationContextMask) UShowtimeClient* client; UShowtimeServer* server; END_DEFINE_SPEC(ShowtimeClientSpec) void ShowtimeClientSpec::Define() { BeforeEach([this]() { client = NewObject<UShowtimeClient>(); server = NewObject<UShowtimeServer>(); client->Handle()->init("ue4_client", true); server->Handle()->init(TCHAR_TO_UTF8(*GetBeautifiedTestName())); client->Handle()->auto_join_by_name(TCHAR_TO_UTF8(*GetBeautifiedTestName())); }); Describe("init()", [this](){ It("should return true when successful", [this]() { TestTrue("is_init_completed", client->Handle()->is_init_completed()); }); }); Describe("auto_join_by_name()", [this]() { It("should connect to a broadcasting server", [this]() { TestTrue("is_connected", client->Handle()->is_connected()); }); }); Describe("add_log_adaptor()", [this]() { LatentIt("should capture log records", [this](const FDoneDelegate& Done) { // Log::app(Log::Level::debug, "test"); client->Handle()->poll_once(); Done.Execute(); //BackendService->QueryItems(this, &FMyCustomSpec::HandleQueryItemComplete, Done); }); }); AfterEach([this]() { client->Handle()->destroy(); server->Handle()->destroy(); }); } //void ShowtimeClientSpec::HandleLogRecord(FDoneDelegate Done) //{ // TestEqual("Items.Num() == 5", Items.Num(), 5); // Done.Execute(); //}
32.140351
162
0.615175
straycatss
c6d632f520f712ecea4ff6bc54e8ed18bc6f2906
7,444
cpp
C++
installer/dev/install.cpp
mrlacey/ProjectReunion
1714557cad5e740c0153e451fbf0311c8e5bdfc1
[ "CC-BY-4.0", "MIT" ]
null
null
null
installer/dev/install.cpp
mrlacey/ProjectReunion
1714557cad5e740c0153e451fbf0311c8e5bdfc1
[ "CC-BY-4.0", "MIT" ]
null
null
null
installer/dev/install.cpp
mrlacey/ProjectReunion
1714557cad5e740c0153e451fbf0311c8e5bdfc1
[ "CC-BY-4.0", "MIT" ]
1
2021-03-10T22:19:06.000Z
2021-03-10T22:19:06.000Z
#include "pch.h" #include "packages.h" #include "install.h" using namespace winrt; using namespace Windows::ApplicationModel; using namespace Windows::Foundation; using namespace Windows::Management::Deployment; using namespace Windows::System; namespace ProjectReunionInstaller { winrt::hresult AddPackage(const Uri& packageUri) { PackageManager packageManager; const auto deploymentOperation{ packageManager.AddPackageAsync(packageUri, nullptr, DeploymentOptions::None) }; deploymentOperation.get(); if (deploymentOperation.Status() != AsyncStatus::Completed) { return deploymentOperation.ErrorCode(); } return S_OK; } winrt::hresult ProvisionPackage(const std::wstring& packageFamilyName) { PackageManager packageManager; const auto deploymentOperation{ packageManager.ProvisionPackageForAllUsersAsync(packageFamilyName.c_str()) }; deploymentOperation.get(); if (deploymentOperation.Status() != AsyncStatus::Completed) { return deploymentOperation.ErrorCode(); } return S_OK; } bool IsArchitectureApplicable(const ProcessorArchitecture& arch) { SYSTEM_INFO systemInfo{}; GetNativeSystemInfo(&systemInfo); const auto systemArchitecture{ static_cast<ProcessorArchitecture>(systemInfo.wProcessorArchitecture) }; // Neutral package architecture is applicable on all systems. if (arch == ProcessorArchitecture::Neutral) { return true; } // Same-arch is always applicable. if (arch == systemArchitecture) { return true; } // On x64 systems, x86 architecture is also applicable. if (systemArchitecture == ProcessorArchitecture::X64 && arch == ProcessorArchitecture::X86) { return true; } // On Arm64 systems, all current package architectures are applicable. if (systemArchitecture == ProcessorArchitecture::Arm64) { return true; } return false; } wil::com_ptr<IStream> CreateMemoryStream(const BYTE* data, size_t size) { wil::com_ptr<IStream> retval; retval.attach(::SHCreateMemStream(data, size)); return retval; } wil::com_ptr<IStream> GetResourceStream(const std::wstring& resourceName, const std::wstring& resourceType) { HMODULE const hModule = GetModuleHandle(NULL); HRSRC hResourceSource = ::FindResource(hModule, resourceName.c_str(), resourceType.c_str()); THROW_LAST_ERROR_IF_NULL(hResourceSource); HGLOBAL hResource = LoadResource(hModule, hResourceSource); THROW_LAST_ERROR_IF_NULL(hResource); const BYTE* data = reinterpret_cast<BYTE*>(::LockResource(hResource)); THROW_LAST_ERROR_IF_NULL(data); const DWORD size{ ::SizeofResource(hModule, hResourceSource) }; return CreateMemoryStream(data, size); } std::unique_ptr<PackageProperties> GetPackagePropertiesFromStream(wil::com_ptr<IStream>& stream) { // Get PackageId from the manifest. auto factory = wil::CoCreateInstance<AppxFactory, IAppxFactory>(); wil::com_ptr<IAppxPackageReader> reader; THROW_IF_FAILED(factory->CreatePackageReader(stream.get(), wil::out_param(reader))); wil::com_ptr<IAppxManifestReader> manifest; THROW_IF_FAILED(reader->GetManifest(wil::out_param(manifest))); wil::com_ptr<IAppxManifestPackageId> id; THROW_IF_FAILED(manifest->GetPackageId(&id)); // Populate properties from the manifest PackageId auto properties = std::make_unique<PackageProperties>(); THROW_IF_FAILED(id->GetPackageFullName(&properties->fullName)); THROW_IF_FAILED(id->GetPackageFamilyName(&properties->familyName)); APPX_PACKAGE_ARCHITECTURE arch{}; THROW_IF_FAILED(id->GetArchitecture(&arch)); properties->architecture = static_cast<ProcessorArchitecture>(arch); THROW_IF_FAILED(id->GetVersion(&properties->version)); return properties; } wil::com_ptr<IStream> OpenFileStream(PCWSTR path) { wil::com_ptr<IStream> outstream; THROW_IF_FAILED(SHCreateStreamOnFileEx(path, STGM_WRITE | STGM_READ | STGM_SHARE_DENY_WRITE | STGM_CREATE, FILE_ATTRIBUTE_NORMAL, TRUE, nullptr, wil::out_param(outstream))); return outstream; } void DeployPackageFromResource(const ProjectReunionInstaller::ResourcePackageInfo& resource, const bool quiet) { // Get package properties by loading the resource as a stream and reading the manifest. auto packageStream = GetResourceStream(resource.id, resource.resourceType); auto packageProperties = GetPackagePropertiesFromStream(packageStream); // Skip non-applicable architectures. if (!IsArchitectureApplicable(packageProperties->architecture)) { return; } wchar_t packageFilename[MAX_PATH]; THROW_LAST_ERROR_IF(0 == GetTempFileName(std::filesystem::temp_directory_path().c_str(), L"PRP", 0u, packageFilename)); // GetTempFileName will create the temp file by that name due to the unique parameter being specified. // From here on out if we leave scope for any reason we will attempt to delete that file. auto removeTempFileOnScopeExit = wil::scope_exit([&] { LOG_IF_WIN32_BOOL_FALSE(::DeleteFile(packageFilename)); }); if (!quiet) { std::wcout << "Package Full Name: " << packageProperties->fullName.get() << std::endl; std::wcout << "Temp package path: " << packageFilename << std::endl; } // Write the package to a temp file. The PackageManager APIs require a Uri. wil::com_ptr<IStream> outStream{ OpenFileStream(packageFilename) }; ULARGE_INTEGER streamSize{}; THROW_IF_FAILED(::IStream_Size(packageStream.get(), &streamSize)); THROW_IF_FAILED(packageStream->CopyTo(outStream.get(), streamSize, nullptr, nullptr)); THROW_IF_FAILED(outStream->Commit(STGC_OVERWRITE)); outStream.reset(); // Add the package Uri packageUri{ packageFilename }; hresult hrAddResult = AddPackage(packageUri); if (!quiet) { std::wcout << "Package deployment result : 0x" << std::hex << hrAddResult.value << std::endl; } THROW_IF_FAILED(static_cast<HRESULT>(hrAddResult)); // Provisioning is expected to fail if the program is not run elevated or the user is not admin. hresult hrProvisionResult = ProvisionPackage(packageProperties->familyName.get()); if (!quiet) { std::wcout << "Provisioning result : 0x" << std::hex << hrProvisionResult.value << std::endl; } LOG_IF_FAILED(static_cast<HRESULT>(hrProvisionResult)); return; } HRESULT DeployPackages(bool quiet) noexcept try { for (const auto& package : ProjectReunionInstaller::c_packages) { DeployPackageFromResource(package, quiet); } return S_OK; } CATCH_RETURN() }
39.595745
182
0.650591
mrlacey
c6d67777260dd4575bcbe420163e2ab249931c60
15,948
cpp
C++
source/location/City.cpp
Tomash667/carpg
7e89d83f51cb55a89baf509915a9a9f8c642825f
[ "MIT" ]
19
2015-05-30T12:14:07.000Z
2021-05-26T19:17:21.000Z
source/location/City.cpp
Tomash667/carpg
7e89d83f51cb55a89baf509915a9a9f8c642825f
[ "MIT" ]
402
2016-02-26T08:39:21.000Z
2021-07-06T16:47:16.000Z
source/location/City.cpp
Tomash667/carpg
7e89d83f51cb55a89baf509915a9a9f8c642825f
[ "MIT" ]
21
2015-07-28T14:11:39.000Z
2020-12-11T07:54:09.000Z
#include "Pch.h" #include "City.h" #include "BitStreamFunc.h" #include "BuildingScript.h" #include "Content.h" #include "GameCommon.h" #include "GroundItem.h" #include "Level.h" #include "Object.h" #include "Unit.h" #include "World.h" #include <ResourceManager.h> #include <Terrain.h> //================================================================================================= City::~City() { DeleteElements(inside_buildings); } //================================================================================================= void City::Apply(vector<std::reference_wrapper<LocationPart>>& parts) { parts.push_back(*this); for(InsideBuilding* ib : inside_buildings) parts.push_back(*ib); } //================================================================================================= void City::Save(GameWriter& f) { OutsideLocation::Save(f); f << citizens; f << citizens_world; f << flags; f << variant; if(last_visit == -1) { // list of buildings in this location is generated f << buildings.size(); for(CityBuilding& b : buildings) f << b.building->id; } else { f << entry_points; f << gates; f << buildings.size(); for(CityBuilding& b : buildings) { f << b.building->id; f << b.pt; f << b.unit_pt; f << b.dir; f << b.walk_pt; } f << inside_offset; f << inside_buildings.size(); for(InsideBuilding* b : inside_buildings) b->Save(f); f << quest_mayor; f << quest_mayor_time; f << quest_captain; f << quest_captain_time; f << arena_time; f << arena_pos; } } //================================================================================================= void City::Load(GameReader& f) { OutsideLocation::Load(f); f >> citizens; f >> citizens_world; if(LOAD_VERSION < V_0_12) f >> target; f >> flags; f >> variant; if(last_visit == -1) { // list of buildings in this location is generated uint count; f >> count; buildings.resize(count); for(CityBuilding& b : buildings) { b.building = Building::Get(f.ReadString1()); assert(b.building != nullptr); } } else { f >> entry_points; f >> gates; uint count; f >> count; buildings.resize(count); for(CityBuilding& b : buildings) { b.building = Building::Get(f.ReadString1()); f >> b.pt; f >> b.unit_pt; f >> b.dir; f >> b.walk_pt; assert(b.building != nullptr); if(LOAD_VERSION < V_0_14 && b.building->id == "mages_tower") { const float rot = DirToRot(b.dir); Mesh::Point* point = b.building->mesh->FindPoint("o_s_point"); Vec3 pos; if(b.dir != GDIR_DOWN) { const Matrix m = point->mat * Matrix::RotationY(rot); pos = Vec3::TransformZero(m); } else pos = Vec3::TransformZero(point->mat); pos += Vec3(float(b.pt.x + b.building->shift[b.dir].x) * 2, 0.f, float(b.pt.y + b.building->shift[b.dir].y) * 2); b.walk_pt = pos; game_level->terrain->SetHeightMap(h); game_level->terrain->SetY(b.walk_pt); game_level->terrain->RemoveHeightMap(); } } f >> inside_offset; f >> count; inside_buildings.resize(count); int index = 0; for(InsideBuilding*& b : inside_buildings) { b = new InsideBuilding(index); b->Load(f); b->mine = Int2(b->level_shift.x * 256, b->level_shift.y * 256); b->maxe = b->mine + Int2(256, 256); ++index; } f >> quest_mayor; f >> quest_mayor_time; f >> quest_captain; f >> quest_captain_time; f >> arena_time; f >> arena_pos; } } //================================================================================================= void City::Write(BitStreamWriter& f) { OutsideLocation::Write(f); f.WriteCasted<byte>(flags); f.WriteCasted<byte>(entry_points.size()); for(EntryPoint& entry_point : entry_points) { f << entry_point.exit_region; f << entry_point.exit_y; } f.WriteCasted<byte>(buildings.size()); for(CityBuilding& building : buildings) { f << building.building->id; f << building.pt; f.WriteCasted<byte>(building.dir); } f.WriteCasted<byte>(inside_buildings.size()); for(InsideBuilding* inside_building : inside_buildings) inside_building->Write(f); } //================================================================================================= bool City::Read(BitStreamReader& f) { if(!OutsideLocation::Read(f)) return false; // entry points const int ENTRY_POINT_MIN_SIZE = 20; byte count; f.ReadCasted<byte>(flags); f >> count; if(!f.Ensure(count * ENTRY_POINT_MIN_SIZE)) { Error("Read level: Broken packet for city."); return false; } entry_points.resize(count); for(EntryPoint& entry : entry_points) { f.Read(entry.exit_region); f.Read(entry.exit_y); } if(!f) { Error("Read level: Broken packet for entry points."); return false; } // buildings const int BUILDING_MIN_SIZE = 10; f >> count; if(!f.Ensure(BUILDING_MIN_SIZE * count)) { Error("Read level: Broken packet for buildings count."); return false; } buildings.resize(count); for(CityBuilding& building : buildings) { const string& building_id = f.ReadString1(); f >> building.pt; f.ReadCasted<byte>(building.dir); if(!f) { Error("Read level: Broken packet for buildings."); return false; } building.building = Building::Get(building_id); if(!building.building) { Error("Read level: Invalid building id '%s'.", building_id.c_str()); return false; } } // inside buildings const int INSIDE_BUILDING_MIN_SIZE = 73; f >> count; if(!f.Ensure(INSIDE_BUILDING_MIN_SIZE * count)) { Error("Read level: Broken packet for inside buildings count."); return false; } inside_buildings.resize(count); int index = 0; for(InsideBuilding*& ib : inside_buildings) { ib = new InsideBuilding(index); if(!ib->Read(f)) { Error("Read level: Failed to loading inside building %d.", index); return false; } ++index; } return true; } //================================================================================================= bool City::IsInsideCity(const Vec3& pos) { Int2 tile(int(pos.x / 2), int(pos.z / 2)); if(tile.x <= int(0.15f*size) || tile.y <= int(0.15f*size) || tile.x >= int(0.85f*size) || tile.y >= int(0.85f*size)) return false; else return true; } //================================================================================================= InsideBuilding* City::FindInsideBuilding(Building* building, int* out_index) { assert(building); int index = 0; for(InsideBuilding* i : inside_buildings) { if(i->building == building) { if(out_index) *out_index = index; return i; } ++index; } if(out_index) *out_index = -1; return nullptr; } //================================================================================================= InsideBuilding* City::FindInsideBuilding(BuildingGroup* group, int* out_index) { assert(group); int index = 0; for(InsideBuilding* i : inside_buildings) { if(i->building->group == group) { if(out_index) *out_index = index; return i; } ++index; } if(out_index) *out_index = -1; return nullptr; } //================================================================================================= CityBuilding* City::FindBuilding(BuildingGroup* group, int* out_index) { assert(group); int index = 0; for(CityBuilding& b : buildings) { if(b.building->group == group) { if(out_index) *out_index = index; return &b; } ++index; } if(out_index) *out_index = -1; return nullptr; } //================================================================================================= CityBuilding* City::FindBuilding(Building* building, int* out_index) { assert(building); int index = 0; for(CityBuilding& b : buildings) { if(b.building == building) { if(out_index) *out_index = index; return &b; } ++index; } if(out_index) *out_index = -1; return nullptr; } //================================================================================================= void City::GenerateCityBuildings(vector<Building*>& buildings, bool required) { cstring script_name; switch(target) { default: case CITY: script_name = "city"; break; case CAPITAL: script_name = "capital"; break; case VILLAGE: script_name = "village"; break; } BuildingScript* script = BuildingScript::Get(script_name); if(variant == -1) variant = Rand() % script->variants.size(); BuildingScript::Variant* v = script->variants[variant]; int* code = v->code.data(); int* end = code + v->code.size(); for(uint i = 0; i < BuildingScript::MAX_VARS; ++i) script->vars[i] = 0; script->vars[BuildingScript::V_COUNT] = 1; script->vars[BuildingScript::V_CITIZENS] = citizens; script->vars[BuildingScript::V_CITIZENS_WORLD] = citizens_world; if(!required) code += script->required_offset; vector<int> stack; int if_level = 0, if_depth = 0; int shuffle_start = -1; int& building_count = script->vars[BuildingScript::V_COUNT]; while(code != end) { BuildingScript::Code c = (BuildingScript::Code)*code++; switch(c) { case BuildingScript::BS_ADD_BUILDING: if(if_level == if_depth) { BuildingScript::Code type = (BuildingScript::Code)*code++; if(type == BuildingScript::BS_BUILDING) { Building* b = (Building*)*code++; for(int i = 0; i < building_count; ++i) buildings.push_back(b); } else { BuildingGroup* bg = (BuildingGroup*)*code++; for(int i = 0; i < building_count; ++i) buildings.push_back(RandomItem(bg->buildings)); } } else code += 2; break; case BuildingScript::BS_RANDOM: { uint count = (uint)*code++; if(if_level != if_depth) { code += count * 2; break; } for(int i = 0; i < building_count; ++i) { uint index = Rand() % count; BuildingScript::Code type = (BuildingScript::Code)*(code + index * 2); if(type == BuildingScript::BS_BUILDING) { Building* b = (Building*)*(code + index * 2 + 1); buildings.push_back(b); } else { BuildingGroup* bg = (BuildingGroup*)*(code + index * 2 + 1); buildings.push_back(RandomItem(bg->buildings)); } } code += count * 2; } break; case BuildingScript::BS_SHUFFLE_START: if(if_level == if_depth) shuffle_start = (int)buildings.size(); break; case BuildingScript::BS_SHUFFLE_END: if(if_level == if_depth) { int new_pos = (int)buildings.size(); if(new_pos - shuffle_start >= 2) Shuffle(buildings.begin() + shuffle_start, buildings.end()); shuffle_start = -1; } break; case BuildingScript::BS_REQUIRED_OFF: if(required) goto cleanup; break; case BuildingScript::BS_PUSH_INT: if(if_level == if_depth) stack.push_back(*code++); else ++code; break; case BuildingScript::BS_PUSH_VAR: if(if_level == if_depth) stack.push_back(script->vars[*code++]); else ++code; break; case BuildingScript::BS_SET_VAR: if(if_level == if_depth) { script->vars[*code++] = stack.back(); stack.pop_back(); } else ++code; break; case BuildingScript::BS_INC: if(if_level == if_depth) ++script->vars[*code++]; else ++code; break; case BuildingScript::BS_DEC: if(if_level == if_depth) --script->vars[*code++]; else ++code; break; case BuildingScript::BS_IF: if(if_level == if_depth) { BuildingScript::Code op = (BuildingScript::Code)*code++; int right = stack.back(); stack.pop_back(); int left = stack.back(); stack.pop_back(); bool ok = false; switch(op) { case BuildingScript::BS_EQUAL: ok = (left == right); break; case BuildingScript::BS_NOT_EQUAL: ok = (left != right); break; case BuildingScript::BS_GREATER: ok = (left > right); break; case BuildingScript::BS_GREATER_EQUAL: ok = (left >= right); break; case BuildingScript::BS_LESS: ok = (left < right); break; case BuildingScript::BS_LESS_EQUAL: ok = (left <= right); break; } ++if_level; if(ok) ++if_depth; } else { ++code; ++if_level; } break; case BuildingScript::BS_IF_RAND: if(if_level == if_depth) { int a = stack.back(); stack.pop_back(); if(a > 0 && Rand() % a == 0) ++if_depth; } ++if_level; break; case BuildingScript::BS_ELSE: if(if_level == if_depth) --if_depth; break; case BuildingScript::BS_ENDIF: if(if_level == if_depth) --if_depth; --if_level; break; case BuildingScript::BS_CALL: case BuildingScript::BS_ADD: case BuildingScript::BS_SUB: case BuildingScript::BS_MUL: case BuildingScript::BS_DIV: if(if_level == if_depth) { int b = stack.back(); stack.pop_back(); int a = stack.back(); stack.pop_back(); int result = 0; switch(c) { case BuildingScript::BS_CALL: if(a == b) result = a; else if(b > a) result = Random(a, b); break; case BuildingScript::BS_ADD: result = a + b; break; case BuildingScript::BS_SUB: result = a - b; break; case BuildingScript::BS_MUL: result = a * b; break; case BuildingScript::BS_DIV: if(b != 0) result = a / b; break; } stack.push_back(result); } break; case BuildingScript::BS_NEG: if(if_level == if_depth) stack.back() = -stack.back(); break; } } cleanup: citizens = script->vars[BuildingScript::V_CITIZENS]; citizens_world = script->vars[BuildingScript::V_CITIZENS_WORLD]; } //================================================================================================= void City::GetEntry(Vec3& pos, float& rot) { if(entry_points.size() == 1) { pos = entry_points[0].spawn_region.Midpoint().XZ(); rot = entry_points[0].spawn_rot; } else { // check which spawn rot i closest to entry rot float best_dif = 999.f; int best_index = -1, index = 0; float dir = ConvertNewAngleToOld(world->GetTravelDir()); for(vector<EntryPoint>::iterator it = entry_points.begin(), end = entry_points.end(); it != end; ++it, ++index) { float dif = AngleDiff(dir, it->spawn_rot); if(dif < best_dif) { best_dif = dif; best_index = index; } } pos = entry_points[best_index].spawn_region.Midpoint().XZ(); rot = entry_points[best_index].spawn_rot; } } //================================================================================================= void City::PrepareCityBuildings(vector<ToBuild>& tobuild) { // required buildings tobuild.reserve(buildings.size()); for(CityBuilding& cb : buildings) tobuild.push_back(ToBuild(cb.building, true)); buildings.clear(); // not required buildings LocalVector<Building*> buildings; GenerateCityBuildings(buildings.Get(), false); tobuild.reserve(tobuild.size() + buildings.size()); for(Building* b : buildings) tobuild.push_back(ToBuild(b, false)); // set flags for(ToBuild& tb : tobuild) { if(tb.building->group == BuildingGroup::BG_TRAINING_GROUNDS) flags |= HaveTrainingGrounds; else if(tb.building->group == BuildingGroup::BG_BLACKSMITH) flags |= HaveBlacksmith; else if(tb.building->group == BuildingGroup::BG_MERCHANT) flags |= HaveMerchant; else if(tb.building->group == BuildingGroup::BG_ALCHEMIST) flags |= HaveAlchemist; else if(tb.building->group == BuildingGroup::BG_FOOD_SELLER) flags |= HaveFoodSeller; else if(tb.building->group == BuildingGroup::BG_INN) flags |= HaveInn; else if(tb.building->group == BuildingGroup::BG_ARENA) flags |= HaveArena; } } //================================================================================================= Vec3 CityBuilding::GetUnitPos() { return Vec3(float(unit_pt.x) * 2 + 1, 0, float(unit_pt.y) * 2 + 1); } //================================================================================================= float CityBuilding::GetUnitRot() { return DirToRot(dir); }
23.591716
117
0.57468
Tomash667
c6d7392e21965efda5c3c8f814ec2e5932d5726f
2,793
cpp
C++
WebKit2-7534.57.7/WebKit2-7534.57.7/UIProcess/qt/ChunkedUpdateDrawingAreaProxyQt.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7534.57.7/WebKit2-7534.57.7/UIProcess/qt/ChunkedUpdateDrawingAreaProxyQt.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7534.57.7/WebKit2-7534.57.7/UIProcess/qt/ChunkedUpdateDrawingAreaProxyQt.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) * * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "ChunkedUpdateDrawingAreaProxy.h" #include "DrawingAreaMessageKinds.h" #include "DrawingAreaProxyMessageKinds.h" #include "UpdateChunk.h" #include "WKAPICast.h" #include "WebPageProxy.h" #include "qgraphicswkview.h" #include <QPainter> using namespace WebCore; namespace WebKit { WebPageProxy* ChunkedUpdateDrawingAreaProxy::page() const { return toImpl(m_webView->page()->pageRef()); } void ChunkedUpdateDrawingAreaProxy::ensureBackingStore() { if (!m_backingStoreImage.isNull()) return; m_backingStoreImage = QImage(size().width(), size().height(), QImage::Format_RGB32); } void ChunkedUpdateDrawingAreaProxy::invalidateBackingStore() { m_backingStoreImage = QImage(); } bool ChunkedUpdateDrawingAreaProxy::platformPaint(const IntRect& rect, QPainter* painter) { if (m_backingStoreImage.isNull()) return false; painter->drawImage(QPoint(0, 0), m_backingStoreImage); return true; } void ChunkedUpdateDrawingAreaProxy::drawUpdateChunkIntoBackingStore(UpdateChunk* updateChunk) { ensureBackingStore(); QImage image(updateChunk->createImage()); const IntRect& updateChunkRect = updateChunk->rect(); QPainter painter(&m_backingStoreImage); painter.drawImage(updateChunkRect.location(), image); m_webView->update(QRect(updateChunkRect)); } } // namespace WebKit
33.650602
93
0.758324
mlcldh
c6d8fe023ee8b7cc93adbf56dc053594520b514f
34
hpp
C++
Blik2D/addon/blik_addon_zip.hpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
13
2017-02-22T02:20:06.000Z
2018-06-06T04:18:03.000Z
Blik2D/addon/blik_addon_zip.hpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
null
null
null
Blik2D/addon/blik_addon_zip.hpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
null
null
null
#pragma once #include <blik.hpp>
11.333333
19
0.705882
BonexGu
c6d926c83c98c23c7e224343eb3578e79193f343
15,018
hpp
C++
include/flusspferd/object.hpp
Flusspferd/flusspferd
f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5
[ "MIT" ]
7
2015-06-08T09:59:36.000Z
2021-02-27T18:45:17.000Z
include/flusspferd/object.hpp
Flusspferd/flusspferd
f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5
[ "MIT" ]
null
null
null
include/flusspferd/object.hpp
Flusspferd/flusspferd
f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5
[ "MIT" ]
3
2016-07-06T20:47:01.000Z
2021-06-30T19:09:47.000Z
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) 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 FLUSSPFERD_OBJECT_HPP #define FLUSSPFERD_OBJECT_HPP #ifndef PREPROC_DEBUG #include "spidermonkey/object.hpp" #include "property_attributes.hpp" #include "arguments.hpp" #include "value.hpp" #include "convert.hpp" //#include "string.hpp" #include <string> #include <memory> #endif #include "detail/limit.hpp" #include <boost/preprocessor.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/utility/enable_if.hpp> namespace flusspferd { #ifndef PREPROC_DEBUG class string; class value; class context; class native_object_base; class property_iterator; template<typename> class convert; #endif /** * A Javascript object. * * @see flusspferd::create_object() * * @ingroup value_types * @ingroup property_types */ class object : public Impl::object_impl { public: #ifndef PREPROC_DEBUG /** * Construct a new <code>null</code> object. * * Use flusspferd::create_object() to create a simple object. */ object(); #ifndef IN_DOXYGEN object(Impl::object_impl const &o) : Impl::object_impl(o) { } #endif /// Destructor. ~object(); /** * Check if the object is null. * * @return Whether the object is null. */ bool is_null() const; /** * Check if the object is an array. * * @return Whether the object is an array. */ bool is_array() const; /** * Check if the object is a generator (i.e. return from a function which uses * yield). Due to limitations in the current Spidermonkey API there is a very * small chance this cant return true erroneously, but only if someone has * gone out of their way to make it happen. * * @return Whether the object is a generator. */ bool is_generator() const; /** * Check if an object is an instance of the given constructor. * * @param constructor The constructor (not a string!). * @return Whether the object is an instance of the constructor. */ bool instance_of(value constructor) const; /** * Seal the object. * * @param deep Whether to seal all reachable sub-objects, too. */ void seal(bool deep); /// Get the object's parent (__parent__). object parent() const; /// Get the object's prototype (__proto__). object prototype() const; /// Get the object's constructor. object constructor() const; /** * Set the object's parent (__parent__). * * @param parent The object to set the parent to. */ void set_parent(object const &parent); /** * Set the object's prototype (__proto__). * * @param prototype The object to set the prototype to. */ void set_prototype(object const &prototype); #endif /** * @name Method / function invocation * * Calling methods and functions. */ //@{ /** * Check whether the object is a function. */ bool is_function() const; /** * Determine the arity. */ unsigned function_arity() const; /** * Determine the function name. */ string function_name() const; /** * Apply a function to this object. * * @param fn The function to apply to this object. * @param arg The function arguments. * @return The function's return value. */ value apply(object const &fn, arguments const &arg); /** * Call an object method. * * @param name The method name. * @param arg The %function %arguments. * @return The method's return value. */ value call(char const *name, arguments const &arg); /** * Call an object method. * * @param name The method name. * @param arg The %function %arguments. * @return The method's return value. */ value call(std::string const &name, arguments const &arg); /** * Call this object as a %function and apply it to @p obj. * * @param obj The object to apply this %function to. * @param arg The %function %arguments. * @return The %function's return value. */ value call(object obj, arguments const &arg); /** * Call this object as a function on the global object. * * @param arg The %function %arguments. * @return The %function's return value. */ value call(arguments const &arg = arguments()); #ifndef IN_DOXYGEN #define FLUSSPFERD_CALL_N(z, n, d) \ FLUSSPFERD_CALL_N_2( \ n, \ BOOST_PP_TUPLE_ELEM(2, 0, d), \ BOOST_PP_TUPLE_ELEM(2, 1, d)) \ /* */ #define FLUSSPFERD_CALL_N_2(n, f_name, arg_type) \ BOOST_PP_EXPR_IF(n, template<) \ BOOST_PP_ENUM_PARAMS(n, typename T) \ BOOST_PP_EXPR_IF(n, >) \ value f_name( \ arg_type x \ BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n, T, const &arg)) \ { \ arguments arg; \ BOOST_PP_REPEAT(n, FLUSSPFERD_CALL_ADD_PARAM, ~) \ return f_name(x, arg); \ } \ /* */ #define FLUSSPFERD_CALL_ADD_PARAM(z, n, d) \ typename convert<BOOST_PP_CAT(T, n) const &>::to_value BOOST_PP_CAT(c, n); \ arg.push_root(BOOST_PP_CAT(c, n).perform(BOOST_PP_CAT(arg, n))); \ /* */ #define FLUSSPFERD_CALLS(name, arg_type) \ BOOST_PP_REPEAT( \ BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT), \ FLUSSPFERD_CALL_N, \ (name, arg_type)) FLUSSPFERD_CALLS(apply, object const &) FLUSSPFERD_CALLS(call, char const *) FLUSSPFERD_CALLS(call, std::string const &) FLUSSPFERD_CALLS(call, object const &) #else // IN_DOXYGEN /** * Apply a %function to this object. * * @param fn The %function to apply to this object. * @param ... The %function %arguments. * @return The function's return value. */ value apply(object const &fn, ...); /** * Call an object method. * * @param name The method name. * @param ... The %function %arguments. * @return The method's return value. */ value call(char const *name, ...); /** * Call an object method. * * @param name The method name. * @param ... The %function %arguments. * @return The method's return value. */ value call(std::string const &name, ...); /** * Call this object as a %function and apply it to @p obj. * * @param obj The object to apply this %function to. * @param ... The %function %arguments. * @return The function's return value. */ value call(object const &obj, ...); #endif //@} #ifndef PREPROC_DEBUG /** * @name Properties * * Accessing properties and their attributes. */ //@{ /** * Define a property. * * @param name The property's name. * @param init_value The initial value. * @param attrs The property's attributes. */ void define_property( string const &name, value const &init_value = value(), property_attributes const &attrs = property_attributes()); /** * Define a property. * * @param id The property's ID. * @param init_value The initial value. * @param attrs The property's attributes. */ void define_property( value const &id, value const &init_value = value(), property_attributes const &attrs = property_attributes()); /** * Define a property. * * The property will be initialised with <code>undefined</code>. * * @param name The property's name. * @param attrs The property's attributes. */ void define_property( string const &name, property_attributes const &attrs) { return define_property(name, value(), attrs); } private: class define_property_helper { object &obj; property_attributes attr; public: define_property_helper(object &obj, property_attributes const &attr) : obj(obj), attr(attr) {} template<typename T> define_property_helper operator()(T const &id) { obj.define_property(id, attr); return *this; } template<typename T, typename U> define_property_helper operator()(T const &id, U const &v) { obj.define_property(id, flusspferd::value(v), attr); return *this; } }; public: /** * Define multiple properties. * * Example: * @code obj.define_properties(read_only_property)("name1", value1)("name2", value2)("name3"); @endcode * * @param attr The property attributes. */ define_property_helper define_properties(property_attributes const &attr = property_attributes()) { return define_property_helper(*this, attr); } /** * Get a property's attributes. * * @param id The property's name / ID. * @return The attributes or boost::none if property does not exist. */ boost::optional<property_attributes> get_property_attributes(string const &id) const; /** * Get a property's attributes. * * @param id The property's ID. * @param[out] attrs The property's attributes. * @return The attributes or boost::none if property does not exist. */ boost::optional<property_attributes> get_property_attributes(value const &id) const; /** * Set a property. * * @param name The property's name. * @param v The new value. * @return @p v */ value set_property(char const *name, value const &v); /** * Set a property. * * @param name The property's name. * @param v The new value. * @return @p v */ value set_property(std::string const &name, value const &v); /** * Set a property. * * @param id The property's name / ID. * @param v The new value. * @return @p v */ value set_property(value const &id, value const &v); /** * Set a property. * * @param id The property's name / ID. * @param v The new value. * @return @p v */ template<typename T, typename U> value set_property(T const &id, U const &v #ifndef IN_DOXYGEN , typename boost::disable_if<boost::is_same<U, value> >::type * = 0 #endif ) { return set_property(id, value(v)); } private: struct set_property_helper { object &obj; set_property_helper(object &obj) : obj(obj) {} template<typename T, typename U> set_property_helper operator()(T const &id, U const &v) { obj.set_property(id, v); return *this; } }; public: /** * Set multiple properties. * * Example: * @code obj.set_properties("name1", value1)("name2", value2); @endcode * * @param id The first property's name / ID. * @param v The new value for the first property. */ template<typename T, typename U> set_property_helper set_properties(T const &id, U const &v) { return set_property_helper(*this)(id, v); } /** * Get a property. * * @param name The property's name. * @return The current value. */ value get_property(char const *name) const; /** * Get a property. * * @param name The property's name. * @return The current value. */ value get_property(std::string const &name) const; /** * Get a property. * * @param id The property's name / ID. * @return The current value. */ value get_property(value const &id) const; /** * Get a property (as an object). * * @param id The property's name / ID. * @return The current value (as an object). */ template<typename T> object get_property_object(T const &id) const { return get_property(id).to_object(); } /** * Check whether a property exists on the object or any of its prototypes. * * @param name The property's name. * @return Whether the property exists. */ bool has_property(char const *name) const; /** * Check whether a property exists on the object or any of its prototypes. * * @param name The property's name. * @return Whether the property exists. */ bool has_property(std::string const &name) const; /** * Check whether a property exists on the object or any of its prototypes. * * @param id The property's name / ID. * @return Whether the property exists. */ bool has_property(value const &id) const; /** * Check whether a property exists directly on the object. * * @param name The property's name. * @return Whether the property exists. */ bool has_own_property(char const *name) const; /** * Check whether a property exists directly on the object. * * @param name The property's name. * @return Whether the property exists. */ bool has_own_property(std::string const &name) const; /** * Check whether a property exists directly on the object. * * @param id The property's name / ID. * @return Whether the property exists. */ bool has_own_property(value const &id) const; /** * Delete a property from the object. * * @param name The property's name. */ void delete_property(char const *name); /** * Delete a property from the object. * * @param name The property's name. */ void delete_property(std::string const &name); /** * Delete a property from the object. * * @param id The property's name / ID. */ void delete_property(value const &id); /** * Return a property_iterator to the first property (in arbitrary order). * * @return The property_iterator to the first property. */ property_iterator begin() const; /** * Return a property_iterator to behind the last property * (in arbitrary order). * * @return The property_iterator to behind the last property. */ property_iterator end() const; //@} #endif }; #ifndef PREPROC_DEBUG /** * Compare two object%s for equality. * * @relates object */ inline bool operator==(object const &a, object const &b) { return Impl::operator==(a, b); } /** * Compare two object%s for inequality. * * @relates object */ inline bool operator!=(object const &a, object const &b) { return Impl::operator!=(a, b); } template<> struct detail::convert<object> { typedef to_value_helper<object> to_value; struct from_value { root_value root; object perform(value const &v) { object o = v.to_object(); root = o; return o; } }; }; #endif } #endif /* FLUSSPFERD_OBJECT_HPP */
23.914013
101
0.657811
Flusspferd
c6de1a1d53d1bc5743f253b22849aa0c1993565b
2,649
cpp
C++
sp/src/game/server/hl2/grenade_frag.cpp
95Navigator/insolence-2013
d6f75214602a4e14b51a5abf8af0355f679ae94d
[ "Unlicense" ]
11
2018-11-04T16:19:35.000Z
2020-11-21T22:03:16.000Z
sp/src/game/server/hl2/grenade_frag.cpp
95Navigator/insolence-2013
d6f75214602a4e14b51a5abf8af0355f679ae94d
[ "Unlicense" ]
null
null
null
sp/src/game/server/hl2/grenade_frag.cpp
95Navigator/insolence-2013
d6f75214602a4e14b51a5abf8af0355f679ae94d
[ "Unlicense" ]
null
null
null
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "basegrenade_shared.h" #include "grenade_frag.h" ConVar sk_plr_dmg_fraggrenade ( "sk_plr_dmg_fraggrenade","0"); ConVar sk_npc_dmg_fraggrenade ( "sk_npc_dmg_fraggrenade","0"); ConVar sk_fraggrenade_radius ( "sk_fraggrenade_radius", "0"); #define GRENADE_MODEL "models/Weapons/w_grenade.mdl" class CGrenadeFrag : public CBaseGrenade { DECLARE_CLASS( CGrenadeFrag, CBaseGrenade ); public: void Spawn( void ); void Precache( void ); bool CreateVPhysics( void ); void SetTimer( float timer ); void SetVelocity( const Vector &velocity, const AngularImpulse &angVelocity ); void TakeDamage( const CTakeDamageInfo &inputInfo ); }; LINK_ENTITY_TO_CLASS( npc_grenade_frag, CGrenadeFrag ); void CGrenadeFrag::Spawn( void ) { Precache( ); SetModel( GRENADE_MODEL ); m_flDamage = sk_plr_dmg_fraggrenade.GetFloat(); m_DmgRadius = sk_fraggrenade_radius.GetFloat(); m_takedamage = DAMAGE_YES; m_iHealth = 1; CreateVPhysics(); } bool CGrenadeFrag::CreateVPhysics() { // Create the object in the physics system VPhysicsInitNormal( SOLID_BBOX, 0, false ); return true; } void CGrenadeFrag::Precache( void ) { engine->PrecacheModel( GRENADE_MODEL ); BaseClass::Precache(); } void CGrenadeFrag::SetTimer( float timer ) { SetThink( &CGrenadeFrag::PreDetonate ); SetNextThink( gpGlobals->curtime + timer ); } void CGrenadeFrag::SetVelocity( const Vector &velocity, const AngularImpulse &angVelocity ) { IPhysicsObject *pPhysicsObject = VPhysicsGetObject(); if ( pPhysicsObject ) { pPhysicsObject->AddVelocity( &velocity, &angVelocity ); } } void CGrenadeFrag::TakeDamage( const CTakeDamageInfo &inputInfo ) { // Grenades only suffer blast damage and burn damage. if( !(inputInfo.GetDamageType() & (DMG_BLAST|DMG_BURN) ) ) return; BaseClass::TakeDamage( inputInfo ); } CBaseGrenade *Fraggrenade_Create( const Vector &position, const QAngle &angles, const Vector &velocity, const AngularImpulse &angVelocity, CBaseEntity *pOwner, float timer ) { CGrenadeFrag *pGrenade = (CGrenadeFrag *)CBaseEntity::Create( "npc_grenade_frag", position, angles, pOwner ); // Set the timer for 1 second less than requested. We're going to issue a SOUND_DANGER // one second before detonation. pGrenade->SetTimer( timer - 1.5 ); pGrenade->SetVelocity( velocity, angVelocity ); pGrenade->SetThrower( ToBaseCombatCharacter( pOwner ) ); pGrenade->m_takedamage = DAMAGE_YES; return pGrenade; }
26.49
173
0.718384
95Navigator
c6e6afe9f878920511da2aa0c613f196fb9b4732
7,565
hpp
C++
mcppalloc_sparse/mcppalloc_sparse/include/mcppalloc/mcppalloc_sparse/allocator_block.hpp
garyfurnish/mcppalloc
5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf
[ "MIT" ]
null
null
null
mcppalloc_sparse/mcppalloc_sparse/include/mcppalloc/mcppalloc_sparse/allocator_block.hpp
garyfurnish/mcppalloc
5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf
[ "MIT" ]
null
null
null
mcppalloc_sparse/mcppalloc_sparse/include/mcppalloc/mcppalloc_sparse/allocator_block.hpp
garyfurnish/mcppalloc
5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf
[ "MIT" ]
null
null
null
#pragma once #include "sparse_allocator_block_base.hpp" #include <algorithm> #include <mcppalloc/block.hpp> #include <mcppalloc/default_allocator_policy.hpp> #include <mcpputil/mcpputil/boost/property_tree/ptree_fwd.hpp> #include <mcpputil/mcpputil/container.hpp> #include <mcpputil/mcpputil/make_unique.hpp> #include <string> #include <vector> namespace mcppalloc { template <typename Policy, typename OS> auto get_allocated_memory(const ::std::tuple<block_t<Policy>, OS *> &allocation) { return ::std::get<0>(allocation).m_ptr; } template <typename Policy, typename OS> auto get_allocated_size(const ::std::tuple<block_t<Policy>, OS *> &allocation) { return ::std::get<0>(allocation).m_size; } template <typename Policy, typename OS> bool allocation_valid(const ::std::tuple<block_t<Policy>, OS *> &allocation) { return nullptr != get_allocated_memory(allocation); } template <typename Policy, typename OS> auto get_allocation_object_state(const ::std::tuple<block_t<Policy>, OS *> &allocation) { return ::std::get<1>(allocation); } namespace sparse::details { struct default_sparse_allocator_block_policy_t { using byte_pointer_type = uint8_t *; using size_type = size_t; }; /** * \brief Allocator block. * * This is designed to be moved to where it is used for cache linearity. * The fields in this should be organized to maximize cache hits. * This class is incredibly cache layout sensitive. * * Internally this implements a linked list of object_state_t followed by data. * The last valid object_state_t always points to an object_state_t at end(). **/ template <typename Allocator_Policy> class allocator_block_t : public sparse_allocator_block_base_t<default_sparse_allocator_block_policy_t> { public: using size_type = size_t; using allocator_policy_type = Allocator_Policy; static_assert(::std::is_base_of<allocator_policy_tag_t, allocator_policy_type>::value, "Allocator policy must be allocator_policy"); using allocator = typename allocator_policy_type::internal_allocator_type; using user_data_type = typename allocator_policy_type::user_data_type; using object_state_type = ::mcppalloc::details::object_state_t<allocator_policy_type>; static user_data_type s_default_user_data; using block_type = block_t<allocator_policy_type>; using allocation_return_type = ::std::tuple<block_type, object_state_type *>; allocator_block_t() = default; /** * \brief Constructor * @param start Start of memory block that this allocator uses. * @param length Length of memory block that this allocator uses * @param minimum_alloc_length Minimum length of object that can be allocated using this allocator. * @param maximum_alloc_length Maximum length of object that can be allocated using this allocator. **/ MCPPALLOC_ALWAYS_INLINE allocator_block_t(void *start, size_t length, size_t minimum_alloc_length, size_t maximum_alloc_length) noexcept; allocator_block_t(const allocator_block_t &) = delete; MCPPALLOC_ALWAYS_INLINE allocator_block_t(allocator_block_t &&) noexcept; allocator_block_t &operator=(const allocator_block_t &) = delete; MCPPALLOC_ALWAYS_INLINE allocator_block_t &operator=(allocator_block_t &&) noexcept; ~allocator_block_t(); /** * \brief Allocate size bytes on the block. * * @return Valid pointer if possible, nullptr otherwise. **/ auto allocate(size_t size) -> allocation_return_type; /** * \brief Destroy a v that is on the block. * * The usual cause of failure would be the pointer not being in the block. * @return True on success, false on failure. **/ bool destroy(void *v); /** * \brief Destroy a v that is on the block. * * The usual cause of failure would be the pointer not being in the block. * @param v Pointer to destroy. * @param last_collapsed_size Max size of allocation made available by destroying. * @param last_max_alloc_available Return the previous last max alloc available. * @return True on success, false on failure. **/ bool destroy(void *v, size_t &last_collapsed_size, size_t &last_max_alloc_available); /** * \brief Collect any adjacent blocks that may have formed into one block. * @param num_quasifreed Increment by number of quasifreed found. **/ void collect(size_t &num_quasifreed); /** * \brief Return the maximum allocation size available. **/ size_t max_alloc_available(); /** * \brief Verify object state os. * * Code may optimize out in release mode. * @param state Object state to verify. **/ void _verify(const object_state_type *state); /** * \brief Clear all control structures and invalidate. **/ void clear(); /** * \brief Return true if no more allocations can be performed. **/ bool full() const noexcept; /** * \brief Return minimum object allocation length. **/ size_t minimum_allocation_length() const; /** * \brief Return maximum object allocation length. **/ size_t maximum_allocation_length() const; /** * \brief Return updated last max alloc available. **/ size_t last_max_alloc_available() const noexcept; /** * \brief Return the bytes of secondary memory used. **/ size_t secondary_memory_used() const noexcept; /** * \brief Shrink secondary data structures to fit. **/ void shrink_secondary_memory_usage_to_fit(); /** * \brief Put information about abs into a property tree. * @param level Level of information to give. Higher is more verbose. **/ void to_ptree(::boost::property_tree::ptree &ptree, int level) const; public: /** * \brief Default user data option. * * The allocated memory is stored in control allocator. **/ mcpputil::allocator_unique_ptr_t<user_data_type, allocator> m_default_user_data; /** * \brief Updated last max alloc available. * * Designed to sync with allocator block sets. **/ size_t m_last_max_alloc_available = 0; /** * \brief Maximum object allocation length. * * This is at end as it is not needed for allocation (cache allignment). **/ size_t m_maximum_alloc_length = 0; /** * \brief Free list for this block. * * Uses control allocator for control data. **/ ::boost::container::flat_set<mcppalloc::details::object_state_base_t *, mcppalloc::details::os_size_compare, typename allocator::template rebind<mcppalloc::details::object_state_base_t *>::other> m_free_list; }; template <typename Allocator_Policy> inline bool allocator_block_t<Allocator_Policy>::full() const noexcept { return m_next_alloc_ptr == nullptr && m_free_list.empty(); } template <typename Block_Policy> void allocator_block_t<Block_Policy>::clear() { m_free_list.clear(); m_next_alloc_ptr = nullptr; m_end = nullptr; m_start = nullptr; } } } #include "allocator_block_impl.hpp"
38.207071
121
0.665169
garyfurnish
c6e6aff7b869e946e8ce197c512959410aa8f360
2,344
hpp
C++
LAStools/LASlib/inc/lasreaderstored.hpp
RohitDhankar/dcGIS
835c66edd319372b590c0c7b92450694ff8920cd
[ "MIT" ]
null
null
null
LAStools/LASlib/inc/lasreaderstored.hpp
RohitDhankar/dcGIS
835c66edd319372b590c0c7b92450694ff8920cd
[ "MIT" ]
null
null
null
LAStools/LASlib/inc/lasreaderstored.hpp
RohitDhankar/dcGIS
835c66edd319372b590c0c7b92450694ff8920cd
[ "MIT" ]
null
null
null
/* =============================================================================== FILE: lasreaderstored.hpp CONTENTS: Reads LiDAR points from another LASreader and stores them in compressed form so they can be read from memory on the second read. This is especially used for piping LiDAR from one process to another for those modules that perform two reading passes over the input. PROGRAMMERS: martin.isenburg@rapidlasso.com - http://rapidlasso.com COPYRIGHT: (c) 2007-2017, martin isenburg, rapidlasso - fast tools to catch reality This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the LICENSE.txt file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: 9 December 2017 -- created at Octopus Resort on Waya Island in Fiji =============================================================================== */ #ifndef LAS_READER_STORED_HPP #define LAS_READER_STORED_HPP #include "lasreader.hpp" #include "laswriter.hpp" #include "bytestreamin_array.hpp" #include "bytestreamout_array.hpp" class LASreaderStored : public LASreader { public: BOOL open(LASreader* lasreader); BOOL reopen(); LASreader* get_lasreader() const { return lasreader; }; I32 get_format() const; void set_index(LASindex* index); LASindex* get_index() const; void set_filter(LASfilter* filter); void set_transform(LAStransform* transform); BOOL inside_tile(const F32 ll_x, const F32 ll_y, const F32 size); BOOL inside_circle(const F64 center_x, const F64 center_y, const F64 radius); BOOL inside_rectangle(const F64 min_x, const F64 min_y, const F64 max_x, const F64 max_y); BOOL seek(const I64 p_index){ return FALSE; }; ByteStreamIn* get_stream() const { return 0; }; void close(BOOL close_stream=TRUE); LASreaderStored(); ~LASreaderStored(); protected: BOOL read_point_default(); private: LASreader* lasreader; LASwriter* laswriter; ByteStreamInArray* streaminarray; ByteStreamOutArray* streamoutarray; }; #endif
29.3
93
0.671928
RohitDhankar
c6e769d7965258076e7d507f9d20465a263dfad2
1,926
cc
C++
bench/x16-transpose.cc
arkhadem/XNNPACK
276871c0d32e2779e485af07fbdeda565d8794ed
[ "BSD-3-Clause" ]
null
null
null
bench/x16-transpose.cc
arkhadem/XNNPACK
276871c0d32e2779e485af07fbdeda565d8794ed
[ "BSD-3-Clause" ]
null
null
null
bench/x16-transpose.cc
arkhadem/XNNPACK
276871c0d32e2779e485af07fbdeda565d8794ed
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <xnnpack/AlignedAllocator.h> #include <xnnpack/common.h> #include <xnnpack/params.h> #include <xnnpack/transpose.h> #include <algorithm> #include <cmath> #include <functional> #include <random> #include <vector> #include "bench/utils.h" #include <benchmark/benchmark.h> static void x16_transpose( benchmark::State& state, xnn_x16_transpose_ukernel_function transpose, size_t ukernel_size, benchmark::utils::IsaCheckFunction isa_check = nullptr) { if (isa_check && !isa_check(state)) { return; } std::random_device random_device; auto rng = std::mt19937(random_device()); auto u16rng = std::bind(std::uniform_int_distribution<uint16_t>(), rng); const size_t ukernel_bytes = ukernel_size * sizeof(uint16_t); std::vector<uint16_t, AlignedAllocator<uint16_t, 64>> x( ukernel_size * ukernel_size + XNN_EXTRA_BYTES / sizeof(uint16_t)); std::vector<uint16_t, AlignedAllocator<uint16_t, 64>> y( ukernel_size * ukernel_size + XNN_EXTRA_BYTES / sizeof(uint16_t)); std::generate(x.begin(), x.end(), std::ref(u16rng)); std::fill(y.begin(), y.end(), 0); for (auto _ : state) { transpose(x.data(), y.data(), ukernel_bytes, ukernel_bytes, ukernel_size, ukernel_size); } const uint64_t cpu_frequency = benchmark::utils::GetCurrentCpuFrequency(); if (cpu_frequency != 0) { state.counters["cpufreq"] = cpu_frequency; } } #if XNN_ARCH_X86 || XNN_ARCH_X86_64 BENCHMARK_CAPTURE(x16_transpose, sse2_32, xnn_x16_transpose_ukernel__4x8_sse2, 32) ->UseRealTime(); BENCHMARK_CAPTURE(x16_transpose, sse2_117, xnn_x16_transpose_ukernel__4x8_sse2, 117) ->UseRealTime(); #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #ifndef XNNPACK_BENCHMARK_NO_MAIN BENCHMARK_MAIN(); #endif
31.064516
86
0.727414
arkhadem
c6e9aad65719f1f86f7426a63249dd3065a42239
6,016
cpp
C++
src/receptor.cpp
annanguyen99/FixedRandom_idock
5e4a7705836e22da93bf9962ba5ea4092a08a05d
[ "Apache-2.0" ]
37
2015-02-11T02:24:36.000Z
2022-01-19T13:41:25.000Z
src/receptor.cpp
annanguyen99/FixedRandom_idock
5e4a7705836e22da93bf9962ba5ea4092a08a05d
[ "Apache-2.0" ]
30
2015-02-01T07:21:24.000Z
2021-03-27T12:27:28.000Z
src/receptor.cpp
annanguyen99/FixedRandom_idock
5e4a7705836e22da93bf9962ba5ea4092a08a05d
[ "Apache-2.0" ]
23
2017-04-02T20:16:38.000Z
2022-03-30T13:21:20.000Z
#include <cmath> #include <boost/filesystem/fstream.hpp> #include "array.hpp" #include "scoring_function.hpp" #include "receptor.hpp" receptor::receptor(const path& p, const array<float, 3>& center, const array<float, 3>& size, const float granularity) : center(center), size(size), corner0(center - 0.5f * size), corner1(corner0 + size), granularity(granularity), granularity_inverse(1.0f / granularity), num_probes({static_cast<int>(size[0] * granularity_inverse) + 2, static_cast<int>(size[1] * granularity_inverse) + 2, static_cast<int>(size[2] * granularity_inverse) + 2}), num_probes_product(num_probes[0] * num_probes[1] * num_probes[2]), map_bytes(sizeof(float) * num_probes_product), p_offset(scoring_function::n), maps(scoring_function::n) { // Parse the receptor line by line. atoms.reserve(2000); // A receptor typically consists of <= 2,000 atoms within bound. string residue = "XXXX"; // Current residue sequence located at 1-based [23, 26], used to track residue change, initialized to a dummy value. size_t residue_start; // The starting atom of the current residue. string line; for (boost::filesystem::ifstream ifs(p); getline(ifs, line);) { const string record = line.substr(0, 6); if (record == "ATOM " || record == "HETATM") { // If this line is the start of a new residue, mark the starting index within the atoms vector. if (line[25] != residue[3] || line[24] != residue[2] || line[23] != residue[1] || line[22] != residue[0]) { residue[3] = line[25]; residue[2] = line[24]; residue[1] = line[23]; residue[0] = line[22]; residue_start = atoms.size(); } // Parse the ATOM/HETATM line. atom a(line); // Skip unsupported atom types. if (a.ad_unsupported()) continue; // Skip non-polar hydrogens. if (a.is_nonpolar_hydrogen()) continue; // For a polar hydrogen, the bonded hetero atom must be a hydrogen bond donor. if (a.is_polar_hydrogen()) { for (size_t i = atoms.size(); i > residue_start;) { atom& b = atoms[--i]; if (b.is_hetero() && b.has_covalent_bond(a)) { b.donorize(); break; } } continue; } // For a hetero atom, its connected carbon atoms are no longer hydrophobic. if (a.is_hetero()) { for (size_t i = atoms.size(); i > residue_start;) { atom& b = atoms[--i]; if (!b.is_hetero() && b.has_covalent_bond(a)) { b.dehydrophobicize(); } } } // For a carbon atom, it is no longer hydrophobic when connected to a hetero atom. else { for (size_t i = atoms.size(); i > residue_start;) { const atom& b = atoms[--i]; if (b.is_hetero() && b.has_covalent_bond(a)) { a.dehydrophobicize(); break; } } } // Save the atom if and only if its distance to its projection point on the box is within cutoff. float r2 = 0; for (size_t i = 0; i < 3; ++i) { if (a.coord[i] < corner0[i]) { const float d = a.coord[i] - corner0[i]; r2 += d * d; } else if (a.coord[i] > corner1[i]) { const float d = a.coord[i] - corner1[i]; r2 += d * d; } } if (r2 < scoring_function::cutoff_sqr) { atoms.push_back(move(a)); } } else if (record == "TER ") { residue = "XXXX"; } } } void receptor::precalculate(const scoring_function& sf, const vector<size_t>& xs) { const size_t nxs = xs.size(); for (size_t t0 = 0; t0 < sf.n; ++t0) { vector<size_t>& p = p_offset[t0]; p.resize(nxs); for (size_t i = 0; i < nxs; ++i) { const size_t t1 = xs[i]; p[i] = sf.nr * mp(t0, t1); } } } void receptor::populate(const vector<size_t>& xs, const size_t z, const scoring_function& sf) { const size_t n = xs.size(); const float z_coord = corner0[2] + granularity * z; const size_t z_offset = num_probes[0] * num_probes[1] * z; for (const auto& a : atoms) { assert(!a.is_hydrogen()); const float dz = z_coord - a.coord[2]; const float dz_sqr = dz * dz; const float dydx_sqr_ub = scoring_function::cutoff_sqr - dz_sqr; if (dydx_sqr_ub <= 0) continue; const float dydx_ub = sqrt(dydx_sqr_ub); const float y_lb = a.coord[1] - dydx_ub; const float y_ub = a.coord[1] + dydx_ub; const size_t y_beg = y_lb > corner0[1] ? (y_lb < corner1[1] ? static_cast<size_t>((y_lb - corner0[1]) * granularity_inverse) : num_probes[1]) : 0; const size_t y_end = y_ub > corner0[1] ? (y_ub < corner1[1] ? static_cast<size_t>((y_ub - corner0[1]) * granularity_inverse) + 1 : num_probes[1]) : 0; const vector<size_t>& p = p_offset[a.xs]; size_t zy_offset = z_offset + num_probes[0] * y_beg; float dy = corner0[1] + granularity * y_beg - a.coord[1]; for (size_t y = y_beg; y < y_end; ++y, zy_offset += num_probes[0], dy += granularity) { const float dy_sqr = dy * dy; const float dx_sqr_ub = dydx_sqr_ub - dy_sqr; if (dx_sqr_ub <= 0) continue; const float dx_ub = sqrt(dx_sqr_ub); const float x_lb = a.coord[0] - dx_ub; const float x_ub = a.coord[0] + dx_ub; const size_t x_beg = x_lb > corner0[0] ? (x_lb < corner1[0] ? static_cast<size_t>((x_lb - corner0[0]) * granularity_inverse) : num_probes[0]) : 0; const size_t x_end = x_ub > corner0[0] ? (x_ub < corner1[0] ? static_cast<size_t>((x_ub - corner0[0]) * granularity_inverse) + 1 : num_probes[0]) : 0; const float dzdy_sqr = dz_sqr + dy_sqr; size_t zyx_offset = zy_offset + x_beg; float dx = corner0[0] + granularity * x_beg - a.coord[0]; for (size_t x = x_beg; x < x_end; ++x, ++zyx_offset, dx += granularity) { const float dx_sqr = dx * dx; const float r2 = dzdy_sqr + dx_sqr; if (r2 >= scoring_function::cutoff_sqr) continue; const size_t r_offset = static_cast<size_t>(sf.ns * r2); for (size_t i = 0; i < n; ++i) { maps[xs[i]][zyx_offset] += sf.e[p[i] + r_offset]; } } } } }
35.597633
616
0.610539
annanguyen99
c6ed6c668c7966dd0052b64c22c541f2127ba936
2,935
cpp
C++
kernel/thor/generic/fiber.cpp
avdgrinten/managarm
4c4478cbde21675ca31e65566f10e1846b268bd5
[ "MIT" ]
13
2017-02-13T23:29:44.000Z
2021-09-30T05:41:21.000Z
kernel/thor/generic/fiber.cpp
avdgrinten/managarm
4c4478cbde21675ca31e65566f10e1846b268bd5
[ "MIT" ]
12
2016-12-03T13:06:13.000Z
2018-05-04T15:49:17.000Z
kernel/thor/generic/fiber.cpp
avdgrinten/managarm
4c4478cbde21675ca31e65566f10e1846b268bd5
[ "MIT" ]
1
2021-12-01T19:01:53.000Z
2021-12-01T19:01:53.000Z
#include "kernel.hpp" #include "fiber.hpp" namespace thor { void KernelFiber::blockCurrent(FiberBlocker *blocker) { auto this_fiber = thisFiber(); while(true) { // Run the WQ outside of the locks. this_fiber->_associatedWorkQueue.run(); StatelessIrqLock irq_lock; auto lock = frigg::guard(&this_fiber->_mutex); // Those are the important tests; they are protected by the fiber's mutex. if(blocker->_done) break; if(this_fiber->_associatedWorkQueue.check()) continue; assert(!this_fiber->_blocked); this_fiber->_blocked = true; getCpuData()->executorContext = nullptr; getCpuData()->activeFiber = nullptr; Scheduler::suspendCurrent(); forkExecutor([&] { runDetached([] (frigg::LockGuard<frigg::TicketLock> lock) { lock.unlock(); localScheduler()->reschedule(); }, frigg::move(lock)); }, &this_fiber->_executor); } } void KernelFiber::exitCurrent() { frigg::infoLogger() << "thor: Fix exiting fibers" << frigg::endLog; FiberBlocker blocker; blocker.setup(); KernelFiber::blockCurrent(&blocker); } void KernelFiber::unblockOther(FiberBlocker *blocker) { auto fiber = blocker->_fiber; auto irq_lock = frigg::guard(&irqMutex()); auto lock = frigg::guard(&fiber->_mutex); assert(!blocker->_done); blocker->_done = true; if(!fiber->_blocked) return; fiber->_blocked = false; Scheduler::resume(fiber); } void KernelFiber::run(UniqueKernelStack stack, void (*function)(void *), void *argument) { AbiParameters params; params.ip = (uintptr_t)function; params.argument = (uintptr_t)argument; auto fiber = frigg::construct<KernelFiber>(*kernelAlloc, std::move(stack), params); Scheduler::associate(fiber, localScheduler()); Scheduler::resume(fiber); } KernelFiber *KernelFiber::post(UniqueKernelStack stack, void (*function)(void *), void *argument) { AbiParameters params; params.ip = (uintptr_t)function; params.argument = (uintptr_t)argument; auto fiber = frigg::construct<KernelFiber>(*kernelAlloc, std::move(stack), params); Scheduler::associate(fiber, localScheduler()); return fiber; } KernelFiber::KernelFiber(UniqueKernelStack stack, AbiParameters abi) : _blocked{false}, _fiberContext{std::move(stack)}, _executor{&_fiberContext, abi} { _executorContext.associatedWorkQueue = &_associatedWorkQueue; } void KernelFiber::invoke() { assert(!intsAreEnabled()); getCpuData()->executorContext = &_executorContext; getCpuData()->activeFiber = this; restoreExecutor(&_executor); } void KernelFiber::AssociatedWorkQueue::wakeup() { auto self = frg::container_of(this, &KernelFiber::_associatedWorkQueue); auto irq_lock = frigg::guard(&irqMutex()); auto lock = frigg::guard(&self->_mutex); if(!self->_blocked) return; self->_blocked = false; Scheduler::resume(self); } void FiberBlocker::setup() { _fiber = thisFiber(); _done = false; } KernelFiber *thisFiber() { return getCpuData()->activeFiber; } } // namespace thor
24.872881
84
0.720613
avdgrinten
c6ee2f9ebe0f6cebd85327fae888484e4d978d04
8,802
hpp
C++
VTIL-Architecture/routine/serialization.hpp
wallds/VTIL-Core
8ca24f7b4b4bdd918bfe6ae084fe408984634fa2
[ "BSD-3-Clause" ]
906
2020-05-04T01:45:29.000Z
2022-03-31T21:45:05.000Z
VTIL-Architecture/routine/serialization.hpp
wallds/VTIL-Core
8ca24f7b4b4bdd918bfe6ae084fe408984634fa2
[ "BSD-3-Clause" ]
44
2020-05-04T22:33:21.000Z
2022-03-30T08:52:34.000Z
VTIL-Architecture/routine/serialization.hpp
wallds/VTIL-Core
8ca24f7b4b4bdd918bfe6ae084fe408984634fa2
[ "BSD-3-Clause" ]
131
2020-05-02T17:27:03.000Z
2022-03-28T16:50:01.000Z
// Copyright (c) 2020 Can Boluk and contributors of the VTIL Project // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of VTIL Project 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. // #pragma once #include <ostream> #include <istream> #include <fstream> #include <vector> #include <string> #include <filesystem> #include "routine.hpp" #include "basic_block.hpp" #include "instruction.hpp" #include "call_convention.hpp" #pragma warning(disable:4267) namespace vtil { namespace impl { // Check if type is a standard container. // template <typename T> static constexpr bool _is_std_container( ... ) { return false; } template <typename container_type, typename iterator_type = typename container_type::iterator, typename value_type = typename container_type::value_type, typename = decltype( std::declval<container_type>().begin() ), typename = decltype( std::declval<container_type>().end() ), typename = decltype( std::declval<container_type>().clear() ), typename = decltype( std::declval<container_type>().insert( std::declval<iterator_type>(), std::declval<value_type>() ) ) > static constexpr bool _is_std_container( bool v ) { return true; } template <typename T> static constexpr bool is_std_container_v = _is_std_container<std::remove_cvref_t<T>>( true ); // Check if the type is a linear container. (std::vector or std::*string) // template <typename T> struct _is_linear_container : std::false_type {}; template <typename T> struct _is_linear_container<std::vector<T>> : std::true_type {}; template <typename T> struct _is_linear_container<std::basic_string<T>> : std::true_type {}; template <typename T> static constexpr bool is_linear_container_v = _is_linear_container<std::remove_cvref_t<T>>::value; // Check if the container::push_back(value&&) is valid. // template <typename T> static constexpr bool _has_push_back( ... ) { return false; } template <typename container_type, typename = decltype( std::declval<container_type>().push_back( std::declval<typename container_type::value_type&&>() ) )> static constexpr auto _has_push_back( bool v ) { return true; } template <typename T> static constexpr bool has_push_back_v = _has_push_back<std::remove_cvref_t<T>>( true ); // Check if the container::insert(value&&) is valid. // template <typename T> static constexpr bool _has_insert_value( ... ) { return false; } template <typename container_type, typename = decltype( std::declval<container_type>().insert( std::declval<typename container_type::value_type&&>() ) )> static constexpr auto _has_insert_value( bool v ) { return true; } template <typename T> static constexpr bool has_insert_value_v = _has_insert_value<std::remove_cvref_t<T>>( true ); // Move the given value to the end of the container. // template<typename T> static void move_back( T& container, typename T::value_type&& value ) { if constexpr ( has_push_back_v<T> ) container.push_back( std::move( value ) ); else if constexpr ( has_insert_value_v<T> ) container.insert( std::move( value ) ); else container.insert( container.end(), std::move( value ) ); } }; // Container lengths are encoded using 32-bit integers instead of the 64-bit size_t. // using clength_t = int32_t; // Serialization of any type except standard containers and pointers. // template<typename T, std::enable_if_t<!std::is_pointer_v<T> && !impl::is_std_container_v<T>, int> = 0> static void serialize( std::ostream& ss, const T& v ) { // Write the actual value. // ss.write( ( const char* ) &v, sizeof( T ) ); } template<typename T, std::enable_if_t<!std::is_pointer_v<T> && !impl::is_std_container_v<T>, int> = 0> static void deserialize( std::istream& ss, T& v ) { // Read the actual value. // ss.read( ( char* ) &v, sizeof( T ) ); if ( ss.eof() || ss.fail() ) throw std::out_of_range( "Reading past file end." ); } // Serialization of standard containers. // template<typename T, std::enable_if_t<impl::is_std_container_v<T>, int> = 0> static void serialize( std::ostream& ss, const T& v ) { using value_type = typename T::value_type; // Serialize the number of entries. // clength_t n = v.size(); serialize<clength_t>( ss, n ); // If container stores data linearly and trivial data is stored: // if constexpr ( impl::is_linear_container_v<T> && std::is_trivial<value_type>::value ) { // Resize the container to expected size and read all entries at once. // ss.write( ( char* ) v.data(), n * sizeof( value_type ) ); } // Otherwise, default back to per-element invokation. // else { // Serialize each entry. // for ( auto& entry : v ) serialize( ss, entry ); } } template<typename T, std::enable_if_t<impl::is_std_container_v<T>, int> = 0> static void deserialize( std::istream& ss, T& v ) { using value_type = typename T::value_type; // Deserialize the entry counter from the stream and reset the container. // clength_t n; deserialize( ss, n ); // If container stores data linearly and trivial data is stored: // if constexpr ( impl::is_linear_container_v<T> && std::is_trivial<value_type>::value ) { // Resize the container to expected size and read all entries at once. // v.resize( n ); ss.read( ( char* ) v.data(), n * sizeof( value_type ) ); if ( ss.eof() || ss.fail() ) throw std::out_of_range( "Reading past file end." ); } // Otherwise, default back to per-element invokation. // else { // Clear the container just in-case. // v.clear(); // Until counter reaches zero, deserialize an entry and then insert it at the end. // while ( n-- > 0 ) { value_type value; deserialize( ss, value ); impl::move_back( v, std::move( value ) ); } } } // Serialization of VTIL calling conventions. // void serialize( std::ostream& out, const call_convention& in ); void deserialize( std::istream& in, call_convention& out ); // Serialization of VTIL blocks. // void serialize( std::ostream& out, const basic_block* in ); void deserialize( std::istream& in, routine* rtn, basic_block*& blk ); // Serialization of VTIL routines. // void serialize( std::ostream& out, const routine* rtn ); void deserialize( std::istream& in, routine*& rtn ); // Serialization of VTIL instructions. // void serialize( std::ostream& out, const instruction& in ); void deserialize( std::istream& in, instruction& out ); // Serialization of VTIL operands. // void serialize( std::ostream& out, const operand& in ); void deserialize( std::istream& in, operand& out ); // Simple wrappers for serialize / deserialize routine. // static void save_routine( const routine* rtn, const std::filesystem::path& path ) { std::ofstream fs( path, std::ios::binary ); serialize( fs, rtn ); } static routine* load_routine( const std::filesystem::path& path ) { routine* rtn; std::ifstream fs( path, std::ios::binary ); deserialize( fs, rtn ); return rtn; } }; #pragma warning(default:4267)
37.139241
159
0.676096
wallds
c6f09efecc6a375cacf8f116d3b90cffdb5b17d9
3,582
cpp
C++
test/KOMO/factored/main.cpp
Jung-Su/rai
8bd074ab933692815f0f2e19c5593625cdc364cb
[ "MIT" ]
null
null
null
test/KOMO/factored/main.cpp
Jung-Su/rai
8bd074ab933692815f0f2e19c5593625cdc364cb
[ "MIT" ]
null
null
null
test/KOMO/factored/main.cpp
Jung-Su/rai
8bd074ab933692815f0f2e19c5593625cdc364cb
[ "MIT" ]
null
null
null
#include <KOMO/komo.h> #include <Kin/TM_default.h> #include <Kin/F_collisions.h> #include <Kin/viewer.h> #include <Kin/F_pose.h> #include <Optim/MP_Solver.h> //=========================================================================== void testFactored(){ rai::Configuration C("../switches/model2.g"); rai::Frame* g = C["gripper"]; g->ensure_X(); rai::Frame* g2 = new rai::Frame(C, g); g2->name = "gripperDUP"; g2->setShape(rai::ST_box, {.1,.05,.05}); //usually not! g2->setParent(C.frames.first(), true); g2->setJoint(rai::JT_free); //== define the full problem KOMO komo; komo.setModel(C, false); komo.setTiming(2.5, 3, 5., 2); komo.add_qControlObjective({}, 2); komo.addQuaternionNorms(); //consistency constraint komo.addObjective({}, FS_poseDiff, {"gripper", "gripperDUP"}, OT_eq, {1e2}); //grasp // komo.addSwitch_stable(1., 2., "table", "gripper", "box"); komo.addModeSwitch({1., 2.}, rai::SY_stable, {"gripper", "box"}, true); komo.addObjective({1.}, FS_positionDiff, {"gripperDUP", "box"}, OT_eq, {1e2}); komo.addObjective({1.}, FS_scalarProductXX, {"gripperDUP", "box"}, OT_eq, {1e2}, {0.}); komo.addObjective({1.}, FS_vectorZ, {"gripperDUP"}, OT_eq, {1e2}, {0., 0., 1.}); //slow & down-up komo.addObjective({1.}, FS_qItself, {}, OT_eq, {}, {}, 1); komo.addObjective({.9,1.1}, FS_position, {"gripper"}, OT_eq, {}, {0.,0.,.1}, 2); //place // komo.addSwitch_stable(2., -1., "gripper", "table", "box", false); komo.addModeSwitch({2., -1.}, rai::SY_stable, {"table", "box"}, false); komo.addObjective({2.}, FS_positionDiff, {"box", "table"}, OT_eq, {1e2}, {0,0,.08}); //arr({1,3},{0,0,1e2}) komo.addObjective({2.}, FS_vectorZ, {"gripper"}, OT_eq, {1e2}, {0., 0., 1.}); //slow & down-up komo.addObjective({2.}, FS_qItself, {}, OT_eq, {}, {}, 1); komo.addObjective({1.9,2.1}, FS_position, {"gripper"}, OT_eq, {}, {0.,0.,.1}, 2); //== get info from the factored problem { std::shared_ptr<MathematicalProgram_Factored> mp = komo.mp_Factored(); mp->report(cout, 3); } //== three equivalent options to solve the full problem: #if 0 komo.verbose = 4; switch(0){ case 0: { //old style komo.optimize(); } break; case 1: { //generic solver with exact same transcription as old-style NLP_Solver() .setProblem(*komo.nlp_SparseNonFactored()) .solve(); } break; case 2: { //generic solver with factored transcription NLP_Solver() .setProblem(*komo.nlp_Factored()) .solve(); } break; } komo.view(true, "optimized motion"); while(komo.view_play(true)); #endif std::shared_ptr<MathematicalProgram_Factored> mp = komo.mp_Factored(); mp->report(cout, 3); uintA gripperDUP_vars; for(uint i=0;i<mp->variableDimensions.N;i++){ if(mp->getVariableName(i).startsWith("gripperDUP")) gripperDUP_vars.append(i); } cout <<gripperDUP_vars <<endl; mp->subSelect(gripperDUP_vars, {}); cout <<"======== SUBSELECT ==========" <<endl; mp->report(cout, 3); checkJacobianCP(*mp, komo.x, 1e-6); MP_Solver() .setProblem(mp) .solve(); mp->report(cout, 3); // komo.checkGradients(); // komo.optimize(); // komo.view(true, "optimized motion"); // NLP_Solver() // .setProblem(*nlp) // .solve(); // komo.view(true, "optimized motion"); // checkJacobianCP(*nlp); } //=========================================================================== int main(int argc,char** argv){ rai::initCmdLine(argc,argv); // rnd.clockSeed(); testFactored(); return 0; }
27.136364
109
0.585427
Jung-Su
c6f1ec5756a982a0c4cad44ac739391d4c1af330
33,301
cc
C++
wise/src/node/application/wiseMultiCameraPeriodicApp_ICF/WiseMultiCameraPeriodicApp_ICF.cc
qwertyh26/wisemnet
1d8269d141be255642ca36dbff8b594892085685
[ "Naumen", "Condor-1.1", "MS-PL" ]
6
2017-12-07T05:33:01.000Z
2021-02-20T21:15:48.000Z
wise/src/node/application/wiseMultiCameraPeriodicApp_ICF/WiseMultiCameraPeriodicApp_ICF.cc
MultiCameraNetworks/wisemnet
1d8269d141be255642ca36dbff8b594892085685
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
wise/src/node/application/wiseMultiCameraPeriodicApp_ICF/WiseMultiCameraPeriodicApp_ICF.cc
MultiCameraNetworks/wisemnet
1d8269d141be255642ca36dbff8b594892085685
[ "Naumen", "Condor-1.1", "MS-PL" ]
4
2018-09-17T14:01:11.000Z
2020-05-28T15:47:01.000Z
// ***************************************************************************************** // Copyright (C) 2017 Juan C. SanMiguel and Andrea Cavallaro // You may use, distribute and modify this code under the terms of the ACADEMIC PUBLIC // license (see the attached LICENSE_WISE file). // // This file is part of the WiseMnet simulator // // Updated contact information: // - Juan C. SanMiguel - Universidad Autonoma of Madrid - juancarlos.sanmiguel@uam.es // - Andrea Cavallaro - Queen Mary University of London - a.cavallaro@qmul.ac.uk // // Please cite the following reference when publishing results obtained with WiseMnet: // J. SanMiguel & A. Cavallaro, // "Networked Computer Vision: the importance of a holistic simulator", // IEEE Computer, 50(7):35-43, Jul 2017, http://ieeexplore.ieee.org/document/7971873/ // ***************************************************************************************** /** * \file WiseMultiCameraPeriodicApp_ICF.cc * \author Juan C. SanMiguel (2017) * \brief Source file for the WiseMultiCameraPeriodicApp_ICF class * \version 1.4 */ #include <wise/src/node/application/wiseMultiCameraPeriodicApp_ICF/WiseMultiCameraPeriodicApp_ICF.h> #include <wise/src/world/gui/opencv/WiseGuiWorldOpencv.h> //class to print data/targets in the ground-plane #include <wise/src/utils/WiseDebug.h> //for logs/debug (constant WISE_DEBUG_LEVEL must be defined first) using namespace std; Define_Module(WiseMultiCameraPeriodicApp_ICF);//register module in simulator std::ofstream *writerICF=NULL; //additional log for tracking data /*! Class initialization and getting of user-defined variables in omnetpp.ini*/ void WiseMultiCameraPeriodicApp_ICF::at_startup() { // Called upon simulation start-up WISE_DEBUG_32("WiseCamPerAppICF::at_startup()"); readParameters();//Read parameters initStructures();//create internal structures if (writerICF == NULL) writerICF = new ofstream(); //Create streams for logging results if(_collectAccuracyStats) { std::ostringstream os; os << base_out_path.c_str() << "ICF" << "_r" << std::setfill('0') << std::setw(4) << _currentRun << "_N" << std::setfill('0') << std::setw(2) << n_nodes << "_T" << std::setfill('0') << std::setw(2) << _n_targets << "_I" << std::setfill('0') << std::setw(2) << _iter_max << ".dat"; if (!writerICF->is_open()){ writerICF->open(os.str().c_str()); *writerICF << "# _procNoiseCov=" << _procNoiseCov << " _measNoiseCov=" << _measNoiseCov << " iter_max=" << _iter_max << " alpha=" << _alpha << endl; *writerICF << "#Simulation_time,tracking_step,NodeID,TargetID,MeasurementX,MeasurementY,EstimateX,EstimateY,GroundTruthX,GroundTruthY,Error,ErrorAcc,ResultsDelay" << endl; *writerICF << "#t_sim\tt_step\tNID\tTID\tZx\tZy\tX_x\tX_y\tXx\tXy\tGTx\tGTy\tErr\tErrAcc\tDelay" << endl; } } if(_collectPowerStats) { std::ostringstream os1; os1 << base_out_path.c_str() << "ICF" << "_r" << std::setfill('0') << std::setw(4) << _currentRun << "_N" << std::setfill('0') << std::setw(2) << n_nodes << "_T" << std::setfill('0') << std::setw(2) << _n_targets << "_I" << std::setfill('0') << std::setw(2) << _iter_max << "_CPU" << std::setfill('0') << std::setw(3) << resMgr->getPROClk()/1e5 << "_FR" << std::setfill('0') << std::setw(2) << resMgr->getSENFrameRate_user() << ".res" << std::setfill('0') << std::setw(3) << self; resMgr->initLogger(os1.str().c_str(), self, _camID); //energy-consumption log } if(_collectNetworkStats) { std::ostringstream os2; os2 << base_out_path.c_str() << "ICF" << "_r" << std::setfill('0') << std::setw(4) << _currentRun << "_N" << std::setfill('0') << std::setw(2) << n_nodes << "_T" << std::setfill('0') << std::setw(2) << _n_targets << "_I" << std::setfill('0') << std::setw(2) << _iter_max << ".rad"; radioModule->initLogger(os2.str().c_str()); } WISE_DEBUG_32("WiseCamPerAppICF::\t procNoiseCov=" << _procNoiseCov << " measNoiseCov=" << _measNoiseCov << " iter_max=" << _iter_max << " alpha=" << _alpha << " share=" << _share); } /*! Read parameters of MTT_ICF*/ void WiseMultiCameraPeriodicApp_ICF::readParameters() { WISE_DEBUG_32("WiseCamPerAppICF::readParameters()"); // Access related-module parameters (read number of targets) cModule *network = getParentModule()->getParentModule(); _n_targets = network->par("numPhysicalProcesses"); //ICF Filter settings _procNoiseCov = hasPar("procNoiseCov") ? par("procNoiseCov") : 0.1; _measNoiseCov = hasPar("measNoiseCov") ? par("measNoiseCov") : 1e-1; // Consensus settings _iter_max = hasPar("iter_max") ? par("iter_max") : 20; _alpha = hasPar("alpha") ? par("alpha") : 0.1; _share = hasPar("share")?par("share").stringValue() : "COM"; _collectNetworkStats = hasPar("collectNetworkStats")?par("collectNetworkStats").boolValue() : false; _collectPowerStats = hasPar("collectPowerStats")?par("collectPowerStats").boolValue() : false; _collectAccuracyStats = hasPar("collectAccuracyStats")?par("collectAccuracyStats").boolValue() : false; _displayStats = hasPar("displayStats")?par("displayStats").boolValue() : false; } /*! Initialization of structures for tracking targets*/ void WiseMultiCameraPeriodicApp_ICF::initStructures() { WISE_DEBUG_32("WiseCamPerAppICF::initStructures()"); _tracking_step_counter = 0; _time_atsample=0; _time_pkt_processing=0; _bytesTXround=0; _bytesRXround=0; _bytesTXprev=0; _bytesRXprev=0; _dimS = icf::DIM_STATE_T_4D; _dimM = icf::DIM_MEASUREMENT_T_2D; //status for each target _camStatus.clear(); _camStatus.resize(_n_targets); _node_controls.clear(); for (int tid = 0; tid < _n_targets; tid++) { //create control data icf::node_ctrl_t ctrl(tid,n_nodes,icf::MAX_SIZE_BUFFER,_dimS); //determine the neighbourgs to share (FOV or COM graphs) _share.compare("FOV") == 0 ? ctrl.n_neighbors = _neighborsFOVoverlap.size(): ctrl.n_neighbors = _neighborsCOM.size(); _node_controls.push_back(ctrl);//store in list } WISE_DEBUG_32("WiseCamPerAppICF::\tNew resources (" << _node_controls.size() << " structs) for "<< _n_targets << " targets, " << n_nodes << " nodes and " << icf::MAX_SIZE_BUFFER << " max iterations to buffer)"); } /*! * Destroy resources for tracking. Declared in base class WiseCameraPeriodicApp. */ void WiseMultiCameraPeriodicApp_ICF::at_finishSpecific() { WISE_DEBUG_32("WiseCamPerAppICF::at_finishSpecific()"); if (writerICF) { writerICF->close(); delete writerICF; writerICF=NULL; } } /*! * This function defines the behavior to specific alarms generated by the WiseMultiCameraPeriodicApp_ICF * * @param[in] index Code of the generated alarm. */ void WiseMultiCameraPeriodicApp_ICF::at_timer_fired(int index) { WISE_DEBUG_32("WiseCamPerAppICF::at_timer_fired() ALARM: " << _alarm_str[index]); switch (index) { case ALARM_WAIT_NEGOTIATION: //go to the FSM to check completion of negotiation fsm_app(INVALID); break; default: WISE_DEBUG_32("WiseCamPerAppICF::\tWRONG ALARM!!: index=" << index); } } /*! * This function receives detections from SensorManager (ie, targets within camera's FOV) and organizes * them in an ordered list as measurements (detections+noise) which is later processed by ICFs. * * Called to properly read the sample: when a new sample is available a measurement has to be created from it * * @param[in] dt List of WiseTargetDetections (using vector template) */ void WiseMultiCameraPeriodicApp_ICF::make_measurements(const vector<WiseTargetDetection>&dt) { WISE_DEBUG_32("WiseCamPerAppICF::make_measurements()"); // reorder target detections so we directly associate lists of measurements and targets. Uses ID of targets (ie, ground-truth) vector<const WiseTargetDetection*> ordered; ordered.resize(_n_targets, NULL); for(vector<WiseTargetDetection>::const_iterator d = dt.begin(); d != dt.end(); ++d) ordered[d->target_id] = &(*d); // get data from ordered list of 'WiseTargetDetections' and copy data to 'state_t' and 'measurement_t' lists for (int tid = 0; tid < _n_targets && tid < (int)dt.size(); tid++) { if (ordered[tid] == NULL) { _node_controls[tid].detection_miss = true; continue; } const WiseTargetDetection &d = *(ordered[tid]); if (!d.valid) { _ICFs[tid].z = cv::Mat::zeros(_dimM, 1, CV_64F); _node_controls[tid].detection_miss = true; continue; } //measurements + Gaussian noise _ICFs[tid].z.at<double>(0) = (d.ext_bb_x_tl + d.ext_bb_x_br) / 2 + normal(0, _measNoiseCov, 0); _ICFs[tid].z.at<double>(1) = (d.ext_bb_y_tl + d.ext_bb_y_br) / 2 + normal(0, _measNoiseCov, 0); _node_controls[tid].detection_miss = false; WISE_DEBUG_32("WiseCamPerAppICF::\t tid=" << tid << " -> MAKE MEASUREMENT z=" << format(mat2vec(_ICFs[tid].z), cv::Formatter::FMT_DEFAULT)); } //copy the real positions in the ground-truth lists for (int tid = 0; tid < _n_targets; tid++) { const WiseTargetDetection &d = *(ordered[tid]); _ICFs[tid].xgt.at<double>(0) = (d.true_bb_x_tl + d.true_bb_x_br) / 2; _ICFs[tid].xgt.at<double>(1) = (d.true_bb_y_tl + d.true_bb_y_br) / 2; } } /*! * Init resources for ICF processing. Declared in base class WiseCameraSimplePeriodicTracker. */ bool WiseMultiCameraPeriodicApp_ICF::at_init() { WISE_DEBUG_32("WiseCamPerAppICF::at_init()"); _ICFs.clear(); _tracking_step_counter= 0; // ICF filters for each target.. for (int tid = 0; tid < _n_targets; tid++) { //create ICF filter icf::ICF_t icf(_dimS,_dimM,_procNoiseCov,_measNoiseCov,n_nodes); _ICFs.push_back(icf); //store in list //update the neighbourgs to share (FOV or COM graphs) icf::node_ctrl_t& ctrl = _node_controls[tid]; _share.compare("FOV") == 0 ? ctrl.n_neighbors = _neighborsFOVoverlap.size(): ctrl.n_neighbors = _neighborsCOM.size(); } WISE_DEBUG_32("WiseCamPerAppICF::Initialized " << _ICFs.size() << " ICF filters for "<< _n_targets << " targets, " << n_nodes << " nodes and " << icf::MAX_SIZE_BUFFER << " iterations"); return true; } /*! * ICF processing for first sample. Called when the first sample (image) is ready.Currently first sample is * treated as the others. Declared in base class WiseCameraSimplePeriodicTracker. */ bool WiseMultiCameraPeriodicApp_ICF::at_first_sample() { // Called when the first sample (image) is ready WISE_DEBUG_32("WiseCamPerAppICF::at_first_sample()"); //find the maximum neighborg degree _max_neigb_network = 0; for (int i = 0; i < n_nodes; i++) { cModule *m = getParentModule()->getParentModule(); // m=SN m = m->getSubmodule("node", i)->getSubmodule("Application"); WiseMultiCameraPeriodicApp_ICF *c = check_and_cast<WiseMultiCameraPeriodicApp_ICF*>(m); if (_share.compare("FOV") == 0){ if (c->_neighborsFOVoverlap.size() > (unsigned int)_max_neigb_network) _max_neigb_network = c->_neighborsFOVoverlap.size(); } else{ if (_neighborsCOM.size() > (unsigned int)_max_neigb_network) _max_neigb_network = _neighborsCOM.size(); } } //initialize structures to save data _rdata.clear(); for (int tid = 0; tid < _n_targets; tid++){ std::vector<icf::round_data_t> rdata; _rdata.push_back(rdata); } //initialize targets with ground-truth data for (int tid = 0; tid < _n_targets; tid++){ icf::ICF_t &icf = _ICFs[tid]; icf.initICFstate(_ICFs[tid].xgt); _node_controls[tid].initialized = true; _node_controls[tid].first_start_time = SIMTIME_DBL(simTime()); WISE_DEBUG_32("WiseCamPerAppICF::\ttid=" << tid << " -> INIT x_=" << mat2vec(icf.x_) << " xgt=" << mat2vec(_ICFs[tid].xgt)); } //do processing //return at_sample(); return true; } /*! * ICF processing for first sample end of lifetime. Called when the first sample (image) is no longer valid. Currently * first sample is treated as the others. Declared in base class WiseCameraSimplePeriodicTracker. */ bool WiseMultiCameraPeriodicApp_ICF::at_end_first_sample() { // Called when the first sample (image) is no longer valid WISE_DEBUG_32("WiseCamPerAppICF::at_end_first_sample()"); // We can: // 1- either put here any first-sample specific code // 2- or simply treat the first sample as the others return at_end_sample(); // option 2 } /*! * Called when a new sample (image) is ready. For each target, ICF processing consist on computing and initial detection/estimation, * which is later sent to other neighbors to initiate consensus. Declared in base class WiseCameraSimplePeriodicTracker. */ bool WiseMultiCameraPeriodicApp_ICF::at_sample() { // Called when a new sample (image) is ready WISE_DEBUG_32("WiseCamPerAppICF::at_sample()"); _tracking_step_counter++; if(_tracking_step_counter==1) at_first_sample(); // NOTE: Measurement has been made through the make_measurements() method and is available in the measurement vector for (int tid = 0; tid < _n_targets; tid++) { _rdata[tid].clear(); _camStatus[tid] = icf::COLLABORATION; //flag to indicate that the camera is busy doing consensus //check if there is consensus under progress if (_node_controls[tid].iter_counter > 0){ WISE_DEBUG_32("WiseCamPerAppICF::\tStart consensus without ending previous iter > curr=" << _node_controls[tid].iter_counter << " max=" << _iter_max); return false; } else WISE_DEBUG_32("WiseCamPerAppICF::\ttid=" << tid << " -> PROCESS SAMPLE t=" << _tracking_step_counter); //record initial time for consensus _node_controls[tid].start_time = simTime().dbl(); //compute internal information vector & matrix _ICFs[tid].prepData(_node_controls[tid].detection_miss); //start consensus iterations consensusStart(tid); } return true; } /*! * Called when a new sample is no longer valid. Declared in base class "WiseCameraSimplePeriodicTracker". */ bool WiseMultiCameraPeriodicApp_ICF::at_end_sample() { // Called when a new sample (image) is no longer valid WISE_DEBUG_32("WiseCamPerAppICF::at_end_sample()"); //check if the camera is doing consensus for any target int camStatusTotal=0; for (int tid = 0; tid < _n_targets; tid++) if (_camStatus[tid] == icf::INACTIVE) camStatusTotal++; if (camStatusTotal != _n_targets) { WISE_DEBUG_32("WiseCamPerAppICF::\tnode not ready (own," << camStatusTotal << "/" << _n_targets <<" targets done)"); setTimer(ALARM_WAIT_NEGOTIATION,_sampling_time); //we check again after a certain time return false; } else WISE_DEBUG_32("WiseCamPerAppICF::\tnode ready (own," << camStatusTotal << "/" << _n_targets <<" targets done)"); /*for (int tid = 0; tid < n_targets; tid++) { icf::node_ctrl_t &ctrl = node_controls[tid]; //get the control structure associated to target 'tid' //int index = findIndexInBuffer(tid, iter_max); // Index of the buffer for the last iteration int c=0; for (int i=0; i < n_nodes; i++) if(ctrl.nb_data_buffer[0].nb_data[i].end_collaboration == true) c++; if (c!=ctrl.n_neighbors) { LOGGER << "node not ready (own, waiting for COLLABORATION END)" << c << "/"<< ctrl.n_neighbors << endl; setTimer(ALARM_WAIT_NEGOTIATION,sampling_time); //we check again after a certain time return false; } }*/ /*if (_dummy_comms==false) { //perform some additional checking at network level since 'real wireless' may desynchronize nodes // TODO: implement a protocol to sync the end of the consensus iteration for (int i = 0; i< n_nodes; i++) if (i!= self) { cModule *m = getParentModule()->getParentModule(); // m=SN m = m->getSubmodule("node", i)->getSubmodule("Application"); WiseMultiCameraPeriodicApp_ICF*c = check_and_cast<WiseMultiCameraPeriodicApp_ICF*>(m); camStatusTotal=0; for (int tid = 0; tid < _n_targets; tid++) if (c->_camStatus[tid] == icf::INACTIVE) camStatusTotal++; if (camStatusTotal != _n_targets) { LOGGER << "node not ready (netcheck)" << camStatusTotal << "/" << _n_targets <<" targets done)" << std::endl; setTimer(ALARM_WAIT_NEGOTIATION,_sampling_time); //we check again after a certain time return false; } } } */ //restart 'busy' state of other cameras for (int tid = 0; tid < _n_targets; tid++) { icf::node_ctrl_t &ctrl = _node_controls[tid]; //get the control structure associated to target 'tid' //int index = findIndexInBuffer(tid, iter_max); // Index of the buffer for the last iteration for (int i=0; i < n_nodes; i++) ctrl.nb_data_buffer[0].nb_data[i].end_collaboration = false; }/**/ WISE_DEBUG_32("WiseCamPerAppICF::\tnode ready"); if(_displayStats && _tracking_step_counter > 1) displayStats(); return true; } /*! * Called when a packet is received from the network using standard or dummy protocols. In this function, a node * receives data from its neighbors, stores the pkt content and when all the data is available (from all neighbors), * it calls consensusProcess function to initiate a round of consensus when needed * * @param[in] pkt Received packet (should be casted to a WiseMultiCameraPeriodicApp_ICFMessage type) */ bool WiseMultiCameraPeriodicApp_ICF::process_network_message(WiseBaseAppPacket *pkt) { WISE_DEBUG_32("WiseCamPerAppICF::process_network_message()"); double e2=0,e1 = cv::getTickCount(); int i=0,c=0, index=-1; WiseMultiCameraPeriodicApp_ICFPacket *m = check_and_cast<WiseMultiCameraPeriodicApp_ICFPacket*>(pkt); ApplicationInteractionControl_type ctl = m->getApplicationInteractionControl(); WISE_DEBUG_32("WiseCamPerAppICF::\tRX from " << ctl.source << ". Packet content: [ tid=" << m->getTargetID() << " t=" << m->getTrackingCount() << " k="<< m->getIterationStep() << " ]"); //source node and target IDs of recv packet int node = atoi(ctl.source.c_str()); int tid = m->getTargetID(); icf::node_ctrl_t &ctrl = _node_controls[tid]; //get the control structure associated to target 'tid' switch (m->getPktTypeICF()){ case ICF_COLLABORATION_DATA1: { WISE_DEBUG_32("WiseCamPerAppICF::\tCollaboration..."); // store recv data in buffer if(ctrl.storeDataInBuffer((int)m->getIterationStep(), node, m) == -1) WISE_DEBUG_32("WiseCamPerAppICF::\tERROR BUFFER!!"); //check matching of iteration number between node and recv data if (m->getIterationStep() != ctrl.iter_counter) WISE_DEBUG_32("WiseCamPerAppICF::\tWRONG ITERATION!! (curr=" << ctrl.iter_counter << " rcv=" << m->getIterationStep() << ")" << " tid="<<tid); // get data for current consensus iteration of the node index = ctrl.findIndexInBuffer((int)ctrl.iter_counter); // Index of the buffer //count the number of received data from nodes (to start consensus if all data has been recv) std::vector<int> missing; for (i=0; i < n_nodes; i++) if (ctrl.nb_data_buffer[index].nb_data[i].rcv_data == true){ c++; } else{ map<string, bool>::const_iterator n; for (n = _connectivity_map_comms.begin(); n != _connectivity_map_comms.end(); ++n) if ((*n).second == true) if (atoi((*n).first.c_str()) != this->self) if (atoi((*n).first.c_str()) == i) missing.push_back(i); } //compute the consensus if we have all neighbor's data if (c==ctrl.n_neighbors) consensusProcess(tid); else WISE_DEBUG_32("WiseCamPerAppICF::\tWaiting for " << ctrl.n_neighbors-c << "/" << ctrl.n_neighbors << print_vector(missing) << "for consensus k=" << ctrl.iter_counter << " tid="<<tid); break; } case ICF_COLLABORATION_END: if ((int)m->getTrackingCount() == _tracking_step_counter) { ctrl.nb_data_buffer[0].nb_data[node].end_collaboration=true; WISE_DEBUG_32("WiseCamPerAppICF::\tCOLLABORATION END RECEIVED from node=" << node << " tid="<<tid); } else WISE_DEBUG_32("WiseCamPerAppICF::\tLate??? COLLABORATION END RECEIVED from node=" << node << " tid="<<tid << " t_curr=" << _tracking_step_counter << " t_rcv="<<(int)m->getTrackingCount()); break; default: WISE_DEBUG_32("WiseCamPerAppICF::\t UNKNOWN PACKET!!"); break; } e2 = cv::getTickCount(); _time_pkt_processing += (e2 - e1)/ cv::getTickFrequency(); //CPU time for processing packets return true; } /*! * Processing of the received network messages through direct connection (so no * communication protocol is applied). This communication is faster than using network * protocols allowing direct communication. * * @param[in] pkt Received packet (should be a WiseApplicationPacket type) */ void WiseMultiCameraPeriodicApp_ICF::handleDirectApplicationMessage(WiseBaseAppPacket *pkt) { // Called when a DirectApplication Message is received WISE_DEBUG_32("WiseCamPerAppICF::handleDirectApplicationMessage()"); // In this case we treat the message received through DirectApplication as a normal // network message. However, the two mechanisms could be used independently. process_network_message(pkt); } /*! * Function to start the consensus iterations. It sends data to neighbors * (if any). If there are not, then it estimates target position. * * @param[in] tid Target ID of the associated ICF structures */ void WiseMultiCameraPeriodicApp_ICF::consensusStart(int tid) { WISE_DEBUG_32("WiseCamPerAppICF::consensusStart()"); _node_controls[tid].iter_counter=1; if (_node_controls[tid].n_neighbors > 0 && _iter_max > 0) sendICFmessage(tid); // send estimation to neighbors else { //perform final state estimation if there are no neighbors or maximum iterations reached _ICFs[tid].estimate_and_predict_state(); logResult(tid);//save data } } /*! * Function to process a consensus iteration after receiving data * from all neighborgs. * * @param[in] tid Target ID of the associated ICF structures * @param[in] k Number of the current iteration */ void WiseMultiCameraPeriodicApp_ICF::consensusProcess(int tid) { icf::node_ctrl_t &ctrl = _node_controls[tid]; WISE_DEBUG_32("WiseCamPerAppICF::consensusProcess()for k=" << ctrl.iter_counter); //accumulate round data to display stats icf::round_data_t rdata; rdata.round = ctrl.iter_counter; //consensus round rdata.terr = _ICFs[tid].compute_error(); rdata.delay = simTime().dbl()-_node_controls[tid].start_time; _rdata[tid].push_back(rdata); int index = ctrl.findIndexInBuffer(ctrl.iter_counter); // Index of the buffer //combine estimations of neighbors _ICFs[tid].update_state_neighbors(ctrl.nb_data_buffer[index].nb_data,_alpha,ctrl.n_neighbors,_max_neigb_network); //restart status of received data for (int i=0; i < n_nodes; i++) ctrl.nb_data_buffer[index].nb_data[i].rcv_data = false; //free the buffer position for further usage ctrl.nb_data_buffer[index].iter_buffer = -1; //continue consensus if not exceed the max iterations ctrl.iter_counter++; //send message to neighbors (posterior state OR collaboration end) sendICFmessage(tid); //check if data for next consensus round is already buffer checkNextConsensusRound(tid); if (ctrl.iter_counter > _iter_max) { _ICFs[tid].estimate_and_predict_state(); //perform final state estimation when maximum iterations reached logResult(tid);//save data ctrl.iter_counter=0;//return to initial status } else{ _ICFs[tid].estimate_state(); WISE_DEBUG_32("WiseCamPerAppICF::\ttid=" << tid << " -> PAR RESULT x_=" << mat2vec(_ICFs[tid].x_) <<" x=" << mat2vec(_ICFs[tid].x) <<" err=" << setprecision(3) << _ICFs[tid].compute_error()); } } /*! * Send a message to all neighbors in the VISION (FOV) graph. The message contains the current estimation * of the node: <x,y> position and <u,U> information vector&matrix. * * @param[in] tid Target ID of the associated KF structures */ int WiseMultiCameraPeriodicApp_ICF::sendICFmessage(int tid) { WISE_DEBUG_32("WiseCamPerAppICF::sendICFmessage()"); //create message & copy data std::ostringstream os; os << "ICF: node=" << self << " tid=" << tid << " t=" << _tracking_step_counter << " k=" << _node_controls[tid].iter_counter; WiseMultiCameraPeriodicApp_ICFPacket *pkt = new WiseMultiCameraPeriodicApp_ICFPacket(os.str().c_str(), APPLICATION_PACKET); pkt->setTrackingCount(_tracking_step_counter); //current step counter pkt->setIterationStep(_node_controls[tid].iter_counter); //data for new iteration pkt->setTargetID(tid); //target id pkt->setSubType(WISE_APP_NORMAL); //normal APP for the network //send message containing the posterior state estimation OR collaboration end if (_node_controls[tid].iter_counter > _iter_max){ WISE_DEBUG_32("WiseCamPerAppICF::\ttid=" << tid << " -> SENDING MSG to FOVs to END consensus"); pkt->setByteLength(icf::ICFpkt_size[ICF_COLLABORATION_END]); pkt->setPktTypeICF(ICF_COLLABORATION_END); _camStatus[tid] = icf::INACTIVE;//flag to indicate that the node has finished consensus } else { WISE_DEBUG_32("WiseCamPerAppICF::\ttid=" << tid << " -> SENDING MSG to FOVs for k=" << _node_controls[tid].iter_counter); pkt->setICFv(_ICFs[tid].v); //information vector pkt->setICFV(_ICFs[tid].V); //information matrix pkt->setByteLength(icf::ICFpkt_size[ICF_COLLABORATION_DATA1]); pkt->setPktTypeICF(ICF_COLLABORATION_DATA1); } // Distribute the data among neighbors using the FOV or COM graphs. // NOTE: For real wireless channels, it is better to send unicast messages so we can keep control of missing TX packets // If "send_message(pkt)" is used, some packets may be lost without being noticed. if (_share.compare("FOV") == 0) { pkt->setSubTypeNeighbor(WISE_NEIGHBOR_FOV); //type defined in "WiseCameraSimplePeriodicTracker.msg" send_messageNeighboursFOV(pkt);//unicast message } else{ pkt->setSubTypeNeighbor(WISE_NEIGHBOR_COM); send_messageNeighboursCOM(pkt);//unicast message } // We assume a broadcast packet for FOVs/COMs in dummy channels so count TX packets only once if (_dummy_comms == true) _bytesTX = _bytesTX - (_node_controls[tid].n_neighbors-1)*pkt->getByteLength(); return 1; } void WiseMultiCameraPeriodicApp_ICF::checkNextConsensusRound(int tid) { WISE_DEBUG_32("WiseCamPerAppICF::checkNextConsensusRound()"); icf::node_ctrl_t &ctrl = _node_controls[tid]; //get the control structure associated to target 'tid' // get data for current consensus iteration of the node int index = ctrl.findIndexInBuffer(ctrl.iter_counter); // Index of the buffer int c=0; for (int i=0; i < n_nodes; i++) if (ctrl.nb_data_buffer[index].nb_data[i].rcv_data == true){ c++; } //compute the consensus if we have all neighbor's data if (c==ctrl.n_neighbors){ WISE_DEBUG_32("WiseCamPerAppICF::\ttid=" << tid << " -> DATA for k=" << _node_controls[tid].iter_counter << " already available"); consensusProcess(tid); } } /*! * Write results in txt files * * @param[in] pkt Received packet (should be a WiseApplicationPacket type) */ void WiseMultiCameraPeriodicApp_ICF::logResult(int tid) { WISE_DEBUG_32("WiseCamPerAppICF::logResult()"); double delay = simTime().dbl()-_node_controls[tid].start_time; double err = _ICFs[tid].compute_error(); _ICFs[tid].errAcc += err; WISE_DEBUG_32("WiseCamPerAppICF::\ttid=" << tid <<" t="<< _tracking_step_counter << " FINAL -> x=" << mat2vec(_ICFs[tid].x) << " J=" << cv::trace(_ICFs[tid].J).val[0] << " x_=" << mat2vec(_ICFs[tid].x_) << "," << "] J_=" << cv::trace(_ICFs[tid].J_).val[0] << " z=" << mat2vec(_ICFs[tid].z) << " gt=" << mat2vec(_ICFs[tid].xgt)); *writerICF << std::setprecision(6) << simTime().dbl() << "\t" << _tracking_step_counter << "\t" << self << "\t" << tid << "\t" << setprecision(4) << _ICFs[tid].z.at<double>(0) << "\t" << setprecision(4) << _ICFs[tid].z.at<double>(1) << "\t" << setprecision(4) << _ICFs[tid].x_.at<double>(0) << "\t" << setprecision(4) << _ICFs[tid].x_.at<double>(1) << "\t" << setprecision(4) << _ICFs[tid].x.at<double>(0) << "\t" << setprecision(4) << _ICFs[tid].x.at<double>(1) << "\t" << setprecision(4) << _ICFs[tid].xgt.at<double>(0) << "\t" << setprecision(4) << _ICFs[tid].xgt.at<double>(1) << "\t" << setprecision(4) << err << "\t" << setprecision(4) << _ICFs[tid].errAcc << "\t" << delay << endl; } /*! * Display visual statistics during execution * */ bool WiseMultiCameraPeriodicApp_ICF::displayStats() { WISE_DEBUG_32("WiseCamPerAppICF::displayStats()"); double scale = 0.8; double enePRO = resMgr->getCurSpentEnergy(WISE_ENERGY_PRO_TOT); double eneCOM = resMgr->getCurSpentEnergy(WISE_ENERGY_COM_TOT); double tiRound = _sampling_time; double TXrate = 1/tiRound * resMgr->getCOMBytesTXdone(); //rateTX_achieve (bps) double RXrate = 1/tiRound * resMgr->getCOMBytesRXdone(); //rateRX_achieve (bps) //get the color list cModule *node = getParentModule(); node = node->getParentModule()->getSubmodule("wiseTerrain"); WiseBaseTerrain *terrain = check_and_cast<WiseBaseTerrain*>(node); WiseGuiWorldOpencv *gui=check_and_cast<WiseGuiWorldOpencv*>(terrain->get_GUI()); std::map<int,cv::Scalar> clist = gui->getColorList(); cv::Scalar colorCam = clist[(int)self]; for (int tid = 0; tid < _n_targets; tid++) { std::ostringstream winStats; winStats << "Stats for Cam id="<< _camID << " TargetID=" << tid<< std::endl; cv::namedWindow(winStats.str().c_str()); cv::Mat img = cv::Mat::zeros((_iter_max+1)*50, 850, CV_8UC3); std::ostringstream ss0,ss1,ss2,ss3; ss0 << "SUMMARY for Cam id=" << _camID << " TargetID=" << tid << " K=" << _tracking_step_counter << " (Time="<<simTime().dbl()<<"s)"; cv::putText(img, ss0.str().c_str(), cv::Point(50,50), cv::FONT_HERSHEY_SIMPLEX, scale, colorCam, 2, CV_AA); ss1 << "Time at-sample="<<_time_atsample*1e3 << "ms Processing="<<_time_pkt_processing*1e3 << "ms"; cv::putText(img, ss1.str().c_str(), cv::Point(50,100), cv::FONT_HERSHEY_SIMPLEX, 0.8*scale,colorCam, 2, CV_AA); ss2 << "Bandwidth: TXrate=" << TXrate/1e3 << "KBps RXrate=" << RXrate/1e3 << "KBps (MAX " << resMgr->getCOMInfo().bitrateTX/8 *1/1e3<< "KBps)"; cv::putText(img, ss2.str().c_str(), cv::Point(50,150), cv::FONT_HERSHEY_SIMPLEX, 0.8*scale,colorCam, 2, CV_AA); ss3 << "Consumption: EnergyPRO=" << enePRO*1e3<<"mJ EnergyCOM=" << eneCOM*1e3<<"mJ"; cv::putText(img, ss3.str().c_str(), cv::Point(50,200), cv::FONT_HERSHEY_SIMPLEX, 0.8*scale,colorCam, 2, CV_AA); for (int i=0;i<(int)_rdata[tid].size();i++) { int round = _rdata[tid][i].round; double rerr=_rdata[tid][i].terr; double delay=_rdata[tid][i].delay; std::ostringstream ss; ss<<"r="<< setprecision(2)<<round <<" error="<< setprecision(4)<<rerr<<" m Delay="<<delay*1e3<<" ms"; cv::putText(img, ss.str().c_str(), cv::Point(50,200+30*(i+1)), cv::FONT_HERSHEY_SIMPLEX, 0.8*scale,colorCam, 2, CV_AA); } cv::imshow(winStats.str().c_str(), img); std::cout << "cam "<<_camID << ": display stats for step="<< _tracking_step_counter << " (SimTime="<<simTime().dbl()<<"s)"<< std::endl; if (_n_targets < 6) { WiseTargetInfo t; t.id=self; t.pos_x=_ICFs[tid].x.at<double>(0); t.pos_y=_ICFs[tid].x.at<double>(1); t.unique_color=false; //gui->draw_target(t); terrain->place_target(t); } } return true; }
43.587696
289
0.646647
qwertyh26
c6f61fe935245587970f19d399b9f0041beffed1
707
cpp
C++
Controls/Label.cpp
Carson-Shook/Winclipper
b8b0e7d1a1755f095df974d3eafa8f0fdb5c60f4
[ "MIT" ]
6
2018-06-19T15:50:24.000Z
2022-01-13T09:28:07.000Z
Controls/Label.cpp
Carson-Shook/Winclipper
b8b0e7d1a1755f095df974d3eafa8f0fdb5c60f4
[ "MIT" ]
7
2018-01-07T21:07:55.000Z
2021-12-16T18:55:12.000Z
Controls/Label.cpp
Carson-Shook/Winclipper
b8b0e7d1a1755f095df974d3eafa8f0fdb5c60f4
[ "MIT" ]
null
null
null
#include "Label.h" bool Controls::Label::Create() { RECT boxsize = { 0, 0, 0, 0 }; int finalWidth = 0; int finalHeight = 0; if (AutoSize) { MeasureString(text, font, &boxsize); finalWidth = boxsize.right; finalHeight = boxsize.bottom; } else { finalWidth = DpiScaleX(width); finalHeight = DpiScaleX(height); } handle = CreateWindowExW(WS_EX_LEFT, WC_STATIC, text, WS_CHILD | WS_VISIBLE, DpiScaleX(x), DpiScaleY(y), finalWidth, finalHeight, parentHandle, (HMENU)id, hInstance, nullptr); return handle != nullptr; } Controls::Label::Label() : Control{} { } Controls::Label::Label(HWND hWnd, UINT_PTR id, HINSTANCE hInstance) : Control{ hWnd, id, hInstance } { }
16.833333
67
0.673267
Carson-Shook
05038a7d89c57c565c22429e2cba171f62597b70
1,128
cpp
C++
codeforces/A - Business trip/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Business trip/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Business trip/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Feb/16/2018 18:01 * solution_verdict: Accepted language: GNU C++14 * run_time: 30 ms memory_used: 2000 KB * problem: https://codeforces.com/contest/149/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; long arr[14],k; bool cmp(long a,long b) { return a>b; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>k; for(long i=1;i<=12;i++)cin>>arr[i]; sort(arr+1,arr+13,cmp); if(k==0) { cout<<0<<endl; return 0; } long sum=0; for(long i=1;i<=12;i++) { sum+=arr[i]; if(sum>=k) { cout<<i<<endl; return 0; } } cout<<-1<<endl; return 0; }
28.2
111
0.356383
kzvd4729
0503f4e26fc826777334b7eb4a6ab9b97768c2b5
5,573
cpp
C++
aws-cpp-sdk-elasticbeanstalk/source/model/CPUUtilization.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2020-07-16T19:03:13.000Z
2020-07-16T19:03:13.000Z
aws-cpp-sdk-elasticbeanstalk/source/model/CPUUtilization.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-elasticbeanstalk/source/model/CPUUtilization.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2021-10-01T15:29:44.000Z
2021-10-01T15:29:44.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/elasticbeanstalk/model/CPUUtilization.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace ElasticBeanstalk { namespace Model { CPUUtilization::CPUUtilization() : m_user(0.0), m_userHasBeenSet(false), m_nice(0.0), m_niceHasBeenSet(false), m_system(0.0), m_systemHasBeenSet(false), m_idle(0.0), m_idleHasBeenSet(false), m_iOWait(0.0), m_iOWaitHasBeenSet(false), m_iRQ(0.0), m_iRQHasBeenSet(false), m_softIRQ(0.0), m_softIRQHasBeenSet(false) { } CPUUtilization::CPUUtilization(const XmlNode& xmlNode) : m_user(0.0), m_userHasBeenSet(false), m_nice(0.0), m_niceHasBeenSet(false), m_system(0.0), m_systemHasBeenSet(false), m_idle(0.0), m_idleHasBeenSet(false), m_iOWait(0.0), m_iOWaitHasBeenSet(false), m_iRQ(0.0), m_iRQHasBeenSet(false), m_softIRQ(0.0), m_softIRQHasBeenSet(false) { *this = xmlNode; } CPUUtilization& CPUUtilization::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode userNode = resultNode.FirstChild("User"); if(!userNode.IsNull()) { m_user = StringUtils::ConvertToDouble(StringUtils::Trim(userNode.GetText().c_str()).c_str()); m_userHasBeenSet = true; } XmlNode niceNode = resultNode.FirstChild("Nice"); if(!niceNode.IsNull()) { m_nice = StringUtils::ConvertToDouble(StringUtils::Trim(niceNode.GetText().c_str()).c_str()); m_niceHasBeenSet = true; } XmlNode systemNode = resultNode.FirstChild("System"); if(!systemNode.IsNull()) { m_system = StringUtils::ConvertToDouble(StringUtils::Trim(systemNode.GetText().c_str()).c_str()); m_systemHasBeenSet = true; } XmlNode idleNode = resultNode.FirstChild("Idle"); if(!idleNode.IsNull()) { m_idle = StringUtils::ConvertToDouble(StringUtils::Trim(idleNode.GetText().c_str()).c_str()); m_idleHasBeenSet = true; } XmlNode iOWaitNode = resultNode.FirstChild("IOWait"); if(!iOWaitNode.IsNull()) { m_iOWait = StringUtils::ConvertToDouble(StringUtils::Trim(iOWaitNode.GetText().c_str()).c_str()); m_iOWaitHasBeenSet = true; } XmlNode iRQNode = resultNode.FirstChild("IRQ"); if(!iRQNode.IsNull()) { m_iRQ = StringUtils::ConvertToDouble(StringUtils::Trim(iRQNode.GetText().c_str()).c_str()); m_iRQHasBeenSet = true; } XmlNode softIRQNode = resultNode.FirstChild("SoftIRQ"); if(!softIRQNode.IsNull()) { m_softIRQ = StringUtils::ConvertToDouble(StringUtils::Trim(softIRQNode.GetText().c_str()).c_str()); m_softIRQHasBeenSet = true; } } return *this; } void CPUUtilization::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_userHasBeenSet) { oStream << location << index << locationValue << ".User=" << StringUtils::URLEncode(m_user) << "&"; } if(m_niceHasBeenSet) { oStream << location << index << locationValue << ".Nice=" << StringUtils::URLEncode(m_nice) << "&"; } if(m_systemHasBeenSet) { oStream << location << index << locationValue << ".System=" << StringUtils::URLEncode(m_system) << "&"; } if(m_idleHasBeenSet) { oStream << location << index << locationValue << ".Idle=" << StringUtils::URLEncode(m_idle) << "&"; } if(m_iOWaitHasBeenSet) { oStream << location << index << locationValue << ".IOWait=" << StringUtils::URLEncode(m_iOWait) << "&"; } if(m_iRQHasBeenSet) { oStream << location << index << locationValue << ".IRQ=" << StringUtils::URLEncode(m_iRQ) << "&"; } if(m_softIRQHasBeenSet) { oStream << location << index << locationValue << ".SoftIRQ=" << StringUtils::URLEncode(m_softIRQ) << "&"; } } void CPUUtilization::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_userHasBeenSet) { oStream << location << ".User=" << StringUtils::URLEncode(m_user) << "&"; } if(m_niceHasBeenSet) { oStream << location << ".Nice=" << StringUtils::URLEncode(m_nice) << "&"; } if(m_systemHasBeenSet) { oStream << location << ".System=" << StringUtils::URLEncode(m_system) << "&"; } if(m_idleHasBeenSet) { oStream << location << ".Idle=" << StringUtils::URLEncode(m_idle) << "&"; } if(m_iOWaitHasBeenSet) { oStream << location << ".IOWait=" << StringUtils::URLEncode(m_iOWait) << "&"; } if(m_iRQHasBeenSet) { oStream << location << ".IRQ=" << StringUtils::URLEncode(m_iRQ) << "&"; } if(m_softIRQHasBeenSet) { oStream << location << ".SoftIRQ=" << StringUtils::URLEncode(m_softIRQ) << "&"; } } } // namespace Model } // namespace ElasticBeanstalk } // namespace Aws
28.28934
129
0.656379
woohoou
050974096f41be59440c679d1dac374fd28d1e0a
7,948
inl
C++
include/voxigen/volume/regionHandle.inl
caseymcc/voxigen
cfb7c7e999a02cdf40fd7344b2d744bf9446837c
[ "MIT" ]
38
2017-05-13T20:14:18.000Z
2022-01-20T12:39:59.000Z
include/voxigen/volume/regionHandle.inl
caseymcc/voxigen
cfb7c7e999a02cdf40fd7344b2d744bf9446837c
[ "MIT" ]
null
null
null
include/voxigen/volume/regionHandle.inl
caseymcc/voxigen
cfb7c7e999a02cdf40fd7344b2d744bf9446837c
[ "MIT" ]
6
2018-01-04T23:59:27.000Z
2021-02-19T03:48:50.000Z
namespace voxigen { template<typename _Region> RegionHandle<_Region>::RegionHandle(RegionHash regionHash, IGridDescriptors *descriptors/*, GeneratorQueue<_Grid> *generatorQueue, DataStore<_Grid> *dataStore, UpdateQueue *updateQueue*/): //m_status(Unknown), m_state(HandleState::Unknown), m_action(HandleAction::Idle), m_version(0), m_hash(regionHash), m_descriptors(descriptors), //m_generatorQueue(generatorQueue), //m_dataStore(dataStore), //m_updateQueue(updateQueue), m_cachedOnDisk(false), m_empty(false) { m_index=descriptors->getRegionIndex(regionHash); } template<typename _Region> void RegionHandle<_Region>::generate(IGridDescriptors *descriptors, Generator *generator, size_t lod) { glm::vec3 startPos=descriptors->getRegionOffset(m_hash); #ifdef DEBUG_ALLOCATION allocated++; Log::debug("RegionHandle (%llx) allocating by generate\n", m_hash); #endif glm::ivec3 size=details::regionCellSize<RegionType, ChunkType>(); // size.z=1;//only heighmap so only 1 z m_heightMap.resize(size.x*size.y); unsigned int validCells=generator->generateRegion(startPos, size, m_heightMap.data(), m_heightMap.size()*sizeof(Cells), lod); if(validCells<=0) { m_heightMapLod=0; release(); setEmpty(true); } else { // m_memoryUsed=m_heightMap.size()*sizeof(typename ChunkType::CellType); m_heightMapLod=lod; setEmpty(false); } } template<typename _Region> void RegionHandle<_Region>::release() { if(!m_heightMap.empty()) { #ifdef DEBUG_ALLOCATION allocated--; Log::debug("RegionHandle (%llx) freeing (%d)\n", m_hash, allocated); #endif } m_heightMap.clear(); // m_memoryUsed=0; } template<typename _Region> bool RegionHandle<_Region>::load(const std::string &directory) { m_directory=directory; if(!fs::is_directory(directory)) { if(fs::exists(directory)) return false; fs::create_directory(directory); } m_configFile=m_directory+"/regionConfig.json"; if(!fs::exists(m_configFile)) saveConfig(); else loadConfig(); loadDataStore(); verifyDirectory(); // m_status=Loaded; m_state=HandleState::Memory; return true; } template<typename _Region> typename RegionHandle<_Region>::DataHandle *RegionHandle<_Region>::newHandle(HashType chunkHash) { glm::ivec3 regionIndex=m_descriptors->getRegionIndex(m_hash); glm::ivec3 chunkIndex=m_descriptors->getChunkIndex(chunkHash); return new ChunkHandleType(m_hash, regionIndex, chunkHash, chunkIndex); } template<typename _Region> void RegionHandle<_Region>::loadConfig() { generic::JsonDeserializer deserializer; deserializer.open(m_configFile.c_str()); deserializer.openObject(); if(deserializer.key("version")) m_version=deserializer.getUInt(); if(deserializer.key("chunks")) { if(deserializer.openArray()) { do { if(deserializer.openObject()) { if(deserializer.key("id")) { RegionHash hash=deserializer.getUInt(); SharedChunkHandle chunkHandle(newHandle(hash)); chunkHandle->setCachedOnDisk(true); if(deserializer.key("empty")) chunkHandle->setEmpty(deserializer.getBool()); else chunkHandle->setEmpty(true); this->m_dataHandles.insert(typename SharedDataHandleMap::value_type(hash, chunkHandle)); } deserializer.closeObject(); } } while(deserializer.advance()); deserializer.closeArray(); } } deserializer.closeObject(); } template<typename _Region> void RegionHandle<_Region>::saveConfig() { saveConfigTo(m_configFile); } template<typename _Region> void RegionHandle<_Region>::saveConfigTo(std::string configFile) { generic::JsonSerializer serializer; serializer.open(m_configFile.c_str()); serializer.startObject(); serializer.addKey("version"); serializer.addInt(m_version); serializer.addKey("chunks"); serializer.startArray(); for(auto &handle:this->m_dataHandles) { if(handle.second->empty()) { serializer.startObject(); serializer.addKey("id"); serializer.addUInt(handle.second->hash()); serializer.addKey("empty"); serializer.addBool(handle.second->empty()); serializer.endObject(); } } serializer.endArray(); serializer.endObject(); } template<typename _Region> void RegionHandle<_Region>::addConfig(ChunkHandleType *handle) { if(handle->empty()) { std::string tempConfig=m_configFile+".tmp"; saveConfigTo(tempConfig); fs::copy_file(tempConfig, m_configFile, true); } } template<typename _Region> void RegionHandle<_Region>::loadDataStore() { std::vector<std::string> directories=fs::get_directories(m_directory); for(auto &entry:directories) { std::istringstream fileNameStream(entry); ChunkHash chunkHash; fileNameStream.ignore(6); fileNameStream>>std::hex>>chunkHash; glm::ivec3 regionIndex=m_descriptors->getRegionIndex(m_hash); glm::ivec3 chunkIndex=m_descriptors->getChunkIndex(chunkHash); SharedChunkHandle handle=std::make_shared<ChunkHandleType>(m_hash, regionIndex, chunkHash, chunkIndex); handle->setCachedOnDisk(true); handle->setEmpty(false); this->m_dataHandles.insert(typename SharedDataHandleMap::value_type(chunkHash, handle)); } } template<typename _Region> void RegionHandle<_Region>::verifyDirectory() { } template<typename _Region> typename RegionHandle<_Region>::SharedChunkHandle RegionHandle<_Region>::getChunk(ChunkHash chunkHash) { SharedChunkHandle chunkHandle=this->getDataHandle(chunkHash); glm::ivec3 chunkIndex=m_descriptors->getChunkIndex(chunkHash); chunkHandle->setRegionOffset(glm::ivec3(ChunkType::sizeX::value, ChunkType::sizeY::value, ChunkType::sizeZ::value)*chunkIndex); // if(chunkHandle->status!=ChunkHandleType::Memory) // { // if(chunkHandle->empty) //empty is already loaded // { // chunkHandle->status=ChunkHandleType::Memory; // m_updateQueue->add(Key(hash, chunkHash)); // } // else // { // //we dont have it in memory so we need to load or generate it // if(!chunkHandle->cachedOnDisk) // m_generatorQueue->add(chunkHandle); // else // m_dataStore->read(chunkHandle); // } // } return chunkHandle; } //template<typename _Region> //void RegionHandle<_Region>::loadChunk(SharedChunkHandle chunkHandle, size_t lod, bool force) //{ // if(force || (chunkHandle->state() != HandleState::Memory)) // { // //an action is in process lets not start something else as well // if(chunkHandle->action()!=HandleAction::Idle) // return; // // if(chunkHandle->empty()) //empty is already loaded // { //// m_dataStore->empty(chunkHandle); // } // else // { // //we dont have it in memory so we need to load or generate it // if(!chunkHandle->cachedOnDisk()) // m_dataStore->generate(chunkHandle, lod); // else // m_dataStore->read(chunkHandle, lod); // } // } //} // //template<typename _Region> //void RegionHandle<_Region>::cancelLoadChunk(SharedChunkHandle chunkHandle) //{ // //if we are not doing anything ignore // if(chunkHandle->action()==HandleAction::Idle) // return; // // m_dataStore->cancel(chunkHandle); //} } //namespace voxigen
27.50173
188
0.641042
caseymcc
050a78a0320b2da22e02cee94aa29d21fa760a53
28,442
cpp
C++
src/neuralnet/tally.cpp
theMarix/Gridcoin-Research
19e30fa7e4591a423aacb20c6e7824131aefd596
[ "MIT" ]
null
null
null
src/neuralnet/tally.cpp
theMarix/Gridcoin-Research
19e30fa7e4591a423aacb20c6e7824131aefd596
[ "MIT" ]
null
null
null
src/neuralnet/tally.cpp
theMarix/Gridcoin-Research
19e30fa7e4591a423aacb20c6e7824131aefd596
[ "MIT" ]
null
null
null
#include "main.h" #include "neuralnet/accrual/newbie.h" #include "neuralnet/accrual/null.h" #include "neuralnet/accrual/research_age.h" #include "neuralnet/accrual/snapshot.h" #include "neuralnet/claim.h" #include "neuralnet/cpid.h" #include "neuralnet/quorum.h" #include "neuralnet/superblock.h" #include "neuralnet/tally.h" #include "util.h" #include <unordered_map> using namespace NN; using LogFlags = BCLog::LogFlags; extern int64_t g_v11_timestamp; namespace { //! //! \brief Set the correct CPID from the block claim when the block index //! contains a zero CPID. //! //! There were reports of 0000 cpid in index where INVESTOR should have been. //! //! \param pindex Index of the block to repair. //! void RepairZeroCpidIndex(CBlockIndex* const pindex) { const ClaimOption claim = GetClaimByIndex(pindex); if (!claim) { return; } if (claim->m_mining_id != pindex->GetMiningId()) { LogPrint(LogFlags::TALLY, "WARNING: BlockIndex CPID %s did not match %s in block {%s %d}", pindex->GetMiningId().ToString(), claim->m_mining_id.ToString(), pindex->GetBlockHash().GetHex(), pindex->nHeight); /* Repair the cpid field */ pindex->SetMiningId(claim->m_mining_id); #if 0 if(!WriteBlockIndex(CDiskBlockIndex(pindex))) error("LoadBlockIndex: writing CDiskBlockIndex failed"); #endif } } //! //! \brief Contains the two-week network average tally used to produce the //! magnitude unit for legacy research age reward calculations (version 10 //! blocks and below). //! //! Before block version 11, the network used a feedback filter to limit the //! total research reward generated over a rolling two week window. To scale //! rewards accordingly, the magnitude unit acts as a multiplier and changes //! in response to the amount of research rewards minted over the two weeks. //! This class holds state for the parameters that produce a magnitude units //! at a point in time. //! class NetworkTally { public: //! //! \brief Number of days that the tally scans backward from to calculate //! the average network payment. //! static constexpr size_t TALLY_DAYS = 14; //! //! \brief Get the maximum network-wide research reward amount per day. //! //! \param payment_time Determines the max reward based on a schedule. //! //! \return Maximum daily emission in units of GRC (not COIN). //! static double MaxEmission(const int64_t payment_time) { return BLOCKS_PER_DAY * GetMaxResearchSubsidy(payment_time); } //! //! \brief Get the current network-wide magnitude unit. //! //! \param payment_time Determines the max reward based on a schedule. //! //! \return Magnitude unit based on the current network averages. //! double GetMagnitudeUnit(const int64_t payment_time) const { double max_emission = MaxEmission(payment_time); max_emission -= m_two_week_research_subsidy / TALLY_DAYS; if (max_emission < 1) max_emission = 1; const double magnitude_unit = (max_emission / m_total_magnitude) * 1.25; // Just in case we lose a superblock or something strange happens: if (magnitude_unit > 5) { return 5.0; } return SnapToGrid(magnitude_unit); } //! //! \brief Reset the two-week averages to the provided values. //! //! \param research_subsidy Sum of research payments over the last two weeks. //! void Reset(double research_subsidy) { m_two_week_research_subsidy = research_subsidy / COIN; } //! //! \brief Load the total network magnitude from the provided superblock. //! //! \param superblock Provides the total network magnitude for subsequent //! magnitude unit calculations. //! void ApplySuperblock(const SuperblockPtr superblock) { LogPrint(LogFlags::TALLY, "NetworkTally::ApplySuperblock(%" PRId64 ")", superblock.m_height); m_total_magnitude = superblock->m_cpids.TotalMagnitude(); } private: uint32_t m_total_magnitude = 0; //!< Sum of the magnitude of all CPIDs. double m_two_week_research_subsidy = 0; //!< Sum of research subsidy payments. //! //! \brief Round a magnitude unit value to intervals of 0.025. //! static double SnapToGrid(double d) { double dDither = .04; double dOut = RoundFromString(RoundToString(d * dDither, 3), 3) / dDither; return dOut; } }; // NetworkTally //! //! \brief Tracks research payments for each CPID in the network. //! class ResearcherTally { public: //! //! \brief Initialize the research reward context for each CPID in the //! network. //! //! This scans historical block metadata to create an in-memory database of //! the pending accrual owed to each CPID in the network. //! //! \param pindex Index for the first research age block. //! \param current_superblock Used to bootstrap snapshot accrual. //! //! \return \c true if the tally initialized without an error. //! bool Initialize(CBlockIndex* pindex, SuperblockPtr current_superblock) { LogPrintf("Initializing research reward tally..."); m_start_pindex = pindex; for (; pindex; pindex = pindex->pnext) { if (pindex->nHeight + 1 == GetV11Threshold()) { // Set the timestamp for the block version 11 threshold. This // is temporary. Remove this variable in a release that comes // after the hard fork. For now, this is the least cumbersome // place to set the value: // g_v11_timestamp = pindex->nTime; // This will finish loading the research accounting context // for snapshot accrual (block version 11+): return ActivateSnapshotAccrual(pindex, current_superblock); } if (pindex->nResearchSubsidy <= 0) { continue; } if (const CpidOption cpid = pindex->GetMiningId().TryCpid()) { if (cpid->IsZero()) { RepairZeroCpidIndex(pindex); } RecordRewardBlock(*cpid, pindex); } } // If this function does not return from the loop above to activate // snapshot accrual, the local blockchain data contains no snapshot // accrual blocks, so we erase any accrual snapshots that may exist // from a prior sync. This avoids issues when starting over without // any version 11 blocks (like a sync from the genesis block): // LogPrintf("Resetting accrual directory."); return m_snapshots.EraseAll(); } //! //! \brief Get a traversable object for the research accounts stored in //! the tally. //! //! \return Provides range-based iteration over every research account. //! ResearchAccountRange Accounts() { return ResearchAccountRange(m_researchers); } //! //! \brief Get the research account for the specified CPID. //! //! \param cpid The CPID of the account to fetch. //! //! \return An account that matches the CPID or a blank account if no //! research reward data exists for the CPID. //! const ResearchAccount& GetAccount(const Cpid cpid) { auto iter = m_researchers.find(cpid); if (iter == m_researchers.end()) { return m_new_account; } return iter->second; } //! //! \brief Record a block's research reward data in the tally. //! //! \param cpid The CPID of the research account to record the block for. //! \param pindex Contains information about the block to record. //! void RecordRewardBlock(const Cpid cpid, const CBlockIndex* const pindex) { ResearchAccount& account = m_researchers[cpid]; account.m_total_research_subsidy += pindex->nResearchSubsidy; if (pindex->nMagnitude > 0) { account.m_accuracy++; account.m_total_magnitude += pindex->nMagnitude; } if (account.m_first_block_ptr == nullptr) { account.m_first_block_ptr = pindex; account.m_last_block_ptr = pindex; } else { assert(pindex->nHeight > account.m_last_block_ptr->nHeight); account.m_last_block_ptr = pindex; } } //! //! \brief Disassociate a block's research reward data from the tally. //! //! \param cpid The CPID of the research account to drop the block for. //! \param pindex Contains information about the block to erase. //! void ForgetRewardBlock(const Cpid cpid, const CBlockIndex* pindex) { auto iter = m_researchers.find(cpid); assert(iter != m_researchers.end()); ResearchAccount& account = iter->second; assert(account.m_first_block_ptr != nullptr); assert(pindex == account.m_last_block_ptr); if (pindex == account.m_first_block_ptr) { m_researchers.erase(iter); return; } account.m_total_research_subsidy -= pindex->nResearchSubsidy; if (pindex->nMagnitude > 0) { account.m_accuracy--; account.m_total_magnitude -= pindex->nMagnitude; } pindex = pindex->pprev; while (pindex && (pindex->nResearchSubsidy <= 0 || pindex->GetMiningId() != cpid)) { pindex = pindex->pprev; } assert(pindex && pindex != pindexGenesisBlock); account.m_last_block_ptr = pindex; } //! //! \brief Update the account data with information from a new superblock. //! //! \param superblock Refers to the current active superblock. //! //! \return \c false if an IO error occurred while processing the superblock. //! bool ApplySuperblock(SuperblockPtr superblock) { // The network publishes version 2+ superblocks after the mandatory // switch to block version 11. // if (superblock->m_version >= 2) { TallySuperblockAccrual(superblock.m_timestamp); if (!m_snapshots.Store(superblock.m_height, m_researchers)) { return false; } } m_current_superblock = std::move(superblock); return true; } //! //! \brief Reset the account data to a state before the current superblock. //! //! \param superblock Refers to the current active superblock (before the //! reverted superblock). //! //! \return \c false if an IO error occurred while processing the superblock. //! bool RevertSuperblock(SuperblockPtr superblock) { if (m_current_superblock->m_version >= 2) { try { if (!m_snapshots.Drop(m_current_superblock.m_height) || !m_snapshots.ApplyLatest(m_researchers)) { return false; } } catch (const SnapshotStateError& e) { LogPrintf("%s: %s", __func__, e.what()); return RebuildAccrualSnapshots(); } } m_current_superblock = std::move(superblock); return true; } //! //! \brief Switch from legacy research age accrual calculations to the //! superblock snapshot accrual system. //! //! \param pindex Index of the block to enable snapshot accrual for. //! \param superblock Refers to the current active superblock. //! //! \return \c false if the snapshot system failed to initialize because of //! an error. //! bool ActivateSnapshotAccrual( const CBlockIndex* const baseline_pindex, SuperblockPtr superblock) { if (!baseline_pindex || !IsV11Enabled(baseline_pindex->nHeight + 1)) { return false; } m_snapshot_baseline_pindex = baseline_pindex; m_current_superblock = std::move(superblock); try { if (!m_snapshots.Initialize()) { return false; } // If the node initialized the snapshot accrual system before, we // should already have the latest snapshot. Otherwise, create the // baseline snapshot and scan context for the remaining blocks: // if (!m_snapshots.HasBaseline()) { return BuildAccrualSnapshots(); } // Check the integrity of the baseline superblock snapshot: // if (const CBlockIndex* pindex = FindBaselineSuperblockHeight()) { m_snapshots.AssertMatch(pindex->nHeight); } // Finish loading the research account context for the remaining // blocks after the snapshot accrual threshold. Verify snapshots // along the way: // for (const CBlockIndex* pindex = baseline_pindex; pindex; pindex = pindex->pnext) { if (pindex->nIsSuperBlock == 1) { m_snapshots.AssertMatch(pindex->nHeight); } if (pindex->nResearchSubsidy <= 0) { continue; } if (const CpidOption cpid = pindex->GetMiningId().TryCpid()) { RecordRewardBlock(*cpid, pindex); } } m_snapshots.PruneSnapshotFiles(); return m_snapshots.ApplyLatest(m_researchers); } catch (const SnapshotStateError& e) { LogPrintf("%s: %s", __func__, e.what()); } return RebuildAccrualSnapshots(); } //! //! \brief Erase the snapshot files and clear the registry. //! //! \return \c false if the snapshots and registery deletion failed because //! of an error. //! bool EraseSnapshots() { return m_snapshots.EraseAll(); } private: //! //! \brief An empty account to return as a reference when requesting an //! account for a CPID with no historical record. //! const ResearchAccount m_new_account; //! //! \brief The set of all research accounts in the network. //! ResearchAccountMap m_researchers; //! //! \brief A link to the current active superblock for snapshot accrual //! calculations. //! SuperblockPtr m_current_superblock = SuperblockPtr::Empty(); //! //! \brief Manages snapshots for delta accrual calculations (version 2+ //! superblocks). //! AccrualSnapshotRepository m_snapshots; //! //! \brief Index of the first block that the tally tracks research rewards //! for. //! const CBlockIndex* m_start_pindex = nullptr; //! //! \brief Points to the index of the block when snapshot accrual activates //! (the block just before protocol enforces snapshot accrual). //! const CBlockIndex* m_snapshot_baseline_pindex = nullptr; //! //! \brief Get the block index entry of the block when research accounting //! begins. //! CBlockIndex* GetStartHeight() { // A node syncing from zero does not know the block index entry of the // starting height yet, so the tally will initialize without it. // if (m_start_pindex == nullptr && pindexGenesisBlock != nullptr) { const int32_t threshold = GetResearchAgeThreshold(); const CBlockIndex* pindex = pindexGenesisBlock; for (; pindex && pindex->nHeight < threshold; pindex = pindex->pnext); m_start_pindex = pindex; } // Tally initialization will repair block index entries with zero CPID // values to workaround an old bug so we remove the const specifier on // this pointer. Besides this, the tally will never mutate block index // objects, so remove the const_cast after deprecating the repair: // return const_cast<CBlockIndex*>(m_start_pindex); } //! //! \brief Tally research rewards accrued since the current superblock //! arrived. //! //! \param payment_time Time of payment to calculate rewards at. //! void TallySuperblockAccrual(const int64_t payment_time) { const SnapshotCalculator calc(payment_time, m_current_superblock); for (auto& account_pair : m_researchers) { const Cpid cpid = account_pair.first; ResearchAccount& account = account_pair.second; if (account.LastRewardHeight() >= m_current_superblock.m_height) { account.m_accrual = 0; } account.m_accrual += calc.AccrualDelta(cpid, account); } } //! //! \brief Locate the block index entry of the superblock before the //! snapshot accrual threshold. //! //! \return The block index entry of the superblock used to build the //! baseline snapshot. //! const CBlockIndex* FindBaselineSuperblockHeight() const { assert(m_snapshot_baseline_pindex != nullptr); for (const CBlockIndex* pindex = m_snapshot_baseline_pindex; pindex; pindex = pindex->pprev) { if (pindex->nIsSuperBlock != 1) { continue; } return pindex; } return nullptr; } //! //! \brief Locate the superblock before the snapshot accrual threshold. //! //! \return The superblock used to build the baseline snapshot. //! SuperblockPtr FindBaselineSuperblock() const { const CBlockIndex* pindex = FindBaselineSuperblockHeight(); return SuperblockPtr::ReadFromDisk(pindex); } //! //! \brief Reset the tally to the snapshot accrual baseline and store the //! baseline snapshot to disk. //! //! \return \c false if an error occurred. //! bool BuildBaselineSnapshot() { assert(m_snapshot_baseline_pindex != nullptr); SuperblockPtr superblock = FindBaselineSuperblock(); if (!superblock->WellFormed()) { return error("%s: unable to load baseline superblock", __func__); } m_current_superblock = superblock; SnapshotBaselineBuilder builder(m_researchers); if (!builder.Run(m_snapshot_baseline_pindex, std::move(superblock))) { return false; } if (!m_snapshots.StoreBaseline(superblock.m_height, m_researchers)) { return false; } return true; } //! //! \brief Create the baseline accrual snapshot and any remaining snapshots //! above the snapshot accrual threshold. //! //! Because snapshot accrual depends on the last reward blocks in research //! accounts, this method expects that the tally's research accounts state //! exists as it would at the snapshot accrual threshold (the block before //! version 11 blocks begin). This method finishes importing any remaining //! research account data from the block index entries above the threshold //! as it scans the chain to create accrual snapshots. //! //! \return \c false if an IO error occurred. //! bool BuildAccrualSnapshots() { if (!BuildBaselineSnapshot()) { return false; } CBlock block; // Scan forward to the chain tip and reapply snapshot accrual for each // account while writing snapshot files for every superblock along the // way. Finish rescanning the research accounts: // for (const CBlockIndex* pindex = m_snapshot_baseline_pindex->pnext; pindex; pindex = pindex->pnext) { if (pindex->nIsSuperBlock == 1) { if (!ApplySuperblock(SuperblockPtr::ReadFromDisk(pindex))) { return false; } } if (pindex->nResearchSubsidy > 0) { if (const CpidOption cpid = pindex->GetMiningId().TryCpid()) { RecordRewardBlock(*cpid, pindex); } } } return true; } //! //! \brief Wipe out the entire snapshot accrual state and rebuild the //! snapshots and each account's accrual from the initial threshold. //! //! This provides the ability to repair the snapshot accrual system in //! case of corruption or user error. //! //! TODO: Rebuilding the entire snapshot history is not necessary. Each //! snapshot effectively contains the rolled-up state of snapshots that //! exist before it, so we can store just the snapshots near the tip of //! the chain. //! //! \return \c false if an error occurred. //! bool RebuildAccrualSnapshots() { assert(m_snapshot_baseline_pindex != nullptr); // Reset the research accounts and reinitialize the whole tally. We // need to make sure that an account contains the last reward block // below the baseline: // m_researchers.clear(); LogPrintf("%s: rebuilding from %" PRId64 " to %" PRId64 "...", __func__, m_snapshot_baseline_pindex->nHeight, pindexBest->nHeight); if (!m_snapshots.EraseAll()) { return false; } return Initialize(GetStartHeight(), SuperblockPtr::Empty()); } }; // ResearcherTally ResearcherTally g_researcher_tally; //!< Tracks lifetime research rewards. NetworkTally g_network_tally; //!< Tracks legacy two-week network averages. } // Anonymous namespace // ----------------------------------------------------------------------------- // Class: Tally // ----------------------------------------------------------------------------- bool Tally::Initialize(CBlockIndex* pindex) { if (!pindex || !IsResearchAgeEnabled(pindex->nHeight)) { LogPrintf("Tally initialization not needed."); // Also destroy any existing accrual snapshots, because if this is called from // init below the research age enabled height, the accrual directory must be stale // (i.e. this is a resync.) g_researcher_tally.EraseSnapshots(); LogPrintf("Accrual directory reset."); return true; } const int64_t start_time = GetTimeMillis(); g_researcher_tally.Initialize(pindex, Quorum::CurrentSuperblock()); LogPrintf( "Tally initialization complete. Scan time %15" PRId64 "ms\n", GetTimeMillis() - start_time); return true; } bool Tally::ActivateSnapshotAccrual(const CBlockIndex* const pindex) { LogPrint(LogFlags::TALLY, "Activating snapshot accrual..."); // Activate any pending superblocks that may exist before the snapshot // system kicks-in. The legacy tally caches superblocks in the pending // state for 10 blocks before the recount trigger height. // Quorum::CommitSuperblock(pindex->nHeight); return g_researcher_tally.ActivateSnapshotAccrual( pindex, Quorum::CurrentSuperblock()); } bool Tally::IsLegacyTrigger(const uint64_t height) { return height % TALLY_GRANULARITY == 0; } CBlockIndex* Tally::FindLegacyTrigger(CBlockIndex* pindex) { // Scan backwards until we find one where accepting it would // trigger a tally. for (; pindex && pindex->pprev && !IsLegacyTrigger(pindex->nHeight); pindex = pindex->pprev); return pindex; } int64_t Tally::MaxEmission(const int64_t payment_time) { return NetworkTally::MaxEmission(payment_time) * COIN; } double Tally::GetMagnitudeUnit(const CBlockIndex* const pindex) { if (pindex->nVersion >= 11) { return SnapshotCalculator::MagnitudeUnit(); } return g_network_tally.GetMagnitudeUnit(pindex->nTime); } ResearchAccountRange Tally::Accounts() { return g_researcher_tally.Accounts(); } const ResearchAccount& Tally::GetAccount(const Cpid cpid) { return g_researcher_tally.GetAccount(cpid); } int64_t Tally::GetAccrual( const Cpid cpid, const int64_t payment_time, const CBlockIndex* const last_block_ptr) { return GetComputer(cpid, payment_time, last_block_ptr)->Accrual(); } AccrualComputer Tally::GetComputer( const Cpid cpid, const int64_t payment_time, const CBlockIndex* const last_block_ptr) { if (!last_block_ptr) { return MakeUnique<NullAccrualComputer>(); } if (last_block_ptr->nVersion >= 11) { return GetSnapshotComputer(cpid, payment_time, last_block_ptr); } return GetLegacyComputer(cpid, payment_time, last_block_ptr); } AccrualComputer Tally::GetSnapshotComputer( const Cpid cpid, const ResearchAccount& account, const int64_t payment_time, const CBlockIndex* const last_block_ptr, const SuperblockPtr superblock) { return MakeUnique<SnapshotAccrualComputer>( cpid, account, payment_time, last_block_ptr->nHeight, std::move(superblock)); } AccrualComputer Tally::GetSnapshotComputer( const Cpid cpid, const int64_t payment_time, const CBlockIndex* const last_block_ptr) { return GetSnapshotComputer( cpid, GetAccount(cpid), payment_time, last_block_ptr, Quorum::CurrentSuperblock()); } AccrualComputer Tally::GetLegacyComputer( const Cpid cpid, const int64_t payment_time, const CBlockIndex* const last_block_ptr) { const ResearchAccount& account = GetAccount(cpid); if (!account.IsActive(last_block_ptr->nHeight)) { return MakeUnique<NewbieAccrualComputer>( cpid, account, payment_time, g_network_tally.GetMagnitudeUnit(payment_time), Quorum::CurrentSuperblock()->m_cpids.MagnitudeOf(cpid).Floating()); } return MakeUnique<ResearchAgeComputer>( cpid, account, Quorum::CurrentSuperblock()->m_cpids.MagnitudeOf(cpid).Floating(), payment_time, g_network_tally.GetMagnitudeUnit(payment_time), last_block_ptr->nHeight); } void Tally::RecordRewardBlock(const CBlockIndex* const pindex) { if (!pindex || pindex->nResearchSubsidy <= 0) { return; } if (const CpidOption cpid = pindex->GetMiningId().TryCpid()) { g_researcher_tally.RecordRewardBlock(*cpid, pindex); } } void Tally::ForgetRewardBlock(const CBlockIndex* const pindex) { if (!pindex || pindex->nResearchSubsidy <= 0) { return; } if (const CpidOption cpid = pindex->GetMiningId().TryCpid()) { g_researcher_tally.ForgetRewardBlock(*cpid, pindex); } } bool Tally::ApplySuperblock(SuperblockPtr superblock) { return g_researcher_tally.ApplySuperblock(std::move(superblock)); } bool Tally::RevertSuperblock() { return g_researcher_tally.RevertSuperblock(Quorum::CurrentSuperblock()); } void Tally::LegacyRecount(const CBlockIndex* pindex) { if (!pindex) { return; } LogPrint(LogFlags::TALLY, "Tally::LegacyRecount(%" PRId64 ")", pindex->nHeight); const int64_t consensus_depth = pindex->nHeight - CONSENSUS_LOOKBACK; const int64_t lookback_depth = BLOCKS_PER_DAY * NetworkTally::TALLY_DAYS; int64_t max_depth = consensus_depth - (consensus_depth % TALLY_GRANULARITY); int64_t min_depth = max_depth - lookback_depth; if (fTestNet && !IsV9Enabled_Tally(pindex->nHeight)) { LogPrint(LogFlags::TALLY, "Tally::LegacyRecount(): retired tally"); max_depth = consensus_depth - (consensus_depth % BLOCK_GRANULARITY); min_depth -= (max_depth - lookback_depth) % TALLY_GRANULARITY; } // Seek to the head of the tally window: while (pindex->nHeight > max_depth) { if (!pindex->pprev) { return; } pindex = pindex->pprev; } if (Quorum::CommitSuperblock(max_depth)) { g_network_tally.ApplySuperblock(Quorum::CurrentSuperblock()); } int64_t total_research_subsidy = 0; while (pindex->nHeight > min_depth) { if (!pindex->pprev) { return; } pindex = pindex->pprev; total_research_subsidy += pindex->nResearchSubsidy; } g_network_tally.Reset(total_research_subsidy); }
30.714903
90
0.62587
theMarix
050a7f611711a8241488923681e602b91680ae66
2,337
hpp
C++
include/eve/arch/expected_cardinal.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/arch/expected_cardinal.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/arch/expected_cardinal.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #pragma once #include <eve/arch/spec.hpp> #include <eve/detail/meta.hpp> #include <eve/arch/cardinals.hpp> #include <eve/concept/rebindable.hpp> #include <type_traits> #include <cstddef> #include <utility> #include <array> namespace eve { template<typename Type, regular_abi ABI = EVE_CURRENT_ABI> struct expected_cardinal : fixed<ABI::template expected_cardinal<Type>> { using type = fixed<ABI::template expected_cardinal<Type>>; }; namespace detail { template<typename ABI, typename T> constexpr std::ptrdiff_t scard(always<T>) noexcept { auto cardinals = []<std::size_t... X>(std::index_sequence<X...> const&) { return std::array<std::ptrdiff_t,sizeof...(X)> { expected_cardinal< std::tuple_element_t<X,T>,ABI>::value... }; }( std::make_index_sequence<std::tuple_size<T>::value>{} ); std::ptrdiff_t r = cardinals[0]; for(auto c : cardinals) r = std::min(r,c); return r; } template<typename ABI, typename T> using scard_t = fixed<scard<ABI>(always<T>{})>; } template<typename Type, regular_abi ABI> requires( rebindable<Type> ) struct expected_cardinal<Type,ABI> : detail::scard_t<ABI,Type> { using type = detail::scard_t<ABI,Type>; }; template<typename Type, regular_abi ABI = EVE_CURRENT_ABI> using expected_cardinal_t = typename expected_cardinal<Type, ABI>::type; template<typename Type, regular_abi ABI = EVE_CURRENT_ABI> constexpr inline auto expected_cardinal_v = expected_cardinal<Type, ABI>::value; //================================================================================================ // Cardinal template inline object for passing cardinal values to functions like load/store //================================================================================================ template<typename Type, typename API = EVE_CURRENT_ABI> inline constexpr expected_cardinal<Type,API> const expected = {}; }
32.458333
100
0.563971
orao
050c358474303c62e21d1235654cc73d78715399
482
hh
C++
dune/gdt/spaces/continuouslagrange.hh
ftalbrecht/dune-gdt
574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9
[ "BSD-2-Clause" ]
null
null
null
dune/gdt/spaces/continuouslagrange.hh
ftalbrecht/dune-gdt
574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9
[ "BSD-2-Clause" ]
null
null
null
dune/gdt/spaces/continuouslagrange.hh
ftalbrecht/dune-gdt
574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9
[ "BSD-2-Clause" ]
1
2018-08-13T11:51:27.000Z
2018-08-13T11:51:27.000Z
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_HH #define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_HH #warning This header is deprecated, include <dune/gdt/spaces/cg.hh> instead (21.11.2014)! #include <dune/gdt/spaces/cg.hh> #endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_HH
37.076923
89
0.788382
ftalbrecht
050eb0549e2f8900c0aeb8ef37b0697eb790d62a
4,921
cpp
C++
SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.cpp
ErwanLegrand/Arduino-Source
21dd2087b3941db10542ab5858663d07ca0de751
[ "MIT" ]
null
null
null
SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.cpp
ErwanLegrand/Arduino-Source
21dd2087b3941db10542ab5858663d07ca0de751
[ "MIT" ]
null
null
null
SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.cpp
ErwanLegrand/Arduino-Source
21dd2087b3941db10542ab5858663d07ca0de751
[ "MIT" ]
null
null
null
/* Max Lair Detect Path Map * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include "CommonFramework/Tools/ErrorDumper.h" #include "CommonFramework/Inference/ImageTools.h" #include "NintendoSwitch/Commands/NintendoSwitch_PushButtons.h" #include "PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h" #include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" #include "PokemonSwSh_MaxLair_Detect_PathMap.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonSwSh{ namespace MaxLairInternal{ bool read_type_array( ConsoleHandle& console, const QImage& screen, const ImageFloatBox& box, std::deque<InferenceBoxScope>& hits, size_t count, PokemonType* type, ImagePixelBox* boxes ){ QImage image = extract_box(screen, box); for (size_t c = 0; c < count; c++){ type[c] = PokemonType::NONE; } std::multimap<double, std::pair<PokemonType, ImagePixelBox>> candidates = find_symbols(image, 0.20); if (candidates.size() < count){ // dump_image(console, screen, "ReadPath"); return false; } std::multimap<pxint_t, const std::pair<PokemonType, ImagePixelBox>*> sorted; // std::deque<InferenceBoxScope> hits; hits.clear(); size_t c = 0; for (const auto& item : candidates){ hits.emplace_back(console.overlay(), translate_to_parent(screen, box, item.second.second), Qt::green); sorted.emplace(item.second.second.min_x, &item.second); c++; if (c >= count){ break; } } c = 0; for (const auto& item : sorted){ type[c] = item.second->first; if (boxes != nullptr){ boxes[c] = item.second->second; } c++; } return true; } QImage read_type_array_retry( ProgramEnvironment& env, ConsoleHandle& console, const ImageFloatBox& box, std::deque<InferenceBoxScope>& hits, size_t count, PokemonType* type, ImagePixelBox* boxes, size_t max_attempts = 3 ){ QImage screen; for (size_t c = 0; c < max_attempts; c++){ screen = console.video().snapshot(); if (read_type_array(console, screen, box, hits, count, type, boxes)){ return QImage(); } env.wait_for(std::chrono::milliseconds(200)); } return screen; } bool read_path( ProgramEnvironment& env, ConsoleHandle& console, PathMap& path, const ImageFloatBox& box ){ console.botbase().wait_for_all_requests(); std::deque<InferenceBoxScope> hits; QImage error_image; error_image = read_type_array_retry(env, console, box, hits, 2, path.mon1, nullptr); if (!error_image.isNull()){ dump_image(console, env.program_info(), "ReadPath", error_image); return false; } pbf_move_right_joystick(console, 128, 0, 70, 50); console.botbase().wait_for_all_requests(); ImagePixelBox boxes[4]; error_image = read_type_array_retry(env, console, box, hits, 4, path.mon2, boxes); if (!error_image.isNull()){ dump_image(console, env.program_info(), "ReadPath", error_image); return false; } while (true){ pbf_move_right_joystick(console, 128, 0, 80, 50); console.botbase().wait_for_all_requests(); error_image = read_type_array_retry(env, console, box, hits, 4, path.mon3, nullptr); if (error_image.isNull()){ break; } pbf_move_right_joystick(console, 128, 0, 20, 50); console.botbase().wait_for_all_requests(); error_image = read_type_array_retry(env, console, box, hits, 4, path.mon3, nullptr); if (error_image.isNull()){ break; } dump_image(console, env.program_info(), "ReadPath", error_image); return false; } pbf_move_right_joystick(console, 128, 0, 125, 50); console.botbase().wait_for_all_requests(); error_image = read_type_array_retry(env, console, box, hits, 1, &path.boss, nullptr); if (!error_image.isNull()){ dump_image(console, env.program_info(), "ReadPath", error_image); return false; } if (boxes[0].min_y < boxes[2].min_y && boxes[2].min_y < boxes[1].min_y && boxes[1].min_y < boxes[3].min_y ){ path.path_type = 2; return true; } if ( boxes[3].min_y > boxes[0].min_y && boxes[0].min_y > boxes[1].min_y && boxes[0].min_y > boxes[2].min_y ){ path.path_type = 1; return true; } if ( boxes[2].min_y < boxes[0].min_y && boxes[0].min_y < boxes[1].min_y && boxes[1].min_y < boxes[3].min_y ){ path.path_type = 0; return true; } return false; } } } } }
28.281609
111
0.606178
ErwanLegrand
0510e34a6bfe0d0dc2394103bf669939942b44fc
4,243
cpp
C++
source/webserver.cpp
martin-juul/greenhouse
31ddd9e37dd92d0be22c1a41cd84a5e7e45710ff
[ "Apache-2.0" ]
null
null
null
source/webserver.cpp
martin-juul/greenhouse
31ddd9e37dd92d0be22c1a41cd84a5e7e45710ff
[ "Apache-2.0" ]
null
null
null
source/webserver.cpp
martin-juul/greenhouse
31ddd9e37dd92d0be22c1a41cd84a5e7e45710ff
[ "Apache-2.0" ]
null
null
null
#include "http/http_response_builder.h" #include "webserver.h" #include "EthernetInterface.h" #include "mbed.h" #include "website.h" #include <cstring> #include <string> #define IP "192.168.1.100" #define GATEWAY "192.168.1.1" #define NETMASK "255.255.255.0" #define PORT 80 Database *db; EthernetInterface *net; TCPSocket server; TCPSocket *client_socket; SocketAddress client_address; char rx_buffer[1024] = {0}; char tx_buffer[1024] = {0}; int requests = 0; WebServer::WebServer(Database *database) { db = database; } int WebServer::start() { net = new EthernetInterface; if (!net) { return 0; } net->set_network(IP, NETMASK, GATEWAY); // include to use static IP address nsapi_size_or_error_t r = net->connect(); if (r != 0) { printf("[webserver]: error! net->connect() returned: %d\n", r); return r; } // Show the network address SocketAddress ip; SocketAddress netmask; SocketAddress gateway; net->get_ip_address(&ip); net->get_netmask(&netmask); net->get_gateway(&gateway); ip.set_port(PORT); const char *ip_addr = ip.get_ip_address(); const char *netmask_addr = netmask.get_ip_address(); const char *gateway_addr = gateway.get_ip_address(); printf("[webserver]: IP address: %s\n", ip_addr ? ip_addr : "None"); printf("[webserver]: Netmask: %s\n", netmask_addr ? netmask_addr : "None"); printf("[webserver]: Gateway: %s\n", gateway_addr ? gateway_addr : "None"); server.open(net); server.bind(ip); server.listen(MAX_CONN); return 1; }; void http_ok() { sprintf(tx_buffer, "HTTP/1.1 200 OK\n" "Content-Length: %d\n" "Content-Type: text\n" "Connection: Close\n", strlen(rx_buffer)); } void http_no_content() { sprintf(tx_buffer, "HTTP/1.1 204 No Content\n" "Connection: Close\n"); } void http_not_found() { sprintf(tx_buffer, "HTTP/1.1 404 Not Found\n" "Connection: Close\n"); } void http_internal_server_error() { sprintf(tx_buffer, "HTTP/1.1 500 Internal Server Error\n" "Connection: Close\n"); } void WebServer::tick() { printf("=========================================\n"); nsapi_error_t error = 0; client_socket = server.accept(&error); requests++; if (error != 0) { printf("[webserver]: Connection failed!\n"); } else { client_socket->set_timeout( 0); // timeout of 0 makes it a non-blocking connection client_socket->getpeername(&client_address); printf("[webserver]: Client with IP address %s connected.\n", client_address.get_ip_address()); error = client_socket->recv(rx_buffer, sizeof(rx_buffer)); switch (error) { case 0: printf("[webserver]: Recieved buffer is empty.\n"); http_internal_server_error(); break; case -1: printf("[webserver]: Failed to read data from client.\n"); http_internal_server_error(); break; default: printf("[webserver]: Recieved Data: %d bytes\n%.*s\n", strlen(rx_buffer), strlen(rx_buffer), rx_buffer); printf("%c", rx_buffer[4]); if (rx_buffer[0] == 'G' && rx_buffer[1] == 'E' && rx_buffer[2] == 'T' && rx_buffer[4] == '/' && rx_buffer[5] == ' ') { // setup http response header & data http_ok(); strcpy(tx_buffer, homepage); } else if (rx_buffer[0] == 'P' && rx_buffer[1] == 'O' && rx_buffer[2] == 'S' && rx_buffer[3] == 'T') { // POST request string s = string(rx_buffer); int len = s.length(); string data = s.substr(len - 11, len); string temp = data.substr(0, 4); string dewity = data.substr(4, 4).substr(1, 2); // wat 🤡 string humidity = data.substr(8, 9); Row r = Row(); r.temperature = temp; r.dewity = dewity; r.humidity = humidity; db->append(r); HttpResponseBuilder builder(204); builder.send(client_socket, nullptr, 0); http_no_content(); } else { http_not_found(); } client_socket->send(tx_buffer, strlen(tx_buffer)); break; } } client_socket->close(); } TCPSocket *WebServer::getSocket() { return client_socket; }
25.715152
79
0.605232
martin-juul
0515c6c4967582ad580d47c8cbd5b4faa862daa8
952
cpp
C++
codeforces/1408B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1408B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1408B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// B. Arrays Sum #include <iostream> #include <set> using namespace std; int main(){ int t; cin >> t; while (t--){ int n, k; cin >> n >> k; set<int> st; int tmp; for (int i=0; i<n; ++i){ cin >> tmp; st.insert(tmp); } int ans; int c = st.size(); // Editorial - https://codeforces.com/blog/entry/83233 // Errichto's - https://www.youtube.com/watch?v=-L7ZmRjlHmI if (k==1) { if (c>1) ans = -1; else ans = 1; } /* Test: #9 1 4 4 1 1 1 1 */ else if (k >= c){ ans = 1; } else { --c; // https://stackoverflow.com/questions/17944/how-to-round-up-the-result-of-integer-division ans = (c + (k-1)-1) / (k-1); } cout << ans << endl; } return 0; }
16.135593
103
0.392857
sgrade
05162d4e4ecefcbe8121d9ce2d4723fd18a4357a
601
cpp
C++
prime_factor.cpp
fastestmk/Competitive-Programming-Algorithms
45ecdfadb070659bcdd4c007205a785442ffe7f1
[ "MIT" ]
null
null
null
prime_factor.cpp
fastestmk/Competitive-Programming-Algorithms
45ecdfadb070659bcdd4c007205a785442ffe7f1
[ "MIT" ]
null
null
null
prime_factor.cpp
fastestmk/Competitive-Programming-Algorithms
45ecdfadb070659bcdd4c007205a785442ffe7f1
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; // A function to print all prime factors of a given number n void primeFactor(int n){ // Print the number of 2s that divide n while(n%2 == 0){ cout << 2 << " "; n = n/2; } // // Print the number of other prime(3, 5, .....) that divide n for(int i = 3; i <= sqrt(n); i+=2 ){ while(n%i == 0){ cout << i << " "; n = n/i; } } // This condition is to handle the case when n // is a prime number greater than 2 (e.g. 1025 gives 5 5 41) if(n>2) cout << n << " "; } int main(){ int n; cin >> n; primeFactor(n); }
17.171429
65
0.560732
fastestmk
051969b5127e23b415713ed19592072d50df4047
2,743
cpp
C++
test/std/input.output/iostreams.base/ios.base/ios.types/ios_fmtflags/fmtflags.pass.cpp
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
test/std/input.output/iostreams.base/ios.base/ios.types/ios_fmtflags/fmtflags.pass.cpp
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
test/std/input.output/iostreams.base/ios.base/ios.types/ios_fmtflags/fmtflags.pass.cpp
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <ios> // class ios_base // static const fmtflags boolalpha; // static const fmtflags dec; // static const fmtflags fixed; // static const fmtflags hex; // static const fmtflags internal; // static const fmtflags left; // static const fmtflags oct; // static const fmtflags right; // static const fmtflags scientific; // static const fmtflags showbase; // static const fmtflags showpoint; // static const fmtflags showpos; // static const fmtflags skipws; // static const fmtflags unitbuf; // static const fmtflags uppercase; // static const fmtflags adjustfield = left | right | internal; // static const fmtflags basefield = dec | oct | hex; // static const fmtflags floatfield = scientific | fixed; #include <ios.hxx> #include <cassert.hxx> #include "test_macros.h" int main(int, char**) { assert(std::ios_base::boolalpha); assert(std::ios_base::dec); assert(std::ios_base::fixed); assert(std::ios_base::hex); assert(std::ios_base::internal); assert(std::ios_base::left); assert(std::ios_base::oct); assert(std::ios_base::right); assert(std::ios_base::scientific); assert(std::ios_base::showbase); assert(std::ios_base::showpoint); assert(std::ios_base::showpos); assert(std::ios_base::skipws); assert(std::ios_base::unitbuf); assert(std::ios_base::uppercase); assert ( ( std::ios_base::boolalpha & std::ios_base::dec & std::ios_base::fixed & std::ios_base::hex & std::ios_base::internal & std::ios_base::left & std::ios_base::oct & std::ios_base::right & std::ios_base::scientific & std::ios_base::showbase & std::ios_base::showpoint & std::ios_base::showpos & std::ios_base::skipws & std::ios_base::unitbuf & std::ios_base::uppercase) == 0 ); assert(std::ios_base::adjustfield == (std::ios_base::left | std::ios_base::right | std::ios_base::internal)); assert(std::ios_base::basefield == (std::ios_base::dec | std::ios_base::oct | std::ios_base::hex)); assert(std::ios_base::floatfield == (std::ios_base::scientific | std::ios_base::fixed)); return 0; }
32.270588
80
0.575283
K-Wu
0519ca19d336fb508420d08db88d6b43f60eb97c
3,574
cpp
C++
algorithms/graph_algorithms/traversal/advanced/dfs_general.cpp
kruztev/FMI-DSA
f509dba6cd95792ec9c4c9ad55620a3dc06c6602
[ "MIT" ]
24
2017-12-21T13:57:34.000Z
2021-12-08T01:12:32.000Z
algorithms/graph_algorithms/traversal/advanced/dfs_general.cpp
kruztev/FMI-DSA
f509dba6cd95792ec9c4c9ad55620a3dc06c6602
[ "MIT" ]
28
2018-11-01T23:34:08.000Z
2019-10-07T17:42:54.000Z
algorithms/graph_algorithms/traversal/advanced/dfs_general.cpp
kruztev/FMI-DSA
f509dba6cd95792ec9c4c9ad55620a3dc06c6602
[ "MIT" ]
4
2018-04-24T19:28:51.000Z
2020-07-19T14:06:23.000Z
/******************************************************************************* * This file is part of the "Data structures and algorithms" course. FMI 2018/19 *******************************************************************************/ /** * @file dfs_general.cpp * @author Ivan Filipov * @date 01.2019 * @brief Traversing a given graph using depth first search (DFS) strategy. * Searching for a path from a vertex to another. * * @see https://en.wikipedia.org/wiki/Depth-first_search */ #include <cstdio>// std::printf(), std::putchar() #include <queue> // std::queue #include <array> // std::array #include <vector>// std::vector #include <unordered_map> // std::unordered_map /// maximum value of each vertex const unsigned int MAX_VER_VAL = 26; /// each vertex will be a characte typedef char vertex; /// using lists of adjacent vertices representation of graph using graph = std::unordered_map<vertex, std::vector<vertex>>; /// visited array using visited = std::array<bool, MAX_VER_VAL + 1>; /** * @brief Creates a graph with some edges. * @retval the created graph */ graph init_graph() { graph G; G['A'] = { 'B' }; G['B'] = { 'C', 'D' }; G['C'] = { 'F', 'H' }; G['D'] = { 'L' }; G['F'] = { 'I' }; G['H'] = { 'I' }; G['I'] = { 'J' }; G['J'] = { 'K' }; G['L'] = { 'H' }; return G; } /** * @brief Recursively searching for path. * @param[in] G: the graph * @param[in] current: current vertex * @param[in] target: target vertex * @param[in,out] is_visited: markers for visited vertices * @retval true if there is a path */ bool dfs_find_rec(const graph& G, vertex current, vertex target, visited& is_visited) { // entering in this vertex printf("-> %c", current); // check if it is the target if (current == target) return true; // mark it as visited is_visited[current - 'A'] = true; // get iterator for the adjacent list graph::const_iterator it = G.find(current); // no such vertex if (it == G.end()) { putchar('\n'); return false; } // if we have a list for this vertex // for each of it's adjacent vertices for (vertex adj: it->second) { // if the adjacent is not visited if (!is_visited[adj - 'A']) { // go in the adjacent and run the algorithm from there if (dfs_find_rec(G, adj, target, is_visited)) return true; // if in the recursion we have found the target, return true // output that we are going back from an adjacent printf("<- %c\n",adj); } } // if we got here there are not path between current and target return false; } /// a wrapper around the recursive function bool dfs_find(const graph& G, vertex start, vertex target) { // create visited array visited is_visited = { false, }; // returns the result from the recursive function return dfs_find_rec(G, start, target, is_visited); } int main() { /* fill the graph with some vertices and edges */ graph G = init_graph(); /* which are the start and target vertices */ vertex start = 'A'; vertex target = 'P'; std::printf("\nsearching for vertex %c from %c using DFS\n\n", target, start); /* runs the algorithm with start and target */ if (dfs_find(G, start, target)) std::printf("\nfound vertex %c\n", target); else std::printf("\ncan't find vertex %c\n",target); /* change the target */ target = 'I'; std::printf("\n\nsearching for vertex %c from %c using DFS\n\n", target, start); /* runs the algorithm again */ if (dfs_find(G, start, target)) std::printf("\nfound vertex %c\n", target); else std::printf("\ncan't find %c\n", target); return 0; }
28.365079
81
0.619194
kruztev
05205ab806326da52b1ffd661aa9403c1f0d654e
170
cpp
C++
main.cpp
Orikson/Custom-3D-Physics-Engine
245bdaef7608d06545f54a29200ba3754480b5bf
[ "MIT" ]
null
null
null
main.cpp
Orikson/Custom-3D-Physics-Engine
245bdaef7608d06545f54a29200ba3754480b5bf
[ "MIT" ]
null
null
null
main.cpp
Orikson/Custom-3D-Physics-Engine
245bdaef7608d06545f54a29200ba3754480b5bf
[ "MIT" ]
null
null
null
#include "Engine/Kernel/kernel.h" int main(int argc, char* argv[]) { Kernel* kernel; kernel->start("3D Rendering", 700, 700);//argc, argv); return 0; }
18.888889
59
0.605882
Orikson
0521d0b883edce2d9225412f281780f758ffb8c7
980
cpp
C++
examples/meme_likes/main.cpp
nzikic/lru_cache
74913307bf712f94bf1f9eaff1397d0ac0c91372
[ "MIT" ]
2
2019-10-03T20:00:04.000Z
2020-08-12T07:42:46.000Z
examples/meme_likes/main.cpp
nzikic/lru_cache
74913307bf712f94bf1f9eaff1397d0ac0c91372
[ "MIT" ]
null
null
null
examples/meme_likes/main.cpp
nzikic/lru_cache
74913307bf712f94bf1f9eaff1397d0ac0c91372
[ "MIT" ]
null
null
null
#include "cache.h" #include <iostream> int main() { using namespace cache; MemeProvider provider{new MemeDataBase, 4}; auto doge = provider.get("Doge"); auto girlfriend = provider.get("Girlfriend"); auto derpina = provider.get("Derpina"); // std::cout << "I like doggos\n"; doge->like(); // std::cout << "I prefer Derpina over overly attached girlfriends..."; girlfriend->like(); derpina->like(); derpina->like(); // std::cout << "But cats are my favourites!\n"; auto cate = provider.get("Woman Yelling at a Cat"); cate->like(); // auto trollface = provider.get("Trollface"); if (trollface) trollface->like(); else std::cout << "They don't have trollface :/\n"; std::cout << "\n\n" "***********************************\n" " It's not 9gag but it's still fun!\n" "***********************************\n"; return 0; }
23.902439
72
0.508163
nzikic
0523a5ddb1a60da941f4ce7fdddd6b8b352ba398
296
cxx
C++
test/input/Class-template-recurse.cxx
radoslawcybulski/CastXML
7d8d719fdea8cad7702e62b6174b2665a4bf2ca5
[ "Apache-2.0" ]
428
2015-01-06T17:01:38.000Z
2022-03-22T12:34:03.000Z
test/input/Class-template-recurse.cxx
radoslawcybulski/CastXML
7d8d719fdea8cad7702e62b6174b2665a4bf2ca5
[ "Apache-2.0" ]
175
2015-01-06T17:07:37.000Z
2022-03-07T23:06:02.000Z
test/input/Class-template-recurse.cxx
radoslawcybulski/CastXML
7d8d719fdea8cad7702e62b6174b2665a4bf2ca5
[ "Apache-2.0" ]
101
2015-01-25T14:18:42.000Z
2022-02-05T08:56:06.000Z
template <typename T> struct A; template <typename T> struct C; template <typename T> struct B { typedef C<T> type; }; template <typename T> struct C { C() { /* clang-format off */ static_cast<void>(sizeof(typename B< A<T> >::type)); /* clang-format on */ } }; C<void> start;
14.095238
56
0.618243
radoslawcybulski
0524df31e203cdd8a198b77a0c11e540738b5690
950
cpp
C++
backup/2/codesignal/c++/longest-word.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/codesignal/c++/longest-word.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/codesignal/c++/longest-word.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/codesignal/longest-word.html . #include <regex> std::string longestWord(std::string text) { using namespace std; regex reg("[a-zA-Z]+"); string res = ""; for (auto it = sregex_iterator(text.begin(), text.end(), reg); it != sregex_iterator(); it++) { auto item = it->str(); if (item.size() > res.size()) { res = item; } } return res; }
45.238095
345
0.668421
yangyanzhan
0527053a95db27eea4c3da0542103e5a146f0f09
1,172
cpp
C++
src/Date.cpp
Abdsaddik/Hotel-Reservation-System
f376a7134de634b4912c5bd5bc00dcf655c40cd8
[ "MIT" ]
null
null
null
src/Date.cpp
Abdsaddik/Hotel-Reservation-System
f376a7134de634b4912c5bd5bc00dcf655c40cd8
[ "MIT" ]
null
null
null
src/Date.cpp
Abdsaddik/Hotel-Reservation-System
f376a7134de634b4912c5bd5bc00dcf655c40cd8
[ "MIT" ]
null
null
null
#include "Date.hpp" constexpr int Date::monthDays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; Date::Date(std::string day, std::string month, std::string year) : day_{ day } , month_{ month } , year_{ year } { } std::istream& operator>>(std::istream& i, Date& d) { std::string date; while (true) { std::cout << "for which date (enter birth in format DD.MM.YYYY): "; std::getline(std::cin, date, '\n'); if (std::regex_match(date, date_expr)) { std::remove(date.begin(), date.end(), ' '); d.day_ = date.substr(0, 2); d.month_ = date.substr(3, 2); d.year_ = date.substr(6, 4); break; } else if (date.size() == 0) return i; else { std::cout << "invalid input\n"; } } return i; } std::ostream& operator<<(std::ostream& o, const Date& d) { return o << d.day_ + '.' + d.month_ + '.' + d.year_; } bool operator==(const Date& d1, const Date& d2) { return (d1.day_ == d2.day_) && (d1.month_ == d1.month_) && (d2.year_ == d2.year_); } Date::~Date() { }
25.478261
87
0.494027
Abdsaddik
05272089ea5994c4f2b46068472150a76ccb8328
274
hpp
C++
include/exotico.hpp
fernandocunhapereira/petfera
6c1a3661df2561f53691abc548b1ce4202a3ba1e
[ "MIT" ]
null
null
null
include/exotico.hpp
fernandocunhapereira/petfera
6c1a3661df2561f53691abc548b1ce4202a3ba1e
[ "MIT" ]
null
null
null
include/exotico.hpp
fernandocunhapereira/petfera
6c1a3661df2561f53691abc548b1ce4202a3ba1e
[ "MIT" ]
1
2020-11-18T21:06:29.000Z
2020-11-18T21:06:29.000Z
#pragma once #include <iostream> using std::string; class Exotico{ protected: string origem; public: Exotico(string origem); virtual ~Exotico(); string getOrigem() const; void setOrigem(string origem); };
15.222222
38
0.569343
fernandocunhapereira
052844a514dcef38eb18e20de165e6fdd03ede7e
3,844
cpp
C++
Code/Applications/ResourceServer/ResourceServerWorker.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
[ "MIT" ]
419
2022-01-27T19:37:43.000Z
2022-03-31T06:14:22.000Z
Code/Applications/ResourceServer/ResourceServerWorker.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
2
2022-01-28T20:35:33.000Z
2022-03-13T17:42:52.000Z
Code/Applications/ResourceServer/ResourceServerWorker.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
20
2022-01-27T20:41:02.000Z
2022-03-26T16:16:57.000Z
#include "ResourceServerWorker.h" //------------------------------------------------------------------------- namespace KRG::Resource { ResourceServerWorker::ResourceServerWorker( TaskSystem* pTaskSystem, String const& workerFullPath ) : m_pTaskSystem( pTaskSystem ) , m_workerFullPath( workerFullPath ) { KRG_ASSERT( pTaskSystem != nullptr && !m_workerFullPath.empty() ); m_SetSize = 1; } ResourceServerWorker::~ResourceServerWorker() { KRG_ASSERT( !subprocess_alive( &m_subProcess ) ); } void ResourceServerWorker::Compile( CompilationRequest* pRequest ) { KRG_ASSERT( IsIdle() ); KRG_ASSERT( pRequest != nullptr && pRequest->IsPending() ); m_pRequest = pRequest; m_pRequest->m_status = CompilationRequest::Status::Compiling; m_status = Status::Compiling; m_pTaskSystem->ScheduleTask( this ); } void ResourceServerWorker::ExecuteRange( TaskSetPartition range, uint32 threadnum ) { KRG_ASSERT( IsCompiling() ); KRG_ASSERT( !m_pRequest->m_compilerArgs.empty() ); char const* processCommandLineArgs[4] = { m_workerFullPath.c_str(), "-compile", m_pRequest->m_compilerArgs.c_str(), nullptr }; // Start compiler process //------------------------------------------------------------------------- m_pRequest->m_compilationTimeStarted = PlatformClock::GetTime(); int32 result = subprocess_create( processCommandLineArgs, subprocess_option_combined_stdout_stderr | subprocess_option_inherit_environment | subprocess_option_no_window, &m_subProcess ); if ( result != 0 ) { m_pRequest->m_status = CompilationRequest::Status::Failed; m_pRequest->m_log = "Resource compiler failed to start!"; m_pRequest->m_compilationTimeFinished = PlatformClock::GetTime(); m_status = Status::Complete; return; } // Wait for compilation to complete //------------------------------------------------------------------------- int32 exitCode; result = subprocess_join( &m_subProcess, &exitCode ); if ( result != 0 ) { m_pRequest->m_status = CompilationRequest::Status::Failed; m_pRequest->m_log = "Resource compiler failed to complete!"; m_pRequest->m_compilationTimeFinished = PlatformClock::GetTime(); m_status = Status::Complete; subprocess_destroy( &m_subProcess ); return; } // Handle completed compilation //------------------------------------------------------------------------- m_pRequest->m_compilationTimeFinished = PlatformClock::GetTime(); switch ( exitCode ) { case 0: { m_pRequest->m_status = CompilationRequest::Status::Succeeded; } break; case 1: { m_pRequest->m_status = CompilationRequest::Status::SucceededWithWarnings; } break; default: { m_pRequest->m_status = CompilationRequest::Status::Failed; } break; } // Read error and output of process //------------------------------------------------------------------------- char readBuffer[512]; while ( fgets( readBuffer, 512, subprocess_stdout( &m_subProcess ) ) ) { m_pRequest->m_log += readBuffer; } m_status = Status::Complete; //------------------------------------------------------------------------- subprocess_destroy( &m_subProcess ); } }
35.925234
195
0.513528
JuanluMorales
0529bd4ec8c30aaca5480ce9d84e4aebd5a7c387
4,070
cpp
C++
snippets/cpp/VS_Snippets_CLR_System/system.Reflection.Emit.CustomAttributeBuilder Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-02-22T09:30:21.000Z
2021-08-02T23:44:31.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Reflection.Emit.CustomAttributeBuilder Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Reflection.Emit.CustomAttributeBuilder Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <Snippet1> using namespace System; using namespace System::Threading; using namespace System::Reflection; using namespace System::Reflection::Emit; // We will apply this custom attribute to our dynamic type. public ref class ClassCreator: public Attribute { private: String^ creator; public: property String^ Creator { String^ get() { return creator; } } ClassCreator( String^ name ) { this->creator = name; } }; // We will apply this dynamic attribute to our dynamic method. public ref class DateLastUpdated: public Attribute { private: String^ dateUpdated; public: property String^ DateUpdated { String^ get() { return dateUpdated; } } DateLastUpdated( String^ theDate ) { this->dateUpdated = theDate; } }; Type^ BuildTypeWithCustomAttributesOnMethod() { AppDomain^ currentDomain = Thread::GetDomain(); AssemblyName^ myAsmName = gcnew AssemblyName; myAsmName->Name = "MyAssembly"; AssemblyBuilder^ myAsmBuilder = currentDomain->DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess::Run ); ModuleBuilder^ myModBuilder = myAsmBuilder->DefineDynamicModule( "MyModule" ); // First, we'll build a type with a custom attribute attached. TypeBuilder^ myTypeBuilder = myModBuilder->DefineType( "MyType", TypeAttributes::Public ); array<Type^>^temp6 = {String::typeid}; array<Type^>^ctorParams = temp6; ConstructorInfo^ classCtorInfo = ClassCreator::typeid->GetConstructor( ctorParams ); array<Object^>^temp0 = {"Joe Programmer"}; CustomAttributeBuilder^ myCABuilder = gcnew CustomAttributeBuilder( classCtorInfo,temp0 ); myTypeBuilder->SetCustomAttribute( myCABuilder ); // Now, let's build a method and add a custom attribute to it. array<Type^>^temp1 = gcnew array<Type^>(0); MethodBuilder^ myMethodBuilder = myTypeBuilder->DefineMethod( "HelloWorld", MethodAttributes::Public, nullptr, temp1 ); array<Type^>^temp7 = {String::typeid}; ctorParams = temp7; classCtorInfo = DateLastUpdated::typeid->GetConstructor( ctorParams ); array<Object^>^temp2 = {DateTime::Now.ToString()}; CustomAttributeBuilder^ myCABuilder2 = gcnew CustomAttributeBuilder( classCtorInfo,temp2 ); myMethodBuilder->SetCustomAttribute( myCABuilder2 ); ILGenerator^ myIL = myMethodBuilder->GetILGenerator(); myIL->EmitWriteLine( "Hello, world!" ); myIL->Emit( OpCodes::Ret ); return myTypeBuilder->CreateType(); } int main() { Type^ myType = BuildTypeWithCustomAttributesOnMethod(); Object^ myInstance = Activator::CreateInstance( myType ); array<Object^>^customAttrs = myType->GetCustomAttributes( true ); Console::WriteLine( "Custom Attributes for Type 'MyType':" ); Object^ attrVal = nullptr; System::Collections::IEnumerator^ myEnum = customAttrs->GetEnumerator(); while ( myEnum->MoveNext() ) { Object^ customAttr = safe_cast<Object^>(myEnum->Current); array<Object^>^temp3 = gcnew array<Object^>(0); attrVal = ClassCreator::typeid->InvokeMember( "Creator", BindingFlags::GetProperty, nullptr, customAttr, temp3 ); Console::WriteLine( "-- Attribute: [{0} = \"{1}\"]", customAttr, attrVal ); } Console::WriteLine( "Custom Attributes for Method 'HelloWorld()' in 'MyType':" ); customAttrs = myType->GetMember( "HelloWorld" )[ 0 ]->GetCustomAttributes( true ); System::Collections::IEnumerator^ myEnum2 = customAttrs->GetEnumerator(); while ( myEnum2->MoveNext() ) { Object^ customAttr = safe_cast<Object^>(myEnum2->Current); array<Object^>^temp4 = gcnew array<Object^>(0); attrVal = DateLastUpdated::typeid->InvokeMember( "DateUpdated", BindingFlags::GetProperty, nullptr, customAttr, temp4 ); Console::WriteLine( "-- Attribute: [{0} = \"{1}\"]", customAttr, attrVal ); } Console::WriteLine( "---" ); array<Object^>^temp5 = gcnew array<Object^>(0); Console::WriteLine( myType->InvokeMember( "HelloWorld", BindingFlags::InvokeMethod, nullptr, myInstance, temp5 ) ); } // </Snippet1>
34.201681
126
0.69656
BohdanMosiyuk
053033c2002f1ab5f2544a96ffce27294f95f20d
7,788
cpp
C++
Compiler/Types/Class.cpp
rozaxe/emojicode
de62ef1871859429e569e4275c38c18bd43c5271
[ "Artistic-2.0" ]
1
2018-12-31T03:57:28.000Z
2018-12-31T03:57:28.000Z
Compiler/Types/Class.cpp
rozaxe/emojicode
de62ef1871859429e569e4275c38c18bd43c5271
[ "Artistic-2.0" ]
null
null
null
Compiler/Types/Class.cpp
rozaxe/emojicode
de62ef1871859429e569e4275c38c18bd43c5271
[ "Artistic-2.0" ]
1
2019-01-01T13:34:14.000Z
2019-01-01T13:34:14.000Z
// // Class.c // EmojicodeCompiler // // Created by Theo Weidmann on 05.01.15. // Copyright (c) 2015 Theo Weidmann. All rights reserved. // #include "Class.hpp" #include "Analysis/SemanticAnalyser.hpp" #include "Compiler.hpp" #include "CompilerError.hpp" #include "Functions/Initializer.hpp" #include "Package/Package.hpp" #include "TypeContext.hpp" #include "Utils/StringUtils.hpp" #include <algorithm> #include <utility> namespace EmojicodeCompiler { Class::Class(std::u32string name, Package *pkg, SourcePosition p, const std::u32string &documentation, bool exported, bool final, bool foreign) : TypeDefinition(std::move(name), pkg, p, documentation, exported), final_(final), foreign_(foreign) { instanceScope() = Scope(2); // reassign a scoper with one offset for the pointer to the class meta } std::vector<Type> Class::superGenericArguments() const { if (superType_ != nullptr && superType_->wasAnalysed()) { return superType_->type().genericArguments(); } return std::vector<Type>(); } void Class::analyseSuperType() { if (superType() == nullptr) { return; } auto classType = Type(this); auto &type = superType()->analyseType(TypeContext(classType)); if (type.type() != TypeType::Class) { throw CompilerError(superType()->position(), "The superclass must be a class."); } if (type.klass()->superType() != nullptr && !type.klass()->superType()->wasAnalysed()) { type.klass()->analyseSuperType(); } if (type.klass()->final()) { package()->compiler()->error(CompilerError(superType()->position(), type.toString(TypeContext(classType)), " can’t be used as superclass as it was marked with 🔏.")); } type.klass()->setHasSubclass(); std::vector<std::u32string> missing; std::set_difference(type.klass()->requiredInitializers_.begin(), type.klass()->requiredInitializers_.end(), requiredInitializers_.begin(), requiredInitializers_.end(), std::back_inserter(missing)); for (auto &name : missing) { package()->compiler()->error(CompilerError(position(), "Required initializer ", utf8(name), " was not implemented.")); } offsetIndicesBy(type.genericArguments().size()); for (size_t i = type.typeDefinition()->superGenericArguments().size(); i < type.genericArguments().size(); i++) { if (type.genericArguments()[i].type() == TypeType::GenericVariable) { auto newIndex = type.genericArguments()[i].genericVariableIndex() + type.genericArguments().size(); type.setGenericArgument(i, Type(newIndex, this)); } else if (type.genericArguments()[i].type() == TypeType::Box && type.genericArguments()[i].unboxedType() == TypeType::GenericVariable) { auto newIndex = type.genericArguments()[i].unboxed().genericVariableIndex() + type.genericArguments().size(); type.setGenericArgument(i, Type(newIndex, this).boxedFor(type.genericArguments()[i].boxedFor())); } } } void Class::inherit(SemanticAnalyser *analyser) { if (superType() == nullptr) { analyser->declareInstanceVariables(Type(this)); eachFunction([](auto *function) { if (function->accessLevel() == AccessLevel::Default) { function->setAccessLevel(AccessLevel::Public); } }); return; } if (instanceVariables().empty() && initializerList().empty()) { inheritsInitializers_ = true; } instanceScope() = superclass()->instanceScope(); instanceScope().markInherited(); analyser->declareInstanceVariables(Type(this)); Type classType = Type(this); instanceVariablesMut().insert(instanceVariables().begin(), superclass()->instanceVariables().begin(), superclass()->instanceVariables().end()); protocols_.reserve(superclass()->protocols().size()); for (auto &protocol : superclass()->protocols()) { auto find = std::find_if(protocols_.begin(), protocols_.end(), [&classType, &protocol](auto &a) { return a->type().identicalTo(protocol->type(), TypeContext(classType), nullptr); }); if (find != protocols_.end()) { analyser->compiler()->error(CompilerError(position(), "Superclass already declared conformance to ", protocol->type().toString(TypeContext(classType)), ".")); } protocols_.emplace_back(protocol); } eachFunctionWithoutInitializers([this, analyser](Function *function) { checkOverride(function, analyser); }); } void Class::checkOverride(Function *function, SemanticAnalyser *analyser) { auto superFunction = findSuperFunction(function); if (function->overriding()) { if (superFunction == nullptr) { throw CompilerError(function->position(), utf8(function->name()), " was declared ✒️ but does not override anything."); } auto layer = analyser->enforcePromises(function, superFunction, Type(superclass()), TypeContext(Type(this)), TypeContext()); if (function->accessLevel() == AccessLevel::Default) { function->setAccessLevel(superFunction->accessLevel()); } if (layer != nullptr) { function->setVirtualTableThunk(layer.get()); addMethod(std::move(layer)); } } else if (superFunction != nullptr) { analyser->compiler()->error(CompilerError(function->position(), "If you want to override ", utf8(function->name()), " add ✒️.")); } else if (function->accessLevel() == AccessLevel::Default) { function->setAccessLevel(AccessLevel::Public); } } void Class::addInstanceVariable(const InstanceVariableDeclaration &declaration) { if (foreign()) { throw CompilerError(position(), "Instance variables are not allowed in foreign class."); } TypeDefinition::addInstanceVariable(declaration); } bool Class::canResolve(TypeDefinition *resolutionConstraint) const { if (auto cl = dynamic_cast<Class *>(resolutionConstraint)) { return inheritsFrom(cl); } return false; } bool Class::inheritsFrom(Class *from) const { for (const Class *a = this; a != nullptr; a = a->superclass()) { if (a == from) { return true; } } return false; } Initializer* Class::lookupInitializer(const std::u32string &name) const { for (auto klass = this; klass != nullptr; klass = klass->superclass()) { if (auto initializer = klass->TypeDefinition::lookupInitializer(name)) { return initializer; } if (!klass->inheritsInitializers()) { break; } } return nullptr; } Function * Class::lookupMethod(const std::u32string &name, Mood mood) const { for (auto klass = this; klass != nullptr; klass = klass->superclass()) { if (auto method = klass->TypeDefinition::lookupMethod(name, mood)) { return method; } } return nullptr; } Function * Class::lookupTypeMethod(const std::u32string &name, Mood mood) const { for (auto klass = this; klass != nullptr; klass = klass->superclass()) { if (auto method = klass->TypeDefinition::lookupTypeMethod(name, mood)) { return method; } } return nullptr; } void Class::handleRequiredInitializer(Initializer *init) { requiredInitializers_.insert(init->name()); } } // namespace EmojicodeCompiler
37.990244
121
0.616975
rozaxe
053217b95f12febd1949efc0ffc8b93b18464f22
5,026
cpp
C++
general/toaster/toastDrv/umdf/func/Driver.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,084
2015-03-18T04:40:32.000Z
2019-05-06T17:14:33.000Z
general/toaster/toastDrv/umdf/func/Driver.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
275
2015-03-19T18:44:41.000Z
2019-05-06T14:13:26.000Z
general/toaster/toastDrv/umdf/func/Driver.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,091
2015-03-19T00:08:54.000Z
2019-05-06T16:42:01.000Z
/*++ Copyright (c) Microsoft Corporation, All Rights Reserved Module Name: Driver.cpp Abstract: This file contains the implementation for the driver object. Environment: Windows User-Mode Driver Framework (WUDF) --*/ #include "stdafx.h" #include "Driver.h" #include "Device.h" #include "Queue.h" #include "internal.h" #include "driver.tmh" //Idle setting for the Toaster device #define IDLEWAKE_TIMEOUT_MSEC 6000 HRESULT CDriver::OnDeviceAdd( _In_ IWDFDriver* pDriver, _In_ IWDFDeviceInitialize* pDeviceInit ) /*++ Routine Description: The framework calls this function when a device is being added to the driver stack. Arguments: IWDFDriver - Framework interface. The driver uses this interface to create device objects. IWDFDeviceInitialize - Framework interface. The driver uses this interface to set device parameters before creating the device obeject. Return Value: HRESULT S_OK - Device added successfully --*/ { IUnknown *pDeviceCallback = NULL; IWDFDevice *pIWDFDevice = NULL; IWDFDevice2 *pIWDFDevice2 = NULL; IUnknown *pIUnkQueue = NULL; // // UMDF Toaster is a function driver so set is as the power policy owner (PPO) // pDeviceInit->SetPowerPolicyOwnership(TRUE); // // Create our device callback object. // HRESULT hr = CDevice::CreateInstance(&pDeviceCallback); // // Ask the framework to create a device object for us. // We pass in the callback object and device init object // as creation parameters. // if (SUCCEEDED(hr)) { hr = pDriver->CreateDevice(pDeviceInit, pDeviceCallback, &pIWDFDevice); } // // Create the queue callback object. // if (SUCCEEDED(hr)) { hr = CQueue::CreateInstance(&pIUnkQueue); } // // Configure the default queue. We pass in our queue callback // object to inform the framework about the callbacks we want. // if (SUCCEEDED(hr)) { IWDFIoQueue * pDefaultQueue = NULL; hr = pIWDFDevice->CreateIoQueue( pIUnkQueue, TRUE, // bDefaultQueue WdfIoQueueDispatchParallel, TRUE, // bPowerManaged FALSE, // bAllowZeroLengthRequests &pDefaultQueue); SAFE_RELEASE(pDefaultQueue); } // // Enable the device interface. // if (SUCCEEDED(hr)) { hr = pIWDFDevice->CreateDeviceInterface(&GUID_DEVINTERFACE_TOASTER, NULL); } // // IWDFDevice2 interface is an extension of IWDFDevice interface that enables // Idle and Wake support. // // // Get a pointer to IWDFDevice2 interface // if (SUCCEEDED(hr)) { hr = pIWDFDevice->QueryInterface(__uuidof(IWDFDevice2), (void**) &pIWDFDevice2); } // // Since this is a virtual device we tell the framework that we cannot wake // ourself if we sleep in S0. Only way the device can be brought to D0 is if // the device recieves an I/O from the system. // if (SUCCEEDED(hr)) { hr = pIWDFDevice2->AssignS0IdleSettings( IdleCannotWakeFromS0, PowerDeviceD3, //the lowest-powered device sleeping state IDLEWAKE_TIMEOUT_MSEC, //idle timeout IdleAllowUserControl, //user can control the device's idle behavior. WdfTrue); } // // TODO: Add the Idle and Wake suupport specific for your hardware // SAFE_RELEASE(pDeviceCallback); SAFE_RELEASE(pIWDFDevice); SAFE_RELEASE(pIWDFDevice2); SAFE_RELEASE(pIUnkQueue); return hr; } VOID CDriver::OnDeinitialize( _In_ IWDFDriver * /* pDriver */ ) /*++ Routine Description: The framework calls this function just before de-initializing itself. All WDF framework resources should be released by driver before returning from this call. Arguments: Return Value: --*/ { return ; } HRESULT CDriver::OnInitialize( _In_ IWDFDriver * /* pDriver */ ) /*++ Routine Description: The framework calls this function just after loading the driver. The driver can perform any global, device independent intialization in this routine. Arguments: Return Value: --*/ { return S_OK; }
24.398058
100
0.557302
ixjf
05363fc8590c06573c0d400b25235f9b3f18c209
525
hpp
C++
cpp/subprojects/common/include/common/pruning/pruning_no.hpp
Waguy02/Boomer-Scripted
b06bb9213d64dca0c05d41701dea12666931618c
[ "MIT" ]
8
2020-06-30T01:06:43.000Z
2022-03-14T01:58:29.000Z
cpp/subprojects/common/include/common/pruning/pruning_no.hpp
Waguy02/Boomer-Scripted
b06bb9213d64dca0c05d41701dea12666931618c
[ "MIT" ]
3
2020-12-14T11:30:18.000Z
2022-02-07T06:31:51.000Z
cpp/subprojects/common/include/common/pruning/pruning_no.hpp
Waguy02/Boomer-Scripted
b06bb9213d64dca0c05d41701dea12666931618c
[ "MIT" ]
4
2020-06-24T08:45:00.000Z
2021-12-23T21:44:51.000Z
/* * @author Michael Rapp (michael.rapp.ml@gmail.com) */ #pragma once #include "common/pruning/pruning.hpp" /** * An implementation of the class `IPruning` that does not actually perform any pruning, but retains all conditions. */ class NoPruning final : public IPruning { public: std::unique_ptr<ICoverageState> prune(IThresholdsSubset& thresholdsSubset, IPartition& partition, ConditionList& conditions, const AbstractPrediction& head) const override; };
26.25
120
0.68
Waguy02
053cac8555a52c5d303f05bea5abd07e57ea494c
795
cpp
C++
test/integral/literals.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
2
2015-05-07T14:29:13.000Z
2015-07-04T10:59:46.000Z
test/integral/literals.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
test/integral/literals.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
/* @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #include <boost/hana/integral.hpp> #include <boost/hana/detail/assert.hpp> #include <boost/hana/type.hpp> using namespace boost::hana; using namespace literals; int main() { BOOST_HANA_CONSTANT_ASSERT(0_c == llong<0>); BOOST_HANA_CONSTANT_ASSERT(1_c == llong<1>); BOOST_HANA_CONSTANT_ASSERT(12_c == llong<12>); BOOST_HANA_CONSTANT_ASSERT(123_c == llong<123>); BOOST_HANA_CONSTANT_ASSERT(1234567_c == llong<1234567>); BOOST_HANA_CONSTANT_ASSERT(-34_c == llong<-34>); BOOST_HANA_CONSTANT_ASSERT(decltype_(-1234_c) == decltype_(llong<-1234>)); BOOST_HANA_CONSTANT_ASSERT(-12_c < 0_c); }
30.576923
78
0.740881
rbock
053d7cdb82041c46ca7dc354a4de7257d9276c88
3,881
cpp
C++
origin/math/matrix/matrix.test/solver.cpp
asutton/origin-google
516482c081a357a06402e5f288d645d3e18f69fa
[ "MIT" ]
7
2017-11-22T19:11:00.000Z
2020-08-16T15:53:10.000Z
origin/math/matrix/matrix.test/solver.cpp
asutton/origin-google
516482c081a357a06402e5f288d645d3e18f69fa
[ "MIT" ]
null
null
null
origin/math/matrix/matrix.test/solver.cpp
asutton/origin-google
516482c081a357a06402e5f288d645d3e18f69fa
[ "MIT" ]
1
2020-08-07T12:31:36.000Z
2020-08-07T12:31:36.000Z
// Copyright (c) 2008-2010 Kent State University // Copyright (c) 2011-2012 Texas A&M University // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #include <random> #include <stdexcept> #include <chrono> #include <origin/math/matrix/matrix.hpp> using namespace std; using namespace std::chrono; using namespace origin; using Mat = matrix<double, 2>; using Vec = matrix<double, 1>; // Random numbers default_random_engine eng(time(0)); // default_random_engine eng; uniform_real_distribution<> dist; auto rng = bind(ref(dist), ref(eng)); Mat random_matrix(size_t n) { Mat r(n, n); generate(r.begin(), r.end(), rng); return r; } Vec random_vector(size_t n) { Vec r(n); generate(r.begin(), r.end(), rng); return r; } template <typename M1, typename T, typename M2> matrix<T, M1::order> scale_and_add(const M1& a, const T& c, const M2& b) { assert(same_extents(a.descriptor(), b.descriptor())); matrix<T, M1::order> r(a.descriptor()); transform(a.begin(), a.end(), b.begin(), r.begin(), [&](T x, T y) { return x * c + y; }); return r; } // This is intended to wrok for vectors, not matrices. template <typename M1, typename M2> double dot_product(const M1& a, const M2& b) { return inner_product(a.begin(), a.end(), b.begin(), 0.0); } Vec multiply(const Mat& A, const Vec& x) { const size_t n = A.rows(); Vec r(n); for (size_t i = 0; i < n; ++i) r(i) = dot_product(A[i], x); return r; } void eliminate_row(Mat& A, Vec& b, size_t j) { const size_t n = A.rows(); // Pick the pivot. Make sure it's not 0. double pivot = A(j, j); if (pivot == 0) throw runtime_error("elimination error"); // Fill zeros into each element under the ith row. for (size_t i = j + 1; i < n; ++i) { double m = A(i, j) / pivot; A[i](slice(j)) = scale_and_add(A[j](slice(j)), -m, A[i](slice(j))); b(i) -= m * b(j); } } void choose_row(Mat& A, Vec& b, size_t j) { const size_t n = A.rows(); size_t r = j; // Look for a suitable pivot. for (size_t k = j + 1; k < n; ++k) { if (abs(A(k, j)) > abs(A(r, j))) r = j; } // Swap rows if we found a better one if (r != j) { A.swap_rows(j, r); swap(b(j), b(r)); } } void classical_elimination(Mat& A, Vec& b) { const size_t n = A.rows(); for (size_t j = 0; j < n - 1; ++j) eliminate_row(A, b, j); } void partial_pivoting(Mat& A, Vec& b) { const size_t n = A.rows(); for (size_t j = 0; j < n; ++j) { choose_row(A, b, j); eliminate_row(A, b, j); } } Vec back_substitution(const Mat& A, const Vec& b) { const size_t n = A.rows(); Vec x(n); for (size_t i = n - 1; i < n; --i) { double s = b(i) - dot_product(A[i](slice(i + 1)), x(slice(i + 1))); if (double m = A(i, i)) x(i) = s / m; else throw runtime_error("back substitution failure"); } return x; } Vec classical_guassian_elimination(Mat A, Vec b) { // classical_elimination(A, b); partial_pivoting(A, b); return back_substitution(A, b); } void solve(size_t n) { Mat A = random_matrix(n); Vec b = random_vector(n); cout << "A = " << pretty(A) << '\n'; cout << "b = " << pretty(b) << '\n'; cout << "==========\n"; try { Vec x = classical_guassian_elimination(A, b); cout << "x = " << x << '\n'; cout << "----------\n"; Vec r = multiply(A, x); cout << "Ax == " << r << '\n'; // should be the same as b // TODO: I could assert this, but I'm not going to. } catch(const exception& e) { cerr << e.what() << '\n'; } } int main() { solve(5); /* size_t i = 0; auto start = system_clock::now(); for ( ; i < 100; ++i) solve(100); auto stop = system_clock::now(); cout << (stop - start).count() / double(i) << '\n'; */ }
20.643617
78
0.580005
asutton
053e63782c7595b71d7c08a91405a9a19c3b3f8e
6,230
hpp
C++
include/Awl/boost/date_time/special_values_parser.hpp
Yalir/Awl
92ef5996d8933bf92ceb37357d8cd2b169cb788e
[ "BSL-1.0" ]
4
2016-07-01T02:33:28.000Z
2020-03-03T17:52:54.000Z
include/Awl/boost/date_time/special_values_parser.hpp
Yalir/Awl
92ef5996d8933bf92ceb37357d8cd2b169cb788e
[ "BSL-1.0" ]
null
null
null
include/Awl/boost/date_time/special_values_parser.hpp
Yalir/Awl
92ef5996d8933bf92ceb37357d8cd2b169cb788e
[ "BSL-1.0" ]
null
null
null
#ifndef DATE_TIME_SPECIAL_VALUES_PARSER_HPP__ #define DATE_TIME_SPECIAL_VALUES_PARSER_HPP__ /* Copyright (c) 2005 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst * $Date: */ #include "Awl/boost/date_time/string_parse_tree.hpp" #include "Awl/boost/date_time/special_defs.hpp" #include <string> #include <vector> namespace boost { namespace date_time { //! Class for special_value parsing /*! * TODO: add doc-comments for which elements can be changed * Parses input stream for strings representing special_values. * Special values parsed are: * - not_a_date_time * - neg_infin * - pod_infin * - min_date_time * - max_date_time */ template<class date_type, typename charT> class special_values_parser { public: typedef std::basic_string<charT> string_type; //typedef std::basic_stringstream<charT> stringstream_type; typedef std::istreambuf_iterator<charT> stream_itr_type; //typedef typename string_type::const_iterator const_itr; //typedef typename date_type::year_type year_type; //typedef typename date_type::month_type month_type; typedef typename date_type::duration_type duration_type; //typedef typename date_type::day_of_week_type day_of_week_type; //typedef typename date_type::day_type day_type; typedef string_parse_tree<charT> parse_tree_type; typedef typename parse_tree_type::parse_match_result_type match_results; typedef std::vector<std::basic_string<charT> > collection_type; typedef charT char_type; static const char_type nadt_string[16]; static const char_type neg_inf_string[10]; static const char_type pos_inf_string[10]; static const char_type min_date_time_string[18]; static const char_type max_date_time_string[18]; //! Creates a special_values_parser with the default set of "sv_strings" special_values_parser() { sv_strings(string_type(nadt_string), string_type(neg_inf_string), string_type(pos_inf_string), string_type(min_date_time_string), string_type(max_date_time_string)); } //! Creates a special_values_parser using a user defined set of element strings special_values_parser(const string_type& nadt_str, const string_type& neg_inf_str, const string_type& pos_inf_str, const string_type& min_dt_str, const string_type& max_dt_str) { sv_strings(nadt_str, neg_inf_str, pos_inf_str, min_dt_str, max_dt_str); } special_values_parser(typename collection_type::iterator beg, typename collection_type::iterator end) { collection_type phrases; std::copy(beg, end, std::back_inserter(phrases)); m_sv_strings = parse_tree_type(phrases, static_cast<int>(not_a_date_time)); } special_values_parser(const special_values_parser<date_type,charT>& svp) { this->m_sv_strings = svp.m_sv_strings; } //! Replace special value strings void sv_strings(const string_type& nadt_str, const string_type& neg_inf_str, const string_type& pos_inf_str, const string_type& min_dt_str, const string_type& max_dt_str) { collection_type phrases; phrases.push_back(nadt_str); phrases.push_back(neg_inf_str); phrases.push_back(pos_inf_str); phrases.push_back(min_dt_str); phrases.push_back(max_dt_str); m_sv_strings = parse_tree_type(phrases, static_cast<int>(not_a_date_time)); } /* Does not return a special_value because if the parsing fails, * the return value will always be not_a_date_time * (mr.current_match retains its default value of -1 on a failed * parse and that casts to not_a_date_time). */ //! Sets match_results.current_match to the corresponding special_value or -1 bool match(stream_itr_type& sitr, stream_itr_type& str_end, match_results& mr) const { unsigned int level = 0; m_sv_strings.match(sitr, str_end, mr, level); return (mr.current_match != match_results::PARSE_ERROR); } /*special_values match(stream_itr_type& sitr, stream_itr_type& str_end, match_results& mr) const { unsigned int level = 0; m_sv_strings.match(sitr, str_end, mr, level); if(mr.current_match == match_results::PARSE_ERROR) { throw std::ios_base::failure("Parse failed. No match found for '" + mr.cache + "'"); } return static_cast<special_values>(mr.current_match); }*/ private: parse_tree_type m_sv_strings; }; template<class date_type, class CharT> const typename special_values_parser<date_type, CharT>::char_type special_values_parser<date_type, CharT>::nadt_string[16] = {'n','o','t','-','a','-','d','a','t','e','-','t','i','m','e'}; template<class date_type, class CharT> const typename special_values_parser<date_type, CharT>::char_type special_values_parser<date_type, CharT>::neg_inf_string[10] = {'-','i','n','f','i','n','i','t','y'}; template<class date_type, class CharT> const typename special_values_parser<date_type, CharT>::char_type special_values_parser<date_type, CharT>::pos_inf_string[10] = {'+','i','n','f','i','n','i','t','y'}; template<class date_type, class CharT> const typename special_values_parser<date_type, CharT>::char_type special_values_parser<date_type, CharT>::min_date_time_string[18] = {'m','i','n','i','m','u','m','-','d','a','t','e','-','t','i','m','e'}; template<class date_type, class CharT> const typename special_values_parser<date_type, CharT>::char_type special_values_parser<date_type, CharT>::max_date_time_string[18] = {'m','a','x','i','m','u','m','-','d','a','t','e','-','t','i','m','e'}; } } //namespace #endif // DATE_TIME_SPECIAL_VALUES_PARSER_HPP__
38.9375
105
0.676886
Yalir
0544eda20f5f7285577ee539f59054822bcab601
5,777
cpp
C++
MC/MC/mcPhaseSpaceIO.cpp
RadOncSys/MC
0d39cb744b16d3bc522032483ff7fbd25dbc8b5e
[ "MIT" ]
5
2018-04-14T07:55:04.000Z
2020-10-28T09:07:09.000Z
MC/MC/mcPhaseSpaceIO.cpp
RadOncSys/MC
0d39cb744b16d3bc522032483ff7fbd25dbc8b5e
[ "MIT" ]
3
2021-11-21T06:12:17.000Z
2021-11-21T06:31:02.000Z
MC/MC/mcPhaseSpaceIO.cpp
RadOncSys/MC
0d39cb744b16d3bc522032483ff7fbd25dbc8b5e
[ "MIT" ]
2
2017-10-05T14:59:40.000Z
2021-08-02T07:24:55.000Z
#include "mcPhaseSpaceIO.h" #include "mcParticle.h" #include "mcDefs.h" #include <float.h> const unsigned int mcPhaseSpaceIO::PHOTON_LATCH = 0x00000000; const unsigned int mcPhaseSpaceIO::NEGATRON_LATCH = 0x40000000; const unsigned int mcPhaseSpaceIO::POSITRON_LATCH = 0x20000000; const unsigned int mcPhaseSpaceIO::BUFFER_SIZE = 1024; mcPhaseSpaceIO::mcPhaseSpaceIO() :open_mode_(NOT_OPEN) , mode_(UNKNOWN) , buf_pos(0) , read_pos(0) , file(nullptr) { short_buffer = new record_short_t[BUFFER_SIZE]; long_buffer = new record_long_t[BUFFER_SIZE]; reset(); } mcPhaseSpaceIO::~mcPhaseSpaceIO() { close(); delete[] short_buffer; delete[] long_buffer; } void mcPhaseSpaceIO::reset() { mode_ = UNKNOWN; if (file) { fclose(file); file = nullptr; } open_mode_ = NOT_OPEN; buf_pos = 0; read_pos = 0; preamble_.n_particles = 0; preamble_.n_photons = 0; preamble_.ekin_max = (float)0.; preamble_.e_min_electrons = FLT_MAX; preamble_.n_incident_particles = float(preamble_.n_particles); } void mcPhaseSpaceIO::close() { // If we were writing, flush the buffers and update the preamble if (open_mode_ == WRITING) { flush(); fseek(file, 5, SEEK_SET); fwrite(&preamble_, sizeof(preamble_t), 1, file); } reset(); } void mcPhaseSpaceIO::stripZLast() { unsigned int i; for (i = 0; i < buf_pos; i++) { short_buffer[i] = *reinterpret_cast<record_short_t *>(long_buffer + i); } } bool mcPhaseSpaceIO::bitReg(unsigned int i)const { unsigned int mask = 0x00000001; mask <<= i; return (latch_ & mask) > 0; } unsigned int mcPhaseSpaceIO::birthReg()const { unsigned int reg = latch_ & 0x1F000000; reg >>= 24; return reg; } void mcPhaseSpaceIO::flush() { if (open_mode_ == WRITING) { fwrite(short_buffer, sizeof(record_short_t), buf_pos, file); // ONLY MODE0 buf_pos = 0; } } void mcPhaseSpaceIO::fill() { if (open_mode_ == READING) { // Try to read the BUFFER_SIZE record, and set buf_size to the actual number // of records read if (mode_ == MODE2) { buf_pos = (unsigned)fread(long_buffer, sizeof(record_long_t), BUFFER_SIZE, file); stripZLast(); } else { buf_pos = (unsigned)fread(short_buffer, sizeof(record_short_t), BUFFER_SIZE, file); } read_pos = 0; // If we've reached the EOF, rewind the stream if (feof(file)) { fseek(file, startData(), SEEK_SET); } } } unsigned mcPhaseSpaceIO::startData() { unsigned offset = (mode_ == MODE0) ? 3 : 7; return offset + 5 + sizeof(preamble_t); } void mcPhaseSpaceIO::open(const char *filename, open_mode_e open_mode) { const char *om; switch (open_mode) { case READING: om = "rb"; break; case WRITING: om = "wb"; break; default: throw std::exception("Unknown opening mode"); } reset(); if (fopen_s(&file, filename, om) != 0) throw std::exception("Cannot open file"); open_mode_ = open_mode; if (open_mode_ == WRITING) mode_ = MODE0; // Can write only MODE0 files else { // Read preamble char modekey[5]; fread(modekey, sizeof(char), 5, file); fread(&preamble_, sizeof(preamble_t), 1, file); if (!strncmp(modekey, "MODE0", 5)) mode_ = MODE0; else if (!strncmp(modekey, "MODE2", 5)) mode_ = MODE2; char dummy[7]; switch (mode_) { case MODE0: fread(dummy, 3, 1, file); break; case MODE2: fread(dummy, 7, 1, file); break; default: throw std::exception("Format of phase space file is different from MODE0 or MODE2"); } } } mcParticle mcPhaseSpaceIO::read() { if (open_mode_ != READING) throw std::exception("File is not open for reading"); if (read_pos >= buf_pos) fill(); if (!buf_pos) fill(); if (!buf_pos) throw std::exception("No records in file"); const record_short_t& rec = short_buffer[read_pos]; read_pos++; latch_ = rec.latch_; geomVector3D r(rec.x_, rec.y_, 0.); double uz2 = 1. - rec.u_*rec.u_ - rec.v_*rec.v_; if (uz2 < 0) uz2 = 0; if (uz2 < 0.) throw std::exception("Bad direction"); double uz = sqrt(uz2); if (rec.weight_times_sign_w_ < 0.) uz = -uz; geomVector3D u(rec.u_, rec.v_, uz); mc_particle_t type = MCP_PHOTON; double ke = rec.energy_; int pq = 0; double weight = fabs(rec.weight_times_sign_w_); if (rec.latch_ & NEGATRON_LATCH) { type = MCP_NEGATRON; ke -= EMASS; pq = -1; } else if (rec.latch_ & POSITRON_LATCH) { type = MCP_POSITRON; ke -= EMASS; pq = 1; } mcParticle particle(type, pq, ke, r, u); particle.weight = weight; return particle; } void mcPhaseSpaceIO::write(const mcParticle& p) { if (open_mode_ != WRITING) throw std::exception("File is not open for writing"); if (!preamble_.n_particles) { fwrite("MODE0", sizeof(char), 5, file); fwrite(&preamble_, sizeof(preamble_t), 1, file); char dummy[7]; fwrite(dummy, 3, 1, file); } if (buf_pos >= BUFFER_SIZE) { flush(); } preamble_.n_particles++; preamble_.n_incident_particles = float(preamble_.n_particles); if (preamble_.ekin_max < p.ke) preamble_.ekin_max = (float)p.ke; record_short_t rec; rec.x_ = (float)p.p.x(); rec.y_ = (float)p.p.y(); rec.u_ = (float)p.u.x(); rec.v_ = (float)p.u.y(); rec.weight_times_sign_w_ = (float)p.weight; if (p.u.z() < 0.) rec.weight_times_sign_w_ = -rec.weight_times_sign_w_; switch (p.t) { case MCP_PHOTON: rec.latch_ = PHOTON_LATCH; rec.energy_ = (float)p.ke; preamble_.n_photons += 1; break; case MCP_POSITRON: rec.latch_ = POSITRON_LATCH; rec.energy_ = float(p.ke + EMASS); if (preamble_.e_min_electrons > float(p.ke + TWICE_EMASS)) preamble_.e_min_electrons = float(p.ke + TWICE_EMASS); break; case MCP_NEGATRON: rec.latch_ = NEGATRON_LATCH; rec.energy_ = float(p.ke + EMASS); if (preamble_.e_min_electrons > float(p.ke)) preamble_.e_min_electrons = float(p.ke); break; default: throw std::exception("Unknown particle type"); } short_buffer[buf_pos] = rec; buf_pos++; }
23.871901
115
0.684265
RadOncSys
054755c22682a3c6976221f944effa18f11dbd72
5,285
cpp
C++
src/lib/statement/class_constant.cpp
paramah/hiphop-php-osx
5ed8c24abe8ad9fd7bc6dd4c28b4ffff23e54362
[ "PHP-3.01", "Zend-2.0" ]
1
2015-11-05T21:45:07.000Z
2015-11-05T21:45:07.000Z
src/lib/statement/class_constant.cpp
brion/hiphop-php
df70a236e6418d533ac474be0c01f0ba87034d7f
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
src/lib/statement/class_constant.cpp
brion/hiphop-php
df70a236e6418d533ac474be0c01f0ba87034d7f
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <lib/statement/class_constant.h> #include <lib/analysis/analysis_result.h> #include <lib/expression/expression_list.h> #include <lib/expression/constant_expression.h> #include <lib/analysis/class_scope.h> #include <lib/analysis/constant_table.h> #include <lib/expression/assignment_expression.h> #include <lib/option.h> using namespace HPHP; using namespace std; using namespace boost; /////////////////////////////////////////////////////////////////////////////// // constructors/destructors ClassConstant::ClassConstant (STATEMENT_CONSTRUCTOR_PARAMETERS, ExpressionListPtr exp) : Statement(STATEMENT_CONSTRUCTOR_PARAMETER_VALUES), m_exp(exp) { } StatementPtr ClassConstant::clone() { ClassConstantPtr stmt(new ClassConstant(*this)); stmt->m_exp = Clone(m_exp); return stmt; } /////////////////////////////////////////////////////////////////////////////// // parser functions void ClassConstant::onParse(AnalysisResultPtr ar) { for (int i = 0; i < m_exp->getCount(); i++) { IParseHandlerPtr ph = dynamic_pointer_cast<IParseHandler>((*m_exp)[i]); ph->onParse(ar); } } /////////////////////////////////////////////////////////////////////////////// // static analysis functions void ClassConstant::analyzeProgram(AnalysisResultPtr ar) { m_exp->analyzeProgram(ar); } ConstructPtr ClassConstant::getNthKid(int n) const { switch (n) { case 0: return m_exp; default: return ConstructPtr(); } ASSERT(0); } int ClassConstant::getKidCount() const { return 1; } int ClassConstant::setNthKid(int n, ConstructPtr cp) { switch (n) { case 0: m_exp = boost::dynamic_pointer_cast<ExpressionList>(cp); return 1; default: return 0; } ASSERT(0); } StatementPtr ClassConstant::preOptimize(AnalysisResultPtr ar) { ar->preOptimize(m_exp); return StatementPtr(); } StatementPtr ClassConstant::postOptimize(AnalysisResultPtr ar) { ar->postOptimize(m_exp); return StatementPtr(); } void ClassConstant::inferTypes(AnalysisResultPtr ar) { m_exp->inferAndCheck(ar, NEW_TYPE(Some), false); } /////////////////////////////////////////////////////////////////////////////// // code generation functions void ClassConstant::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) { cg.printf("const "); m_exp->outputPHP(cg, ar); cg.printf(";\n"); } void ClassConstant::outputCPP(CodeGenerator &cg, AnalysisResultPtr ar) { bool lazyInit = cg.getContext() == CodeGenerator::CppLazyStaticInitializer; if (cg.getContext() != CodeGenerator::CppClassConstantsDecl && cg.getContext() != CodeGenerator::CppClassConstantsImpl && !lazyInit) { return; } ClassScopePtr scope = ar->getClassScope(); for (int i = 0; i < m_exp->getCount(); i++) { AssignmentExpressionPtr exp = dynamic_pointer_cast<AssignmentExpression>((*m_exp)[i]); ConstantExpressionPtr var = dynamic_pointer_cast<ConstantExpression>(exp->getVariable()); TypePtr type = scope->getConstants()->getFinalType(var->getName()); ExpressionPtr value = exp->getValue(); if (!scope->getConstants()->isDynamic(var->getName()) == lazyInit) { continue; } switch (cg.getContext()) { case CodeGenerator::CppClassConstantsDecl: cg.printf("extern const "); if (type->is(Type::KindOfString)) { cg.printf("StaticString"); } else { type->outputCPPDecl(cg, ar); } cg.printf(" %s%s_%s;\n", Option::ClassConstantPrefix, scope->getId().c_str(), var->getName().c_str()); break; case CodeGenerator::CppClassConstantsImpl: cg.printf("const "); if (type->is(Type::KindOfString)) { cg.printf("StaticString"); } else { type->outputCPPDecl(cg, ar); } cg.printf(" %s%s_%s = ", Option::ClassConstantPrefix, scope->getId().c_str(), var->getName().c_str()); value->outputCPP(cg, ar); cg.printf(";\n"); break; case CodeGenerator::CppLazyStaticInitializer: cg.printf("g->%s%s_%s = ", Option::ClassConstantPrefix, scope->getId().c_str(), var->getName().c_str()); value->outputCPP(cg, ar); cg.printf(";\n"); break; default: ASSERT(false); } } }
32.030303
79
0.56878
paramah
0549a80584768f18ad8ff1efd614446145abba17
3,012
cpp
C++
Problem Solving Paradigm/Complete Search/Iterative (Three or more Loops, Harder)/296.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
3
2019-05-22T00:36:23.000Z
2021-03-22T12:23:18.000Z
Problem Solving Paradigm/Complete Search/Iterative (Three or more Loops, Harder)/296.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
null
null
null
Problem Solving Paradigm/Complete Search/Iterative (Three or more Loops, Harder)/296.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
null
null
null
/*------------------------------------------------*/ // Uva Problem No: 296 // Problem Name: Safebreaker // Type: Iterative (Three or More Nested Loops, Harder) (Complete Search) // Autor: Joe Stifler // Data: 2018-01-14 05:35:27 // Runtime: 0.180s // Universidade: Unicamp /*------------------------------------------------*/ #include <bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); while(t--) { int n; scanf("%d%*c", &n); int x[n], y[n]; char tips[n][4]; for (int i = 0; i < n; i++) scanf("%c%c%c%c %d/%d%*c", tips[i], tips[i] + 1, tips[i] + 2, tips[i] + 3, x + i, y + i); int res[4]; bool status = false, indet = false; for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) for (int k = 0; k < 10; k++) for (int l = 0; l < 10; l++) { bool valid = true; int vec1[] = {i, j, k, l}; for (int m = 0; m < n; m++) { int vec2[] = {tips[m][0] - '0', tips[m][1] - '0', tips[m][2] - '0', tips[m][3] - '0'}; bool visited1[] = {false, false, false, false}; bool visited2[] = {false, false, false, false}; int contEq = 0, contEqdif = 0; for (int z = 0; z < 4; z++) { if (vec1[z] == vec2[z]) { visited1[z] = visited2[z] = true; contEq++; } } for (int z = 0; z < 4; z++) { if (visited2[z] == false) { for (int w = 0; w < 4; w++) { if (visited1[w] == false && vec1[w] == vec2[z]) { visited1[w] = visited2[z] = true; contEqdif++; break; } } } } if (contEq != x[m] || contEqdif != y[m]) valid = false; } if (valid) { if (status == false) { status = true; res[0] = i; res[1] = j; res[2] = k; res[3] = l; } else indet = true; } } if (status && !indet) printf("%d%d%d%d\n", res[0], res[1], res[2], res[3]); else if (status && indet) printf("indeterminate\n"); else printf("impossible\n"); } return 0; }
36.731707
114
0.290837
joe-stifler
d728ea6005676b445529f6f305aab773d5b11308
2,095
cpp
C++
dm-heom/src/heom/observation_type.cpp
noma/dm-heom
85c94f947190064d21bd38544094731113c15412
[ "BSD-3-Clause" ]
7
2019-07-28T01:02:52.000Z
2021-11-09T04:01:36.000Z
dm-heom/src/heom/observation_type.cpp
noma/dm-heom
85c94f947190064d21bd38544094731113c15412
[ "BSD-3-Clause" ]
null
null
null
dm-heom/src/heom/observation_type.cpp
noma/dm-heom
85c94f947190064d21bd38544094731113c15412
[ "BSD-3-Clause" ]
2
2020-04-04T15:20:30.000Z
2021-08-24T15:16:40.000Z
// This file is part of DM-HEOM (https://github.com/noma/dm-heom) // // Copyright (c) 2015-2019 Matthias Noack, Zuse Institute Berlin // // Licensed under the 3-clause BSD License, see accompanying LICENSE, // CONTRIBUTORS.md, and README.md for further information. #include "heom/observation_type.hpp" #include <string> #include <noma/typa/parser_error.hpp> #include "heom/common.hpp" namespace heom { std::ostream& operator<<(std::ostream& out, const observation_type_t& t) { out << observation_type_names.at(t); return out; } std::istream& operator>>(std::istream& in, observation_type_t& t) { std::string value; std::getline(in, value); // get key to value // NOTE: we trust observation_type_names to be complete here bool found = false; for (auto it = observation_type_names.begin(); it != observation_type_names.end(); ++it) if (it->second == value) { t = it->first; found = true; break; } if (!found) throw parser::parser_error("'" + value + "' is not a valid observation_type, allowed values: " + parser::get_map_value_list_string(observation_type_names)); return in; } bool is_single_propagation_observation(const observation_type_t& obs_type) { return obs_type == observation_type_t::matrix_diagonal || obs_type == observation_type_t::matrix_complete || obs_type == observation_type_t::matrix_trace_id || obs_type == observation_type_t::hierarchy_norm || obs_type == observation_type_t::hierarchy_complete; } } // namespace heom namespace noma { namespace typa { // see header for explanation const std::string& observation_type_literal() { auto gen_name_exp_str = []() { std::string name_exp_str; for (auto& name : heom::observation_type_names) { if (!name_exp_str.empty()) name_exp_str += "|"; name_exp_str += "\\b" + name.second + "\\b"; // NOTE: "\\b" is an '\b' regex assertion for a word boundary } name_exp_str = "(?:" + name_exp_str + ")"; return name_exp_str; }; static const std::string value { gen_name_exp_str() }; return value; } } // namespace typa } // namespace noma
25.864198
158
0.698329
noma
d729e393137633f1999b0872e797fb5877075b4d
1,189
cpp
C++
Source/Bots/Bot/MortarBot.cpp
thatguyabass/Kill-O-Byte-Source
0d4dfea226514161bb9799f55359f91da0998256
[ "Apache-2.0" ]
2
2016-12-13T19:13:10.000Z
2017-08-14T04:46:52.000Z
Source/Bots/Bot/MortarBot.cpp
thatguyabass/Kill-O-Byte-Source
0d4dfea226514161bb9799f55359f91da0998256
[ "Apache-2.0" ]
null
null
null
Source/Bots/Bot/MortarBot.cpp
thatguyabass/Kill-O-Byte-Source
0d4dfea226514161bb9799f55359f91da0998256
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Snake_Project.h" #include "MortarBot.h" #include "Bots/Controller/MortarAI.h" #include "Powers/Weapons/Weapon.h" #include "Powers/Weapons/Weapon_Single.h" #include "Bots/Misc/RocketTankTargetDecal.h" AMortarBot::AMortarBot() : Super() { IdealDistance = 1500.0f; MissFireRadius = 250.0f; WeaponPlacement = CreateDefaultSubobject<USceneComponent>(TEXT("WeaponPlacement")); WeaponPlacement->AttachTo(RootComponent); } void AMortarBot::SpawnWeapon() { Super::SpawnWeapon(); if (TargetClass) { ProjectileTarget = GetWorld()->SpawnActor<ARocketTankTargetDecal>(TargetClass); } } void AMortarBot::FireWeapon() { AMortarAI* AI = Cast<AMortarAI>(Controller); if (Weapon && Weapon->CanFire() && AI) { PlayFireWeaponSFX(); AActor* Target = ProjectileTarget; if (ProjectileTarget->IsActive()) { Target = GetWorld()->SpawnActor<ARocketTankTargetDecal>(TargetClass); Target->SetLifeSpan(5.0f); } AI->SetWeaponTarget(Target, MissFireRadius); Weapon->SetHomingProjectile(Target, IdealDistance); Cast<AWeapon_Single>(Weapon)->Fire(WeaponPlacement, GetActorRotation()); } }
24.770833
84
0.747687
thatguyabass
d734610af85ea9d5c3a6ecb10388d3d9e28e765b
265
hpp
C++
Hyades/src/Logger.hpp
nbrockett/hyades
18d2218501d1352a88df187efec282174c46d3e0
[ "MIT" ]
null
null
null
Hyades/src/Logger.hpp
nbrockett/hyades
18d2218501d1352a88df187efec282174c46d3e0
[ "MIT" ]
null
null
null
Hyades/src/Logger.hpp
nbrockett/hyades
18d2218501d1352a88df187efec282174c46d3e0
[ "MIT" ]
null
null
null
#pragma once #include "spdlog/spdlog.h" namespace Hyades { class Logger { public: // define static pointer to logger static std::shared_ptr<spdlog::logger> s_logger; static void init(); }; } // namespace Hyades
13.947368
56
0.592453
nbrockett
d7357d8f45dc24e26fba58419f5ad171a51d9d2a
2,231
cpp
C++
aws-cpp-sdk-sagemaker/source/model/DescribeEndpointConfigResult.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-sagemaker/source/model/DescribeEndpointConfigResult.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-sagemaker/source/model/DescribeEndpointConfigResult.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/sagemaker/model/DescribeEndpointConfigResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::SageMaker::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DescribeEndpointConfigResult::DescribeEndpointConfigResult() { } DescribeEndpointConfigResult::DescribeEndpointConfigResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } DescribeEndpointConfigResult& DescribeEndpointConfigResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("EndpointConfigName")) { m_endpointConfigName = jsonValue.GetString("EndpointConfigName"); } if(jsonValue.ValueExists("EndpointConfigArn")) { m_endpointConfigArn = jsonValue.GetString("EndpointConfigArn"); } if(jsonValue.ValueExists("ProductionVariants")) { Array<JsonView> productionVariantsJsonList = jsonValue.GetArray("ProductionVariants"); for(unsigned productionVariantsIndex = 0; productionVariantsIndex < productionVariantsJsonList.GetLength(); ++productionVariantsIndex) { m_productionVariants.push_back(productionVariantsJsonList[productionVariantsIndex].AsObject()); } } if(jsonValue.ValueExists("KmsKeyId")) { m_kmsKeyId = jsonValue.GetString("KmsKeyId"); } if(jsonValue.ValueExists("CreationTime")) { m_creationTime = jsonValue.GetDouble("CreationTime"); } return *this; }
28.602564
138
0.765128
curiousjgeorge
d737459ecfb299cc1bc4ce00c1c05707d075375a
19,198
cxx
C++
PWGPP/TPC/AliPerformanceDEdx.cxx
benjaminaudurier/AliPhysics
c6af480ee4c8139c820cc7effb44e2e5bfdfaa28
[ "BSD-3-Clause" ]
null
null
null
PWGPP/TPC/AliPerformanceDEdx.cxx
benjaminaudurier/AliPhysics
c6af480ee4c8139c820cc7effb44e2e5bfdfaa28
[ "BSD-3-Clause" ]
null
null
null
PWGPP/TPC/AliPerformanceDEdx.cxx
benjaminaudurier/AliPhysics
c6af480ee4c8139c820cc7effb44e2e5bfdfaa28
[ "BSD-3-Clause" ]
null
null
null
//------------------------------------------------------------------------------ // Implementation of AliPerformanceDEdx class. It keeps information from // comparison of reconstructed and MC particle tracks. In addtion, // it keeps selection cuts used during comparison. The comparison // information is stored in the ROOT histograms. Analysis of these // histograms can be done by using Analyse() class function. The result of // the analysis (histograms/graphs) are stored in the folder which is // a data of AliPerformanceDEdx. // // Author: J.Otwinowski 04/02/2008 // Changes by M.Knichel 15/10/2010 //------------------------------------------------------------------------------ /*AliPerformanceDEdx.cxx // after running comparison task, read the file, and get component gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/Macros/LoadMyLibs.C"); LoadMyLibs();cd /hera/alice/atarant/train/trunk/atarant_spectra/qa/ TFile f("Output.root"); //AliPerformanceDEdx * compObj = (AliPerformanceDEdx*)f.Get("AliPerformanceDEdx"); AliPerformanceDEdx * compObj = (AliPerformanceDEdx*)coutput->FindObject("AliPerformanceDEdx"); // Analyse comparison data compObj->Analyse(); // the output histograms/graphs will be stored in the folder "folderDEdx" compObj->GetAnalysisFolder()->ls("*"); // user can save whole comparison object (or only folder with anlysed histograms) // in the seperate output file (e.g.) TFile fout("Analysed_DEdx.root","recreate"); //compObj->Write(); // compObj->GetAnalysisFolder()->Write(); compObj->GetAnalysisFolder()->Write(); fout.Close(); */ #include "TDirectory.h" #include "TAxis.h" #include "TCanvas.h" #include "TH1.h" #include "TH2.h" #include "TF1.h" #include "TSystem.h" #include "TChain.h" #include "AliPerformanceDEdx.h" #include "AliPerformanceTPC.h" #include "AliTPCPerformanceSummary.h" #include "AliESDEvent.h" #include "AliTracker.h" #include "AliMCEvent.h" #include "AliESDtrack.h" #include "AliStack.h" #include "AliLog.h" #include "AliMCInfoCuts.h" #include "AliMathBase.h" #include "AliRecInfoCuts.h" #include "AliTreeDraw.h" #include "AliHeader.h" #include "AliGenEventHeader.h" using namespace std; ClassImp(AliPerformanceDEdx) Bool_t AliPerformanceDEdx::fgMergeTHnSparse = kFALSE; Bool_t AliPerformanceDEdx::fgUseMergeTHnSparse = kFALSE; //_____________________________________________________________________________ AliPerformanceDEdx::AliPerformanceDEdx(const Char_t* name, const Char_t* title, Int_t analysisMode, Bool_t hptGenerator): AliPerformanceObject(name,title), // dEdx fDeDxHisto(0), fFolderObj(0), // Cuts fCutsRC(0), fCutsMC(0), // histogram folder fAnalysisFolder(0) { // named constructor SetAnalysisMode(analysisMode); SetHptGenerator(hptGenerator); Init(); } //_____________________________________________________________________________ AliPerformanceDEdx::~AliPerformanceDEdx() { // destructor if(fDeDxHisto) delete fDeDxHisto; fDeDxHisto=0; if(fAnalysisFolder) delete fAnalysisFolder; fAnalysisFolder=0; } //_____________________________________________________________________________ void AliPerformanceDEdx::Init() { // Init histograms // TPC dEdx // set p bins Int_t nPBins = 50; Double_t pMin = 1.e-2, pMax = 20.; Double_t *binsP = 0; if (IsHptGenerator()) { pMax = 100.; } binsP = CreateLogAxis(nPBins,pMin,pMax); /* Int_t nPBins = 31; Double_t binsP[32] = {0.,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.7,0.8,0.9,1.0,1.2,1.4,1.6,1.8,2.0,2.25,2.5,2.75,3.,3.5,4.,5.,6.,8.,10.}; Double_t pMin = 0., pMax = 10.; if(IsHptGenerator() == kTRUE) { nPBins = 100; pMin = 0.; pMax = 100.; } */ //Int_t binsQA[8] = {300, 50, 50, 50, 50, 50, 80, nPBins}; //Double_t xminQA[8] = {0, -4,-20,-250, -1, -2, 0, pMin}; //Double_t xmaxQA[8] = {300, 4, 20, 250, 1, 2, 160, pMax}; // signal:phi:y:z:snp:tgl:ncls:p:nclsDEdx:nclsF Int_t binsQA[10] = {300, 144, 50, 50, 50, 50, 80, nPBins, 160, 80}; Double_t xminQA[10] = {0, -TMath::Pi(),-20,-250, -1, -2, 0, pMin, 0., 0.}; Double_t xmaxQA[10] = {300, TMath::Pi(), 20, 250, 1, 2, 160, pMax ,160., 1.}; fDeDxHisto = new THnSparseF("fDeDxHisto","dedx:phi:y:z:snp:tgl:ncls:momentum:TPCSignalN:clsF",10,binsQA,xminQA,xmaxQA); fDeDxHisto->SetBinEdges(7,binsP); fDeDxHisto->GetAxis(0)->SetTitle("dedx (a.u.)"); fDeDxHisto->GetAxis(1)->SetTitle("#phi (rad)"); fDeDxHisto->GetAxis(2)->SetTitle("y (cm)"); fDeDxHisto->GetAxis(3)->SetTitle("z (cm)"); fDeDxHisto->GetAxis(4)->SetTitle("sin#phi"); fDeDxHisto->GetAxis(5)->SetTitle("tan#lambda"); fDeDxHisto->GetAxis(6)->SetTitle("ncls"); fDeDxHisto->GetAxis(7)->SetTitle("p (GeV/c)"); fDeDxHisto->GetAxis(8)->SetTitle("number of cls used for dEdx"); fDeDxHisto->GetAxis(9)->SetTitle("number of cls found over findable"); //fDeDxHisto->Sumw2(); // Init cuts if(!fCutsMC) { AliDebug(AliLog::kError, "ERROR: Cannot find AliMCInfoCuts object"); } if(!fCutsRC) { AliDebug(AliLog::kError, "ERROR: Cannot find AliRecInfoCuts object"); } // init folder fAnalysisFolder = CreateFolder("folderDEdx","Analysis de/dx Folder"); // save merge status in object fMergeTHnSparseObj = fgMergeTHnSparse; } //_____________________________________________________________________________ void AliPerformanceDEdx::ProcessTPC(AliStack* const /*stack*/, AliESDtrack *const /*esdTrack*/) { // Fill dE/dx comparison information AliDebug(AliLog::kWarning, "Warning: Not implemented"); } //_____________________________________________________________________________ void AliPerformanceDEdx::ProcessInnerTPC(AliStack* const stack, AliESDtrack *const esdTrack, AliESDEvent* const esdEvent) { // // Fill TPC track information at inner TPC wall // if(!esdEvent) return; if(!esdTrack) return; if( IsUseTrackVertex() ) { // Relate TPC inner params to prim. vertex const AliESDVertex *vtxESD = esdEvent->GetPrimaryVertexTracks(); Double_t x[3]; esdTrack->GetXYZ(x); Double_t b[3]; AliTracker::GetBxByBz(x,b); Bool_t isOK = kFALSE; if(fabs(b[2])>0.000001) isOK = esdTrack->RelateToVertexTPCBxByBz(vtxESD, b, kVeryBig); // Bool_t isOK = esdTrack->RelateToVertexTPCBxByBz(vtxESD, b, kVeryBig); if(!isOK) return; /* // JMT -- recaluclate DCA for HLT if not present if ( dca[0] == 0. && dca[1] == 0. ) { track->GetDZ( vtxESD->GetX(), vtxESD->GetY(), vtxESD->GetZ(), esdEvent->GetMagneticField(), dca ); } */ } // get external param. at inner TPC wall const AliExternalTrackParam *innerParam = esdTrack->GetInnerParam(); if(!innerParam) return; Float_t dca[2], cov[3]; // dca_xy, dca_z, sigma_xy, sigma_xy_z, sigma_z esdTrack->GetImpactParametersTPC(dca,cov); if((esdTrack->GetStatus()&AliESDtrack::kTPCrefit)==0) return; // TPC refit // // select primaries // Double_t dcaToVertex = -1; if( fCutsRC->GetDCAToVertex2D() ) { dcaToVertex = TMath::Sqrt(dca[0]*dca[0]/fCutsRC->GetMaxDCAToVertexXY()/fCutsRC->GetMaxDCAToVertexXY() + dca[1]*dca[1]/fCutsRC->GetMaxDCAToVertexZ()/fCutsRC->GetMaxDCAToVertexZ()); } if(fCutsRC->GetDCAToVertex2D() && dcaToVertex > 1) return; if(!fCutsRC->GetDCAToVertex2D() && TMath::Abs(dca[0]) > fCutsRC->GetMaxDCAToVertexXY()) return; if(!fCutsRC->GetDCAToVertex2D() && TMath::Abs(dca[1]) > fCutsRC->GetMaxDCAToVertexZ()) return; Float_t dedx = esdTrack->GetTPCsignal(); Int_t ncls = esdTrack->GetTPCNcls(); Int_t TPCSignalN = esdTrack->GetTPCsignalN(); //Float_t nCrossedRows = esdTrack->GetTPCClusterInfo(2,1); Float_t nClsF = esdTrack->GetTPCClusterInfo(2,0); Double_t pt = innerParam->Pt(); Double_t lam = TMath::ATan2(innerParam->Pz(),innerParam->Pt()); Double_t p = pt/TMath::Cos(lam); //Double_t alpha = innerParam->GetAlpha(); Double_t phi = TMath::ATan2(innerParam->Py(),innerParam->Px()); //if(phi<0.) phi += 2.*TMath::Phi(); Double_t y = innerParam->GetY(); Double_t z = innerParam->GetZ(); Double_t snp = innerParam->GetSnp(); Double_t tgl = innerParam->GetTgl(); //fill thnspars here coud add oroc mdedium long..............Atti //you should select which pad leng here // http://svnweb.cern.ch/world/wsvn/AliRoot/trunk/STEER/STEERBase/AliTPCdEdxInfo.h // fTPCsignalRegion[4]; //Double_t vDeDxHisto[10] = {dedx,phi,y,z,snp,tgl,ncls,p,TPCSignalN,nCrossedRows}; Double_t vDeDxHisto[10] = {dedx,phi,y,z,snp,tgl,Double_t(ncls),p,Double_t(TPCSignalN),nClsF}; fDeDxHisto->Fill(vDeDxHisto); if(!stack) return; } //_____________________________________________________________________________ void AliPerformanceDEdx::ProcessTPCITS(AliStack* const /*stack*/, AliESDtrack *const /*esdTrack*/) { // Fill dE/dx comparison information AliDebug(AliLog::kWarning, "Warning: Not implemented"); } //_____________________________________________________________________________ void AliPerformanceDEdx::ProcessConstrained(AliStack* const /*stack*/, AliESDtrack *const /*esdTrack*/) { // Fill dE/dx comparison information AliDebug(AliLog::kWarning, "Warning: Not implemented"); } //_____________________________________________________________________________ Long64_t AliPerformanceDEdx::Merge(TCollection* const list) { // Merge list of objects (needed by PROOF) if (!list) return 0; if (list->IsEmpty()) return 1; Bool_t merge = ((fgUseMergeTHnSparse && fgMergeTHnSparse) || (!fgUseMergeTHnSparse && fMergeTHnSparseObj)); TIterator* iter = list->MakeIterator(); TObject* obj = 0; TObjArray* objArrayList = 0; objArrayList = new TObjArray(); // collection of generated histograms Int_t count=0; while((obj = iter->Next()) != 0) { AliPerformanceDEdx* entry = dynamic_cast<AliPerformanceDEdx*>(obj); if (entry == 0) continue; if (merge) { if ((fDeDxHisto) && (entry->fDeDxHisto)) { fDeDxHisto->Add(entry->fDeDxHisto); } } // the analysisfolder is only merged if present if (entry->fFolderObj) { objArrayList->Add(entry->fFolderObj); } count++; } if (fFolderObj) { fFolderObj->Merge(objArrayList); } // to signal that track histos were not merged: reset if (!merge) { fDeDxHisto->Reset(); } // delete if (objArrayList) delete objArrayList; objArrayList=0; return count; } //_____________________________________________________________________________ void AliPerformanceDEdx::Exec(AliMCEvent* const mcEvent, AliESDEvent *const esdEvent, AliESDfriend *const esdFriend, const Bool_t bUseMC, const Bool_t bUseESDfriend) { // Process comparison information // if(!esdEvent) { AliDebug(AliLog::kError, "esdEvent not available"); return; } AliHeader* header = 0; AliGenEventHeader* genHeader = 0; AliStack* stack = 0; TArrayF vtxMC(3); if(bUseMC) { if(!mcEvent) { AliDebug(AliLog::kError, "mcEvent not available"); return; } // get MC event header header = mcEvent->Header(); if (!header) { AliDebug(AliLog::kError, "Header not available"); return; } // MC particle stack stack = mcEvent->Stack(); if (!stack) { AliDebug(AliLog::kError, "Stack not available"); return; } // get MC vertex genHeader = header->GenEventHeader(); if (!genHeader) { AliDebug(AliLog::kError, "Could not retrieve genHeader from Header"); return; } genHeader->PrimaryVertex(vtxMC); } // end bUseMC // use ESD friends if(bUseESDfriend) { if(!esdFriend) { AliDebug(AliLog::kError, "esdFriend not available"); return; } } // trigger if(!bUseMC && GetTriggerClass()) { Bool_t isEventTriggered = esdEvent->IsTriggerClassFired(GetTriggerClass()); if(!isEventTriggered) return; } // get event vertex const AliESDVertex *vtxESD = NULL; if( IsUseTrackVertex() ) { // track vertex vtxESD = esdEvent->GetPrimaryVertexTracks(); } else { // TPC track vertex vtxESD = esdEvent->GetPrimaryVertexTPC(); } if(vtxESD && (vtxESD->GetStatus()<=0)) return; // Process events for (Int_t iTrack = 0; iTrack < esdEvent->GetNumberOfTracks(); iTrack++) { AliESDtrack *track = esdEvent->GetTrack(iTrack); if(!track) continue; if(GetAnalysisMode() == 0) ProcessTPC(stack,track); else if(GetAnalysisMode() == 1) ProcessTPCITS(stack,track); else if(GetAnalysisMode() == 2) ProcessConstrained(stack,track); else if(GetAnalysisMode() == 3) ProcessInnerTPC(stack,track,esdEvent); else { printf("ERROR: AnalysisMode %d \n",fAnalysisMode); return; } } } //_____________________________________________________________________________ void AliPerformanceDEdx::Analyse() { // Analyze comparison information and store output histograms // in the folder "folderDEdx" // //Atti h_tpc_dedx_mips_0 //fai fit con range p(.32,.38) and dEdx(65- 120 or 100) e ripeti cosa fatta per pion e fai trending della media e res, poio la loro differenza //fai dedx vs lamda ma for e e pion separati // TH1::AddDirectory(kFALSE); TH1::SetDefaultSumw2(kFALSE); TH1F *h1D=0; TH2F *h2D=0; TObjArray *aFolderObj = new TObjArray; TString selString; char name[256]; char title[256]; for(Int_t i=1; i<10; i++) { AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, i); } AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, 6, 7); AddProjection(aFolderObj, "dedx", fDeDxHisto, 7, 8, 9); AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, 8, 9); AddProjection(aFolderObj, "dedx", fDeDxHisto, 6, 8, 9); // resolution histograms for mips //-> signal:phi:y:z:snp:tgl:ncls:p:nclsDEdx:nclsF fDeDxHisto->GetAxis(2)->SetRangeUser(-15.,14.999); fDeDxHisto->GetAxis(3)->SetRangeUser(-120.,119.999); fDeDxHisto->GetAxis(4)->SetRangeUser(-0.4, 0.399); fDeDxHisto->GetAxis(5)->SetRangeUser(-0.9,0.89); fDeDxHisto->GetAxis(6)->SetRangeUser(60.,160.); fDeDxHisto->GetAxis(7)->SetRangeUser(0.4,0.499); //p fDeDxHisto->GetAxis(8)->SetRangeUser(60.,160.); selString = "mipsres"; AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, &selString); // TObjArray *arr[10] = {0}; TF1 *f1[10] = {0}; for(Int_t i=1; i<10; i++) { arr[i] = new TObjArray; f1[i] = new TF1("gaus","gaus"); //printf("i %d \n",i); h2D = (TH2F*)fDeDxHisto->Projection(0,i); f1[i]->SetRange(40,60); // should be pion peak h2D->FitSlicesY(f1[i],0,-1,10,"QNR",arr[i]); // gaus fit of pion peak h1D = (TH1F*)arr[i]->At(1); snprintf(name,256,"mean_dedx_mips_vs_%d",i); h1D->SetName(name); snprintf(title,256,"%s vs %s","mean_dedx_mips (a.u.)",fDeDxHisto->GetAxis(i)->GetTitle()); h1D->SetTitle(title); h1D->GetXaxis()->SetTitle(fDeDxHisto->GetAxis(i)->GetTitle()); h1D->GetYaxis()->SetTitle("mean_dedx_mips (a.u.)"); //h1D->SetMinimum(40); //h1D->SetMaximum(60); aFolderObj->Add(h1D); h1D = (TH1F*)arr[i]->At(2); snprintf(name,256,"res_dedx_mips_vs_%d",i); h1D->SetName(name); snprintf(title,256,"%s vs %s","res_dedx_mips (a.u)",fDeDxHisto->GetAxis(i)->GetTitle()); h1D->SetTitle(title); h1D->GetXaxis()->SetTitle(fDeDxHisto->GetAxis(i)->GetTitle()); h1D->GetYaxis()->SetTitle("res_dedx_mips (a.u.)"); //h1D->SetMinimum(0); //h1D->SetMaximum(6); aFolderObj->Add(h1D); } // select MIPs (version from AliTPCPerfomanceSummary) fDeDxHisto->GetAxis(0)->SetRangeUser(35,60); fDeDxHisto->GetAxis(2)->SetRangeUser(-20,19.999); fDeDxHisto->GetAxis(3)->SetRangeUser(-250,249.999); fDeDxHisto->GetAxis(4)->SetRangeUser(-1, 0.99); fDeDxHisto->GetAxis(5)->SetRangeUser(-1,0.99); fDeDxHisto->GetAxis(6)->SetRangeUser(80,160); fDeDxHisto->GetAxis(7)->SetRangeUser(0.4,0.55); fDeDxHisto->GetAxis(8)->SetRangeUser(80,160); fDeDxHisto->GetAxis(9)->SetRangeUser(0.5,1.); selString = "mips"; AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, &selString); selString = "mips_C"; fDeDxHisto->GetAxis(5)->SetRangeUser(-3,0); AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, 5, &selString); AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, 1, &selString); selString = "mips_A"; fDeDxHisto->GetAxis(5)->SetRangeUser(0,3); AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, 5, &selString); AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, 1, &selString); //////////////////////////////////////// atti new start // // select (version from AliTPCPerfomanceSummary) electrons fDeDxHisto->GetAxis(0)->SetRangeUser(70,100); //dedx for electrons fDeDxHisto->GetAxis(2)->SetRangeUser(-20,19.999); fDeDxHisto->GetAxis(3)->SetRangeUser(-250,249.999); fDeDxHisto->GetAxis(4)->SetRangeUser(-1, 0.99); fDeDxHisto->GetAxis(5)->SetRangeUser(-1,0.99); fDeDxHisto->GetAxis(6)->SetRangeUser(80,160); fDeDxHisto->GetAxis(7)->SetRangeUser(0.32,0.38); //momenta for electrons fDeDxHisto->GetAxis(8)->SetRangeUser(80,160); fDeDxHisto->GetAxis(9)->SetRangeUser(0.5,1.); selString = "mipsele"; AddProjection(aFolderObj, "dedx", fDeDxHisto, 0, &selString); //////////////////////////////////////// atti new stop //restore cuts for (Int_t i=0; i<fDeDxHisto->GetNdimensions(); i++) { fDeDxHisto->GetAxis(i)->SetRange(1,fDeDxHisto->GetAxis(i)->GetNbins()); } printf("exportToFolder\n"); // export objects to analysis folder fAnalysisFolder = ExportToFolder(aFolderObj); if (fFolderObj) delete fFolderObj; fFolderObj = aFolderObj; aFolderObj=0; for(Int_t i=0;i<10;i++) { if(f1[i]) delete f1[i]; f1[i]=0; } } //_____________________________________________________________________________ TFolder* AliPerformanceDEdx::ExportToFolder(TObjArray * array) { // recreate folder avery time and export objects to new one // AliPerformanceDEdx * comp=this; TFolder *folder = comp->GetAnalysisFolder(); TString name, title; TFolder *newFolder = 0; Int_t i = 0; Int_t size = array->GetSize(); if(folder) { // get name and title from old folder name = folder->GetName(); title = folder->GetTitle(); // delete old one delete folder; // create new one newFolder = CreateFolder(name.Data(),title.Data()); newFolder->SetOwner(); // add objects to folder while(i < size) { newFolder->Add(array->At(i)); i++; } } return newFolder; } //_____________________________________________________________________________ TFolder* AliPerformanceDEdx::CreateFolder(TString name,TString title) { // create folder for analysed histograms TFolder *folder = 0; folder = new TFolder(name.Data(),title.Data()); return folder; } //_____________________________________________________________________________ TTree* AliPerformanceDEdx::CreateSummary() { // implementaion removed, switched back to use AliPerformanceSummary (now called in AliPerformanceTask) return 0; }
32.050083
205
0.669653
benjaminaudurier
d73792f1e7c58b7301d2e0eca1a73591b7bbb8fa
8,120
cpp
C++
CSB/csb_spmv_test.cpp
sc2020user/jstream
7ee3dfcacfe7a72d37dca53615066a5f8f33ad3a
[ "BSD-4-Clause" ]
1
2021-02-12T01:36:09.000Z
2021-02-12T01:36:09.000Z
CSB/csb_spmv_test.cpp
HPCRL/jstream_SC2020_AE
8b23036f01a46af426dba5bff78548cb0351161d
[ "BSD-4-Clause" ]
null
null
null
CSB/csb_spmv_test.cpp
HPCRL/jstream_SC2020_AE
8b23036f01a46af426dba5bff78548cb0351161d
[ "BSD-4-Clause" ]
1
2021-05-27T04:58:14.000Z
2021-05-27T04:58:14.000Z
#define NOMINMAX #include <iostream> #include <algorithm> #include <numeric> #include <functional> #include <fstream> #include <ctime> #include <cmath> #include <string> #include "timer.gettimeofday.c" #include "cilk_util.h" #include "utility.h" #include "triple.h" #include "csc.h" #include "bicsb.h" #include "bmcsb.h" #include "spvec.h" #include "Semirings.h" using namespace std; #define INDEXTYPE uint32_t #define VALUETYPE float /* Alternative native timer (wall-clock): * timeval tim; * gettimeofday(&tim, NULL); * double t1=tim.tv_sec+(tim.tv_usec/1000000.0); */ int main(int argc, char* argv[]) { #ifndef CILK_STUB int gl_nworkers = __cilkrts_get_nworkers(); #else int gl_nworkers = 0; #endif bool syminput = false; bool binary = false; bool iscsc = false; INDEXTYPE m = 0, n = 0, nnz = 0, forcelogbeta = 0; string inputname; if(argc < 2) { cout << "Normal usage: ./a.out inputmatrix.mtx sym/nosym binary/text triples/csc" << endl; cout << "Assuming matrix.txt is the input, matrix is unsymmetric, and stored in text(ascii) file" << endl; inputname = "matrix.txt"; } else if(argc < 3) { cout << "Normal usage: ./a.out inputmatrix.mtx sym/nosym binary/text triples/csc" << endl; cout << "Assuming that the matrix is unsymmetric, and stored in text(ascii) file" << endl; inputname = argv[1]; } else if(argc < 4) { cout << "Normal usage: ./a.out inputmatrix.mtx sym/nosym binary/text triples/csc" << endl; cout << "Assuming matrix is stored in text(ascii) file" << endl; inputname = argv[1]; string issym(argv[2]); if(issym == "sym") syminput = true; else if(issym == "nosym") syminput = false; else cout << "unrecognized option, assuming nosym" << endl; } else { inputname = argv[1]; string issym(argv[2]); if(issym == "sym") syminput = true; else if(issym == "nosym") syminput = false; else cout << "unrecognized option, assuming unsymmetric" << endl; string isbinary(argv[3]); if(isbinary == "text") binary = false; else if(isbinary == "binary") binary = true; else cout << "unrecognized option, assuming text file" << endl; if(argc > 4) { string type(argv[4]); if(type == "csc") { iscsc = true; cout << "Processing CSC binary" << endl; } } if(argc == 6) forcelogbeta = atoi(argv[5]); } typedef PTSR<VALUETYPE,VALUETYPE> PTDD; Csc<VALUETYPE, INDEXTYPE> * csc; if(binary) { FILE * f = fopen(inputname.c_str(), "r"); if(!f) { cerr << "Problem reading binary input file\n"; return 1; } if(iscsc) { fread(&n, sizeof(INDEXTYPE), 1, f); fread(&m, sizeof(INDEXTYPE), 1, f); fread(&nnz, sizeof(INDEXTYPE), 1, f); } else { fread(&m, sizeof(INDEXTYPE), 1, f); fread(&n, sizeof(INDEXTYPE), 1, f); fread(&nnz, sizeof(INDEXTYPE), 1, f); } if (m <= 0 || n <= 0 || nnz <= 0) { cerr << "Problem with matrix size in binary input file\n"; return 1; } long tstart = cilk_get_time(); // start timer cout << "Reading matrix with dimensions: "<< m << "-by-" << n <<" having "<< nnz << " nonzeros" << endl; INDEXTYPE * rowindices = new INDEXTYPE[nnz]; VALUETYPE * vals = new VALUETYPE[nnz]; INDEXTYPE * colindices; INDEXTYPE * colpointers; if(iscsc) { colpointers = new INDEXTYPE[n+1]; size_t cols = fread(colpointers, sizeof(INDEXTYPE), n+1, f); if(cols != n+1) { cerr << "Problem with FREAD, aborting... " << endl; return -1; } } else { colindices = new INDEXTYPE[nnz]; size_t cols = fread(colindices, sizeof(INDEXTYPE), nnz, f); if(cols != nnz) { cerr << "Problem with FREAD, aborting... " << endl; return -1; } } size_t rows = fread(rowindices, sizeof(INDEXTYPE), nnz, f); size_t nums = fread(vals, sizeof(VALUETYPE), nnz, f); if(rows != nnz || nums != nnz) { cerr << "Problem with FREAD, aborting... " << endl; return -1; } long tend = cilk_get_time(); // end timer cout<< "Reading matrix in binary took " << ((VALUETYPE) (tend-tstart)) /1000 << " seconds" <<endl; fclose(f); if(iscsc) { csc = new Csc<VALUETYPE, INDEXTYPE>(); csc->SetPointers(colpointers, rowindices, vals , nnz, m, n, true); // do the fortran thing // csc itself will manage the data in this case (shallow copy) } else { csc = new Csc<VALUETYPE, INDEXTYPE>(rowindices, colindices, vals , nnz, m, n); delete [] colindices; delete [] rowindices; delete [] vals; } } else { cout << "reading input matrix in text(ascii)... " << endl; ifstream infile(inputname.c_str()); char line[256]; char c = infile.get(); while(c == '%') { infile.getline(line,256); c = infile.get(); } infile.unget(); infile >> m >> n >> nnz; // #{rows}-#{cols}-#{nonzeros} long tstart = cilk_get_time(); // start timer Triple<VALUETYPE, INDEXTYPE> * triples = new Triple<VALUETYPE, INDEXTYPE>[nnz]; if (infile.is_open()) { INDEXTYPE cnz = 0; // current number of nonzeros while (! infile.eof() && cnz < nnz) { infile >> triples[cnz].row >> triples[cnz].col >> triples[cnz].val; // row-col-value triples[cnz].row--; triples[cnz].col--; ++cnz; } assert(cnz == nnz); } long tend = cilk_get_time(); // end timer cout<< "Reading matrix in ascii took " << ((double) (tend-tstart)) /1000 << " seconds" <<endl; cout << "converting to csc ... " << endl; csc= new Csc<VALUETYPE,INDEXTYPE>(triples, nnz, m, n); delete [] triples; } cout << "# workers: "<< gl_nworkers << endl; BiCsb<VALUETYPE, INDEXTYPE> bicsb(*csc, gl_nworkers); // BiCsb<bool, INDEXTYPE> bin_csb(*csc, gl_nworkers); #ifndef NOBM BmCsb<VALUETYPE, INDEXTYPE, RBDIM> bmcsb(*csc, gl_nworkers); ofstream stats("stats.txt"); bmcsb.PrintStats(stats); Spvec<VALUETYPE, INDEXTYPE> y_bmcsb(m); y_bmcsb.fillzero(); #endif INDEXTYPE flops = 2 * nnz; cout << "generating vectors... " << endl; Spvec<VALUETYPE, INDEXTYPE> x(n); Spvec<VALUETYPE, INDEXTYPE> y_bicsb(m); Spvec<VALUETYPE, INDEXTYPE> y_csc(m); y_csc.fillzero(); y_bicsb.fillzero(); x.fillfota(); cout << "starting SpMV ... " << endl; cout << "Row imbalance is: " << RowImbalance(bicsb) << endl; timer_init(); bicsb_gespmv<PTDD>(bicsb, x.getarr(), y_bicsb.getarr()); double t0 = timer_seconds_since_init(); for(int i=0; i < REPEAT; ++i) { bicsb_gespmv<PTDD>(bicsb, x.getarr(), y_bicsb.getarr()); } double t1 = timer_seconds_since_init(); double time = (t1-t0)/REPEAT; cout<< "BiCSB" << " time: " << time << " seconds" <<endl; cout<< "BiCSB" << " mflop/sec: " << flops / (1000000 * time) <<endl; /*************************************************************/ #ifndef NOBM cout << "starting SpMV with BmCSB ... " << endl; cout << "Row imbalance is: " << RowImbalance(bmcsb) << endl; prescantime = 0; bmcsb_gespmv(bmcsb, x.getarr(), y_bmcsb.getarr()); prescantime = 0; t0 = timer_seconds_since_init(); for(int i=0; i < REPEAT; ++i) { bmcsb_gespmv(bmcsb, x.getarr(), y_bmcsb.getarr()); } t1 = timer_seconds_since_init(); double bmtime = ((t1-t0)/REPEAT) - (prescantime/REPEAT); cout<< "BmCSB" << " time: " << bmtime << " seconds" <<endl; cout<< "BmCSB" << " mflop/sec: " << (flops * UNROLL) / (1000000 * bmtime) <<endl; #ifdef BWTEST transform(y_bmcsb.getarr(), y_bmcsb.getarr() + m, y_bmcsb.getarr(), bind2nd(divides<double>(), static_cast<double>(UNROLL))); cout << "Mega register blocks per second: " << (bmcsb.numregb() * UNROLL) / (1000000 * bmtime) << endl; #endif // BWTEST cout<< "Prescan time: " << (prescantime/REPEAT) << " seconds" <<endl; #endif // NOBM // Verify with CSC (serial) y_csc += (*csc) * x; t0 = timer_seconds_since_init(); for(int i=0; i < REPEAT; ++i) { y_csc += (*csc) * x; } t1 = timer_seconds_since_init(); double csctime = (t1-t0)/REPEAT; cout<< "CSC" << " time: " << csctime << " seconds" <<endl; cout<< "CSC" << " mflop/sec: " << flops / (1000000 * csctime) <<endl; Verify(y_csc, y_bicsb, "BiCSB", m); #ifndef NOBM Verify(y_csc, y_bmcsb, "BmCSB", m); #endif delete csc; }
26.79868
126
0.613054
sc2020user
d73d60d77332286dbe2b55775484566f46a515e6
18,451
cpp
C++
app/sys/sys_cli/src/ecalsys_cli.cpp
tcoyvwac/ecal
2e2e446004e306d48e98620208085fd52d35b90b
[ "Apache-2.0" ]
null
null
null
app/sys/sys_cli/src/ecalsys_cli.cpp
tcoyvwac/ecal
2e2e446004e306d48e98620208085fd52d35b90b
[ "Apache-2.0" ]
1
2022-02-22T00:37:20.000Z
2022-02-22T01:02:08.000Z
app/sys/sys_cli/src/ecalsys_cli.cpp
tcoyvwac/ecal
2e2e446004e306d48e98620208085fd52d35b90b
[ "Apache-2.0" ]
1
2022-02-28T10:28:36.000Z
2022-02-28T10:28:36.000Z
/* ========================= eCAL LICENSE ================================= * * Copyright (C) 2016 - 2020 Continental Corporation * * 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. * * ========================= eCAL LICENSE ================================= */ /** * eCALSys Console Application **/ #include <iostream> #include <memory> #include <string> #include <thread> #include <ecal/ecal.h> #include <ecal/ecal_client.h> #include <ecalsys/ecal_sys.h> #include <ecalsys/esys_defs.h> #include <ecal/msg/protobuf/client.h> #include <ecal/msg/protobuf/server.h> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4100 4127 4146 4505 4800 4189 4592) // disable proto warnings #endif #include <ecal/pb/sys/service.pb.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include "ecalsys_service.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4505) // disable tclap warning (unreferenced local function has been removed) #endif #include "tclap/CmdLine.h" #ifdef _MSC_VER #pragma warning(pop) #endif #include <custom_tclap/advanced_tclap_output.h> #include <custom_tclap/fuzzy_value_switch_arg_bool.h> #include <command_executor.h> #include <commands/load_config.h> #include <commands/update_from_cloud.h> #include <commands/start_tasks.h> #include <commands/stop_tasks.h> #include <commands/restart_tasks.h> #include "ecalsys_util.h" #include <ecal_utils/command_line.h> #include <ecal_utils/str_convert.h> #include <ecal_utils/win_cp_changer.h> #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h> #endif // WIN32 bool exit_command_received; #ifdef WIN32 int main() #else int main(int argc, char** argv) #endif { #ifdef WIN32 EcalUtils::WinCpChanger win_cp_changer(CP_UTF8); // The WinCpChanger will set the Codepage back to the original, once destroyed #endif // WIN32 // Define the command line object. TCLAP::CmdLine cmd(ECAL_SYS_LIB_NAME, ' ', ECAL_SYS_VERSION_STRING); TCLAP::UnlabeledMultiArg<std::string> unlabled_config_arg ("config_", "The Configuration file to load.", false, "Path"); TCLAP::ValueArg<std::string> config_arg ("c", "config", "The Configuration file to load. Not supported in remote-control mode.", false, "", "Path"); TCLAP::SwitchArg remote_control_arg ("", "remote-control", "Remote control another eCAL Sys instance.", false); TCLAP::ValueArg<std::string> remote_control_host_arg ("", "remote-host", "Set the hostname for remote-controlling.", false, "", "Hostname"); TCLAP::SwitchArg start_arg ("s", "start", "Start all tasks.", false); TCLAP::SwitchArg stop_arg ("x", "stop", "Stop all tasks.", false); TCLAP::SwitchArg restart_arg ("r", "restart", "Restart all tasks.", false); CustomTclap::FuzzyValueSwitchArgBool local_tasks_only_arg ("", "local-tasks-only", "Only tasks on local host will be considered. Not supported in remote-control mode.", false, false, "true|false"); CustomTclap::FuzzyValueSwitchArgBool use_localhost_for_all_tasks_arg("", "use-localhost-for-all-tasks", "All tasks will be considered as being on local host. Not supported in remote-control mode.", false, false, "true|false"); CustomTclap::FuzzyValueSwitchArgBool no_wait_for_clients_arg ("", "no-wait-for-clients", "Don't wait for eCAL Sys clients before starting / stopping tasks. Waiting is always disabled in interactive and remote-control mode.", false, false, "true|false"); // TODO: This arguments was a simple switch arg before. TCLAP::SwitchArg disable_update_from_cloud_arg ("", "disable-update-from-cloud", "Do not use the monitor to update the tasks for restarting/stopping/monitoring.", false); TCLAP::SwitchArg interactive_dont_exit_arg ("", "interactive-dont-exit", "When in interactive mode, this option prevents eCAL Sys from exiting, when stdin is closed.", false); TCLAP::SwitchArg interactive_arg ("i", "interactive", "Start eCAL Sys and listen for commands on stdin. When not in remote-control mode itself, eCAL Sys will offer the eCAL Sys Service for being remote-controlled. Note that eCAL Sys will exit, when stdin is closed. To prevent that, combine this option with \"" + interactive_dont_exit_arg.getName() + "\". When using interactive mode, waiting for ecal_sys_clients is disabled.", false); std::vector<TCLAP::Arg*> arg_vector = { &config_arg, &remote_control_arg, &remote_control_host_arg, &start_arg, &stop_arg, &restart_arg, &local_tasks_only_arg, &use_localhost_for_all_tasks_arg, &no_wait_for_clients_arg, &disable_update_from_cloud_arg, &interactive_arg, &interactive_dont_exit_arg, &unlabled_config_arg, }; std::stringstream tclap_output_stream; CustomTclap::AdvancedTclapOutput advanced_tclap_output(std::vector<std::ostream*>{ &std::cout }, 75); advanced_tclap_output.setArgumentHidden(&unlabled_config_arg, true); cmd.setOutput(&advanced_tclap_output); for (auto arg_iterator = arg_vector.rbegin(); arg_iterator != arg_vector.rend(); ++arg_iterator) { cmd.add(*arg_iterator); } try { #ifdef WIN32 auto utf8_args_vector = EcalUtils::CommandLine::GetUtf8Argv(); cmd.parse(utf8_args_vector); #else cmd.parse(argc, argv); #endif // WIN32 } catch (TCLAP::ArgException& e) { std::cerr << "Error parsing command line: " << e.what() << std::endl; } std::string cfg_file_name; if (config_arg.isSet()) { cfg_file_name = config_arg .getValue(); } else if (unlabled_config_arg.isSet()) { cfg_file_name = unlabled_config_arg .getValue()[0]; } // Ecalsys instance and ecalsys service. We will only use one of those, depending on the remote-control setting std::shared_ptr<EcalSys> ecalsys_instance; std::shared_ptr<eCAL::protobuf::CServiceClient<eCAL::pb::sys::Service>> remote_ecalsys_service; // Ptrs for eCAL Sys Service (only used in non-remote control mode) std::shared_ptr<eCALSysServiceImpl> ecalsys_service_impl; std::shared_ptr<eCAL::protobuf::CServiceServer<eCAL::pb::sys::Service>> ecalsys_service_server; /************************************************************************/ /* Argument validation */ /************************************************************************/ // remote-host without remote-control if (remote_control_host_arg.isSet() && !remote_control_arg.isSet()) { std::cerr << "Error: " << remote_control_host_arg.getName() << " can only be used in combination with " << remote_control_arg.getName() << "." << std::endl; return EXIT_FAILURE; } // multiple commands if (int(start_arg.isSet()) + int(stop_arg.isSet()) + int(restart_arg.isSet()) > 1) { std::cerr << "Error: Only one argument of " << start_arg.getName() << " / " << restart_arg.getName() << " / " << stop_arg.getName() << " can be used simultaneously." << std::endl; return EXIT_FAILURE; } // No config and not in remote-control or interactive mode if (!config_arg.isSet() && unlabled_config_arg.getValue().empty() && !remote_control_arg.isSet() && !interactive_arg.isSet() && !interactive_dont_exit_arg.isSet()) { std::cerr << "Error: Configuration file needed, when not running as " << remote_control_arg.getName() << " or " << interactive_arg.getName() << std::endl; return EXIT_FAILURE; } // local-tasks-only or use-localhost-for-all-tasks in remote-control mode if (local_tasks_only_arg.isSet() && remote_control_arg.isSet()) { std::cerr << "Error: " << local_tasks_only_arg.getName() << " cannot be used in remote-control mode." << std::endl; return EXIT_FAILURE; } if (use_localhost_for_all_tasks_arg.isSet() && remote_control_arg.isSet()) { std::cerr << "Error: " << use_localhost_for_all_tasks_arg.getName() << " cannot be used in remote-control mode." << std::endl; return EXIT_FAILURE; } // Both local-tasks-only and use-localhost-for-all-tasks is given if ((local_tasks_only_arg.isSet() && local_tasks_only_arg.getValue()) && (use_localhost_for_all_tasks_arg.isSet() && use_localhost_for_all_tasks_arg.getValue())) { std::cerr << "Error: " << local_tasks_only_arg.getName() << " and " << use_localhost_for_all_tasks_arg.getName() << " are mutually excludsive (only one of them can be used)." << std::endl; return EXIT_FAILURE; } // There is nothing to do if (!interactive_arg.isSet() && !interactive_dont_exit_arg.isSet() && !start_arg.isSet() && !stop_arg.isSet() && !restart_arg.isSet()) { std::cerr << "Error: There is nothing to do." << std::endl; return EXIT_FAILURE; } /************************************************************************/ /* Remote control mode */ /************************************************************************/ if (remote_control_arg.isSet()) // Remote-control-mode { eCAL::Initialize(0, nullptr, "eCALSys-Remote", eCAL::Init::All); eCAL::Process::SetState(proc_sev_healthy, proc_sev_level1, "Running"); remote_ecalsys_service = std::make_shared<eCAL::protobuf::CServiceClient<eCAL::pb::sys::Service>>(); } else // Non-remote control mode { eCAL::Initialize(0, nullptr, "eCALSys", eCAL::Init::All); eCAL::Process::SetState(proc_sev_healthy, proc_sev_level1, "Running"); ecalsys_instance = std::make_shared<EcalSys>(); // Create the eCALSys service ecalsys_service_impl = std::make_shared<eCALSysServiceImpl>(ecalsys_instance); ecalsys_service_server = std::make_shared<eCAL::protobuf::CServiceServer<eCAL::pb::sys::Service>>(ecalsys_service_impl); } // Give the monitor some time to connect to eCAL and update std::this_thread::sleep_for(std::chrono::seconds(2)); /************************************************************************/ /* Load the configuration */ /************************************************************************/ if (config_arg.isSet() || !unlabled_config_arg.getValue().empty()) { eCAL::sys::Error error(eCAL::sys::Error::ErrorCode::GENERIC_ERROR); if (ecalsys_instance) { error = eCAL::sys::command::LoadConfig().Execute(ecalsys_instance, {cfg_file_name}); if (error) { std::cerr << error.ToString() << std::endl; return EXIT_FAILURE; } } else { std::cerr << "Warning: Ignoring configuration file in remote control mode" << std::endl; } } /************************************************************************/ /* eCAL Sys Options */ /************************************************************************/ if (ecalsys_instance) { auto options = ecalsys_instance->GetOptions(); bool options_changed = false; // --local-tasks-only if (local_tasks_only_arg.isSet()) { options.local_tasks_only = local_tasks_only_arg.getValue(); if (options.local_tasks_only) options.use_localhost_for_all_tasks = false; options_changed = true; } // --use-localhost-for-all-tasks if (use_localhost_for_all_tasks_arg.isSet()) { options.use_localhost_for_all_tasks = use_localhost_for_all_tasks_arg.getValue(); if (options.use_localhost_for_all_tasks) options.local_tasks_only = false; options_changed = true; } // --no-wait-for-clients if (no_wait_for_clients_arg.isSet()) { options.check_target_reachability = !no_wait_for_clients_arg.getValue(); options_changed = true; } if (options_changed) ecalsys_instance->SetOptions(options); } /************************************************************************/ /* Wait for eCAL Sys Clients */ /************************************************************************/ if (!interactive_arg.isSet() && !interactive_dont_exit_arg.isSet() && !no_wait_for_clients_arg.isSet()) { if (ecalsys_instance) { WaitForClients(ecalsys_instance); } } /************************************************************************/ /* Update from cloud */ /************************************************************************/ if (!disable_update_from_cloud_arg.isSet()) { eCAL::sys::Error error(eCAL::sys::Error::ErrorCode::GENERIC_ERROR); if (ecalsys_instance && ecalsys_instance->IsConfigOpened()) { error = eCAL::sys::command::UpdateFromCloud().Execute(ecalsys_instance, {}); if (error) { std::cerr << "Error: " << error.ToString() << std::endl; return EXIT_FAILURE; } else { ecalsys_instance->WaitForTaskActions(); } } } /************************************************************************/ /* Start Tasks */ /************************************************************************/ if (start_arg.isSet()) { eCAL::sys::Error error(eCAL::sys::Error::ErrorCode::GENERIC_ERROR); if (ecalsys_instance) { error = eCAL::sys::command::StartTask().Execute(ecalsys_instance, {}); if (!error) ecalsys_instance->WaitForTaskActions(); } else { error = eCAL::sys::command::StartTask().Execute(remote_control_host_arg.getValue(), remote_ecalsys_service, {}); } if (error) std::cerr << "Error: " << error.ToString() << std::endl; } /************************************************************************/ /* Restart Tasks */ /************************************************************************/ if (restart_arg.isSet()) { eCAL::sys::Error error(eCAL::sys::Error::ErrorCode::GENERIC_ERROR); if (ecalsys_instance) { error = eCAL::sys::command::RestartTask().Execute(ecalsys_instance, {}); if (!error) ecalsys_instance->WaitForTaskActions(); } else { error = eCAL::sys::command::RestartTask().Execute(remote_control_host_arg.getValue(), remote_ecalsys_service, {}); } if (error) std::cerr << "Error: " << error.ToString() << std::endl; } /************************************************************************/ /* Stop Tasks */ /************************************************************************/ if (stop_arg.isSet()) { eCAL::sys::Error error(eCAL::sys::Error::ErrorCode::GENERIC_ERROR); if (ecalsys_instance) { error = eCAL::sys::command::StopTask().Execute(ecalsys_instance, {}); if (!error) ecalsys_instance->WaitForTaskActions(); } else { error = eCAL::sys::command::StopTask().Execute(remote_control_host_arg.getValue(), remote_ecalsys_service, {}); } if (error) std::cerr << "Error: " << error.ToString() << std::endl; } /************************************************************************/ /* Interactive Mode */ /************************************************************************/ if(interactive_arg.isSet() || interactive_dont_exit_arg.isSet()) { #ifdef WIN32 // Create buffer fo the manual ReadConsoleW call std::wstring w_buffer; w_buffer.reserve(4096); #endif // WIN32 std::cout << "Using interactive mode. Type \"help\" to view a list of all commands." << std::endl; eCAL::sys::CommandExecutor command_executor(ecalsys_instance, remote_control_host_arg.getValue(), remote_ecalsys_service); for(;;) { std::cout << ">> "; std::string line; bool success = false; #ifdef WIN32 HANDLE h_in = GetStdHandle(STD_INPUT_HANDLE); DWORD std_handle_type = GetFileType(h_in); if (std_handle_type == FILE_TYPE_CHAR) { // This is an (interactive) console => read console as UTF16 DWORD chars_read(0); w_buffer.resize(4096); success = ReadConsoleW(h_in, (LPVOID)(w_buffer.data()), static_cast<DWORD>(w_buffer.size()), &chars_read, NULL) != 0; if (success) { w_buffer.resize(chars_read); line = EcalUtils::StrConvert::WideToUtf8(w_buffer); // Trim \r\n at the end for (int i = 0; i < 2; i++) { if (line.size() > 0 && ((line.back() == '\r') || (line.back() == '\n'))) { line.pop_back(); } } } } else { // This is a pipe => read binary data directly as UTF8 success = bool(std::getline(std::cin, line)); } #else success = bool(std::getline(std::cin, line)); #endif // WIN32 if (!success) { std::cout << "Stdin closed." << std::endl; break; } eCAL::sys::Error error = command_executor.ExecuteCommand(line); if (error) { std::cerr << "Error: " << error.ToString() << std::endl; } } } if(interactive_dont_exit_arg.isSet()) { while(eCAL::Ok()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } eCAL::Finalize(); return EXIT_SUCCESS; }
37.199597
486
0.572923
tcoyvwac
d74104ce2b5ef55aa8c52cf408379f0c9769c90c
1,341
hpp
C++
doc/quickbook/oglplus/quickref/context/clip_control.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
364
2015-01-01T09:38:23.000Z
2022-03-22T05:32:00.000Z
doc/quickbook/oglplus/quickref/context/clip_control.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
55
2015-01-06T16:42:55.000Z
2020-07-09T04:21:41.000Z
doc/quickbook/oglplus/quickref/context/clip_control.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
57
2015-01-07T18:35:49.000Z
2022-03-22T05:32:04.000Z
/* * Copyright 2014-2019 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ //[oglplus_context_ClipControlParams namespace context { struct ClipControlParams { ClipControlParams() noexcept; ClipControlParams(__ClipOrigin origin, __ClipDepthMode depth) noexcept; __ClipOrigin Origin() const noexcept; __ClipDepthMode DepthMode() const noexcept; }; //] //[oglplus_context_ClipControlState class ClipControlState { public: #if GL_VERSION_4_5 || GL_ARB_clip_control static void ClipControl(__ClipOrigin origin, __ClipDepthMode depth); /*< Sets the clipping mode. See [glfunc ClipControl]. >*/ static __ClipOrigin ClipOrigin(); /*< Queries the current clip origin setting. See [glfunc Get], [glconst CLIP_ORIGIN]. >*/ static __ClipDepthMode ClipDepthMode(); /*< Queries the current clip depth mode setting. See [glfunc Get], [glconst CLIP_DEPTH_MODE]. >*/ static void ClipControl(const __context_ClipControlParams& params); /*< Sets the clipping control parameters. >*/ static __context_ClipControlParams ClipControl(); /*< Returns the clipping control parameters. >*/ #endif }; } // namespace context //]
25.301887
76
0.712901
matus-chochlik
d74156e48e65274f0c99260ad4003f67edf7f09b
6,230
cpp
C++
src/common/channel/signal/signal_channel.cpp
masterve/test
87a06f974ddc0ca7baf0ca082d7ae8999d9a4196
[ "BSD-3-Clause" ]
1,513
2015-01-02T17:36:20.000Z
2022-03-21T00:10:17.000Z
src/common/channel/signal/signal_channel.cpp
masterve/test
87a06f974ddc0ca7baf0ca082d7ae8999d9a4196
[ "BSD-3-Clause" ]
335
2015-01-02T21:48:21.000Z
2022-01-31T23:10:46.000Z
src/common/channel/signal/signal_channel.cpp
masterve/test
87a06f974ddc0ca7baf0ca082d7ae8999d9a4196
[ "BSD-3-Clause" ]
281
2015-01-08T01:23:41.000Z
2022-03-26T12:31:41.000Z
/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *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 Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS *BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF *THE POSSIBILITY OF SUCH DAMAGE. */ #include "channel/all_includes.hpp" #include "util/helpers.hpp" #include <signal.h> using namespace ardb; static char kReadSigInfoBuf[sizeof(int) + sizeof(siginfo_t)]; static char kWriteSigInfoBuf[sizeof(int) + sizeof(siginfo_t)]; SignalChannel* SignalChannel::m_singleton_instance = NULL; void SignalChannel::SignalCB(int signo, siginfo_t* info, void* ctx) { if (NULL != m_singleton_instance && m_singleton_instance->m_self_write_pipe_fd > 0) { memcpy(kWriteSigInfoBuf, &signo, sizeof(int)); memcpy(kWriteSigInfoBuf + sizeof(int), info, sizeof(siginfo_t)); uint32 writed = 0; uint32 total = (sizeof(int) + sizeof(siginfo_t)); while (writed < total) { int ret = ::write(m_singleton_instance->m_self_write_pipe_fd, kWriteSigInfoBuf + writed, total - writed); if (ret >= 0) { writed += ret; } else { return; } } } } SignalChannel::SignalChannel(ChannelService& factory) : Channel(NULL, factory), m_self_read_pipe_fd(-1), m_self_write_pipe_fd( -1), m_readed_siginfo_len(0) { } bool SignalChannel::DoOpen() { int pipefd[2]; int ret = pipe(pipefd); if (ret == -1) { ERROR_LOG("Failed to create pipe for signal channel."); return false; } m_self_read_pipe_fd = pipefd[0]; m_self_write_pipe_fd = pipefd[1]; ardb::make_fd_nonblocking(m_self_read_pipe_fd); ardb::make_fd_nonblocking(m_self_write_pipe_fd); aeCreateFileEvent(GetService().GetRawEventLoop(), m_self_read_pipe_fd, AE_READABLE, Channel::IOEventCallback, this); m_singleton_instance = this; return true; } int SignalChannel::GetWriteFD() { return m_self_write_pipe_fd; } int SignalChannel::GetReadFD() { return m_self_read_pipe_fd; } bool SignalChannel::DoClose() { if (-1 != m_self_read_pipe_fd && -1 != m_self_write_pipe_fd) { ::close(m_self_read_pipe_fd); ::close(m_self_write_pipe_fd); m_self_read_pipe_fd = -1; m_self_write_pipe_fd = -1; } return true; } void SignalChannel::OnRead() { uint32 sig_ifo_len = sizeof(int) + sizeof(siginfo_t); if (m_readed_siginfo_len < sig_ifo_len) { int readed = ::read(m_self_read_pipe_fd, kReadSigInfoBuf + m_readed_siginfo_len, (sig_ifo_len - m_readed_siginfo_len)); if (readed > 0) { m_readed_siginfo_len += readed; if (m_readed_siginfo_len == sig_ifo_len) { m_readed_siginfo_len = 0; int signo; siginfo_t info; memcpy(&signo, kReadSigInfoBuf, sizeof(int)); memcpy(&info, kReadSigInfoBuf + sizeof(int), sizeof(siginfo_t)); FireSignalReceived(signo, info); } } } } void SignalChannel::FireSignalReceived(int signo, siginfo_t& info) { SignalHandlerMap::iterator it = m_hander_map.find(signo); if (it != m_hander_map.end()) { std::vector<SignalHandler*>& vec = it->second; std::vector<SignalHandler*>::iterator vecit = vec.begin(); while (vecit != vec.end()) { SignalHandler* handler = *vecit; if (NULL != handler) { handler->OnSignal(signo, info); } vecit++; } } } void SignalChannel::Register(uint32 signo, SignalHandler* handler) { SignalHandlerMap::iterator it = m_hander_map.find(signo); if (it == m_hander_map.end() || it->second.empty()) { struct sigaction action; action.sa_sigaction = SignalChannel::SignalCB; sigemptyset(&action.sa_mask); action.sa_flags = SA_SIGINFO; sigaction(signo, &action, NULL); m_hander_map[signo].push_back(handler); } else { it->second.push_back(handler); } } void SignalChannel::Unregister(SignalHandler* handler) { SignalHandlerMap::iterator it = m_hander_map.begin(); while (it != m_hander_map.end()) { std::vector<SignalHandler*>& vec = it->second; std::vector<SignalHandler*>::iterator vecit = vec.begin(); while (vecit != vec.end()) { if (handler == (*vecit)) { vec.erase(vecit); break; } vecit++; } it++; } } void SignalChannel::Clear() { m_hander_map.clear(); } SignalChannel::~SignalChannel() { Clear(); m_singleton_instance = NULL; }
30.390244
80
0.635474
masterve
d742b6120d31bef3329f0faa09cedd603aa3325e
23,708
cpp
C++
src/library/tactic/tactic_state.cpp
soonhokong/lean-windows
06dff344c8e0e3876b56294c8443a3b17c26dd48
[ "Apache-2.0" ]
null
null
null
src/library/tactic/tactic_state.cpp
soonhokong/lean-windows
06dff344c8e0e3876b56294c8443a3b17c26dd48
[ "Apache-2.0" ]
null
null
null
src/library/tactic/tactic_state.cpp
soonhokong/lean-windows
06dff344c8e0e3876b56294c8443a3b17c26dd48
[ "Apache-2.0" ]
1
2018-09-22T14:28:09.000Z
2018-09-22T14:28:09.000Z
/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/fresh_name.h" #include "util/sexpr/option_declarations.h" #include "kernel/type_checker.h" #include "library/constants.h" #include "library/type_context.h" #include "library/pp_options.h" #include "library/trace.h" #include "library/util.h" #include "library/cache_helper.h" #include "library/module.h" #include "library/vm/vm_environment.h" #include "library/vm/vm_exceptional.h" #include "library/vm/vm_format.h" #include "library/vm/vm_options.h" #include "library/vm/vm_name.h" #include "library/vm/vm_nat.h" #include "library/vm/vm_level.h" #include "library/vm/vm_declaration.h" #include "library/vm/vm_expr.h" #include "library/vm/vm_list.h" #include "library/vm/vm_option.h" #include "library/tactic/tactic_state.h" #ifndef LEAN_DEFAULT_PP_INSTANTIATE_GOAL_MVARS #define LEAN_DEFAULT_PP_INSTANTIATE_GOAL_MVARS true #endif namespace lean { static name * g_pp_instantiate_goal_mvars = nullptr; unsigned get_pp_instantiate_goal_mvars(options const & o) { return o.get_unsigned(*g_pp_instantiate_goal_mvars, LEAN_DEFAULT_PP_INSTANTIATE_GOAL_MVARS); } void tactic_state_cell::dealloc() { this->~tactic_state_cell(); get_vm_allocator().deallocate(sizeof(tactic_state_cell), this); } tactic_state::tactic_state(environment const & env, options const & o, metavar_context const & ctx, list<expr> const & gs, expr const & main) { m_ptr = new (get_vm_allocator().allocate(sizeof(tactic_state_cell))) tactic_state_cell(env, o, ctx, gs, main); m_ptr->inc_ref(); } optional<expr> tactic_state::get_main_goal() const { if (empty(goals())) return none_expr(); return some_expr(head(goals())); } optional<metavar_decl> tactic_state::get_main_goal_decl() const { if (empty(goals())) return optional<metavar_decl>(); return mctx().get_metavar_decl(head(goals())); } tactic_state mk_tactic_state_for(environment const & env, options const & o, metavar_context mctx, local_context const & lctx, expr const & type) { expr main = mctx.mk_metavar_decl(lctx, type); return tactic_state(env, o, mctx, list<expr>(main), main); } tactic_state mk_tactic_state_for(environment const & env, options const & o, local_context const & lctx, expr const & type) { metavar_context mctx; return mk_tactic_state_for(env, o, mctx, lctx, type); } tactic_state set_options(tactic_state const & s, options const & o) { return tactic_state(s.env(), o, s.mctx(), s.goals(), s.main()); } tactic_state set_env(tactic_state const & s, environment const & env) { return tactic_state(env, s.get_options(), s.mctx(), s.goals(), s.main()); } tactic_state set_mctx(tactic_state const & s, metavar_context const & mctx) { return tactic_state(s.env(), s.get_options(), mctx, s.goals(), s.main()); } tactic_state set_env_mctx(tactic_state const & s, environment const & env, metavar_context const & mctx) { return tactic_state(env, s.get_options(), mctx, s.goals(), s.main()); } static list<expr> consume_solved_prefix(metavar_context const & mctx, list<expr> const & gs) { if (empty(gs)) return gs; else if (mctx.is_assigned(head(gs))) return consume_solved_prefix(mctx, tail(gs)); else return gs; } tactic_state set_goals(tactic_state const & s, list<expr> const & gs) { return tactic_state(s.env(), s.get_options(), s.mctx(), consume_solved_prefix(s.mctx(), gs), s.main()); } tactic_state set_mctx_goals(tactic_state const & s, metavar_context const & mctx, list<expr> const & gs) { return tactic_state(s.env(), s.get_options(), mctx, consume_solved_prefix(mctx, gs), s.main()); } tactic_state set_env_mctx_goals(tactic_state const & s, environment const & env, metavar_context const & mctx, list<expr> const & gs) { return tactic_state(env, s.get_options(), mctx, consume_solved_prefix(mctx, gs), s.main()); } format tactic_state::pp_expr(formatter_factory const & fmtf, expr const & e) const { type_context ctx = mk_type_context_for(*this, transparency_mode::All); formatter fmt = fmtf(env(), get_options(), ctx); return fmt(e); } format tactic_state::pp_goal(formatter_factory const & fmtf, expr const & g) const { bool inst_mvars = get_pp_instantiate_goal_mvars(get_options()); metavar_decl decl = *mctx().get_metavar_decl(g); local_context lctx = decl.get_context(); metavar_context mctx_tmp = mctx(); type_context ctx(env(), get_options(), mctx_tmp, lctx, transparency_mode::All); formatter fmt = fmtf(env(), get_options(), ctx); if (inst_mvars) lctx = lctx.instantiate_mvars(mctx_tmp); format r = lctx.pp(fmt); unsigned indent = get_pp_indent(get_options()); bool unicode = get_pp_unicode(get_options()); if (!lctx.empty()) r += line(); format turnstile = unicode ? format("\u22A2") /* ⊢ */ : format("|-"); expr type = decl.get_type(); if (inst_mvars) type = mctx_tmp.instantiate_mvars(type); r += turnstile + space() + nest(indent, fmt(type)); if (get_pp_goal_compact(get_options())) r = group(r); return r; } format tactic_state::pp(formatter_factory const & fmtf) const { format r; bool first = true; for (auto const & g : goals()) { if (first) first = false; else r += line() + line(); r += pp_goal(fmtf, g); } if (first) r = format("no goals"); return r; } format tactic_state::pp() const { formatter_factory const & fmtf = get_global_ios().get_formatter_factory(); return pp(fmtf); } format tactic_state::pp_expr(expr const & e) const { formatter_factory const & fmtf = get_global_ios().get_formatter_factory(); return pp_expr(fmtf, e); } format tactic_state::pp_goal(expr const & g) const { lean_assert(is_metavar(g)); lean_assert(mctx().get_metavar_decl(g)); formatter_factory const & fmtf = get_global_ios().get_formatter_factory(); return pp_goal(fmtf, g); } struct vm_tactic_state : public vm_external { tactic_state m_val; vm_tactic_state(tactic_state const & v):m_val(v) {} virtual void dealloc() override { this->~vm_tactic_state(); get_vm_allocator().deallocate(sizeof(vm_tactic_state), this); } }; tactic_state const & to_tactic_state(vm_obj const & o) { lean_assert(is_external(o)); lean_assert(dynamic_cast<vm_tactic_state*>(to_external(o))); return static_cast<vm_tactic_state*>(to_external(o))->m_val; } vm_obj to_obj(tactic_state const & s) { return mk_vm_external(new (get_vm_allocator().allocate(sizeof(vm_tactic_state))) vm_tactic_state(s)); } transparency_mode to_transparency_mode(vm_obj const & o) { return static_cast<transparency_mode>(cidx(o)); } vm_obj to_obj(transparency_mode m) { return mk_vm_simple(static_cast<unsigned>(m)); } vm_obj tactic_state_env(vm_obj const & s) { return to_obj(to_tactic_state(s).env()); } vm_obj tactic_state_to_format(vm_obj const & s) { return to_obj(to_tactic_state(s).pp()); } format pp_expr(tactic_state const & s, expr const & e) { return s.pp_expr(e); } format pp_indented_expr(tactic_state const & s, expr const & e) { formatter_factory const & fmtf = get_global_ios().get_formatter_factory(); return nest(get_pp_indent(s.get_options()), line() + s.pp_expr(fmtf, e)); } vm_obj tactic_state_format_expr(vm_obj const & s, vm_obj const & e) { return to_obj(pp_expr(to_tactic_state(s), to_expr(e))); } optional<tactic_state> is_tactic_success(vm_obj const & o) { if (is_constructor(o) && cidx(o) == 0) { return optional<tactic_state>(to_tactic_state(cfield(o, 1))); } else { return optional<tactic_state>(); } } optional<pair<format, tactic_state>> is_tactic_exception(vm_state & S, options const & opts, vm_obj const & ex) { if (is_constructor(ex) && cidx(ex) == 1) { vm_obj fmt = S.invoke(cfield(ex, 0), to_obj(opts)); return optional<pair<format, tactic_state>>(mk_pair(to_format(fmt), to_tactic_state(cfield(ex, 1)))); } else { return optional<pair<format, tactic_state>>(); } } vm_obj mk_tactic_success(vm_obj const & a, tactic_state const & s) { return mk_vm_constructor(0, a, to_obj(s)); } vm_obj mk_tactic_success(tactic_state const & s) { return mk_tactic_success(mk_vm_unit(), s); } vm_obj mk_tactic_exception(vm_obj const & fn, tactic_state const & s) { return mk_vm_constructor(1, fn, to_obj(s)); } vm_obj mk_tactic_exception(throwable const & ex, tactic_state const & s) { vm_obj _ex = to_obj(ex); vm_obj fn = mk_vm_closure(get_throwable_to_format_fun_idx(), 1, &_ex); return mk_tactic_exception(fn, s); } vm_obj mk_tactic_exception(format const & fmt, tactic_state const & s) { vm_state const & S = get_vm_state(); if (optional<vm_decl> K = S.get_decl(get_combinator_K_name())) { return mk_tactic_exception(mk_vm_closure(K->get_idx(), to_obj(fmt), mk_vm_unit(), mk_vm_unit()), s); } else { throw exception("failed to create tactic exceptional result, combinator.K is not in the environment, " "this can happen when users are hacking the init folder"); } } vm_obj mk_tactic_exception(char const * msg, tactic_state const & s) { return mk_tactic_exception(format(msg), s); } vm_obj mk_tactic_exception(sstream const & strm, tactic_state const & s) { return mk_tactic_exception(strm.str().c_str(), s); } vm_obj mk_tactic_exception(std::function<format()> const & thunk, tactic_state const & s) { return mk_tactic_exception(mk_vm_format_thunk(thunk), s); } vm_obj mk_no_goals_exception(tactic_state const & s) { return mk_tactic_exception("tactic failed, there are no goals to be solved", s); } vm_obj tactic_result(vm_obj const & o) { tactic_state const & s = to_tactic_state(o); metavar_context mctx = s.mctx(); expr r = mctx.instantiate_mvars(s.main()); return mk_tactic_success(to_obj(r), set_mctx(s, mctx)); } vm_obj tactic_format_result(vm_obj const & o) { tactic_state const & s = to_tactic_state(o); metavar_context mctx = s.mctx(); expr r = mctx.instantiate_mvars(s.main()); metavar_decl main_decl = *mctx.get_metavar_decl(s.main()); type_context ctx(s.env(), s.get_options(), mctx, main_decl.get_context(), transparency_mode::All); formatter_factory const & fmtf = get_global_ios().get_formatter_factory(); formatter fmt = fmtf(s.env(), s.get_options(), ctx); return mk_tactic_success(to_obj(fmt(r)), s); } vm_obj tactic_target(vm_obj const & o) { tactic_state const & s = to_tactic_state(o); optional<metavar_decl> g = s.get_main_goal_decl(); if (!g) return mk_no_goals_exception(s); return mk_tactic_success(to_obj(g->get_type()), s); } MK_THREAD_LOCAL_GET_DEF(type_context_cache_manager, get_tcm); type_context mk_type_context_for(environment const & env, options const & o, metavar_context const & mctx, local_context const & lctx, transparency_mode m) { return type_context(env, o, mctx, lctx, get_tcm(), m); } type_context mk_type_context_for(tactic_state const & s, local_context const & lctx, transparency_mode m) { return mk_type_context_for(s.env(), s.get_options(), s.mctx(), lctx, m); } type_context mk_type_context_for(tactic_state const & s, transparency_mode m) { local_context lctx; if (auto d = s.get_main_goal_decl()) lctx = d->get_context(); return mk_type_context_for(s, lctx, m); } type_context mk_type_context_for(vm_obj const & s) { return mk_type_context_for(to_tactic_state(s)); } type_context mk_type_context_for(vm_obj const & s, vm_obj const & m) { return mk_type_context_for(to_tactic_state(s), to_transparency_mode(m)); } vm_obj tactic_infer_type(vm_obj const & e, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); type_context ctx = mk_type_context_for(s); try { return mk_tactic_success(to_obj(ctx.infer(to_expr(e))), s); } catch (exception & ex) { return mk_tactic_exception(ex, s); } } vm_obj tactic_whnf_core(vm_obj const & t, vm_obj const & e, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); type_context ctx = mk_type_context_for(s, to_transparency_mode(t)); try { return mk_tactic_success(to_obj(ctx.whnf(to_expr(e))), s); } catch (exception & ex) { return mk_tactic_exception(ex, s); } } vm_obj tactic_eta_expand(vm_obj const & e, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); type_context ctx = mk_type_context_for(s); try { return mk_tactic_success(to_obj(ctx.eta_expand(to_expr(e))), s); } catch (exception & ex) { return mk_tactic_exception(ex, s); } } vm_obj tactic_is_class(vm_obj const & e, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); type_context ctx = mk_type_context_for(s); try { return mk_tactic_success(mk_vm_bool(static_cast<bool>(ctx.is_class(to_expr(e)))), s); } catch (exception & ex) { return mk_tactic_exception(ex, s); } } vm_obj tactic_mk_instance(vm_obj const & e, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); type_context ctx = mk_type_context_for(s); try { if (auto r = ctx.mk_class_instance(to_expr(e))) { return mk_tactic_success(to_obj(*r), s); } else { auto thunk = [=]() { format m("tactic.mk_instance failed to generate instance for"); m += pp_indented_expr(s, to_expr(e)); return m; }; return mk_tactic_exception(thunk, s); } } catch (exception & ex) { return mk_tactic_exception(ex, s); } } vm_obj tactic_unify_core(vm_obj const & t, vm_obj const & e1, vm_obj const & e2, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); type_context ctx = mk_type_context_for(s, to_transparency_mode(t)); try { bool r = ctx.is_def_eq(to_expr(e1), to_expr(e2)); if (r) return mk_tactic_success(set_mctx(s, ctx.mctx())); else return mk_tactic_exception("unify tactic failed", s); } catch (exception & ex) { return mk_tactic_exception(ex, s); } } vm_obj tactic_is_def_eq_core(vm_obj const & t, vm_obj const & e1, vm_obj const & e2, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); type_context ctx = mk_type_context_for(s, to_transparency_mode(t)); type_context::tmp_mode_scope scope(ctx); try { bool r = ctx.is_def_eq(to_expr(e1), to_expr(e2)); if (r) return mk_tactic_success(s); else return mk_tactic_exception("is_def_eq failed", s); } catch (exception & ex) { return mk_tactic_exception(ex, s); } } vm_obj tactic_get_local(vm_obj const & n, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); optional<metavar_decl> g = s.get_main_goal_decl(); if (!g) return mk_no_goals_exception(s); local_context lctx = g->get_context(); optional<local_decl> d = lctx.get_local_decl_from_user_name(to_name(n)); if (!d) return mk_tactic_exception(sstream() << "get_local tactic failed, unknown '" << to_name(n) << "' local", s); return mk_tactic_success(to_obj(d->mk_ref()), s); } vm_obj tactic_local_context(vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); optional<metavar_decl> g = s.get_main_goal_decl(); if (!g) return mk_no_goals_exception(s); local_context lctx = g->get_context(); buffer<expr> r; lctx.for_each([&](local_decl const & d) { r.push_back(d.mk_ref()); }); return mk_tactic_success(to_obj(to_list(r)), s); } vm_obj tactic_get_unused_name(vm_obj const & n, vm_obj const & vm_i, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); optional<metavar_decl> g = s.get_main_goal_decl(); if (!g) return mk_no_goals_exception(s); name unused_name; if (is_none(vm_i)) { unused_name = g->get_context().get_unused_name(to_name(n)); } else { unsigned i = force_to_unsigned(get_some_value(vm_i), 0); unused_name = g->get_context().get_unused_name(to_name(n), i); } return mk_tactic_success(to_obj(unused_name), s); } vm_obj rotate_left(unsigned n, tactic_state const & s) { buffer<expr> gs; to_buffer(s.goals(), gs); unsigned sz = gs.size(); if (sz == 0) return mk_tactic_success(s); n = n%sz; std::rotate(gs.begin(), gs.begin() + n, gs.end()); return mk_tactic_success(set_goals(s, to_list(gs))); } vm_obj tactic_rotate_left(vm_obj const & n, vm_obj const & s) { return rotate_left(force_to_unsigned(n, 0), to_tactic_state(s)); } vm_obj tactic_get_goals(vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); return mk_tactic_success(to_obj(s.goals()), s); } vm_obj set_goals(list<expr> const & gs, tactic_state const & s) { buffer<expr> new_gs; metavar_context const & mctx = s.mctx(); for (expr const & g : gs) { if (!mctx.get_metavar_decl(g)) { return mk_tactic_exception("invalid set_goals tactic, expressions must be meta-variables " "that have been declared in the current tactic_state", s); } if (!mctx.is_assigned(g)) new_gs.push_back(g); } return mk_tactic_success(set_goals(s, to_list(new_gs))); } vm_obj tactic_set_goals(vm_obj const & gs, vm_obj const & s) { return set_goals(to_list_expr(gs), to_tactic_state(s)); } vm_obj tactic_mk_meta_univ(vm_obj const & s) { metavar_context mctx = to_tactic_state(s).mctx(); level u = mctx.mk_univ_metavar_decl(); return mk_tactic_success(to_obj(u), set_mctx(to_tactic_state(s), mctx)); } vm_obj tactic_mk_meta_var(vm_obj const & t, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); metavar_context mctx = s.mctx(); local_context lctx; if (optional<metavar_decl> g = s.get_main_goal_decl()) { lctx = g->get_context(); } expr m = mctx.mk_metavar_decl(lctx, to_expr(t)); return mk_tactic_success(to_obj(m), set_mctx(s, mctx)); } vm_obj tactic_get_univ_assignment(vm_obj const & u, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); metavar_context mctx = s.mctx(); if (!is_meta(to_level(u))) { return mk_tactic_exception("get_univ_assignment tactic failed, argument is not an universe metavariable", s); } else if (auto r = mctx.get_assignment(to_level(u))) { return mk_tactic_success(to_obj(*r), s); } else { return mk_tactic_exception("get_univ_assignment tactic failed, universe metavariable is not assigned", s); } } vm_obj tactic_get_assignment(vm_obj const & e, vm_obj const & s0) { tactic_state const & s = to_tactic_state(s0); metavar_context mctx = s.mctx(); if (!is_metavar(to_expr(e))) { return mk_tactic_exception("get_assignment tactic failed, argument is not an universe metavariable", s); } else if (auto r = mctx.get_assignment(to_expr(e))) { return mk_tactic_success(to_obj(*r), s); } else { return mk_tactic_exception("get_assignment tactic failed, metavariable is not assigned", s); } } vm_obj tactic_state_get_options(vm_obj const & s) { return to_obj(to_tactic_state(s).get_options()); } vm_obj tactic_state_set_options(vm_obj const & s, vm_obj const & o) { return to_obj(set_options(to_tactic_state(s), to_options(o))); } vm_obj tactic_mk_fresh_name(vm_obj const & s) { return mk_tactic_success(to_obj(mk_fresh_name()), to_tactic_state(s)); } vm_obj tactic_is_trace_enabled_for(vm_obj const & n) { return mk_vm_bool(is_trace_class_enabled(to_name(n))); } vm_obj tactic_instantiate_mvars(vm_obj const & e, vm_obj const & _s) { tactic_state const & s = to_tactic_state(_s); metavar_context mctx = s.mctx(); expr r = mctx.instantiate_mvars(to_expr(e)); return mk_tactic_success(to_obj(r), set_mctx(s, mctx)); } vm_obj tactic_add_decl(vm_obj const & d, vm_obj const & _s) { tactic_state const & s = to_tactic_state(_s); try { environment new_env = module::add(s.env(), check(s.env(), to_declaration(d))); return mk_tactic_success(set_env(s, new_env)); } catch (throwable & ex) { return mk_tactic_exception(ex, s); } } void initialize_tactic_state() { DECLARE_VM_BUILTIN(name({"tactic_state", "env"}), tactic_state_env); DECLARE_VM_BUILTIN(name({"tactic_state", "format_expr"}), tactic_state_format_expr); DECLARE_VM_BUILTIN(name({"tactic_state", "to_format"}), tactic_state_to_format); DECLARE_VM_BUILTIN(name({"tactic_state", "get_options"}), tactic_state_get_options); DECLARE_VM_BUILTIN(name({"tactic_state", "set_options"}), tactic_state_set_options); DECLARE_VM_BUILTIN(name({"tactic", "target"}), tactic_target); DECLARE_VM_BUILTIN(name({"tactic", "result"}), tactic_result); DECLARE_VM_BUILTIN(name({"tactic", "format_result"}), tactic_format_result); DECLARE_VM_BUILTIN(name({"tactic", "infer_type"}), tactic_infer_type); DECLARE_VM_BUILTIN(name({"tactic", "whnf_core"}), tactic_whnf_core); DECLARE_VM_BUILTIN(name({"tactic", "is_def_eq_core"}), tactic_is_def_eq_core); DECLARE_VM_BUILTIN(name({"tactic", "eta_expand"}), tactic_eta_expand); DECLARE_VM_BUILTIN(name({"tactic", "is_class"}), tactic_is_class); DECLARE_VM_BUILTIN(name({"tactic", "mk_instance"}), tactic_mk_instance); DECLARE_VM_BUILTIN(name({"tactic", "unify_core"}), tactic_unify_core); DECLARE_VM_BUILTIN(name({"tactic", "get_local"}), tactic_get_local); DECLARE_VM_BUILTIN(name({"tactic", "local_context"}), tactic_local_context); DECLARE_VM_BUILTIN(name({"tactic", "get_unused_name"}), tactic_get_unused_name); DECLARE_VM_BUILTIN(name({"tactic", "rotate_left"}), tactic_rotate_left); DECLARE_VM_BUILTIN(name({"tactic", "get_goals"}), tactic_get_goals); DECLARE_VM_BUILTIN(name({"tactic", "set_goals"}), tactic_set_goals); DECLARE_VM_BUILTIN(name({"tactic", "mk_meta_univ"}), tactic_mk_meta_univ); DECLARE_VM_BUILTIN(name({"tactic", "mk_meta_var"}), tactic_mk_meta_var); DECLARE_VM_BUILTIN(name({"tactic", "get_univ_assignment"}), tactic_get_univ_assignment); DECLARE_VM_BUILTIN(name({"tactic", "get_assignment"}), tactic_get_assignment); DECLARE_VM_BUILTIN(name({"tactic", "mk_fresh_name"}), tactic_mk_fresh_name); DECLARE_VM_BUILTIN(name({"tactic", "is_trace_enabled_for"}), tactic_is_trace_enabled_for); DECLARE_VM_BUILTIN(name({"tactic", "instantiate_mvars"}), tactic_instantiate_mvars); DECLARE_VM_BUILTIN(name({"tactic", "add_decl"}), tactic_add_decl); g_pp_instantiate_goal_mvars = new name{"pp", "instantiate_goal_mvars"}; register_bool_option(*g_pp_instantiate_goal_mvars, LEAN_DEFAULT_PP_INSTANTIATE_GOAL_MVARS, "(pretty printer) instantiate assigned metavariables before pretty printing goals"); } void finalize_tactic_state() { delete g_pp_instantiate_goal_mvars; } }
39.447587
125
0.681162
soonhokong
d742e11d0b9576ea4c2c155aaf805608361d3437
58,555
cpp
C++
src/axom/sidre/interface/c_fortran/wrapGroup.cpp
raineyeh/axom
57a6ef7ab50e113e4cf4b639657eb84ff10789c0
[ "BSD-3-Clause" ]
null
null
null
src/axom/sidre/interface/c_fortran/wrapGroup.cpp
raineyeh/axom
57a6ef7ab50e113e4cf4b639657eb84ff10789c0
[ "BSD-3-Clause" ]
null
null
null
src/axom/sidre/interface/c_fortran/wrapGroup.cpp
raineyeh/axom
57a6ef7ab50e113e4cf4b639657eb84ff10789c0
[ "BSD-3-Clause" ]
null
null
null
// wrapGroup.cpp // This file is generated by Shroud 0.12.2. Do not edit. // // Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "wrapGroup.h" #include <cstring> #include <string> #include "axom/sidre/core/Buffer.hpp" #include "axom/sidre/core/DataStore.hpp" #include "axom/sidre/core/Group.hpp" #include "axom/sidre/core/View.hpp" #include "axom/sidre/interface/SidreTypes.h" // splicer begin class.Group.CXX_definitions // splicer end class.Group.CXX_definitions extern "C" { // helper ShroudStrCopy // Copy src into dest, blank fill to ndest characters // Truncate if dest is too short. // dest will not be NULL terminated. static void ShroudStrCopy(char* dest, int ndest, const char* src, int nsrc) { if(src == NULL) { std::memset(dest, ' ', ndest); // convert NULL pointer to blank filled string } else { if(nsrc < 0) nsrc = std::strlen(src); int nm = nsrc < ndest ? nsrc : ndest; std::memcpy(dest, src, nm); if(ndest > nm) std::memset(dest + nm, ' ', ndest - nm); // blank fill } } // splicer begin class.Group.C_definitions // splicer end class.Group.C_definitions SIDRE_IndexType SIDRE_Group_get_index(SIDRE_Group* self) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_index axom::sidre::IndexType SHC_rv = SH_this->getIndex(); return SHC_rv; // splicer end class.Group.method.get_index } const char* SIDRE_Group_get_name(const SIDRE_Group* self) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_name const std::string& SHCXX_rv = SH_this->getName(); const char* SHC_rv = SHCXX_rv.c_str(); return SHC_rv; // splicer end class.Group.method.get_name } void SIDRE_Group_get_name_bufferify(const SIDRE_Group* self, char* SHF_rv, int NSHF_rv) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_name_bufferify const std::string& SHCXX_rv = SH_this->getName(); if(SHCXX_rv.empty()) { ShroudStrCopy(SHF_rv, NSHF_rv, nullptr, 0); } else { ShroudStrCopy(SHF_rv, NSHF_rv, SHCXX_rv.data(), SHCXX_rv.size()); } // splicer end class.Group.method.get_name_bufferify } void SIDRE_Group_get_path_bufferify(const SIDRE_Group* self, char* SHF_rv, int NSHF_rv) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_path_bufferify std::string SHCXX_rv = SH_this->getPath(); if(SHCXX_rv.empty()) { ShroudStrCopy(SHF_rv, NSHF_rv, nullptr, 0); } else { ShroudStrCopy(SHF_rv, NSHF_rv, SHCXX_rv.data(), SHCXX_rv.size()); } // splicer end class.Group.method.get_path_bufferify } void SIDRE_Group_get_path_name_bufferify(const SIDRE_Group* self, char* SHF_rv, int NSHF_rv) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_path_name_bufferify std::string SHCXX_rv = SH_this->getPathName(); if(SHCXX_rv.empty()) { ShroudStrCopy(SHF_rv, NSHF_rv, nullptr, 0); } else { ShroudStrCopy(SHF_rv, NSHF_rv, SHCXX_rv.data(), SHCXX_rv.size()); } // splicer end class.Group.method.get_path_name_bufferify } SIDRE_Group* SIDRE_Group_get_parent(const SIDRE_Group* self, SIDRE_Group* SHC_rv) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_parent const axom::sidre::Group* SHCXX_rv = SH_this->getParent(); SHC_rv->addr = const_cast<axom::sidre::Group*>(SHCXX_rv); SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.get_parent } size_t SIDRE_Group_get_num_groups(const SIDRE_Group* self) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_num_groups size_t SHC_rv = SH_this->getNumGroups(); return SHC_rv; // splicer end class.Group.method.get_num_groups } size_t SIDRE_Group_get_num_views(const SIDRE_Group* self) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_num_views size_t SHC_rv = SH_this->getNumViews(); return SHC_rv; // splicer end class.Group.method.get_num_views } SIDRE_DataStore* SIDRE_Group_get_data_store(const SIDRE_Group* self, SIDRE_DataStore* SHC_rv) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_data_store const axom::sidre::DataStore* SHCXX_rv = SH_this->getDataStore(); SHC_rv->addr = const_cast<axom::sidre::DataStore*>(SHCXX_rv); SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.get_data_store } bool SIDRE_Group_has_view(const SIDRE_Group* self, const char* path) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.has_view const std::string SHCXX_path(path); bool SHC_rv = SH_this->hasView(SHCXX_path); return SHC_rv; // splicer end class.Group.method.has_view } bool SIDRE_Group_has_view_bufferify(const SIDRE_Group* self, const char* path, int Lpath) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.has_view_bufferify const std::string SHCXX_path(path, Lpath); bool SHC_rv = SH_this->hasView(SHCXX_path); return SHC_rv; // splicer end class.Group.method.has_view_bufferify } bool SIDRE_Group_has_child_view(const SIDRE_Group* self, const char* name) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.has_child_view const std::string SHCXX_name(name); bool SHC_rv = SH_this->hasChildView(SHCXX_name); return SHC_rv; // splicer end class.Group.method.has_child_view } bool SIDRE_Group_has_child_view_bufferify(const SIDRE_Group* self, const char* name, int Lname) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.has_child_view_bufferify const std::string SHCXX_name(name, Lname); bool SHC_rv = SH_this->hasChildView(SHCXX_name); return SHC_rv; // splicer end class.Group.method.has_child_view_bufferify } SIDRE_IndexType SIDRE_Group_get_view_index(const SIDRE_Group* self, const char* name) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_view_index const std::string SHCXX_name(name); axom::sidre::IndexType SHC_rv = SH_this->getViewIndex(SHCXX_name); return SHC_rv; // splicer end class.Group.method.get_view_index } SIDRE_IndexType SIDRE_Group_get_view_index_bufferify(const SIDRE_Group* self, const char* name, int Lname) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_view_index_bufferify const std::string SHCXX_name(name, Lname); axom::sidre::IndexType SHC_rv = SH_this->getViewIndex(SHCXX_name); return SHC_rv; // splicer end class.Group.method.get_view_index_bufferify } const char* SIDRE_Group_get_view_name(const SIDRE_Group* self, SIDRE_IndexType idx) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_view_name const std::string& SHCXX_rv = SH_this->getViewName(idx); // C_error_pattern if(!axom::sidre::nameIsValid(SHCXX_rv)) { return SIDRE_InvalidName; } const char* SHC_rv = SHCXX_rv.c_str(); return SHC_rv; // splicer end class.Group.method.get_view_name } void SIDRE_Group_get_view_name_bufferify(const SIDRE_Group* self, SIDRE_IndexType idx, char* SHF_rv, int NSHF_rv) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_view_name_bufferify const std::string& SHCXX_rv = SH_this->getViewName(idx); // C_error_pattern if(!axom::sidre::nameIsValid(SHCXX_rv)) { std::memset(SHF_rv, ' ', NSHF_rv); return; } if(SHCXX_rv.empty()) { ShroudStrCopy(SHF_rv, NSHF_rv, nullptr, 0); } else { ShroudStrCopy(SHF_rv, NSHF_rv, SHCXX_rv.data(), SHCXX_rv.size()); } // splicer end class.Group.method.get_view_name_bufferify } SIDRE_View* SIDRE_Group_get_view_from_name(SIDRE_Group* self, const char* path, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_view_from_name const std::string SHCXX_path(path); axom::sidre::View* SHCXX_rv = SH_this->getView(SHCXX_path); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.get_view_from_name } SIDRE_View* SIDRE_Group_get_view_from_name_bufferify(SIDRE_Group* self, const char* path, int Lpath, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_view_from_name_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::View* SHCXX_rv = SH_this->getView(SHCXX_path); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.get_view_from_name_bufferify } SIDRE_View* SIDRE_Group_get_view_from_index(SIDRE_Group* self, const SIDRE_IndexType idx, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_view_from_index axom::sidre::View* SHCXX_rv = SH_this->getView(idx); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.get_view_from_index } SIDRE_IndexType SIDRE_Group_get_first_valid_view_index(const SIDRE_Group* self) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_first_valid_view_index axom::sidre::IndexType SHC_rv = SH_this->getFirstValidViewIndex(); return SHC_rv; // splicer end class.Group.method.get_first_valid_view_index } SIDRE_IndexType SIDRE_Group_get_next_valid_view_index(const SIDRE_Group* self, SIDRE_IndexType idx) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_next_valid_view_index axom::sidre::IndexType SHC_rv = SH_this->getNextValidViewIndex(idx); return SHC_rv; // splicer end class.Group.method.get_next_valid_view_index } SIDRE_View* SIDRE_Group_create_view_empty(SIDRE_Group* self, const char* path, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_empty const std::string SHCXX_path(path); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_empty } SIDRE_View* SIDRE_Group_create_view_empty_bufferify(SIDRE_Group* self, const char* path, int Lpath, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_empty_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_empty_bufferify } SIDRE_View* SIDRE_Group_create_view_from_type(SIDRE_Group* self, const char* path, int type, SIDRE_IndexType num_elems, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_type const std::string SHCXX_path(path); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, num_elems); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_type } SIDRE_View* SIDRE_Group_create_view_from_type_bufferify(SIDRE_Group* self, const char* path, int Lpath, int type, SIDRE_IndexType num_elems, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_type_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, num_elems); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_type_bufferify } SIDRE_View* SIDRE_Group_create_view_from_shape(SIDRE_Group* self, const char* path, int type, int ndims, const SIDRE_IndexType* shape, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_shape const std::string SHCXX_path(path); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, ndims, shape); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_shape } SIDRE_View* SIDRE_Group_create_view_from_shape_bufferify(SIDRE_Group* self, const char* path, int Lpath, int type, int ndims, const SIDRE_IndexType* shape, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_shape_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, ndims, shape); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_shape_bufferify } SIDRE_View* SIDRE_Group_create_view_into_buffer(SIDRE_Group* self, const char* path, SIDRE_Buffer* buff, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_into_buffer const std::string SHCXX_path(path); axom::sidre::Buffer* SHCXX_buff = static_cast<axom::sidre::Buffer*>(buff->addr); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_buff); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_into_buffer } SIDRE_View* SIDRE_Group_create_view_into_buffer_bufferify(SIDRE_Group* self, const char* path, int Lpath, SIDRE_Buffer* buff, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_into_buffer_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::Buffer* SHCXX_buff = static_cast<axom::sidre::Buffer*>(buff->addr); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_buff); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_into_buffer_bufferify } SIDRE_View* SIDRE_Group_create_view_from_type_and_buffer(SIDRE_Group* self, const char* path, int type, SIDRE_IndexType num_elems, SIDRE_Buffer* buff, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_type_and_buffer const std::string SHCXX_path(path); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::Buffer* SHCXX_buff = static_cast<axom::sidre::Buffer*>(buff->addr); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, num_elems, SHCXX_buff); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_type_and_buffer } SIDRE_View* SIDRE_Group_create_view_from_type_and_buffer_bufferify( SIDRE_Group* self, const char* path, int Lpath, int type, SIDRE_IndexType num_elems, SIDRE_Buffer* buff, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_type_and_buffer_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::Buffer* SHCXX_buff = static_cast<axom::sidre::Buffer*>(buff->addr); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, num_elems, SHCXX_buff); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_type_and_buffer_bufferify } SIDRE_View* SIDRE_Group_create_view_from_shape_and_buffer(SIDRE_Group* self, const char* path, int type, int ndims, const SIDRE_IndexType* shape, SIDRE_Buffer* buff, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_shape_and_buffer const std::string SHCXX_path(path); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::Buffer* SHCXX_buff = static_cast<axom::sidre::Buffer*>(buff->addr); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, ndims, shape, SHCXX_buff); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_shape_and_buffer } SIDRE_View* SIDRE_Group_create_view_from_shape_and_buffer_bufferify( SIDRE_Group* self, const char* path, int Lpath, int type, int ndims, const SIDRE_IndexType* shape, SIDRE_Buffer* buff, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin // class.Group.method.create_view_from_shape_and_buffer_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::Buffer* SHCXX_buff = static_cast<axom::sidre::Buffer*>(buff->addr); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, ndims, shape, SHCXX_buff); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_shape_and_buffer_bufferify } SIDRE_View* SIDRE_Group_create_view_external(SIDRE_Group* self, const char* path, void* external_ptr, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_external const std::string SHCXX_path(path); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, external_ptr); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_external } SIDRE_View* SIDRE_Group_create_view_external_bufferify(SIDRE_Group* self, const char* path, int Lpath, void* external_ptr, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_external_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, external_ptr); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_external_bufferify } SIDRE_View* SIDRE_Group_create_view_from_type_external(SIDRE_Group* self, const char* path, int type, SIDRE_IndexType num_elems, void* external_ptr, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_type_external const std::string SHCXX_path(path); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, num_elems, external_ptr); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_type_external } SIDRE_View* SIDRE_Group_create_view_from_type_external_bufferify( SIDRE_Group* self, const char* path, int Lpath, int type, SIDRE_IndexType num_elems, void* external_ptr, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_type_external_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, num_elems, external_ptr); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_type_external_bufferify } SIDRE_View* SIDRE_Group_create_view_from_shape_external(SIDRE_Group* self, const char* path, int type, int ndims, const SIDRE_IndexType* shape, void* external_ptr, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_shape_external const std::string SHCXX_path(path); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, ndims, shape, external_ptr); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_shape_external } SIDRE_View* SIDRE_Group_create_view_from_shape_external_bufferify( SIDRE_Group* self, const char* path, int Lpath, int type, int ndims, const SIDRE_IndexType* shape, void* external_ptr, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_from_shape_external_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createView(SHCXX_path, SHCXX_type, ndims, shape, external_ptr); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_from_shape_external_bufferify } SIDRE_View* SIDRE_Group_create_view_and_allocate_nelems(SIDRE_Group* self, const char* path, int type, SIDRE_IndexType num_elems, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_and_allocate_nelems const std::string SHCXX_path(path); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createViewAndAllocate(SHCXX_path, SHCXX_type, num_elems); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_and_allocate_nelems } SIDRE_View* SIDRE_Group_create_view_and_allocate_nelems_bufferify( SIDRE_Group* self, const char* path, int Lpath, int type, SIDRE_IndexType num_elems, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_and_allocate_nelems_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createViewAndAllocate(SHCXX_path, SHCXX_type, num_elems); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_and_allocate_nelems_bufferify } SIDRE_View* SIDRE_Group_create_view_and_allocate_shape(SIDRE_Group* self, const char* path, int type, int ndims, const SIDRE_IndexType* shape, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_and_allocate_shape const std::string SHCXX_path(path); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createViewAndAllocate(SHCXX_path, SHCXX_type, ndims, shape); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_and_allocate_shape } SIDRE_View* SIDRE_Group_create_view_and_allocate_shape_bufferify( SIDRE_Group* self, const char* path, int Lpath, int type, int ndims, const SIDRE_IndexType* shape, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_and_allocate_shape_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::TypeID SHCXX_type = axom::sidre::getTypeID(type); axom::sidre::View* SHCXX_rv = SH_this->createViewAndAllocate(SHCXX_path, SHCXX_type, ndims, shape); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_and_allocate_shape_bufferify } SIDRE_View* SIDRE_Group_create_view_scalar_int(SIDRE_Group* self, const char* path, int value, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_scalar_int const std::string SHCXX_path(path); axom::sidre::View* SHCXX_rv = SH_this->createViewScalar<int>(SHCXX_path, value); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_scalar_int } SIDRE_View* SIDRE_Group_create_view_scalar_bufferify_int(SIDRE_Group* self, const char* path, int Lpath, int value, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_scalar_bufferify_int const std::string SHCXX_path(path, Lpath); axom::sidre::View* SHCXX_rv = SH_this->createViewScalar<int>(SHCXX_path, value); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_scalar_bufferify_int } SIDRE_View* SIDRE_Group_create_view_scalar_long(SIDRE_Group* self, const char* path, long value, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_scalar_long const std::string SHCXX_path(path); axom::sidre::View* SHCXX_rv = SH_this->createViewScalar<long>(SHCXX_path, value); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_scalar_long } SIDRE_View* SIDRE_Group_create_view_scalar_bufferify_long(SIDRE_Group* self, const char* path, int Lpath, long value, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_scalar_bufferify_long const std::string SHCXX_path(path, Lpath); axom::sidre::View* SHCXX_rv = SH_this->createViewScalar<long>(SHCXX_path, value); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_scalar_bufferify_long } SIDRE_View* SIDRE_Group_create_view_scalar_float(SIDRE_Group* self, const char* path, float value, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_scalar_float const std::string SHCXX_path(path); axom::sidre::View* SHCXX_rv = SH_this->createViewScalar<float>(SHCXX_path, value); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_scalar_float } SIDRE_View* SIDRE_Group_create_view_scalar_bufferify_float(SIDRE_Group* self, const char* path, int Lpath, float value, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_scalar_bufferify_float const std::string SHCXX_path(path, Lpath); axom::sidre::View* SHCXX_rv = SH_this->createViewScalar<float>(SHCXX_path, value); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_scalar_bufferify_float } SIDRE_View* SIDRE_Group_create_view_scalar_double(SIDRE_Group* self, const char* path, double value, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_scalar_double const std::string SHCXX_path(path); axom::sidre::View* SHCXX_rv = SH_this->createViewScalar<double>(SHCXX_path, value); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_scalar_double } SIDRE_View* SIDRE_Group_create_view_scalar_bufferify_double(SIDRE_Group* self, const char* path, int Lpath, double value, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_scalar_bufferify_double const std::string SHCXX_path(path, Lpath); axom::sidre::View* SHCXX_rv = SH_this->createViewScalar<double>(SHCXX_path, value); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_scalar_bufferify_double } SIDRE_View* SIDRE_Group_create_view_string(SIDRE_Group* self, const char* path, const char* value, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_string const std::string SHCXX_path(path); const std::string SHCXX_value(value); axom::sidre::View* SHCXX_rv = SH_this->createViewString(SHCXX_path, SHCXX_value); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_string } SIDRE_View* SIDRE_Group_create_view_string_bufferify(SIDRE_Group* self, const char* path, int Lpath, const char* value, int Lvalue, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_view_string_bufferify const std::string SHCXX_path(path, Lpath); const std::string SHCXX_value(value, Lvalue); axom::sidre::View* SHCXX_rv = SH_this->createViewString(SHCXX_path, SHCXX_value); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_view_string_bufferify } void SIDRE_Group_destroy_view(SIDRE_Group* self, const char* path) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.destroy_view const std::string SHCXX_path(path); SH_this->destroyView(SHCXX_path); // splicer end class.Group.method.destroy_view } void SIDRE_Group_destroy_view_bufferify(SIDRE_Group* self, const char* path, int Lpath) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.destroy_view_bufferify const std::string SHCXX_path(path, Lpath); SH_this->destroyView(SHCXX_path); // splicer end class.Group.method.destroy_view_bufferify } void SIDRE_Group_destroy_view_and_data_name(SIDRE_Group* self, const char* path) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.destroy_view_and_data_name const std::string SHCXX_path(path); SH_this->destroyViewAndData(SHCXX_path); // splicer end class.Group.method.destroy_view_and_data_name } void SIDRE_Group_destroy_view_and_data_name_bufferify(SIDRE_Group* self, const char* path, int Lpath) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.destroy_view_and_data_name_bufferify const std::string SHCXX_path(path, Lpath); SH_this->destroyViewAndData(SHCXX_path); // splicer end class.Group.method.destroy_view_and_data_name_bufferify } void SIDRE_Group_destroy_view_and_data_index(SIDRE_Group* self, SIDRE_IndexType idx) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.destroy_view_and_data_index SH_this->destroyViewAndData(idx); // splicer end class.Group.method.destroy_view_and_data_index } SIDRE_View* SIDRE_Group_move_view(SIDRE_Group* self, SIDRE_View* view, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.move_view axom::sidre::View* SHCXX_view = static_cast<axom::sidre::View*>(view->addr); axom::sidre::View* SHCXX_rv = SH_this->moveView(SHCXX_view); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.move_view } SIDRE_View* SIDRE_Group_copy_view(SIDRE_Group* self, SIDRE_View* view, SIDRE_View* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.copy_view axom::sidre::View* SHCXX_view = static_cast<axom::sidre::View*>(view->addr); axom::sidre::View* SHCXX_rv = SH_this->copyView(SHCXX_view); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.copy_view } bool SIDRE_Group_has_group(SIDRE_Group* self, const char* path) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.has_group const std::string SHCXX_path(path); bool SHC_rv = SH_this->hasGroup(SHCXX_path); return SHC_rv; // splicer end class.Group.method.has_group } bool SIDRE_Group_has_group_bufferify(SIDRE_Group* self, const char* path, int Lpath) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.has_group_bufferify const std::string SHCXX_path(path, Lpath); bool SHC_rv = SH_this->hasGroup(SHCXX_path); return SHC_rv; // splicer end class.Group.method.has_group_bufferify } bool SIDRE_Group_has_child_group(SIDRE_Group* self, const char* name) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.has_child_group const std::string SHCXX_name(name); bool SHC_rv = SH_this->hasChildGroup(SHCXX_name); return SHC_rv; // splicer end class.Group.method.has_child_group } bool SIDRE_Group_has_child_group_bufferify(SIDRE_Group* self, const char* name, int Lname) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.has_child_group_bufferify const std::string SHCXX_name(name, Lname); bool SHC_rv = SH_this->hasChildGroup(SHCXX_name); return SHC_rv; // splicer end class.Group.method.has_child_group_bufferify } SIDRE_IndexType SIDRE_Group_get_group_index(const SIDRE_Group* self, const char* name) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_group_index const std::string SHCXX_name(name); axom::sidre::IndexType SHC_rv = SH_this->getGroupIndex(SHCXX_name); return SHC_rv; // splicer end class.Group.method.get_group_index } SIDRE_IndexType SIDRE_Group_get_group_index_bufferify(const SIDRE_Group* self, const char* name, int Lname) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_group_index_bufferify const std::string SHCXX_name(name, Lname); axom::sidre::IndexType SHC_rv = SH_this->getGroupIndex(SHCXX_name); return SHC_rv; // splicer end class.Group.method.get_group_index_bufferify } const char* SIDRE_Group_get_group_name(const SIDRE_Group* self, SIDRE_IndexType idx) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_group_name const std::string& SHCXX_rv = SH_this->getGroupName(idx); // C_error_pattern if(!axom::sidre::nameIsValid(SHCXX_rv)) { return SIDRE_InvalidName; } const char* SHC_rv = SHCXX_rv.c_str(); return SHC_rv; // splicer end class.Group.method.get_group_name } void SIDRE_Group_get_group_name_bufferify(const SIDRE_Group* self, SIDRE_IndexType idx, char* SHF_rv, int NSHF_rv) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_group_name_bufferify const std::string& SHCXX_rv = SH_this->getGroupName(idx); // C_error_pattern if(!axom::sidre::nameIsValid(SHCXX_rv)) { std::memset(SHF_rv, ' ', NSHF_rv); return; } if(SHCXX_rv.empty()) { ShroudStrCopy(SHF_rv, NSHF_rv, nullptr, 0); } else { ShroudStrCopy(SHF_rv, NSHF_rv, SHCXX_rv.data(), SHCXX_rv.size()); } // splicer end class.Group.method.get_group_name_bufferify } SIDRE_Group* SIDRE_Group_get_group_from_name(SIDRE_Group* self, const char* path, SIDRE_Group* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_group_from_name const std::string SHCXX_path(path); axom::sidre::Group* SHCXX_rv = SH_this->getGroup(SHCXX_path); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.get_group_from_name } SIDRE_Group* SIDRE_Group_get_group_from_name_bufferify(SIDRE_Group* self, const char* path, int Lpath, SIDRE_Group* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_group_from_name_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::Group* SHCXX_rv = SH_this->getGroup(SHCXX_path); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.get_group_from_name_bufferify } SIDRE_Group* SIDRE_Group_get_group_from_index(SIDRE_Group* self, SIDRE_IndexType idx, SIDRE_Group* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_group_from_index axom::sidre::Group* SHCXX_rv = SH_this->getGroup(idx); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.get_group_from_index } SIDRE_IndexType SIDRE_Group_get_first_valid_group_index(const SIDRE_Group* self) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_first_valid_group_index axom::sidre::IndexType SHC_rv = SH_this->getFirstValidGroupIndex(); return SHC_rv; // splicer end class.Group.method.get_first_valid_group_index } SIDRE_IndexType SIDRE_Group_get_next_valid_group_index(const SIDRE_Group* self, SIDRE_IndexType idx) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.get_next_valid_group_index axom::sidre::IndexType SHC_rv = SH_this->getNextValidGroupIndex(idx); return SHC_rv; // splicer end class.Group.method.get_next_valid_group_index } SIDRE_Group* SIDRE_Group_create_group(SIDRE_Group* self, const char* path, SIDRE_Group* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_group const std::string SHCXX_path(path); axom::sidre::Group* SHCXX_rv = SH_this->createGroup(SHCXX_path); // C_error_pattern if(SHCXX_rv == nullptr) { SHC_rv->addr = NULL; SHC_rv->idtor = 0; return NULL; } SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_group } SIDRE_Group* SIDRE_Group_create_group_bufferify(SIDRE_Group* self, const char* path, int Lpath, SIDRE_Group* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.create_group_bufferify const std::string SHCXX_path(path, Lpath); axom::sidre::Group* SHCXX_rv = SH_this->createGroup(SHCXX_path); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.create_group_bufferify } void SIDRE_Group_destroy_group_name(SIDRE_Group* self, const char* path) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.destroy_group_name const std::string SHCXX_path(path); SH_this->destroyGroup(SHCXX_path); // splicer end class.Group.method.destroy_group_name } void SIDRE_Group_destroy_group_name_bufferify(SIDRE_Group* self, const char* path, int Lpath) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.destroy_group_name_bufferify const std::string SHCXX_path(path, Lpath); SH_this->destroyGroup(SHCXX_path); // splicer end class.Group.method.destroy_group_name_bufferify } void SIDRE_Group_destroy_group_index(SIDRE_Group* self, SIDRE_IndexType idx) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.destroy_group_index SH_this->destroyGroup(idx); // splicer end class.Group.method.destroy_group_index } SIDRE_Group* SIDRE_Group_move_group(SIDRE_Group* self, SIDRE_Group* grp, SIDRE_Group* SHC_rv) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.move_group axom::sidre::Group* SHCXX_grp = static_cast<axom::sidre::Group*>(grp->addr); axom::sidre::Group* SHCXX_rv = SH_this->moveGroup(SHCXX_grp); SHC_rv->addr = SHCXX_rv; SHC_rv->idtor = 0; return SHC_rv; // splicer end class.Group.method.move_group } void SIDRE_Group_print(const SIDRE_Group* self) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.print SH_this->print(); // splicer end class.Group.method.print } bool SIDRE_Group_is_equivalent_to(const SIDRE_Group* self, SIDRE_Group* other) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.is_equivalent_to const axom::sidre::Group* SHCXX_other = static_cast<const axom::sidre::Group*>(other->addr); bool SHC_rv = SH_this->isEquivalentTo(SHCXX_other); return SHC_rv; // splicer end class.Group.method.is_equivalent_to } void SIDRE_Group_save(const SIDRE_Group* self, const char* file_path, const char* protocol) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.save const std::string SHCXX_file_path(file_path); const std::string SHCXX_protocol(protocol); SH_this->save(SHCXX_file_path, SHCXX_protocol); // splicer end class.Group.method.save } void SIDRE_Group_save_bufferify(const SIDRE_Group* self, const char* file_path, int Lfile_path, const char* protocol, int Lprotocol) { const axom::sidre::Group* SH_this = static_cast<const axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.save_bufferify const std::string SHCXX_file_path(file_path, Lfile_path); const std::string SHCXX_protocol(protocol, Lprotocol); SH_this->save(SHCXX_file_path, SHCXX_protocol); // splicer end class.Group.method.save_bufferify } void SIDRE_Group_load_0(SIDRE_Group* self, const char* file_path, const char* protocol) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.load_0 const std::string SHCXX_file_path(file_path); const std::string SHCXX_protocol(protocol); SH_this->load(SHCXX_file_path, SHCXX_protocol); // splicer end class.Group.method.load_0 } void SIDRE_Group_load_0_bufferify(SIDRE_Group* self, const char* file_path, int Lfile_path, const char* protocol, int Lprotocol) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.load_0_bufferify const std::string SHCXX_file_path(file_path, Lfile_path); const std::string SHCXX_protocol(protocol, Lprotocol); SH_this->load(SHCXX_file_path, SHCXX_protocol); // splicer end class.Group.method.load_0_bufferify } void SIDRE_Group_load_1(SIDRE_Group* self, const char* file_path, const char* protocol, bool preserve_contents) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.load_1 const std::string SHCXX_file_path(file_path); const std::string SHCXX_protocol(protocol); SH_this->load(SHCXX_file_path, SHCXX_protocol, preserve_contents); // splicer end class.Group.method.load_1 } void SIDRE_Group_load_1_bufferify(SIDRE_Group* self, const char* file_path, int Lfile_path, const char* protocol, int Lprotocol, bool preserve_contents) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.load_1_bufferify const std::string SHCXX_file_path(file_path, Lfile_path); const std::string SHCXX_protocol(protocol, Lprotocol); SH_this->load(SHCXX_file_path, SHCXX_protocol, preserve_contents); // splicer end class.Group.method.load_1_bufferify } void SIDRE_Group_load_external_data(SIDRE_Group* self, const char* file_path) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.load_external_data const std::string SHCXX_file_path(file_path); SH_this->loadExternalData(SHCXX_file_path); // splicer end class.Group.method.load_external_data } void SIDRE_Group_load_external_data_bufferify(SIDRE_Group* self, const char* file_path, int Lfile_path) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.load_external_data_bufferify const std::string SHCXX_file_path(file_path, Lfile_path); SH_this->loadExternalData(SHCXX_file_path); // splicer end class.Group.method.load_external_data_bufferify } bool SIDRE_Group_rename(SIDRE_Group* self, const char* new_name) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.rename const std::string SHCXX_new_name(new_name); bool SHC_rv = SH_this->rename(SHCXX_new_name); return SHC_rv; // splicer end class.Group.method.rename } bool SIDRE_Group_rename_bufferify(SIDRE_Group* self, const char* new_name, int Lnew_name) { axom::sidre::Group* SH_this = static_cast<axom::sidre::Group*>(self->addr); // splicer begin class.Group.method.rename_bufferify const std::string SHCXX_new_name(new_name, Lnew_name); bool SHC_rv = SH_this->rename(SHCXX_new_name); return SHC_rv; // splicer end class.Group.method.rename_bufferify } } // extern "C"
37.439258
87
0.628845
raineyeh
d7517e797ca26e3570dd03a5bf26b6b77eb568c4
16,188
cpp
C++
modules/multiresvolume/rendering/errorhistogrammanager.cpp
scivis-exhibitions/OpenSpace
5b69cf45f110354ecf3bdbcee8cf9d2c75b07e9e
[ "MIT" ]
489
2015-07-14T22:23:10.000Z
2022-03-30T07:59:47.000Z
modules/multiresvolume/rendering/errorhistogrammanager.cpp
scivis-exhibitions/OpenSpace
5b69cf45f110354ecf3bdbcee8cf9d2c75b07e9e
[ "MIT" ]
1,575
2016-07-12T18:10:22.000Z
2022-03-31T20:12:55.000Z
modules/multiresvolume/rendering/errorhistogrammanager.cpp
scivis-exhibitions/OpenSpace
5b69cf45f110354ecf3bdbcee8cf9d2c75b07e9e
[ "MIT" ]
101
2016-03-01T02:22:01.000Z
2022-02-25T15:36:27.000Z
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * 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 <modules/multiresvolume/rendering/errorhistogrammanager.h> #include <modules/multiresvolume/rendering/tsp.h> #include <openspace/util/progressbar.h> #include <ghoul/logging/logmanager.h> #include <ghoul/fmt.h> namespace openspace { ErrorHistogramManager::ErrorHistogramManager(TSP* tsp) : _tsp(tsp) {} bool ErrorHistogramManager::buildHistograms(int numBins) { _numBins = numBins; _file = &(_tsp->file()); if (!_file->is_open()) { return false; } _minBin = 0.f; // Should be calculated from tsp file _maxBin = 1.f; // Should be calculated from tsp file as (maxValue - minValue) unsigned int numOtLevels = _tsp->numOTLevels(); unsigned int numOtLeaves = static_cast<unsigned int>(pow(8, numOtLevels - 1)); unsigned int numBstLeaves = static_cast<unsigned int>( pow(2, _tsp->numBSTLevels() - 1) ); _numInnerNodes = _tsp->numTotalNodes() - numOtLeaves * numBstLeaves; _histograms = std::vector<Histogram>(_numInnerNodes); LINFOC( "ErrorHistogramManager", fmt::format("Build {} histograms with {} bins each", _numInnerNodes, numBins) ); // All TSP Leaves int numOtNodes = _tsp->numOTNodes(); int otOffset = static_cast<int>((pow(8, numOtLevels - 1) - 1) / 7); int numBstNodes = _tsp->numBSTNodes(); int bstOffset = numBstNodes / 2; int numberOfLeaves = (numBstNodes - bstOffset) * (numOtNodes - otOffset); ProgressBar pb(numberOfLeaves); int processedLeaves = 0; bool success = true; for (int bst = bstOffset; bst < numBstNodes; bst++) { for (int ot = otOffset; ot < numOtNodes; ot++) { success &= buildFromLeaf(bst, ot); if (!success) { return false; } pb.print(++processedLeaves); } } return success; } bool ErrorHistogramManager::buildFromLeaf(unsigned int bstOffset, unsigned int octreeOffset) { // Traverse all ancestors of leaf and add errors to their histograms unsigned int brickDim = _tsp->brickDim(); unsigned int paddedBrickDim = _tsp->paddedBrickDim(); unsigned int padding = (paddedBrickDim - brickDim) / 2; int numOtNodes = _tsp->numOTNodes(); unsigned int leafIndex = bstOffset * numOtNodes + octreeOffset; std::vector<float> leafValues = readValues(leafIndex); // int numVoxels = leafValues.size(); int bstNode = bstOffset; bool bstRightOnly = true; unsigned int bstLevel = 0; do { glm::vec3 leafOffset(0.f); // Leaf offset in leaf sized voxels unsigned int octreeLevel = 0; unsigned int octreeNode = octreeOffset; bool octreeLastOnly = true; do { // Visit ancestor if (bstNode != static_cast<int>(bstOffset) || octreeNode != octreeOffset) { // Is actually an ancestor std::vector<float> ancestorVoxels; unsigned int ancestorBrickIndex = bstNode * numOtNodes + octreeNode; unsigned int innerNodeIndex = brickToInnerNodeIndex(ancestorBrickIndex); auto it = _voxelCache.find(innerNodeIndex); if (it == _voxelCache.end()) { // First visit _histograms[innerNodeIndex] = Histogram(_minBin, _maxBin, _numBins); ancestorVoxels = readValues(ancestorBrickIndex); _voxelCache[innerNodeIndex] = ancestorVoxels; } else { ancestorVoxels = it->second; } float voxelScale = static_cast<float>(pow(2.f, octreeLevel)); float invVoxelScale = 1.f / voxelScale; // Calculate leaf offset in ancestor sized voxels glm::vec3 ancestorOffset = (leafOffset * invVoxelScale) + glm::vec3(padding - 0.5f); for (int z = 0; z < static_cast<int>(brickDim); z++) { for (int y = 0; y < static_cast<int>(brickDim); y++) { for (int x = 0; x < static_cast<int>(brickDim); x++) { glm::vec3 leafSamplePoint = glm::vec3(x, y, z) + glm::vec3(static_cast<float>(padding)); glm::vec3 ancestorSamplePoint = ancestorOffset + (glm::vec3(x, y, z) + glm::vec3(0.5)) * invVoxelScale; float leafValue = leafValues[linearCoords(leafSamplePoint)]; float ancestorValue = interpolate( ancestorSamplePoint, ancestorVoxels ); _histograms[innerNodeIndex].addRectangle( leafValue, ancestorValue, std::abs(leafValue - ancestorValue) ); } } } if (bstRightOnly && octreeLastOnly) { _voxelCache.erase(innerNodeIndex); } } // Traverse to next octree ancestor int octreeChild = (octreeNode - 1) % 8; octreeLastOnly &= octreeChild == 7; octreeNode = parentOffset(octreeNode, 8); int childSize = static_cast<int>(pow(2, octreeLevel) * brickDim); leafOffset.x += (octreeChild % 2) * childSize; leafOffset.y += ((octreeChild / 2) % 2) * childSize; leafOffset.z += (octreeChild / 4) * childSize; octreeLevel++; // @TODO(emiax): This does not make sense? unsigned int check against -1 } while (octreeNode != -1); bstRightOnly &= (bstNode % 2 == 0); bstNode = parentOffset(bstNode, 2); bstLevel++; } while (bstNode != -1); return true; } bool ErrorHistogramManager::loadFromFile(const std::filesystem::path& filename) { std::ifstream file(filename, std::ios::in | std::ios::binary); if (!file.is_open()) { return false; } file.read(reinterpret_cast<char*>(&_numInnerNodes), sizeof(int)); file.read(reinterpret_cast<char*>(&_numBins), sizeof(int)); file.read(reinterpret_cast<char*>(&_minBin), sizeof(float)); file.read(reinterpret_cast<char*>(&_maxBin), sizeof(float)); int nFloats = _numInnerNodes * _numBins; float* histogramData = new float[nFloats]; file.read(reinterpret_cast<char*>(histogramData), sizeof(float) * nFloats); _histograms = std::vector<Histogram>(_numInnerNodes); for (int i = 0; i < static_cast<int>(_numInnerNodes); ++i) { int offset = i * _numBins; float* data = new float[_numBins]; memcpy(data, &histogramData[offset], sizeof(float) * _numBins); _histograms[i] = Histogram(_minBin, _maxBin, _numBins, data); } delete[] histogramData; // No need to deallocate histogram data, since histograms take ownership. file.close(); return true; } bool ErrorHistogramManager::saveToFile(const std::filesystem::path& filename) { std::ofstream file(filename, std::ios::out | std::ios::binary); if (!file.is_open()) { return false; } file.write(reinterpret_cast<char*>(&_numInnerNodes), sizeof(int)); file.write(reinterpret_cast<char*>(&_numBins), sizeof(int)); file.write(reinterpret_cast<char*>(&_minBin), sizeof(float)); file.write(reinterpret_cast<char*>(&_maxBin), sizeof(float)); int nFloats = _numInnerNodes * _numBins; float* histogramData = new float[nFloats]; for (unsigned int i = 0; i < _numInnerNodes; ++i) { int offset = i * _numBins; memcpy(&histogramData[offset], _histograms[i].data(), sizeof(float) * _numBins); } file.write(reinterpret_cast<char*>(histogramData), sizeof(float) * nFloats); delete[] histogramData; file.close(); return true; } unsigned int ErrorHistogramManager::linearCoords(const glm::vec3& coords) const { return linearCoords(glm::ivec3(coords)); } unsigned int ErrorHistogramManager::linearCoords(int x, int y, int z) const { return linearCoords(glm::ivec3(x, y, z)); } unsigned int ErrorHistogramManager::linearCoords(const glm::ivec3& coords) const { const unsigned int paddedBrickDim = _tsp->paddedBrickDim(); return coords.z * paddedBrickDim * paddedBrickDim + coords.y * paddedBrickDim + coords.x; } float ErrorHistogramManager::interpolate(const glm::vec3& samplePoint, const std::vector<float>& voxels) const { const int lowX = static_cast<int>(samplePoint.x); const int lowY = static_cast<int>(samplePoint.y); const int lowZ = static_cast<int>(samplePoint.z); const int highX = static_cast<int>(ceil(samplePoint.x)); const int highY = static_cast<int>(ceil(samplePoint.y)); const int highZ = static_cast<int>(ceil(samplePoint.z)); const float interpolatorX = 1.f - (samplePoint.x - lowX); const float interpolatorY = 1.f - (samplePoint.y - lowY); const float interpolatorZ = 1.f - (samplePoint.z - lowZ); const float v000 = voxels[linearCoords(lowX, lowY, lowZ)]; const float v001 = voxels[linearCoords(lowX, lowY, highZ)]; const float v010 = voxels[linearCoords(lowX, highY, lowZ)]; const float v011 = voxels[linearCoords(lowX, highY, highZ)]; const float v100 = voxels[linearCoords(highX, lowY, lowZ)]; const float v101 = voxels[linearCoords(highX, lowY, highZ)]; const float v110 = voxels[linearCoords(highX, highY, lowZ)]; const float v111 = voxels[linearCoords(highX, highY, highZ)]; const float v00 = interpolatorZ * v000 + (1.f - interpolatorZ) * v001; const float v01 = interpolatorZ * v010 + (1.f - interpolatorZ) * v011; const float v10 = interpolatorZ * v100 + (1.f - interpolatorZ) * v101; const float v11 = interpolatorZ * v110 + (1.f - interpolatorZ) * v111; const float v0 = interpolatorY * v00 + (1.f - interpolatorY) * v01; const float v1 = interpolatorY * v10 + (1.f - interpolatorY) * v11; return interpolatorX * v0 + (1.f - interpolatorX) * v1; } const Histogram* ErrorHistogramManager::histogram(unsigned int brickIndex) const { const unsigned int innerNodeIndex = brickToInnerNodeIndex(brickIndex); if (innerNodeIndex < _numInnerNodes) { return &(_histograms[innerNodeIndex]); } else { return nullptr; } } int ErrorHistogramManager::parentOffset(int offset, int base) const { if (offset == 0) { return -1; } const int depth = static_cast<int>( floor(log1p(((base - 1) * offset)) / log(base)) ); const int firstInLevel = static_cast<int>((pow(base, depth) - 1) / (base - 1)); const int inLevelOffset = offset - firstInLevel; const int parentDepth = depth - 1; const int firstInParentLevel = static_cast<int>( (pow(base, parentDepth) - 1) / (base - 1) ); const int parentInLevelOffset = inLevelOffset / base; const int parentOffset = firstInParentLevel + parentInLevelOffset; return parentOffset; } std::vector<float> ErrorHistogramManager::readValues(unsigned int brickIndex) const { const unsigned int paddedBrickDim = _tsp->paddedBrickDim(); const unsigned int numBrickVals = paddedBrickDim * paddedBrickDim * paddedBrickDim; std::vector<float> voxelValues(numBrickVals); std::streampos offset = _tsp->dataPosition() + static_cast<long long>(brickIndex*numBrickVals*sizeof(float)); _file->seekg(offset); _file->read( reinterpret_cast<char*>(voxelValues.data()), static_cast<size_t>(numBrickVals)*sizeof(float) ); return voxelValues; } unsigned int ErrorHistogramManager::brickToInnerNodeIndex(unsigned int brickIndex) const { const unsigned int numOtNodes = _tsp->numOTNodes(); const unsigned int numBstLevels = _tsp->numBSTLevels(); const unsigned int numInnerBstNodes = static_cast<int>( (pow(2, numBstLevels - 1) - 1) * numOtNodes ); if (brickIndex < numInnerBstNodes) { return brickIndex; } const unsigned int numOtLeaves = static_cast<unsigned int>( pow(8, _tsp->numOTLevels() - 1) ); const unsigned int numOtInnerNodes = (numOtNodes - numOtLeaves); const unsigned int innerBstOffset = brickIndex - numInnerBstNodes; const unsigned int rowIndex = innerBstOffset / numOtNodes; const unsigned int indexInRow = innerBstOffset % numOtNodes; if (indexInRow >= numOtInnerNodes) { return std::numeric_limits<unsigned int>::max(); } const unsigned int offset = rowIndex * numOtInnerNodes; const unsigned int leavesOffset = offset + indexInRow; return numInnerBstNodes + leavesOffset; } unsigned int ErrorHistogramManager::innerNodeToBrickIndex( unsigned int innerNodeIndex) const { if (innerNodeIndex >= _numInnerNodes) { return std::numeric_limits<unsigned int>::max(); // Not an inner node } const unsigned int numOtNodes = _tsp->numOTNodes(); const unsigned int numBstLevels = _tsp->numBSTLevels(); const unsigned int numInnerBstNodes = static_cast<unsigned int>( (pow(2, numBstLevels - 1) - 1) * numOtNodes ); if (innerNodeIndex < numInnerBstNodes) { return innerNodeIndex; } const unsigned int numOtLeaves = static_cast<unsigned int>( pow(8, _tsp->numOTLevels() - 1) ); const unsigned int numOtInnerNodes = (numOtNodes - numOtLeaves); const unsigned int innerBstOffset = innerNodeIndex - numInnerBstNodes; const unsigned int rowIndex = innerBstOffset / numOtInnerNodes; const unsigned int indexInRow = innerBstOffset % numOtInnerNodes; const unsigned int offset = rowIndex * numOtNodes; const unsigned int leavesOffset = offset + indexInRow; return numInnerBstNodes + leavesOffset; } } // namespace openspace
40.47
90
0.597109
scivis-exhibitions
d754f406c4bf120d82a0079c3ac1dc57d6730e54
554
cpp
C++
lab/lab3/ex2/main.cpp
YZL24/SUSTech-CS205
c15e4055b3e260e84e94c8db46b4180448c3619f
[ "MIT" ]
null
null
null
lab/lab3/ex2/main.cpp
YZL24/SUSTech-CS205
c15e4055b3e260e84e94c8db46b4180448c3619f
[ "MIT" ]
null
null
null
lab/lab3/ex2/main.cpp
YZL24/SUSTech-CS205
c15e4055b3e260e84e94c8db46b4180448c3619f
[ "MIT" ]
null
null
null
#include <regex> #include "fac.hpp" using namespace std; const regex pattern("^[1-9]+[0-9]*"); int main() { string num; int tar = 0; int64_t f = 1; do { cout << "Please input a positive integer: "; cin >> num; try { tar = stoi(num); } catch (...) { continue; } } while (!regex_match(num, pattern)); if (tar > 20) { cerr << "frac > 20! is not supported yet" << endl; return -1; } for (int i = 1; i <= tar; i++) fac(f, i); return 0; }
18.466667
58
0.462094
YZL24
d7559762fb5c203b8e547632285a8bdb393909d2
881
cpp
C++
UVA/661.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
UVA/661.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
UVA/661.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define f first #define s second using namespace std; int main(){ //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int n, m, c; int cases=1; while((cin >> n >> m >> c) && n!=0 && m!=0 && c!=0){ cout << "Sequence " << cases++ << "\n"; vector<pair<bool, int>> vec(n); int maxC=0, actC=0, d; for(auto &x: vec){ x.f=false; cin >> x.s; } bool fuseBlown=false; for(int i=0; i<m; i++){ cin >> d; d--; if(!vec[d].f){ //Se prendera actC+=vec[d].s; } else{ //Se apagara actC-=vec[d].s; } vec[d].f=!vec[d].f; if(actC>c){ fuseBlown=true; } maxC=max(maxC, actC); } if(fuseBlown){ cout << "Fuse was blown.\n"; } else{ cout << "Fuse was not blown.\n"; cout << "Maximal power consumption was " << maxC << " amperes.\n"; } cout << "\n"; } return 0; }
18.744681
69
0.503973
DT3264
d75d70c97843a9982cc163efc1ad8d80b852fb1a
1,427
cpp
C++
cpp/new_features/cpp17/filesystem/file_size.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
2
2019-12-21T00:53:47.000Z
2020-01-01T10:36:30.000Z
cpp/new_features/cpp17/filesystem/file_size.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
cpp/new_features/cpp17/filesystem/file_size.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
// // Created by kaiser on 19-3-22. // #include <cmath> #include <cstddef> #include <cstdlib> #include <filesystem> #include <iostream> #include <numeric> #include <sstream> #include <string> #include <fmt/core.h> namespace fs = std::filesystem; std::string size_string(std::size_t size) { std::stringstream ss; if (size >= std::pow(2, 30)) { ss << (size / std::pow(2, 30)) << " GB"; } else if (size >= std::pow(2, 20)) { ss << (size / std::pow(2, 20)) << " MB"; } else if (size >= std::pow(2, 10)) { ss << (size / std::pow(2, 10)) << " KB"; } else { ss << size << " Byte"; } return ss.str(); } std::size_t entry_size(const fs::path& path) { if (!fs::is_directory(path)) { // file_size只能对普通文件和符号链接有效, 否则, 会抛出异常 // file_size对符号链接有效, 如果链接失效, 函数还是会抛出异常 return fs::file_size(path); } else { return std::accumulate( fs::directory_iterator{path}, {}, std::size_t{}, [](std::size_t accum, const fs::directory_entry& entry) { return accum + entry_size(entry); }); } } int main(int argc, char* argv[]) { fs::path dir{argc > 1 ? argv[1] : "."}; if (!fs::exists(dir)) { std::cout << "Path " << dir << " does not exist.\n"; std::exit(EXIT_FAILURE); } for (const auto& entry : fs::directory_iterator{dir}) { fmt::print("{:<30}", entry.path().filename().c_str()); fmt::print("{}\n", size_string(entry_size(entry))); } }
23.783333
65
0.573931
KaiserLancelot
d75e053dcc105ad880b6c3c61e490822b6ee8c5c
1,827
hpp
C++
atcoder/persistentsegtree.hpp
habara-k/ac-library
c48e576430c335d7037fa88e9fa5f6a61858e68a
[ "Unlicense" ]
null
null
null
atcoder/persistentsegtree.hpp
habara-k/ac-library
c48e576430c335d7037fa88e9fa5f6a61858e68a
[ "Unlicense" ]
null
null
null
atcoder/persistentsegtree.hpp
habara-k/ac-library
c48e576430c335d7037fa88e9fa5f6a61858e68a
[ "Unlicense" ]
null
null
null
#ifndef ATCODER_PERSISTENTSEGTREE_HPP #define ATCODER_PERSISTENTSEGTREE 1 #include <cassert> #include <vector> namespace atcoder { template<class S, S (*op)(S, S), S (*e)()> struct PersistentSegmentTree { struct Node; using ptr = Node*; struct Node { ptr l=nullptr, r=nullptr; S x; explicit Node(S x_) : x(x_) {} Node(ptr l_, ptr r_) : l(l_), r(r_), x(op(l->x, r->x)) {} }; int n = 0; ptr build(int n_) { return build(std::vector<S>(n_, e())); } ptr build(const std::vector<S>& v) { n = (int)v.size(); return build(0, n, v); } ptr set(ptr root, int k, const S& x) { assert(0 <= k and k < n); return set(root, k, x, 0, n); } S prod(ptr root, int a, int b) { assert(0 <= a and a <= b and b <= n); return prod(root, a, b, 0, n); } S get(ptr root, int k) { assert(0 <= k and k < n); return prod(root, k, k + 1); } private: ptr build(int l, int r, const std::vector<S>& v) const { assert(l < r); if (l+1 == r) return new Node(v[l]); return new Node(build(l, (l+r)>>1, v), build((l+r)>>1, r, v)); } ptr set(ptr t, int k, const S& x, int l, int r) const { assert(l < r); if (k == l and k+1 == r) return new Node(x); if (r <= k or k < l) return t; return new Node(set(t->l, k, x, l, (l+r)>>1), set(t->r, k, x, (l+r)>>1, r)); } S prod(ptr t, int a, int b, int l, int r) const { assert(l < r); if (r <= a or b <= l) return e(); if (a <= l and r <= b) return t->x; return op(prod(t->l, a, b, l, (l+r)>>1), prod(t->r, a, b, (l+r)>>1, r)); } }; } // namespace atcoder #endif // ATCODER_PERSISTENTSEGTREE_HPP
25.732394
70
0.477833
habara-k
d76160a9912e6582aebf9408bbb84bf8af5e2876
2,105
cpp
C++
CursedHeaven/Motor2D/Lines.cpp
golden-rhino-studio/CursedHeaven
16e7bd3e82b64302564251d4856be570add0f98e
[ "MIT" ]
null
null
null
CursedHeaven/Motor2D/Lines.cpp
golden-rhino-studio/CursedHeaven
16e7bd3e82b64302564251d4856be570add0f98e
[ "MIT" ]
1
2019-03-05T18:25:36.000Z
2019-03-05T18:26:39.000Z
CursedHeaven/Motor2D/Lines.cpp
golden-rhino-studio/CursedHeaven
16e7bd3e82b64302564251d4856be570add0f98e
[ "MIT" ]
null
null
null
#include "j1Render.h" #include "Lines.h" #include "j1Scene1.h" #include "j1App.h" #include "j1Window.h" Lines::Lines(SCENE scene_to_remove, SCENE scene_to_appear, j1Color color, float time) : j1Transitions(time) { this->color = color; scene1 = scene_to_remove; scene2 = scene_to_appear; App->win->GetWindowSize(w, h); screen = { -(int)w, 0, (int)w, (int)h }; SDL_SetRenderDrawBlendMode(App->render->renderer, SDL_BLENDMODE_BLEND); initial_x_left = App->render->camera.x; initial_x_right = App->render->camera.x + (int)w; for (int i = 0; i < 11; i++) { // All lines have window width as width and height/10 as height lines[i].h = ((int)h / 10); lines[i].w = (int)w + 5; // 5 lines are placed at the left of the screen if (i % 2 == 0) lines[i].x = initial_x_left; // 5 lines are placed at the right of the screen else lines[i].x = initial_x_right; } // Each one is placed h += h/10 than the previous one for (int i = 0; i < 11; i++) { lines[i].y = height; height += h / 10; } } Lines::~Lines() {} void Lines::Start() { for (int i = 0; i < 11; i++) { if (i % 2 == 0) lines[i].x = (int)Interpolation(-(int)w, -2, percentage); else lines[i].x = (int)Interpolation((int)w, -2, percentage); } SDL_SetRenderDrawColor(App->render->renderer, color.r, color.g, color.b, 255); for (int i = 0; i < 11; i++) SDL_RenderFillRect(App->render->renderer, &lines[i]); j1Transitions::Start(); } void Lines::Change() { screen.x = screen.y = 0; SDL_SetRenderDrawColor(App->render->renderer, color.r, color.g, color.b, 255); SDL_RenderFillRect(App->render->renderer, &screen); App->transitions->SwitchScenes(scene1, scene2); j1Transitions::Change(); } void Lines::Exit() { j1Transitions::Exit(); for (int i = 0; i < 11; i++) { if (i % 2 == 0) lines[i].x = (int)Interpolation(-2, (int)w, percentage); else lines[i].x = (int)Interpolation(-2, -(int)w, percentage); } SDL_SetRenderDrawColor(App->render->renderer, color.r, color.g, color.b, 255); for (int i = 0; i < 11; i++) SDL_RenderFillRect(App->render->renderer, &lines[i]); }
23.651685
109
0.638955
golden-rhino-studio
d762d5fb0bd16a6bef55238b663a37f957338bbe
5,976
cpp
C++
Applications/MainApplication/Gui/MaterialEditor.cpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
Applications/MainApplication/Gui/MaterialEditor.cpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
Applications/MainApplication/Gui/MaterialEditor.cpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
#include <Gui/MaterialEditor.hpp> #include <Engine/RadiumEngine.hpp> #include <Engine/Renderer/RenderObject/RenderObject.hpp> #include <Engine/Renderer/RenderObject/RenderObjectManager.hpp> #include <Engine/Renderer/Material/BlinnPhongMaterial.hpp> #include <Engine/Renderer/RenderTechnique/RenderTechnique.hpp> #include <QCloseEvent> namespace Ra { namespace Gui { MaterialEditor::MaterialEditor( QWidget* parent ) : QWidget( parent ) , m_visible( false ) , m_roIdx( -1 ) , m_usable( false ) { setupUi( this ); typedef void ( QSpinBox::*sigPtr )( int ); connect( kdR, static_cast<sigPtr>( &QSpinBox::valueChanged ), this, &MaterialEditor::onKdColorChanged ); connect( kdG, static_cast<sigPtr>( &QSpinBox::valueChanged ), this, &MaterialEditor::onKdColorChanged ); connect( kdB, static_cast<sigPtr>( &QSpinBox::valueChanged ), this, &MaterialEditor::onKdColorChanged ); connect( ksR, static_cast<sigPtr>( &QSpinBox::valueChanged ), this, &MaterialEditor::onKsColorChanged ); connect( ksG, static_cast<sigPtr>( &QSpinBox::valueChanged ), this, &MaterialEditor::onKsColorChanged ); connect( ksB, static_cast<sigPtr>( &QSpinBox::valueChanged ), this, &MaterialEditor::onKsColorChanged ); connect( exp, static_cast<void ( QDoubleSpinBox::* )( double )>( &QDoubleSpinBox::valueChanged ), this, &MaterialEditor::onExpChanged ); connect( kdColorWidget, &ColorWidget::newColorPicked, this, &MaterialEditor::newKdColor ); connect( ksColorWidget, &ColorWidget::newColorPicked, this, &MaterialEditor::newKsColor ); } void MaterialEditor::onExpChanged( double v ) { if ( m_renderObject && m_usable ) { m_material->m_ns = v; } } void MaterialEditor::onKdColorChanged( int ) { kdColorWidget->colorChanged( kdR->value(), kdG->value(), kdB->value() ); if ( m_renderObject && m_usable ) { Core::Color c( kdR->value() / 255.f, kdG->value() / 255.f, kdB->value() / 255.f, 1.0 ); m_material->m_kd = c; } } void MaterialEditor::onKsColorChanged( int ) { ksColorWidget->colorChanged( ksR->value(), ksG->value(), ksB->value() ); if ( m_renderObject && m_usable ) { Core::Color c( ksR->value() / 255.f, ksG->value() / 255.f, ksB->value() / 255.f, 1.0 ); m_material->m_ks = c; } } void MaterialEditor::newKdColor( const QColor& color ) { const QSignalBlocker br( kdR ); const QSignalBlocker bg( kdG ); const QSignalBlocker bb( kdB ); kdR->setValue( color.red() ); kdG->setValue( color.green() ); kdB->setValue( color.blue() ); if ( m_renderObject && m_usable) { Core::Color c( color.redF(), color.greenF(), color.blueF(), 1.0 ); m_material->m_kd = c; } } void MaterialEditor::newKsColor( const QColor& color ) { const QSignalBlocker br( ksR ); const QSignalBlocker bg( ksG ); const QSignalBlocker bb( ksB ); ksR->setValue( color.red() ); ksG->setValue( color.green() ); ksB->setValue( color.blue() ); if ( m_renderObject && m_usable ) { Core::Color c( color.redF(), color.greenF(), color.blueF(), 1.0 ); m_material->m_ks = c; } } void MaterialEditor::showEvent( QShowEvent* e ) { QWidget::showEvent( e ); m_visible = true; m_engine = Engine::RadiumEngine::getInstance(); m_roMgr = m_engine->getRenderObjectManager(); } void MaterialEditor::closeEvent( QCloseEvent* e ) { m_visible = false; hide(); } void MaterialEditor::changeRenderObject( Core::Index roIdx ) { if ( !m_visible ) { return; } m_roIdx = roIdx; m_renderObject = m_roMgr->getRenderObject( m_roIdx ); /// TODO : replace this ugly dynamic_cast by something more static ... m_material = dynamic_cast<Ra::Engine::BlinnPhongMaterial *>( m_renderObject->getRenderTechnique()->getMaterial().get() ); if ( m_material == nullptr ) { m_usable = false; return; } if ( m_renderObject != nullptr ) { m_renderObjectName->setText( m_renderObject->getName().c_str() ); updateMaterialViz( ); } } void MaterialEditor::updateMaterialViz( ) { const Core::Color kd = m_material->m_kd; const Core::Color ks = m_material->m_ks; int kdr = kd.x() * 255, kdg = kd.y() * 255, kdb = kd.y() * 255; int ksr = ks.x() * 255, ksg = ks.y() * 255, ksb = ks.z() * 255; const QSignalBlocker bdr( kdR ); const QSignalBlocker bdg( kdG ); const QSignalBlocker bdb( kdB ); const QSignalBlocker bsr( ksR ); const QSignalBlocker bsg( ksG ); const QSignalBlocker bsb( ksB ); const QSignalBlocker bns( exp ); kdR->setValue( kdr ); kdG->setValue( kdg ); kdB->setValue( kdb ); ksR->setValue( ksr ); ksG->setValue( ksg ); ksB->setValue( ksb ); exp->setValue( m_material->m_ns ); kdColorWidget->colorChanged( kdr, kdg, kdb ); ksColorWidget->colorChanged( ksr, ksg, ksb ); } } }
33.762712
148
0.536145
nmellado
d7654e4f53245ac61b9d54508798063aa849a222
5,777
cpp
C++
Controller.cpp
capiaghi/GoTender
539dc075b5e6ec5ee97a4e1400f2c0d17c0dd65d
[ "Apache-2.0" ]
null
null
null
Controller.cpp
capiaghi/GoTender
539dc075b5e6ec5ee97a4e1400f2c0d17c0dd65d
[ "Apache-2.0" ]
33
2017-05-02T05:53:36.000Z
2018-04-23T16:27:53.000Z
Controller.cpp
capiaghi/GoTender
539dc075b5e6ec5ee97a4e1400f2c0d17c0dd65d
[ "Apache-2.0" ]
null
null
null
// **************************************************************************** /// \file Controller.cpp /// /// \brief Main Controller for the heater /// /// \details Controller for the run state /// /// \author Christoph Capiaghi /// /// \version 0.1 /// /// \date 20170509 /// /// \copyright 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 /// /// \pre /// /// \bug /// /// \warning /// /// \todo /// // **************************************************************************** // Includes ******************************************************************* #include "Controller.h" // Private constants ********************************************************** static double temperatureOvenSetPoint = -1; static double temperatureMeatSetPoint = -1; static bool allOff = false; // Emergency Off static bool smokerStateOn = false; // Smoker state: off static bool heaterStateOn = false; // Heater state: Off static bool armSmokerState = false; // Smoker is not armed // ---------------------------------------------------------------------------- /// \brief Get temperature set point of the oven /// \detail /// \warning /// \return double temperature set point in celsius /// \todo /// double getTemperatureOvenSetPoint() { return temperatureOvenSetPoint; } // ---------------------------------------------------------------------------- /// \brief Get temperature set point of the meat /// \detail /// \warning /// \return double temperature in celsius /// \todo /// double getTemperatureMeatSetPoint() { return temperatureMeatSetPoint; } // ---------------------------------------------------------------------------- /// \brief Set temperature set point of the oven /// \detail /// \warning /// \return /// \todo /// void setTemperatureOvenSetPoint(double val) { temperatureOvenSetPoint = val; } // ---------------------------------------------------------------------------- /// \brief Set temperature set point of the meat /// \detail /// \warning /// \return /// \todo /// void setTemperatureMeatSetPoint(double val) { temperatureMeatSetPoint = val; } // ---------------------------------------------------------------------------- /// \brief Arms smoker /// \detail Arms smoker, smoker is off /// \warning After this command, the smoker armed (not on) /// \return /// \todo /// void armSmoker(bool state) { armSmokerState = state; } // ---------------------------------------------------------------------------- /// \brief Arms smoker /// \detail Arms smoker, smoker is off /// \warning After this command, the smoker armed (not on) /// \return /// \todo /// void disarmSmoker(bool start) { armSmokerState = false; } // ---------------------------------------------------------------------------- /// \brief Returns Arms smoker state /// \detail Armed: True, not armed: false /// \warning /// \return Smoker state, if armed or not /// \todo /// bool getArmSmokerState() { return armSmokerState; } // ---------------------------------------------------------------------------- /// \brief Enable smoker /// \detail Enables smoker, if system is okay /// \warning After this command, the smoker is on! /// \return /// \todo /// void startSmoker(bool start) { if ( !allOff ) { if ( start ) { if( armSmokerState ) { //Serial.println(F("SWITCH SMOKER ON")); digitalWrite(RELAIS_SMOKER, HIGH); smokerStateOn = true; } } else { //Serial.println(F("SWITCH SMOKER OFF")); digitalWrite(RELAIS_SMOKER, LOW); smokerStateOn = false; } } else { //Serial.println(F("SWITCH SMOKER OFF")); digitalWrite(RELAIS_SMOKER, LOW); smokerStateOn = false; } } // ---------------------------------------------------------------------------- /// \brief Returns smoker state /// \detail /// \warning /// \return bool: true on, false off /// \todo /// bool getSmokerState( void ) { return smokerStateOn; } // ---------------------------------------------------------------------------- /// \brief Enable heater /// \detail /// \warning After this command, the heater is on! /// \return /// \todo /// void startHeater(bool start) { if ( !allOff ) { if( start == TRUE ) { Serial.println(F("SWITCH HEATER ON")); digitalWrite(RELAIS_HEATER, HIGH); heaterStateOn = true; } else { Serial.println(F("SWITCH HEATER OFF")); digitalWrite(RELAIS_HEATER, LOW); heaterStateOn = false; } } else { Serial.println(F("SWITCH HEATER OFF")); digitalWrite(RELAIS_HEATER, LOW); heaterStateOn = false; } } // ---------------------------------------------------------------------------- /// \brief Returns Heater state /// \detail Heater on: true, heater off: false /// \warning /// \return bool heater state /// \todo /// bool getHeaterState() { return heaterStateOn; } // ---------------------------------------------------------------------------- /// \brief Emergency off /// \detail /// \warning Disables heater and smoker /// \return /// \todo Testing /// void emergencyOff( void ) { Serial.println(F("EMERGENCY OFF")); allOff = true; digitalWrite(RELAIS_HEATER, LOW); digitalWrite(RELAIS_SMOKER, LOW); }
23.579592
79
0.464601
capiaghi
d7682d25c6ec6edaa58463c496012d51458582d2
4,337
cpp
C++
oxui/objects/dropdown.cpp
amizu03/oxui
2ffcd7259eff8b783a70c56ca5f348e784fb5a87
[ "MIT" ]
null
null
null
oxui/objects/dropdown.cpp
amizu03/oxui
2ffcd7259eff8b783a70c56ca5f348e784fb5a87
[ "MIT" ]
null
null
null
oxui/objects/dropdown.cpp
amizu03/oxui
2ffcd7259eff8b783a70c56ca5f348e784fb5a87
[ "MIT" ]
null
null
null
#include "dropdown.hpp" #include "../panels/panel.hpp" #include "shapes.hpp" #include "../themes/purple.hpp" void oxui::dropdown::think( ) { auto& parent_window = find_parent< window >( object_window ); auto& cursor_pos = parent_window.cursor_pos; animate( rect( cursor_pos.x, cursor_pos.y, area.w, area.h ) ); if ( shapes::clicking( rect( cursor_pos.x, cursor_pos.y, area.w, area.h ), false, opened ) ) { opened = !opened; g_input = !opened; } /* handle */ if ( opened ) { /* get list end position */ auto end_pos_y = cursor_pos.y + theme.spacing + theme.list_spacing; /* background of the list */ rect list_pos( cursor_pos.x, end_pos_y, area.w, area.h ); hovered_index = 0; auto index = 0; for ( const auto& it : items ) { /* check if we are clicking the thingy */ if ( shapes::clicking( list_pos, false, true ) ) { value = index; /* remove if you want to close it manually instead of automatically (snek) */ { shapes::finished_input_frame = true; shapes::click_start = pos ( 0, 0 ); g_input = true; opened = false; } } else if ( shapes::hovering( list_pos, false, true ) ) { hovered_index = index; } list_pos.y += theme.spacing; index++; } } } void oxui::dropdown::draw( ) { /* change if u want a different arrow size! */ const auto arrow_size = 4; think( ); auto& parent_panel = find_parent< panel >( object_panel ); auto& parent_window = find_parent< window >( object_window ); auto& font = parent_panel.fonts [ OSTR( "object" ) ]; auto& cursor_pos = parent_window.cursor_pos; /* button box */ auto box_area = rect( cursor_pos.x, cursor_pos.y, area.w, area.h ); shapes::box( box_area, fade_timer, true, true, true, true, true, false ); auto hovering_box = shapes::hovering( box_area, false, true ); rect text_size; if ( hovering_box ) binds::text_bounds( font, items [ value ], text_size ); else binds::text_bounds( font, label, text_size ); auto area_center_x = cursor_pos.x + area.w / 2; auto area_center_y = cursor_pos.y + theme.spacing / 2; /* centered text */ if ( hovered_index ) { rect text_size; binds::text_bounds( font, items [ hovered_index ], text_size ); binds::text( pos( area_center_x - text_size.w / 2 - 1, area_center_y - text_size.h / 2 - 1 ), font, items [ hovered_index ], theme.text, false ); } else { binds::text( pos( area_center_x - text_size.w / 2 - 1, area_center_y - text_size.h / 2 - 1 ), font, hovering_box ? items [ value ] : label, theme.text, false ); } /* dropdown arrow! */ { auto arrow_max_alpha = fade_timer > theme.animation_speed ? 255 : int( fade_timer * ( 1.0 / theme.animation_speed ) * 255 ); auto arrow_clr = color( theme.main.r, theme.main.g, theme.main.b, opened ? 255 : arrow_max_alpha ); auto midpoint_x = cursor_pos.x + area.w - theme.spacing / 2 - arrow_size / 2; if ( !opened ) { binds::line( pos( midpoint_x - arrow_size / 2, area_center_y - arrow_size / 2 ), pos( midpoint_x, area_center_y + arrow_size / 2 ), arrow_clr ); binds::line( pos( midpoint_x + arrow_size / 2, area_center_y - arrow_size / 2 ), pos( midpoint_x, area_center_y + arrow_size / 2 ), arrow_clr ); } else { binds::line( pos( midpoint_x - arrow_size / 2, area_center_y + arrow_size / 2 ), pos( midpoint_x, area_center_y - arrow_size / 2 ), arrow_clr ); binds::line( pos( midpoint_x + arrow_size / 2, area_center_y + arrow_size / 2 ), pos( midpoint_x, area_center_y - arrow_size / 2 ), arrow_clr ); } } /* draw items */ if ( opened ) { g_input = false; parent_window.draw_overlay( [ = ] ( ) { /* get list end position */ auto end_pos_y = cursor_pos.y + theme.spacing + theme.list_spacing; /* background of the list */ shapes::box( rect( cursor_pos.x, end_pos_y, area.w, area.h * items.size( ) ), fade_timer, false, true, true, true, true, true ); /* render the items name */ auto index = 0; for ( const auto& it : items ) { /* get the text size */ rect item_text_size; binds::text_bounds( font, it, item_text_size ); /* render the name */ binds::text( pos { area_center_x - item_text_size.w / 2 - 1, end_pos_y + area.h * ( index + 1 ) - area.h / 2 - item_text_size.h / 2 }, font, it, hovered_index == index ? theme.main : theme.text, hovered_index == index ); index++; } } ); } }
33.361538
224
0.649988
amizu03
d769f1c865a4c0de350af72e8ad7693888a6a177
65,136
cpp
C++
source/GTest/Game/GMain.cpp
paradoxnj/Genesis3D
272fc6aa2580de4ee223274ea04a101199c535a1
[ "Condor-1.1", "Unlicense" ]
3
2020-04-29T03:17:50.000Z
2021-05-26T19:53:46.000Z
source/GTest/Game/GMain.cpp
paradoxnj/Genesis3D
272fc6aa2580de4ee223274ea04a101199c535a1
[ "Condor-1.1", "Unlicense" ]
1
2020-04-29T03:12:47.000Z
2020-04-29T03:12:47.000Z
source/GTest/Game/GMain.cpp
paradoxnj/Genesis3D
272fc6aa2580de4ee223274ea04a101199c535a1
[ "Condor-1.1", "Unlicense" ]
null
null
null
/****************************************************************************************/ /* GMain.c */ /* */ /* Author: John Pollard */ /* Description: */ /* */ /* Copyright (c) 1999 WildTangent, Inc.; All rights reserved. */ /* */ /* See the accompanying file LICENSE.TXT for terms on the use of this library. */ /* This library is distributed in the hope that it will be useful but WITHOUT */ /* ANY WARRANTY OF ANY KIND and without any implied warranty of MERCHANTABILITY */ /* or FITNESS FOR ANY PURPOSE. Refer to LICENSE.TXT for more details. */ /* */ /****************************************************************************************/ #include <Windows.h> #include <Assert.h> #include <Math.h> #include "GMain.h" #include "Quatern.h" #define INCHES_PER_METER (39.37007874016f) void GenVS_Error(const char *Msg, ...); //oh, dear. //#define FLY_MODE // FIXME: Take out Genesis.h dependency. Replace with server API code that sits on top // of Genesis calls... geBoolean Client_Control(GenVSI *VSI, void *PlayerData, float Time); static geBoolean Door_Control(GenVSI *VSI, void *PlayerData, float Time); static geBoolean Plat_Control(GenVSI *VSI, void *PlayerData, float Time); static geBoolean Door_Trigger(GenVSI *VSI, void *PlayerData, GPlayer *TargetData, void* data); void SetupPlayerXForm(GenVSI *VSI, void *PlayerData, float Time); geBoolean Bot_Main(GenVSI *VSI, const char *LevelName); static void Player_Spawn(GenVSI *VSI, void *PlayerData, void *ClassData,char *EntityName); static void Door_Spawn(GenVSI *VSI, void *PlayerData, void *ClassData,char *EntityName); static void Plat_Spawn(GenVSI *VSI, void *PlayerData, void *ClassData,char *EntityName); static geBoolean Plat_Trigger(GenVSI *VSI, void *PlayerData, GPlayer *TargetData, void* data); static void PhysicsObject_Spawn(GenVSI* VSI, void* PlayerData, void* Class,char *EntityName); static void PhysicsObject_Destroy(GenVSI *VSI, void *PlayerData, void *ClassData); static geBoolean PhysicsObject_Trigger(GenVSI* VSI, void* PlayerData, GPlayer* TargetData, void* data); static geBoolean PhysicsObject_Control(GenVSI* VSI, void* PlayerData, float Time); static void PhysicsJoint_Spawn(GenVSI* VSI, void* PlayerData, void* Class,char *EntityName); static void PhysicsJoint_Destroy(GenVSI *VSI, void *PlayerData, void *ClassData); static geBoolean PhysicsJoint_Trigger(GenVSI* VSI, void* PlayerData, GPlayer* TargetData, void* data); static geBoolean PhysicsJoint_Control(GenVSI* VSI, void* PlayerData, float Time); static void PhysicalSystem_Spawn(GenVSI* VSI, void* PlayerData, void* Class,char *EntityName); static void PhysicalSystem_Destroy(GenVSI *VSI, void *PlayerData, void *ClassData); static geBoolean PhysicalSystem_Trigger(GenVSI* VSI, void* PlayerData, GPlayer* TargetData, void* data); static geBoolean PhysicalSystem_Control(GenVSI* VSI, void* PlayerData, float Time); static void ForceField_Spawn(GenVSI* VSI, void* PlayerData, void* Class,char *EntityName); static geBoolean ForceField_Trigger(GenVSI* VSI, void* PlayerData, GPlayer* TargetData, void* data); static geBoolean ForceField_Control(GenVSI* VSI, void* PlayerData, float Time); static geBoolean IsKeyDown(int KeyCode); GPlayer *CurrentPlayerStart; //===================================================================================== // Server_Main // Game code called, when server level starts up... //===================================================================================== geBoolean Server_Main(GenVSI *VSI, const char *LevelName) { Bot_Main(VSI, LevelName); CurrentPlayerStart = NULL; // SetClassSpawn functions get called once, and are used for each SetWorld... // Set the calss spawns GenVSI_SetClassSpawn(VSI, "DeathMatchStart", Player_Spawn, NULL); // Doors/Plats/PhysicalObjects/PhysicsJoints/PhysicalSystems/etc. GenVSI_SetClassSpawn(VSI, "Door", Door_Spawn, NULL); GenVSI_SetClassSpawn(VSI, "MovingPlat", Plat_Spawn, NULL); GenVSI_SetClassSpawn(VSI, "PhysicsObject", PhysicsObject_Spawn, PhysicsObject_Destroy); GenVSI_SetClassSpawn(VSI, "PhysicsJoint", PhysicsJoint_Spawn, PhysicsJoint_Destroy); GenVSI_SetClassSpawn(VSI, "PhysicalSystem", PhysicalSystem_Spawn, PhysicalSystem_Destroy); GenVSI_SetClassSpawn(VSI, "ForceField", ForceField_Spawn, NULL); // Change level trigger GenVSI_SetClassSpawn(VSI, "ChangeLevel", ChangeLevel_Spawn, NULL); // Items GenVSI_SetClassSpawn(VSI, "ItemHealth", Item_HealthSpawn, NULL); GenVSI_SetClassSpawn(VSI, "ItemArmor", Item_ArmorSpawn, NULL); GenVSI_SetClassSpawn(VSI, "ItemRocket", Item_RocketSpawn, NULL); GenVSI_SetClassSpawn(VSI, "ItemRocketAmmo", Item_RocketAmmoSpawn, NULL); GenVSI_SetClassSpawn(VSI, "ItemGrenade", Item_GrenadeSpawn, NULL); GenVSI_SetClassSpawn(VSI, "ItemGrenadeAmmo", Item_GrenadeAmmoSpawn, NULL); GenVSI_SetClassSpawn(VSI, "ItemShredder", Item_ShredderSpawn, NULL); GenVSI_SetClassSpawn(VSI, "ItemShredderAmmo", Item_ShredderAmmoSpawn, NULL); GenVSI_SetClassSpawn(VSI, "AttackerTurret", Attacker_TurretSpawn, Attacker_TurretDestroy); // Set the level with these spawns... // FIXME: Rename to: Server_ExecuteClassSpawns(Server, LevelName);??????? GenVSI_SetWorld(VSI, SetupWorldCB, ShutdownWorldCB, LevelName); // Use the level name supplied by the host // Proc indexes GenVSI_ProcIndex(VSI, 0, Client_Control); GenVSI_ProcIndex(VSI, 1, Door_Control); GenVSI_ProcIndex(VSI, 2, Door_Trigger); GenVSI_ProcIndex(VSI, 3, Plat_Control); GenVSI_ProcIndex(VSI, 4, Plat_Trigger); GenVSI_ProcIndex(VSI, 5, Blaster_Control); GenVSI_ProcIndex(VSI, 6, Rocket_Control); GenVSI_ProcIndex(VSI, 7, Grenade_Control); GenVSI_ProcIndex(VSI, 8, Shredder_Control); GenVSI_ProcIndex(VSI, 9, Item_ControlHealth); return GE_TRUE; } //===================================================================================== // Client_Main //===================================================================================== geBoolean Client_Main(GenVSI *VSI) { GenVSI_ProcIndex(VSI, 0, Client_Control); GenVSI_ProcIndex(VSI, 1, Door_Control); GenVSI_ProcIndex(VSI, 2, Door_Trigger); GenVSI_ProcIndex(VSI, 3, Plat_Control); GenVSI_ProcIndex(VSI, 4, Plat_Trigger); GenVSI_ProcIndex(VSI, 5, Blaster_Control); GenVSI_ProcIndex(VSI, 6, Rocket_Control); GenVSI_ProcIndex(VSI, 7, Grenade_Control); GenVSI_ProcIndex(VSI, 8, Shredder_Control); GenVSI_ProcIndex(VSI, 9, Item_ControlHealth); return GE_TRUE; } // Returns GE_FALSE if colliding with self, or owner to self... geBoolean SelfCollisionCB(geWorld_Model *Model, geActor *Actor, void *Context) { if (Actor) { CData *Data; Data = (CData*)Context; assert(Data); assert(Data->Player); if (GenVSI_ActorToPlayer(Data->VSI, Actor) == Data->Player) return GE_FALSE; // NOTE - Owner CAN be NULL... if (GenVSI_ActorToPlayer(Data->VSI, Actor) == Data->Player->Owner) return GE_FALSE; } return GE_TRUE; } // Returns GE_FALSE if colliding with self... geBoolean SelfCollisionCB2(geWorld_Model *Model, geActor *Actor, void *Context) { if (Actor) { CData *Data; Data = (CData*)Context; assert(Data); assert(Data->Player); if (GenVSI_ActorToPlayer(Data->VSI, Actor) == Data->Player) return GE_FALSE; } return GE_TRUE; } int32 GMode; extern int32 MenuBotCount; //===================================================================================== // GetDMSpawn //===================================================================================== void *GetDMSpawn(GenVSI *VSI) { //if (GenVSI_GetMode(VSI) == 0) if (GMode == 0 && !MenuBotCount) { CurrentPlayerStart = (GPlayer*)GenVSI_GetNextPlayer(VSI, CurrentPlayerStart, "PlayerStart"); if (!CurrentPlayerStart) CurrentPlayerStart = (GPlayer*)GenVSI_GetNextPlayer(VSI, NULL, "PlayerStart"); //if (!CurrentPlayerStart) // GenVS_Error( "Game_SpawnClient: No PlayerStart!\n"); if (!CurrentPlayerStart) CurrentPlayerStart = (GPlayer*)GenVSI_GetNextPlayer(VSI, NULL, "DeathMatchStart"); if (!CurrentPlayerStart) GenVS_Error( "Game_SpawnClient: No PlayerStart or DeathMatchStart!\n"); } else { CurrentPlayerStart = (GPlayer*)GenVSI_GetNextPlayer(VSI, CurrentPlayerStart, "DeathMatchStart"); if (!CurrentPlayerStart) CurrentPlayerStart = (GPlayer*)GenVSI_GetNextPlayer(VSI, NULL, "DeathMatchStart"); if (!CurrentPlayerStart) GenVS_Error( "Game_SpawnClient: No DeathMatchStart!\n"); } return CurrentPlayerStart; } //===================================================================================== // Game_SpawnClient //===================================================================================== geBoolean Game_SpawnClient(GenVSI *VSI, geWorld *World, void *PlayerData, void *ClassData) { int32 i; GPlayer *Player; //Player = (GPlayer*)GenVSI_GetPlayerData(VSI, PlayerHandle); Player = (GPlayer*)PlayerData; geXForm3d_SetIdentity(&Player->XForm); // Get a DM start #ifndef FLY_MODE { GPlayer *DMStart; DMStart = static_cast<GPlayer*>(GetDMSpawn(VSI)); Player->XForm = DMStart->XForm; } //GenVSI_SetPlayerBox(VSI, PlayerHandle, &Mins, &Maxs); Player->Mins.X = -30.0f; Player->Mins.Y = -10.0f; Player->Mins.Z = -30.0f; Player->Maxs.X = 30.0f; Player->Maxs.Y = 160.0f; Player->Maxs.Z = 30.0f; #else Player->Mins.X =-5.0f; Player->Mins.Y =-5.0f; Player->Mins.Z =-5.0f; Player->Maxs.X = 5.0f; Player->Maxs.Y = 5.0f; Player->Maxs.Z = 5.0f; #endif Player->Time = 0.0f; Player->JustSpawned = GE_TRUE; //GenVSI_SetClientGunOffset(VSI, ClientHandle, 0.0f, 130.0f, 0.0f); Player->GunOffset.X = 0.0f; Player->GunOffset.Y = 130.0f; Player->GunOffset.Z = 0.0f; Player->Scale = 2.7f; // Set the view info Player->ViewFlags = VIEW_TYPE_ACTOR | VIEW_TYPE_YAW_ONLY | VIEW_TYPE_COLLIDEMODEL; Player->ViewIndex = ACTOR_INDEX_PLAYER; Player->MotionIndex = ACTOR_MOTION_PLAYER_RUN; Player->DammageFlags = DAMMAGE_TYPE_NORMAL | DAMMAGE_TYPE_RADIUS; // Hook player up to client physics controller Player->ControlIndex = 0; Player->Control = Client_Control; // Set the view player on this machine to the clients player GenVSI_SetViewPlayer(VSI, Player->ClientHandle, Player); // Players keep track of scoring, health, etc for now. // Server_SetClientScore/Health must be called to update a particular client // that is associated with a player... Player->Health = 100; Player->Score = 0; // FIXME: Soon, Scores, Health, etc won't be so arbitrary. Maybe somthing like // Quake2's Layouts will be used instead, making it easier to make games that don't // use this sort of scoring system... GenVSI_SetClientScore(VSI, Player->ClientHandle, Player->Score); GenVSI_SetClientHealth(VSI, Player->ClientHandle, Player->Health); for (i=0; i< MAX_PLAYER_ITEMS; i++) { Player->Inventory[i] = 0; Player->InventoryHas[i] = GE_FALSE; } Player->CurrentWeapon = 0; GenVSI_SetClientInventory(VSI, Player->ClientHandle, ITEM_GRENADES, 0, GE_FALSE); GenVSI_SetClientInventory(VSI, Player->ClientHandle, ITEM_ROCKETS, 0, GE_FALSE); GenVSI_SetClientInventory(VSI, Player->ClientHandle, ITEM_SHREDDER, 0, GE_FALSE); Player->NextWeaponTime = 0.0f; return GE_TRUE; } //===================================================================================== // Game_DestroyClient //===================================================================================== void Game_DestroyClient(GenVSI *VSI, void *PlayerData, void *ClassData) { //GenVS_Error( "Client destroyed..."); // For debugging... } //===================================================================================== // Local static functions... //===================================================================================== //extern geEngine *Engine; //===================================================================================== // PlayerLiquid // // Checks to see if the player is in a liquid state, and returns the power of the state // Stronger numbers mean thicker liquid, etc... //===================================================================================== int32 PlayerLiquid(GPlayer *Player) { if (Player->State == PSTATE_InLava) return 10; else if (Player->State == PSTATE_InWater) return 5; return 0; } //===================================================================================== // CheckPlayer //===================================================================================== static geBoolean CheckPlayer(GenVSI *VSI, void *PlayerData) { geVec3d Mins, Maxs, Pos; GE_Contents Contents; GPlayer *Player; uint32 ColFlags; Player = (GPlayer*)PlayerData; Mins = Player->Mins; Maxs = Player->Maxs; Pos = Player->XForm.Translation; ColFlags = GE_COLLIDE_MODELS; if (geWorld_GetContents(GenVSI_GetWorld(VSI), &Pos, &Mins, &Maxs, ColFlags, 0, NULL, NULL, &Contents)) { if (Contents.Contents & GE_CONTENTS_SOLID) { //geEngine_Printf(Engine, 10, 85, "Stuck"); if (Player->JustSpawned) { GenVS_Error("Player_CheckPlayer: the player's starting position is bad - some of the player's bounding box is in solid space."); } Player->XForm.Translation = Player->LastGoodPos; Player->JustSpawned = 0; return GE_TRUE; } } Player->JustSpawned = 0; return GE_FALSE; } #define STEP_HEIGHT 42.0f //===================================================================================== // MovePlayerUpStep //===================================================================================== geBoolean MovePlayerUpStep(GenVSI *VSI, void *PlayerData, GE_Collision *Collision) { geVec3d Mins, Maxs, Pos1, Pos2; GE_Collision Collision2; GPlayer *Player; geWorld *World; Player = (GPlayer*)PlayerData; World = GenVSI_GetWorld(VSI); assert(World); Mins = Player->Mins; Maxs = Player->Maxs; Pos1 = Player->XForm.Translation; Pos2 = Player->XForm.Translation; Pos2.Y += STEP_HEIGHT; // Try to "pop" up on the step if (geWorld_Collision(World, &Mins, &Maxs, &Pos1, &Pos2, GE_CONTENTS_CANNOT_OCCUPY, GE_COLLIDE_MODELS, 0, NULL, NULL, &Collision2)) return GE_FALSE; // Can't move // Move forward (opposite the normal) Pos1 = Pos2; geVec3d_AddScaled(&Pos2, &Collision->Plane.Normal, -0.5f, &Pos2); if (geWorld_Collision(World, &Mins, &Maxs, &Pos1, &Pos2, GE_CONTENTS_CANNOT_OCCUPY, GE_COLLIDE_MODELS, 0, NULL, NULL, &Collision2)) return GE_FALSE; // Can't move // Put him back on the ground Pos1 = Pos2; Pos2.Y -= (STEP_HEIGHT+1.0f); // NOTE that this should allways return a collision if (geWorld_Collision(World, &Mins, &Maxs, &Pos1, &Pos2, GE_CONTENTS_CANNOT_OCCUPY, GE_COLLIDE_MODELS, 0, NULL, NULL, &Collision2)) { Pos2 = Collision2.Impact; Player->State = PSTATE_Normal; } else return GE_FALSE; Player->XForm.Translation = Pos2; return GE_TRUE; } #define MAX_CLIP_PLANES 5 //===================================================================================== // CheckVelocity // Adjust players Velocity. based on what it's doing in the world //===================================================================================== geBoolean CheckVelocity(GenVSI *VSI, void *PlayerData, float BounceScale, geBoolean AllowBounce, float Time) { int32 NumHits, NumPlanes; GE_Collision Collision; int32 HitCount, i, j; geVec3d Mins, Maxs; geVec3d Planes[MAX_CLIP_PLANES]; geVec3d Pos, NewPos, OriginalVelocity, PrimalVelocity; geVec3d NewVelocity, Dir; float TimeLeft, Dist; GE_Contents Contents; GPlayer *Player; geWorld *World; uint32 ColFlags; #if 0 geEntity_EntitySet * Set; geEntity * Entity; geVec3d boundingBoxCenter, boundingBoxScale, forceFieldCenterToBBCenter; #endif // end VAR section //////////////////////////////////////////////////////////////////////////////////////////////////// // BEGIN Player = (GPlayer*)PlayerData; World = GenVSI_GetWorld(VSI); assert(World); Mins = Player->Mins; Maxs = Player->Maxs; geVec3d_Copy(&Player->Velocity, &OriginalVelocity); geVec3d_Copy(&Player->Velocity, &PrimalVelocity); TimeLeft = Time; NumHits = 4; NumPlanes = 0; if (Player->State == PSTATE_Normal) Player->State = PSTATE_InAir; ColFlags = GE_COLLIDE_MODELS; //////////////////////////////////////////////////////////////////////////////////////////////////// // check for penetration of Player's bounding box into the radius of a ForceField entity #if 0 geVec3d_Copy(&Player->XForm.Translation, &boundingBoxCenter); boundingBoxScale.X = (float)fabs(0.5f * (Maxs.X - Mins.X)); boundingBoxScale.Y = (float)fabs(0.5f * (Maxs.Y - Mins.Y)); boundingBoxScale.Z = (float)fabs(0.5f * (Maxs.Z - Mins.Z)); #pragma message ("Use: GenVSI_GetNextPlayer here...") Set = NULL; Set = geWorld_GetEntitySet(World, "ForceField"); if (Set != NULL) { for (Entity = geEntity_EntitySetGetNextEntity(Set, NULL); Entity != NULL; Entity = geEntity_EntitySetGetNextEntity(Set, Entity)) { ForceField* ff; float forceMultiplier; float distToFFCenter; float forceMagnitude; geVec3d forceDir; geVec3d forceToApply; geVec3d impulse; ff = geEntity_GetUserData(Entity); assert(ff != NULL); if (! ff->affectsPlayers) continue; geVec3d_Subtract(&boundingBoxCenter, &ff->Origin, &forceFieldCenterToBBCenter); geVec3d_Copy(&forceFieldCenterToBBCenter, &forceDir); #pragma message("does geVec3d_Normalize() return length?") geVec3d_Normalize(&forceDir); distToFFCenter = geVec3d_Length(&forceFieldCenterToBBCenter); if (distToFFCenter < 1.f) distToFFCenter = 1.f; if ((boundingBoxCenter.X + boundingBoxScale.X) < (ff->Origin.X - ff->radius)) continue; if ((boundingBoxCenter.X - boundingBoxScale.X) > (ff->Origin.X + ff->radius)) continue; if ((boundingBoxCenter.Y + boundingBoxScale.Y) < (ff->Origin.Y - ff->radius)) continue; if ((boundingBoxCenter.Y - boundingBoxScale.Y) > (ff->Origin.Y + ff->radius)) continue; if ((boundingBoxCenter.Z + boundingBoxScale.Z) < (ff->Origin.Z - ff->radius)) continue; if ((boundingBoxCenter.Z - boundingBoxScale.Z) > (ff->Origin.Z + ff->radius)) continue; //////////////////////////////////////////////////////////////////////////////////////////////////// // player is inside radius of force field, figure out how much force // to apply based on force field's falloff function switch(ff->falloffType) { case FALLOFF_NONE: forceMultiplier = 1.f; break; case FALLOFF_ONE_OVER_D: forceMultiplier = 1 / distToFFCenter; break; case FALLOFF_ONE_OVER_DSQUARED: forceMultiplier = 1 / (distToFFCenter * distToFFCenter); break; default: forceMultiplier = 1.f; } forceMagnitude = ff->strength * forceMultiplier * 1000.f; geVec3d_Scale(&forceDir, forceMagnitude, &forceToApply); geVec3d_Scale(&forceToApply, Time, &impulse); geVec3d_Add(&impulse, &Player->Velocity, &Player->Velocity); } // while } // if #endif //////////////////////////////////////////////////////////////////////////////////////////////////// for (HitCount=0 ; HitCount<NumHits ; HitCount++) { float Fd, Bd; //Server_Player *UPlayer; Pos = Player->XForm.Translation; geVec3d_AddScaled(&Pos, &Player->Velocity, TimeLeft, &NewPos); // Make sure the pos did not start out in solid if (geWorld_GetContents(World, &Pos, &Mins, &Maxs, GE_COLLIDE_MODELS, 0, NULL, NULL, &Contents)) { if (Contents.Contents & GE_CONTENTS_SOLID) { if (geWorld_GetContents(World, &NewPos, &Mins, &Maxs, GE_COLLIDE_MODELS, 0, NULL, NULL, &Contents)) { if (Contents.Contents & GE_CONTENTS_SOLID) { geVec3d_Copy(&Player->LastGoodPos, &Player->XForm.Translation); geVec3d_Clear(&Player->Velocity); return GE_TRUE; } } } } if (!geWorld_Collision(World, &Mins, &Maxs, &Pos, &NewPos, GE_CONTENTS_CANNOT_OCCUPY, GE_COLLIDE_MODELS, 0, NULL, NULL, &Collision)) return GE_TRUE; // Covered the entire distance... if (Collision.Plane.Normal.Y > 0.7f) { if (Player->State == PSTATE_InAir) Player->State = PSTATE_Normal; // Put the player on the ground if in air else if (Player->State == PSTATE_Dead) Player->State = PSTATE_DeadOnGround; // Put the player on the ground if in air if (Collision.Model) { GPlayer *Target; Target = (GPlayer*)geWorld_ModelGetUserData(Collision.Model); if (Target && Target->Trigger && Target->ViewFlags & VIEW_TYPE_STANDON) Target->Trigger(VSI, Target, Player, NULL); } } if (Collision.Model) { GPlayer *Target; #pragma message ("Use: GenVSI_ModelToPlayer...") Target = (GPlayer*)geWorld_ModelGetUserData(Collision.Model); if (Target && Target->Trigger && Target->ViewFlags & VIEW_TYPE_PHYSOB) Target->Trigger(VSI, Target, Player, (void*)&Collision); } if (Collision.Actor) // Just stop at actors for now... { geVec3d_Copy(&Player->LastGoodPos, &Player->XForm.Translation); geVec3d_Clear(&Player->Velocity); return GE_TRUE; } // FIXME: Save this ratio in the impact function... Fd = geVec3d_DotProduct(&Pos, &Collision.Plane.Normal) - Collision.Plane.Dist; Bd = geVec3d_DotProduct(&NewPos, &Collision.Plane.Normal) - Collision.Plane.Dist; Collision.Ratio = Fd / (Fd - Bd); if (Collision.Ratio > 0.00f) // Actually covered some distance { // Set the players pos to the impact point geVec3d_Copy(&Collision.Impact, &Player->XForm.Translation); // Restore Velocity geVec3d_Copy(&Player->Velocity, &OriginalVelocity); NumPlanes = 0; } if (!Collision.Plane.Normal.Y) { if (MovePlayerUpStep(VSI, Player, &Collision)) { continue; } } //TimeLeft -= TimeLeft * Collision.Ratio; // Clipped to another plane if (NumPlanes >= MAX_CLIP_PLANES) { GenVSI_ConsolePrintf(VSI, "MAX_CLIP_PLANES!!!\n"); geVec3d_Clear(&Player->Velocity); return GE_TRUE; } // Add the plane hit, to the plane list geVec3d_Copy (&Collision.Plane.Normal, &Planes[NumPlanes]); NumPlanes++; // // Modify original_velocity so it parallels all of the clip planes // for (i=0 ; i<NumPlanes ; i++) { ReflectVelocity(&OriginalVelocity, &Planes[i], &NewVelocity, BounceScale); for (j=0 ; j<NumPlanes ; j++) { if (j != i) { if (geVec3d_DotProduct(&NewVelocity, &Planes[j]) < 0.0f) break; // not ok } } if (j == NumPlanes) break; } if (i != NumPlanes) { // Go along this plane geVec3d_Copy(&NewVelocity, &Player->Velocity); } else { if (NumPlanes != 2) { //Console_Printf(Server->Host->Console, "Clip velocity, numplanes == %i\n",NumPlanes); geVec3d_Clear(&Player->Velocity); return GE_TRUE; } //Console_Printf(Server->Host->Console, "Cross product\n",NumPlanes); geVec3d_CrossProduct(&Planes[0], &Planes[1], &Dir); Dist = geVec3d_DotProduct(&Dir, &Player->Velocity); geVec3d_Scale(&Dir, Dist, &Player->Velocity); } // // Don't allow new velocity to go against original velocity unless told otherwise // if (!AllowBounce && geVec3d_DotProduct (&Player->Velocity, &PrimalVelocity) <= 0.0f) { geVec3d_Clear(&Player->Velocity); return GE_TRUE; } } return GE_TRUE; } //===================================================================================== // PlayerPhysics //===================================================================================== geBoolean PlayerPhysics(GenVSI *VSI, void *PlayerData, float GroundFriction, float AirFriction, float LiquidFriction, float Gravity, float BounceScale, geBoolean AllowBounce, float Time) { float Speed; GPlayer *Player; Player = (GPlayer*)PlayerData; #ifndef FLY_MODE Player->LastGoodPos = Player->XForm.Translation; // Add gravity switch (Player->State) { case PSTATE_InLava: case PSTATE_InWater: Player->Velocity.Y -= PLAYER_GRAVITY*Time*0.05f; break; default: Player->Velocity.Y -= PLAYER_GRAVITY*Time; break; } CheckVelocity(VSI, Player, BounceScale, AllowBounce, Time); SqueezeVector(&Player->Velocity, 0.2f); geVec3d_AddScaled(&Player->XForm.Translation, &Player->Velocity, Time, &Player->XForm.Translation); CheckPlayer(VSI, Player); #else // Fly through walls Player->State = PSTATE_InAir; SqueezeVector(&Player->Velocity, 0.2f); geVec3d_AddScaled(&Player->XForm.Translation, &Player->Velocity, Time, &Player->XForm.Translation); #endif Speed = geVec3d_Length(&Player->Velocity); // Apply friction if (Speed > 0.001) { float NewSpeed; if (Player->State == PSTATE_Normal || Player->State == PSTATE_DeadOnGround) NewSpeed = Speed - Time*Speed*PLAYER_GROUND_FRICTION; else if (Player->State == PSTATE_InAir || Player->State == PSTATE_Dead) NewSpeed = Speed - Time*Speed*PLAYER_AIR_FRICTION; else if (PlayerLiquid(Player)) NewSpeed = Speed - Time*Speed*PLAYER_LIQUID_FRICTION; if (NewSpeed < 0.0f) NewSpeed = 0.0f; NewSpeed /= Speed; // Apply movement friction geVec3d_Scale(&Player->Velocity, NewSpeed, &Player->Velocity); } UpdatePlayerContents(VSI, Player, Time); return GE_TRUE; } //===================================================================================== // UpdatePlayerContents //===================================================================================== geBoolean UpdatePlayerContents(GenVSI *VSI, void *PlayerData, float Time) { GPlayer *Player; geWorld *World; GE_Contents Contents; World = GenVSI_GetWorld(VSI); assert(World); Player = (GPlayer*)PlayerData; if (geWorld_GetContents(World, &Player->XForm.Translation, &Player->Mins, &Player->Maxs, GE_COLLIDE_MODELS, 0, NULL, NULL, &Contents)) { // Check to see if player is in lava... if (Contents.Contents & CONTENTS_WATER) { Player->State = PSTATE_InWater; } else if (Contents.Contents & CONTENTS_LAVA) { Player->State = PSTATE_InLava; } else if (PlayerLiquid(Player)) Player->State = PSTATE_Normal; } else if (PlayerLiquid(Player)) Player->State = PSTATE_Normal; return GE_TRUE; } geBoolean PlayerDead(GPlayer *Player) { assert(Player); if (Player->State == PSTATE_Dead) return GE_TRUE; if (Player->State == PSTATE_DeadOnGround) return GE_TRUE; return GE_FALSE; } static int32 Hack2; //===================================================================================== // Client_Control //===================================================================================== geBoolean Client_Control(GenVSI *VSI, void *PlayerData, float Time) { geVec3d LVect, InVect; float Speed; GE_Contents Contents; geVec3d CMins, CMaxs; float MoveSpeed; geBoolean DoWalk = GE_FALSE; geXForm3d XForm; GPlayer *Player; GenVSI_CMove *Move; geWorld *World; uint32 ColFlags; CData Data; Player = (GPlayer*)PlayerData; assert(Player); assert(Player->ClientHandle != CLIENT_NULL_HANDLE); // FIXME: Make this function take care of dead players also. Use a switch statement or somthing. // We should not be changing control functions on the fly like that. Could confuse the server/client... //assert(Player->State != PSTATE_Dead && Player->State != PSTATE_DeadOnGround); if (PlayerDead(Player)) return GE_TRUE; if (IsKeyDown('L')) { GenVSI_SetWorld(VSI, SetupWorldCB, ShutdownWorldCB, "Levels\\GenVs.Bsp"); return GE_TRUE; } Move = GenVSI_GetClientMove(VSI, Player->ClientHandle); if (!Move) return GE_TRUE; assert(Move); Player->Time += Time; // Make sure the xform is valid SetupPlayerXForm(VSI, Player, Time); geXForm3d_SetYRotation(&XForm, Move->Angles.Y); geXForm3d_GetLeft(&XForm, &LVect); #ifdef FLY_MODE geXForm3d_GetIn(&Player->XForm, &InVect); // Use the real in vector for liquid #else if (PlayerLiquid(Player)) geXForm3d_GetIn(&Player->XForm, &InVect); // Use the real in vector for liquid else geXForm3d_GetIn(&XForm, &InVect); #endif //if (VSI->Mode == MODE_Server) if (Move->ButtonBits & HOST_BUTTON_FIRE) { uint16 Amount; geBoolean Has; Player->CurrentWeapon = Move->Weapon; assert(Player->CurrentWeapon >= 0 && Player->CurrentWeapon <= 3); assert(Player->ClientHandle != CLIENT_NULL_HANDLE); FireWeapon(VSI, PlayerData, Time); assert(Player->Inventory[Player->CurrentWeapon] >= 0 && Player->Inventory[Player->CurrentWeapon] < 65535); Amount = (uint16)Player->Inventory[Player->CurrentWeapon]; Has = Player->InventoryHas[Player->CurrentWeapon]; GenVSI_SetClientInventory(VSI, Player->ClientHandle, Player->CurrentWeapon, Amount, Has); // Force a weapon update } MoveSpeed = Time; if (Player->State != PSTATE_Normal) MoveSpeed *= 0.15f; // Set his movement Velocity if (Move->ForwardSpeed) { geVec3d_MA(&Player->Velocity, Move->ForwardSpeed*MoveSpeed, &InVect, &Player->Velocity); } if (Move->ButtonBits & HOST_BUTTON_LEFT) geVec3d_MA(&Player->Velocity, PLAYER_SIDE_SPEED*MoveSpeed, &LVect, &Player->Velocity); if (Move->ButtonBits & HOST_BUTTON_RIGHT) geVec3d_MA(&Player->Velocity, -PLAYER_SIDE_SPEED*MoveSpeed, &LVect, &Player->Velocity); if ((Move->ButtonBits & HOST_BUTTON_JUMP) && (PlayerLiquid(Player) || Player->State == PSTATE_Normal)) { GenVSI_PlaySound(VSI, SOUND_INDEX_JUMP, &Player->XForm.Translation); if (Player->State == PSTATE_Normal) Player->Velocity.Y += PLAYER_JUMP_THRUST; else Player->Velocity.Y += PLAYER_JUMP_THRUST*0.2f; } // Run polayer physics code... PlayerPhysics(VSI, Player, PLAYER_GROUND_FRICTION, PLAYER_AIR_FRICTION, PLAYER_LIQUID_FRICTION, PLAYER_GRAVITY, 1.0f, GE_FALSE, Time); World = GenVSI_GetWorld(VSI); assert(World); ColFlags = GE_COLLIDE_MODELS; if (VSI->Mode == MODE_Server) // Only do this stuff when we are in server mode... { if (!PlayerDead(Player) && Player->Roll > 0.0f) Player->Roll -= Time; #ifndef FLY_MODE if (Player->State == PSTATE_InLava) { if (Player->Roll <= 0.0f) { DammagePlayer(VSI, NULL, Player, 20, 0.0f, Time); Player->Roll = 0.5f; } } #endif // Get a box a little bigger than the player for doors, etc... CMins = Player->Mins; CMaxs = Player->Maxs; CMins.X -= 100; CMins.Y -= 10; CMins.Z -= 100; CMaxs.X += 100; CMaxs.Y += 10; CMaxs.Z += 100; if (geWorld_GetContents(World, &Player->XForm.Translation, &CMins, &CMaxs, GE_COLLIDE_MODELS, 0, NULL, NULL, &Contents)) { if (Contents.Model) { GPlayer *TPlayer; TPlayer = (GPlayer*)geWorld_ModelGetUserData(Contents.Model); if (TPlayer) { Hack2 = 0; } if (TPlayer && TPlayer->Trigger && TPlayer->ViewFlags & VIEW_TYPE_TOUCH) { TPlayer->Trigger(VSI, TPlayer, Player, NULL); } } } Data.VSI = VSI; Data.Player = Player; if (geWorld_GetContents(World, &Player->XForm.Translation, &CMins, &CMaxs, GE_COLLIDE_ACTORS, 0xffffffff, SelfCollisionCB, &Data, &Contents)) //if (geWorld_GetContents(World, &Player->XForm.Translation, &CMins, &CMaxs, GE_COLLIDE_ACTORS, 0xffffffff, NULL, NULL, &Contents)) { if (Contents.Actor) { GPlayer *TPlayer; static int32 HackV; //GenVSI_ConsoleHeaderPrintf(VSI, Player->ClientHandle, GE_FALSE, "Hit actor:%i", HackV++); TPlayer = (GPlayer*)GenVSI_ActorToPlayer(VSI, Contents.Actor); if (TPlayer && TPlayer->Trigger)// && TPlayer->ViewFlags & VIEW_TYPE_TOUCH) { TPlayer->Trigger(VSI, TPlayer, Player, NULL); } } } } Speed = geVec3d_Length(&Player->Velocity); if ((Move->ButtonBits & HOST_BUTTON_LEFT) || (Move->ButtonBits & HOST_BUTTON_RIGHT) || Move->ForwardSpeed) { if (Player->MotionIndex != ACTOR_MOTION_PLAYER_RUN) Player->FrameTime = 0.0f; Player->MotionIndex = ACTOR_MOTION_PLAYER_RUN; DoWalk = GE_TRUE; } if (Speed > 0.1f && DoWalk) { if (Player->MotionIndex == ACTOR_MOTION_PLAYER_RUN) { Speed*=0.004f; if (Move->ForwardSpeed<0) Speed *= -1.0f; } else Speed = 1.0f; if (AnimatePlayer(VSI, Player, Player->MotionIndex, Time*Speed, GE_TRUE)) { if (Player->MotionIndex != ACTOR_MOTION_PLAYER_RUN) Player->FrameTime = 0.0f; Player->MotionIndex = ACTOR_MOTION_PLAYER_RUN; } } else { if (Player->MotionIndex != ACTOR_MOTION_PLAYER_IDLE) { Player->MotionIndex = ACTOR_MOTION_PLAYER_IDLE; Player->FrameTime = 0.0f; } AnimatePlayer(VSI, Player, Player->MotionIndex, Time, GE_TRUE); } // Make sure the xform is valid SetupPlayerXForm(VSI, Player, Time); Player->VPos = Player->XForm.Translation; return GE_TRUE; } //===================================================================================== // Player_Spawn //===================================================================================== void Player_Spawn(GenVSI *VSI, void *PlayerData, void *ClassData, char *EntityName) { PlayerStart *Ps; GPlayer *Player; Player = (GPlayer*)PlayerData; Player->Control = NULL; Player->Trigger = NULL; Player->Blocked = NULL; Player->Time = 0.0f; if (ClassData == NULL) { GenVS_Error("Player_Spawn: entity missing class data ('%s')\n",EntityName); } Ps = (PlayerStart*)ClassData; geXForm3d_SetIdentity(&Player->XForm); geXForm3d_SetTranslation(&Player->XForm, Ps->Origin.X, Ps->Origin.Y, Ps->Origin.Z); Player->VPos = Player->XForm.Translation; //return GE_TRUE; } //===================================================================================== // Door_Control //===================================================================================== static geBoolean Door_Control(GenVSI *VSI, void *PlayerData, float Time) { geWorld_Model *Model; geMotion *Motion; float StartTime, EndTime, NewTime; geXForm3d DestXForm; gePath *Path; GPlayer *Player; geWorld *World; Player = (GPlayer*)PlayerData; if (Player->State != PSTATE_Opened) return GE_TRUE; World = GenVSI_GetWorld(VSI); assert(World); Model = Player->Model; assert(Model); Motion = geWorld_ModelGetMotion(Model); assert(Motion); NewTime = Player->FrameTime + Time; Path = geMotion_GetPath(Motion, 0); assert(Path); geMotion_GetTimeExtents(Motion, &StartTime , &EndTime); if (NewTime >= EndTime) // Played through, done... { NewTime = StartTime; Player->State = PSTATE_Closed; Player->ViewFlags &= ~VIEW_TYPE_MODEL_OPEN; } // Get the xform for the current time gePath_Sample(Path, NewTime, &DestXForm); // If the player can move, then update time, and xform if (GenVSI_MovePlayerModel(VSI, Player, &DestXForm)) { Player->XForm = DestXForm; //DData->AnimTime = NewTime; Player->FrameTime = NewTime; } //geWorld_GetModelRotationalCenter(World, Model, &Player->VPos); //geVec3d_Add(&Player->VPos, &Player->XForm.Translation, &Player->VPos); return GE_TRUE; } //===================================================================================== // Plat_Control //===================================================================================== static geBoolean Plat_Control(GenVSI *VSI, void *PlayerData, float Time) { geWorld_Model *Model; geMotion *Motion; float StartTime, EndTime, NewTime; geXForm3d DestXForm; gePath *Path; GPlayer *Player; geWorld *World; MovingPlat *Plat; Player = (GPlayer*)PlayerData; if (Player->State != PSTATE_Opened) return GE_TRUE; World = GenVSI_GetWorld(VSI); assert(World); Model = Player->Model; assert(Model); Motion = geWorld_ModelGetMotion(Model); assert(Motion); NewTime = Player->FrameTime + Time; Path = geMotion_GetPath(Motion, 0); assert(Path); geMotion_GetTimeExtents(Motion, &StartTime , &EndTime); if (NewTime >= EndTime) // Played through, done... { NewTime = StartTime; Player->State = PSTATE_Closed; Player->ViewFlags &= ~VIEW_TYPE_MODEL_OPEN; Plat = (MovingPlat*)Player->ClassData; /* if (Plat->Loop) { Player->Trigger(VSI, Player, NULL); } */ } // Get the xform for the current time gePath_Sample(Path, NewTime, &DestXForm); // If the player can move, then update time, and xform if (GenVSI_MovePlayerModel(VSI, Player, &DestXForm)) { Player->XForm = DestXForm; //DData->AnimTime = NewTime; Player->FrameTime = NewTime; } //geWorld_GetModelRotationalCenter(World, Model, &Player->VPos); //geVec3d_Add(&Player->VPos, &Player->XForm.Translation, &Player->VPos); return GE_TRUE; } //===================================================================================== // Door_Trigger //===================================================================================== static geBoolean Door_Trigger(GenVSI *VSI, void *PlayerData, GPlayer *TargetData, void* data) { GPlayer *Player, *Target; Player = (GPlayer*)PlayerData; Target = TargetData; if (Player->State == PSTATE_Opened) return GE_TRUE; Player->State = PSTATE_Opened; Player->FrameTime = 0.0f; assert(Player->Model); Player->ViewFlags |= VIEW_TYPE_MODEL_OPEN; GenVSI_PlaySound(VSI, 2, &Player->XForm.Translation); return GE_TRUE; } //===================================================================================== // Door_Blocked //===================================================================================== static geBoolean Door_Blocked(GenVSI *VSI, void *PlayerData, GPlayer *TargetData) { return GE_TRUE; } //===================================================================================== // Door_Spawn //===================================================================================== static void Door_Spawn(GenVSI *VSI, void *PlayerData, void *ClassData, char *EntityName) { geWorld_Model *Model; geMotion *Motion; gePath *Path; GPlayer *Player; Door *FuncDoor; geWorld *World; Player = (GPlayer*)PlayerData; Player->Control = Door_Control; Player->Trigger = Door_Trigger; Player->Blocked = Door_Blocked; Player->ControlIndex = 1; //Player->TriggerIndex = 2; Player->Time = 0.0f; // Setup the doors local user data (not passed accross network) // Grab the model FuncDoor = (Door*)ClassData; Player->VPos = FuncDoor->Origin; Model = FuncDoor->Model; if (!Model) { GenVS_Error( "Door_Spawn: No model for entity:%s.\n",EntityName); return; } World = GenVSI_GetWorld(VSI); //geWorld_GetModelRotationalCenter(World, Model, &Player->VPos); // Set the default xform to time 0 of the animation Motion = geWorld_ModelGetMotion(Model); if (!Motion) { GenVS_Error( "Door_Spawn: No motion for model ('%s').\n",EntityName); return; } Path = geMotion_GetPath(Motion, 0); if (!Path) { GenVS_Error( "Door_Spawn: No path for model motion ('%s').\n",EntityName); return; } // Put model at default position gePath_Sample(Path, 0.0f, &Player->XForm); Player->ViewFlags = VIEW_TYPE_MODEL | VIEW_TYPE_TOUCH; Player->ViewIndex = GenVSI_ModelToViewIndex(VSI, Model); // Special index // Register the model with the player if all is ok // NOTE - If somthing went bad, then this should not be called!!! GenVSI_RegisterPlayerModel(VSI, Player, Model); //return GE_TRUE; } //===================================================================================== // Plat_Trigger //===================================================================================== static geBoolean Plat_Trigger(GenVSI *VSI, void *PlayerData, GPlayer *TargetData, void* data) { geVec3d Pos; GPlayer *Player, *Target; Player = (GPlayer*)PlayerData; Target = (GPlayer*)TargetData; if (Player->State == PSTATE_Opened) return GE_TRUE; Player->State = PSTATE_Opened; Player->FrameTime = 0.0f; if (Target) { Pos = Target->XForm.Translation; } else { geWorld *World; World = GenVSI_GetWorld(VSI); assert(World); geWorld_GetModelRotationalCenter(World, Player->Model, &Pos); geVec3d_Add(&Pos, &Player->XForm.Translation, &Pos); } GenVSI_PlaySound(VSI, 2, &Pos); return GE_TRUE; } //===================================================================================== // Plat_Spawn //===================================================================================== static void Plat_Spawn(GenVSI *VSI, void *PlayerData, void *ClassData, char *EntityName) { geWorld_Model *Model; geMotion *Motion; gePath *Path; GPlayer *Player; MovingPlat *Plat; geWorld *World; Player = (GPlayer*)PlayerData; Player->Control = Plat_Control; Player->Trigger = Plat_Trigger; Player->Time = 0.0f; Player->ControlIndex = 3; //Player->TriggerIndex = 4; // Setup the plats local user data (not passed accross network) Plat = (MovingPlat*)ClassData; Player->VPos = Plat->Origin; // Grab the model Model = Plat->Model; if (!Model) { GenVS_Error( "Plat_Spawn: No model for entity ('%s').\n",EntityName); return; } World = GenVSI_GetWorld(VSI); //geWorld_GetModelRotationalCenter(World, Model, &Player->VPos); // Set the default xform to time 0 of the animation Motion = geWorld_ModelGetMotion(Model); if (!Motion) { GenVS_Error( "Plat_Spawn: No motion for model ('%s').\n",EntityName); return; } Path = geMotion_GetPath(Motion, 0); if (!Path) { GenVS_Error( "Plat_Spawn: No path for model motion ('%s').\n",EntityName); return; } // Put model at default position gePath_Sample(Path, 0.0f, &Player->XForm); Player->ViewFlags = VIEW_TYPE_MODEL | VIEW_TYPE_STANDON; Player->ViewIndex = GenVSI_ModelToViewIndex(VSI, Model); // Special index // Register the model with the player if all is ok // NOTE - If somthing went bad, then this should not be called!!! GenVSI_RegisterPlayerModel(VSI, Player, Model); /* if (Plat->Loop) { Player->Trigger(VSI, Player, NULL); } */ //return GE_TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //===================================================================================== // PhysicsObject_Spawn //===================================================================================== static void PhysicsObject_Spawn(GenVSI *VSI, void *PlayerData, void *ClassData, char *EntityName) { geWorld_Model *Model; GPlayer *Player; PhysicsObject *po; geWorld *World; geVec3d Mins; geVec3d Maxs; Player = (GPlayer*)PlayerData; Player->Control = PhysicsObject_Control; Player->Trigger = PhysicsObject_Trigger; Player->Time = 0.0f; po = NULL; po = (PhysicsObject*)ClassData; if (po == NULL) { GenVS_Error( "PhysicsObject_Spawn: NULL class data for physics entity '%s'. (at coordinates: x=%f y=%f z=%f)\n", EntityName,po->Origin.X,po->Origin.Y,po->Origin.Z); return; } Model = po->Model; Player->VPos = po->Origin; if (!Model) { GenVS_Error( "PhysicsObject_Spawn: No model for physics entity '%s'. (at coordinates: x=%f y=%f z=%f)\n", EntityName,po->Origin.X,po->Origin.Y,po->Origin.Z); return; } World = GenVSI_GetWorld(VSI); //////////////////////////////////////////////////////////////////////////////////////////////////// Player->ViewFlags = VIEW_TYPE_MODEL | VIEW_TYPE_PHYSOB; Player->ViewIndex = GenVSI_ModelToViewIndex(VSI, Model); #define PHYSOB_MAX_DAMPING (1.f) #define PHYSOB_MIN_DAMPING (0.f) if (po->linearDamping < PHYSOB_MIN_DAMPING) po->linearDamping = PHYSOB_MIN_DAMPING; else if (po->linearDamping > PHYSOB_MAX_DAMPING) po->linearDamping = PHYSOB_MAX_DAMPING; if (po->angularDamping < PHYSOB_MIN_DAMPING) po->angularDamping = PHYSOB_MIN_DAMPING; else if (po->angularDamping > PHYSOB_MAX_DAMPING) po->angularDamping = PHYSOB_MAX_DAMPING; geWorld_ModelGetBBox(World, po->Model, &Mins, &Maxs); #pragma message("Mins / maxs should be OK in the next build") po->stateInfo = gePhysicsObject_Create(&po->Origin, po->mass, po->isAffectedByGravity, po->respondsToForces, po->linearDamping, po->angularDamping, &Mins, &Maxs, 0.01f); //po->physicsScale); if (po->stateInfo == NULL) { GenVS_Error( "PhysicsObject_Spawn: gePhysicsObject_Create failed for physics entity '%s'\n",EntityName); return; } Player->userData = po->stateInfo; // Register the model with the player if all is ok // NOTE - If somthing went bad, then this should not be called!!! GenVSI_RegisterPlayerModel(VSI, Player, Model); } static void PhysicsObject_Destroy(GenVSI *VSI, void *PlayerData, void *ClassData) { GPlayer *Player; PhysicsObject *po; Player = (GPlayer*)PlayerData; po = (PhysicsObject*)ClassData; if (po) if (po->stateInfo) { gePhysicsObject_Destroy(&po->stateInfo); } } static geBoolean PhysicsObject_Trigger(GenVSI *VSI, void *PlayerData, GPlayer *Target, void *data) { //////////////////////////////////////////////////////////////////////////////////////////////////// // PlayerData actually points to the PhysicsObject. // Target is R. Havoc. // Makes sense, doesn't it? :^D GPlayer *Player; PhysicsObject* poPtr; gePhysicsObject* podPtr; GE_Collision* collisionInfo; float velMagN; geVec3d radiusVector; geVec3d force; geVec3d poCOM; int activeConfigIndex; float scale; Player = (GPlayer*)PlayerData; poPtr = (PhysicsObject*)Player->ClassData; podPtr = (gePhysicsObject*)Player->userData; collisionInfo = (GE_Collision*)data; scale = gePhysicsObject_GetPhysicsScale(podPtr); activeConfigIndex = gePhysicsObject_GetActiveConfig(podPtr); gePhysicsObject_GetLocationInEditorSpace(podPtr, &poCOM, activeConfigIndex); geVec3d_Subtract(&collisionInfo->Impact, &poCOM, &radiusVector); velMagN = geVec3d_DotProduct(&Target->Velocity, &collisionInfo->Plane.Normal); geVec3d_Scale(&collisionInfo->Plane.Normal, velMagN * 4.f, &force); geVec3d_Scale(&radiusVector, scale, &radiusVector); gePhysicsObject_ApplyGlobalFrameForce(podPtr, &force, &radiusVector, GE_TRUE, activeConfigIndex); return GE_TRUE; } geVec3d bboxVerts[8] = { {-1.0f, 1.0f, 1.0f}, {-1.0f, -1.0f, 1.0f}, {1.0f, -1.0f, 1.0f}, {1.0f, 1.0f, 1.0f}, {-1.0f, 1.0f, -1.0f}, {-1.0f, -1.0f, -1.0f}, {1.0f, -1.0f, -1.0f}, {1.0f, 1.0f, -1.0f} }; #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) static geBoolean PhysicsObject_Control(GenVSI* VSI, void* PlayerData, float Time) { GPlayer* player; gePhysicsObject* pod; int activeConfigIndex; geXForm3d destXForm; #if 0 geXForm3d xform; geWorld* world; geVec3d bbmin, bbmax, bbdims; geVec3d tmpVec; int i; Matrix33 A; geVec3d boundingBoxCenter; geEntity_EntitySet* Set; geEntity* Entity; geVec3d boundingBoxScale; #endif //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// player = (GPlayer*)PlayerData; if (player == NULL) { GenVS_Error( "PhysicsObject_Control: invalid player.\n"); return GE_FALSE; } pod = (gePhysicsObject*)player->userData; if (pod == NULL) { GenVS_Error( "PhysicsObject_Control: pod = NULL.\n"); return GE_FALSE; } activeConfigIndex = gePhysicsObject_GetActiveConfig(pod); #if 0 world = GenVSI_GetWorld(VSI); geWorld_ModelGetBBox(world, player->Model, &bbmin, &bbmax); gePhysicsObject_GetLocation(pod, &boundingBoxCenter); geVec3d_Scale(&bbmin, PHYSOB_SCALE, &bbmin); geVec3d_Scale(&bbmax, PHYSOB_SCALE, &bbmax); geVec3d_Subtract(&bbmax, &bbmin, &bbdims); geVec3d_Scale(&bbdims, 0.5f, &boundingBoxScale); gePhysicsObject_GetXForm(pod, &xform); Matrix33_ExtractFromXForm3d(&xform, &A); //////////////////////////////////////////////////////////////////////////////////////////////////// // check for penetration of one or more model vertices into the radius of a ForceField entity Set = NULL; Set = geWorld_GetEntitySet(world, "ForceField"); if (Set != NULL) { for (Entity = geEntity_EntitySetGetNextEntity(Set, NULL); Entity != NULL; Entity = geEntity_EntitySetGetNextEntity(Set, Entity)) { ForceField* ff; geVec3d vertPos; float forceMultiplier; float distToFFCenter; float forceMagnitude; geVec3d forceDir; geVec3d forceToApply, ptOfApplication; geVec3d ffOriginInPhysicsSpace; ff = geEntity_GetUserData(Entity); assert(ff != NULL); if (! ff->affectsPhysicsObjects) continue; for (i = 0; i < 8; i++) { tmpVec.X = boundingBoxScale.X * bboxVerts[i].X; tmpVec.Y = boundingBoxScale.Y * bboxVerts[i].Y; tmpVec.Z = boundingBoxScale.Z * bboxVerts[i].Z; Matrix33_MultiplyVec3d(&A, &tmpVec, &vertPos); geVec3d_Add(&boundingBoxCenter, &vertPos, &vertPos); geVec3d_Scale(&ff->Origin, PHYSOB_SCALE, &ffOriginInPhysicsSpace); geVec3d_Subtract(&vertPos, &ffOriginInPhysicsSpace, &forceDir); distToFFCenter = geVec3d_Length(&forceDir); if (distToFFCenter > ff->radius) continue; geVec3d_Normalize(&forceDir); //////////////////////////////////////////////////////////////////////////////////////////////////// // figure out how much force to apply based on force field's falloff function switch(ff->falloffType) { case FALLOFF_NONE: forceMultiplier = 1.f; break; case FALLOFF_ONE_OVER_D: forceMultiplier = 1 / distToFFCenter; break; case FALLOFF_ONE_OVER_DSQUARED: forceMultiplier = 1 / (distToFFCenter * distToFFCenter); break; default: forceMultiplier = 1.f; } forceMagnitude = ff->strength * forceMultiplier * 1000.f * PHYSOB_SCALE; geVec3d_Scale(&forceDir, forceMagnitude, &forceToApply); geVec3d_Subtract(&vertPos, &boundingBoxCenter, &ptOfApplication); gePhysicsObject_ApplyGlobalFrameForce(pod, &forceToApply, &ptOfApplication, GE_TRUE); } // for i } // while } // if #endif // update model's xform gePhysicsObject_GetXFormInEditorSpace(pod, &destXForm, activeConfigIndex); if (GenVSI_MovePlayerModel(VSI, player, &destXForm)) { //gePhysicsObject_GetXFormInEditorSpace(pod, &xform, activeConfigIndex); geXForm3d_Copy(&destXForm, &player->XForm); } return GE_TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //===================================================================================== // PhysicsJoint_Spawn //===================================================================================== static void PhysicsJoint_Spawn(GenVSI *VSI, void *PlayerData, void *ClassData, char *EntityName) { GPlayer *Player; PhysicsJoint *ij; Player = (GPlayer*)PlayerData; ij = NULL; ij = (PhysicsJoint*)ClassData; if (ij == NULL) { GenVS_Error( "PhysicsJoint_Spawn: NULL Class Data ('%s').\n",EntityName); return; } Player->ViewFlags = VIEW_TYPE_LOCAL; #define JOINT_MIN_ASSEMBLY_RATE (0.01f) #define JOINT_MAX_ASSEMBLY_RATE (1.f) if (ij->assemblyRate < JOINT_MIN_ASSEMBLY_RATE) ij->assemblyRate = JOINT_MIN_ASSEMBLY_RATE; else if (ij->assemblyRate > JOINT_MAX_ASSEMBLY_RATE) ij->assemblyRate = JOINT_MAX_ASSEMBLY_RATE; ij->jointData = NULL; ij->jointData = gePhysicsJoint_Create((gePhysicsJoint_Kind)ij->jointType, &ij->Origin, ij->assemblyRate, ij->physicsObject1 ? ij->physicsObject1->stateInfo : NULL, ij->physicsObject2 ? ij->physicsObject2->stateInfo : NULL, 0.01f); //ij->physicsScale); if (ij->jointData == NULL) { GenVS_Error( "PhysicsJoint_Spawn: Couldn't Create('%s').\n",EntityName); return; } //return GE_TRUE; } //===================================================================================== //===================================================================================== static void PhysicsJoint_Destroy(GenVSI *VSI, void *PlayerData, void *ClassData) { GPlayer *Player; PhysicsJoint *ij; Player = (GPlayer*)PlayerData; ij = NULL; ij = (PhysicsJoint*)ClassData; assert(ij->jointData); gePhysicsJoint_Destroy(&ij->jointData); } //===================================================================================== //===================================================================================== static geBoolean PhysicsJoint_Trigger(GenVSI* VSI, void* PlayerData, void* TargetData, void* data) { return GE_TRUE; } static geBoolean PhysicsJoint_Control(GenVSI* VSI, void* PlayerData, float Time) { return GE_TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //===================================================================================== // PhysicalSystem_Spawn //===================================================================================== static void PhysicalSystem_Spawn(GenVSI *VSI, void *PlayerData, void *ClassData, char *EntityName) { GPlayer *Player; PhysicalSystem *ips; PhysicsObject *Object; PhysicsObject *Object2; PhysicsJoint *PhysicsJoint; Player = NULL; Player = (GPlayer*)PlayerData; if (Player == NULL) { GenVS_Error( "PhysicalSystem_Spawn: NULL Player ('%s').\n",EntityName); return; } Player->Control = PhysicalSystem_Control; if (Player->Control == NULL) { GenVS_Error( "PhysicalSystem_Spawn: NULL Player control ('%s').\n",EntityName); return; } Player->Blocked = NULL; Player->Trigger = NULL; Player->ViewFlags = VIEW_TYPE_LOCAL; Player->ViewIndex = VIEW_INDEX_NONE; geXForm3d_SetIdentity(&Player->XForm); ips = NULL; ips = (PhysicalSystem*)ClassData; if (ips == NULL) { GenVS_Error( "PhysicalSystem_Spawn: NULL Class Data ('%s').\n",EntityName); return; } ips->physsysData = NULL; ips->physsysData = gePhysicsSystem_Create(); if (ips->physsysData == NULL) { GenVS_Error( "PhysicalSystem_Spawn: Couldn't Create('%s').\n",EntityName); return; } Object = ips->physicsObjectListHeadPtr; Object2 = Object; while (Object) { if (gePhysicsSystem_AddObject(ips->physsysData, Object->stateInfo) == GE_FALSE) { GenVS_Error( "PhysicalSystem_Spawn: Couldn't AddObject('%s').\n",EntityName); return; } Object = Object->Next; if (Object2) { Object2 = Object2->Next; if (Object2) { Object2=Object2->Next; if (Object2) { if (Object2==Object) { GenVS_Error("PhysicalSystem_Spawn: Detected circular linked list in Next field('%s')\n",EntityName); return; } } } } } PhysicsJoint = ips->jointListHeadPtr; while (PhysicsJoint) { if (PhysicsJoint->jointData == NULL) { GenVS_Error( "PhysicalSystem_Spawn: Null jointData ('%s').\n",EntityName); return; } if (gePhysicsSystem_AddJoint(ips->physsysData, PhysicsJoint->jointData) == GE_FALSE) { GenVS_Error( "PhysicalSystem_Spawn: Couldn't AddPhysicsJoint('%s').\n",EntityName); return; } PhysicsJoint = PhysicsJoint->Next; } //return GE_TRUE; } //===================================================================================== //===================================================================================== static void PhysicalSystem_Destroy(GenVSI *VSI, void *PlayerData, void *ClassData) { GPlayer *Player; PhysicalSystem *ips; Player = (GPlayer*)PlayerData; ips = (PhysicalSystem*)ClassData; assert(ips); assert(ips->physsysData); gePhysicsSystem_Destroy(&ips->physsysData); } //===================================================================================== //===================================================================================== static geBoolean PhysicalSystem_Trigger(GenVSI* VSI, void* PlayerData, void* TargetData, void* data) { return GE_TRUE; } //===================================================================================== //===================================================================================== static geBoolean PhysicalSystem_Control(GenVSI* VSI, void* PlayerData, float Time) { GPlayer* player; PhysicalSystem* psPtr; player = (GPlayer*)PlayerData; psPtr = (PhysicalSystem*)player->ClassData; if (!gePhysicsSystem_Iterate(psPtr->physsysData, Time)) { GenVS_Error( "PhysicalSystem_Control: Iterate() failed.\n"); return GE_FALSE; } return GE_TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// // force field-related stuff static void ForceField_Spawn(GenVSI* VSI, void* PlayerData, void* Class, char *EntityName) { GPlayer* player; ForceField* ff; player = (GPlayer*)PlayerData; if (player == NULL) { GenVS_Error( "ForceField_Spawn: player = NULL ('%s').\n",EntityName); return; } ff = (ForceField*)player->ClassData; if (ff == NULL) { GenVS_Error( "ForceField_Spawn: ff = NULL ('%s').\n",EntityName); return; } player->ViewFlags = VIEW_TYPE_LOCAL; player->Blocked = NULL; player->Control = ForceField_Control; player->Trigger = ForceField_Trigger; //return GE_TRUE; } static geBoolean ForceField_Trigger(GenVSI* VSI, void* PlayerData, GPlayer* TargetData, void* data) { return GE_TRUE; } static geBoolean ForceField_Control(GenVSI* VSI, void* PlayerData, float Time) { return GE_TRUE; } /* //===================================================================================== // Spawn_AmbientSound //===================================================================================== static geBoolean Spawn_AmbientSound(Server_Server *Server, Server_Player *Player, void *ClassData) { Player->SoundIndex = SOUND_INDEX_WATERFALL; } */ //===================================================================================== // SqueezeVector //===================================================================================== void SqueezeVector(geVec3d *Vect, float Epsilon) { if (Vect->X > -Epsilon && Vect->X < Epsilon) Vect->X = 0.0f; if (Vect->Y > -Epsilon && Vect->Y < Epsilon) Vect->Y = 0.0f; if (Vect->Z > -Epsilon && Vect->Z < Epsilon) Vect->Z = 0.0f; } //===================================================================================== // ClampVector //===================================================================================== void ClampVector(geVec3d *Vect, float Epsilon) { if (Vect->X > Epsilon) Vect->X = Epsilon; if (Vect->Y > Epsilon) Vect->Y = Epsilon; if (Vect->Z > Epsilon) Vect->Z = Epsilon; if (Vect->X < -Epsilon) Vect->X = -Epsilon; if (Vect->Y < -Epsilon) Vect->Y = -Epsilon; if (Vect->Z < -Epsilon) Vect->Z = -Epsilon; } //===================================================================================== // ReflectVelocity //===================================================================================== void ReflectVelocity(geVec3d *In, geVec3d *Normal, geVec3d *Out, float Scale) { float Reflect; Reflect = geVec3d_DotProduct(In, Normal) * Scale; Out->X = In->X - Normal->X*Reflect; Out->Y = In->Y - Normal->Y*Reflect; Out->Z = In->Z - Normal->Z*Reflect; SqueezeVector(Out, 0.1f); } //===================================================================================== // IsKeyDown //===================================================================================== static geBoolean IsKeyDown(int KeyCode) { if (GetAsyncKeyState(KeyCode) & 0x8000) return GE_TRUE; return GE_FALSE; } //===================================================================================== // XFormFromVector //===================================================================================== BOOL XFormFromVector(const geVec3d *Source, const geVec3d *Target, float Roll, geXForm3d *Out) { geVec3d p1, p2, Vect; geVec3d Origin = {0.0f, 0.0f, 0.0f}; geVec3d_Subtract(Source, Target, &Vect); if (geVec3d_Compare(&Vect, &Origin, 0.05f)) { Vect.Y = -1.0f; } // First clear the xform geXForm3d_SetIdentity(Out); geVec3d_Normalize(&Vect); // Now set the IN vector Out->AZ = Vect.X; Out->BZ = Vect.Y; Out->CZ = Vect.Z; // Get a straight up vector p2.X = 0.0f; p2.Y = 1.0f; p2.Z = 0.0f; // Use it with the in vector to get the RIGHT vector geVec3d_CrossProduct(&p2, &Vect, &p1); geVec3d_Normalize(&p1); // Put the RIGHT vector in the matrix Out->AX = p1.X; Out->BX = p1.Y; Out->CX = p1.Z; // Now use the RIGHT vector with the IN vector to get the real UP vector geVec3d_CrossProduct(&Vect, &p1, &p2); geVec3d_Normalize(&p2); // Put the UP vector in the matrix Out->AY = p2.X; Out->BY = p2.Y; Out->CY = p2.Z; // Put the translation in... Out->Translation = *Source; return TRUE; } //===================================================================================== // SetupPlayerXForm //===================================================================================== void SetupPlayerXForm(GenVSI *VSI, void *PlayerData, float Time) { geVec3d Pos; GPlayer *Player; GenVSI_CMove *Move; Player = (GPlayer*)PlayerData; assert(Player->ClientHandle != CLIENT_NULL_HANDLE); Move = GenVSI_GetClientMove(VSI, Player->ClientHandle); assert(Move); Pos = Player->XForm.Translation; // Clear the matrix geXForm3d_SetIdentity(&Player->XForm); // Rotate then translate. geXForm3d_RotateZ(&Player->XForm, Move->Angles.Z+Player->Roll); geXForm3d_RotateX(&Player->XForm, Move->Angles.X); geXForm3d_RotateY(&Player->XForm, Move->Angles.Y); geXForm3d_Translate(&Player->XForm, Pos.X, Pos.Y, Pos.Z); } //===================================================================================== // AnimatePlayer //===================================================================================== geBoolean AnimatePlayer(GenVSI *VSI, void *PlayerData, uint16 MotionIndex, float Speed, geBoolean Loop) { float StartTime, EndTime, DeltaT; geBoolean Looped; GPlayer *Player; Player = (GPlayer*)PlayerData; Looped = GE_FALSE; GenVSI_GetPlayerTimeExtents(VSI, Player, MotionIndex, &StartTime, &EndTime); if (Speed > 0) { Player->FrameTime += Speed; DeltaT = EndTime - StartTime; if (Player->FrameTime >= EndTime) { if (Loop) Player->FrameTime -= DeltaT; else Player->FrameTime = EndTime; Looped = GE_TRUE; } } else if (Speed < 0) { Player->FrameTime += Speed; DeltaT = EndTime - StartTime; if (Player->FrameTime <= StartTime) { if (Loop) Player->FrameTime += DeltaT; else Player->FrameTime = StartTime; Looped = GE_TRUE; } } return Looped; } //===================================================================================== // AnimatePlayer //===================================================================================== geBoolean AnimatePlayer2(GenVSI *VSI, void *PlayerData, int32 MotionSlot, float Speed, geBoolean Loop) { float StartTime, EndTime, DeltaT; geBoolean Looped; GPlayer *Player; uint16 MotionIndex; float MotionTime; Player = (GPlayer*)PlayerData; assert(MotionSlot < Player->NumMotionData); Looped = GE_FALSE; MotionIndex = Player->MotionData[MotionSlot].MotionIndex; MotionTime = Player->MotionData[MotionSlot].MotionTime; GenVSI_GetPlayerTimeExtents(VSI, Player, MotionIndex, &StartTime, &EndTime); if (Speed > 0) { MotionTime += Speed; DeltaT = EndTime - StartTime; if (MotionTime >= EndTime) { if (Loop) MotionTime -= DeltaT; else MotionTime = EndTime; Looped = GE_TRUE; } } else if (Speed < 0) { MotionTime += Speed; DeltaT = EndTime - StartTime; if (MotionTime <= StartTime) { if (Loop) MotionTime += DeltaT; else MotionTime = StartTime; Looped = GE_TRUE; } } Player->MotionData[MotionSlot].MotionTime = MotionTime; return Looped; } //===================================================================================== // UpdateClientInventory //===================================================================================== void UpdateClientInventory(GenVSI *VSI, GPlayer *Player, int32 Slot) { uint16 Amount; geBoolean Has; assert(Player->Inventory[Player->CurrentWeapon] >= 0 && Player->Inventory[Player->CurrentWeapon] <= 65535); Amount = (uint16)Player->Inventory[Slot]; Has = Player->InventoryHas[Slot]; GenVSI_SetClientInventory(VSI, Player->ClientHandle, Slot, Amount, Has); }
28.063766
143
0.598333
paradoxnj
d76b2436653e0b1c717997efa36db65f71b1e2e7
983
cpp
C++
chapter-07/screen.cpp
aufziehvogel/cpp-primer
1ae8fdcda8580ea5d646a725fbb76110f138dbc8
[ "MIT" ]
null
null
null
chapter-07/screen.cpp
aufziehvogel/cpp-primer
1ae8fdcda8580ea5d646a725fbb76110f138dbc8
[ "MIT" ]
null
null
null
chapter-07/screen.cpp
aufziehvogel/cpp-primer
1ae8fdcda8580ea5d646a725fbb76110f138dbc8
[ "MIT" ]
null
null
null
#include "screen.h" #include <stdexcept> Window_mgr::Window_mgr() { screens = {Screen(24, 80, ' ')}; } Screen Window_mgr::get(ScreenIdx idx) const { if (screens.size() <= idx) throw std::runtime_error("Trying to access invalid screen, actual size: " + screens.size()); return screens[idx]; } void Window_mgr::clear(ScreenIdx idx) { if (screens.size() <= idx) throw std::runtime_error("Trying to access invalid screen, actual size: " + screens.size()); Screen screen = screens[idx]; screen.contents = std::string(screen.windowRows * screen.windowCols, ' '); } char Screen::get(pos row, pos col) const { Screen::pos cursorPos = row * windowCols + col; return contents[cursorPos]; } Screen& Screen::set(pos row, pos col, char c) { Screen::pos cursorPos = row * windowCols + col; contents[cursorPos] = c; return *this; } Screen& Screen::move(pos row, pos col) { cursor = row * windowCols + col; return *this; }
22.340909
100
0.649034
aufziehvogel
d76f7d40e7de3541ba27cd42060688c0efc4757c
3,068
hpp
C++
include/seqan3/alignment/matrix/detail/alignment_trace_matrix_base.hpp
joergi-w/seqan3
b757646eee3cddf1f2487db8f1c9f3576ee37391
[ "CC-BY-4.0", "CC0-1.0" ]
283
2017-03-14T23:43:33.000Z
2022-03-28T02:30:02.000Z
include/seqan3/alignment/matrix/detail/alignment_trace_matrix_base.hpp
joergi-w/seqan3
b757646eee3cddf1f2487db8f1c9f3576ee37391
[ "CC-BY-4.0", "CC0-1.0" ]
2,754
2017-03-21T18:39:02.000Z
2022-03-31T13:26:15.000Z
include/seqan3/alignment/matrix/detail/alignment_trace_matrix_base.hpp
joergi-w/seqan3
b757646eee3cddf1f2487db8f1c9f3576ee37391
[ "CC-BY-4.0", "CC0-1.0" ]
88
2017-03-20T12:43:42.000Z
2022-03-17T08:56:13.000Z
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- /*!\file * \brief Provides seqan3::detail::alignment_trace_matrix_base. * \author Rene Rahn <rene.rahn AT fu-berlin.de> */ #pragma once #include <vector> #include <seqan3/alignment/matrix/detail/advanceable_alignment_coordinate.hpp> #include <seqan3/alignment/matrix/detail/trace_directions.hpp> #include <seqan3/alignment/matrix/detail/two_dimensional_matrix.hpp> #include <seqan3/utility/container/aligned_allocator.hpp> #include <seqan3/utility/simd/concept.hpp> namespace seqan3::detail { /*!\brief A crtp-base class for alignment traceback matrices. * \tparam derived_t The derived type. * \tparam trace_t The type of the trace directions. * \ingroup alignment_matrix * * \details * * Manages the actual storage as a std::vector. How much memory is allocated is handled by the derived type. * The `trace_t` must be either a seqan3::detail::trace_directions enum value or a seqan3::detail::simd_conceptvector * over seqan3::detail::trace_directions. */ template <typename trace_t> struct alignment_trace_matrix_base { protected: static_assert(std::same_as<trace_t, trace_directions> || simd_concept<trace_t>, "Value type must either be a trace_directions object or a simd vector."); //!\brief The coordinate type. using coordinate_type = advanceable_alignment_coordinate<advanceable_alignment_coordinate_state::row>; //!\brief The actual element type. using element_type = trace_t; //!\brief The allocator type. Uses seqan3::aligned_allocator if storing seqan3::detail::simd_concepttypes. using allocator_type = std::conditional_t<detail::simd_concept<trace_t>, aligned_allocator<element_type, sizeof(element_type)>, std::allocator<element_type>>; //!\brief The type of the underlying memory pool. using pool_type = two_dimensional_matrix<element_type, allocator_type, matrix_major_order::column>; //!\brief The size type. using size_type = size_t; public: //!\brief The linearised matrix storing the trace data in column-major-order. pool_type data{}; //!\brief Internal cache for the trace values to the left. std::vector<element_type, allocator_type> cache_left{}; //!\brief Internal cache for the last trace value above. element_type cache_up{}; //!\brief The number of columns. size_type num_cols{}; //!\brief The number of num_rows. size_type num_rows{}; }; } // namespace seqan3::detail
43.211268
117
0.676988
joergi-w
d7733136bff8161c2876c70bb24915465ddf0b5c
217
cpp
C++
Runtime/Collision/CCollisionEdge.cpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
267
2016-03-10T21:59:16.000Z
2021-03-28T18:21:03.000Z
Runtime/Collision/CCollisionEdge.cpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
129
2016-03-12T10:17:32.000Z
2021-04-05T20:45:19.000Z
Runtime/Collision/CCollisionEdge.cpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
31
2016-03-20T00:20:11.000Z
2021-03-10T21:14:11.000Z
#include "Runtime/Collision/CCollisionEdge.hpp" namespace metaforce { CCollisionEdge::CCollisionEdge(CInputStream& in) { x0_index1 = in.readUint16Big(); x2_index2 = in.readUint16Big(); } } // namespace metaforce
24.111111
50
0.764977
Jcw87
d7759e6eddbe3820cfd6c5d605415de59210ef0b
5,855
hpp
C++
AVL & BST/avl.hpp
gch144/Data-Structures
462cb009eebc7259409d44b9b5c62c9fd9051d48
[ "MIT" ]
null
null
null
AVL & BST/avl.hpp
gch144/Data-Structures
462cb009eebc7259409d44b9b5c62c9fd9051d48
[ "MIT" ]
null
null
null
AVL & BST/avl.hpp
gch144/Data-Structures
462cb009eebc7259409d44b9b5c62c9fd9051d48
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <algorithm> template <typename Key, typename Info> class AVLTree { // Node of the AVL tree struct Node { public: Key key; Info info; Node *left; Node *right; int height; Node(const Key &key, const Info &info) { this->key = key; this->info = info; this->left = nullptr; this->right = nullptr; this->height = 0; } } * root; // Size of the AVL tree int size; // Recursively copy node data void copy(Node *node) { if (node) { insert(node->key, node->info); copy(node->left); copy(node->right); } } // Recursively delete nodes void del(Node *n) { if (n) { del(n->left); del(n->right); delete n; } } // Get height int height(Node *n) const { if (n) return n->height; return 0; } // Rotate right Node *rotr(Node *y) { Node *x = y->left; Node *T2 = x->right; x->right = y; y->left = T2; y->height = std::max(height(y->left), height(y->right)) + 1; x->height = std::max(height(x->left), height(x->right)) + 1; return x; } // Rotate left Node *rotl(Node *x) { Node *y = x->right; Node *T2 = y->left; y->left = x; x->right = T2; x->height = std::max(height(x->left), height(x->right)) + 1; y->height = std::max(height(y->left), height(y->right)) + 1; return y; } // Get the balance factor int balance_factor(Node *n) const { if (n) return height(n->left) - height(n->right); return 0; } // Insert a element Node *insert(Node *n, const Key &key, const Info &info) { // Find the correct postion and insert the node if (n == nullptr) { size++; return (new Node(key, info)); } if (n->key == key) return n; if (key < n->key) n->left = insert(n->left, key, info); else if (key > n->key) n->right = insert(n->right, key, info); else return n; // Update the balance factor of each node and balance the tree n->height = 1 + std::max(height(n->left), height(n->right)); int b = balance_factor(n); if (b > 1) { if (key < n->left->key) { return rotr(n); } else if (key > n->left->key) { n->left = rotl(n->left); return rotr(n); } } if (b < -1) { if (key > n->right->key) { return rotl(n); } else if (key < n->right->key) { n->right = rotr(n->right); return rotl(n); } } return n; } // Find the node with the given key Node *find(Node *n, const Key &key) const { if (n) { if (n->key < key) return find(n->right, key); else if (n->key > key) return find(n->left, key); return n; } return nullptr; } // Print the tree graphically void print_tree(Node *n, std::string &indent, const bool &last) const { if (n != nullptr) { std::cout << indent; if (last) { std::cout << "R----"; indent += " "; } else { std::cout << "L----"; indent += "| "; } std::cout << n->key << std::endl; print_tree(n->left, indent, false); print_tree(n->right, indent, true); } } void print_inorder(Node *n) { if (n) { // Traverse left print_inorder(n->left); // Traverse root std::cout << n->key << " -> "; // Traverse right print_inorder(n->right); } } void get_elements(std::vector<std::pair<Key, Info>> &elements, Node *node) const { if (node) { get_elements(elements, node->left); elements.emplace_back(std::pair<Key, Info>(node->key, node->info)); get_elements(elements, node->right); } } public: AVLTree() { root = nullptr; size = 0; } AVLTree(const AVLTree &src) { *this = src; } ~AVLTree() { del(root); } AVLTree &operator=(const AVLTree &src) { if (this != &src) { clear(); copy(src.root); } return *this; } bool insert(const Key &key, const Info &info) { int s = size; root = insert(root, key, info); if (s == size) return false; return true; } Info &find(const Key &key) const { Node *n = find(root, key); if (n) return n->info; throw std::invalid_argument("Not found!"); } Info &operator[](const Key &key) { Node *n = find(root, key); if (n) return n->info; throw std::invalid_argument("Not found!"); } int count() { return size; } void clear() { del(root); root = nullptr; size = 0; } void print_tree() { print_tree(root); } void print_inorder() { print_inorder(root); } std::vector<std::pair<Key, Info>> get_elements() const { std::vector<std::pair<Key, Info>> elements; get_elements(elements, root); return elements; } }; AVLTree<std::string, int> &counter(const std::string &fileName) { AVLTree<std::string, int> *dict = new AVLTree<std::string, int>; std::ifstream file(fileName); std::string word; while (file >> word) { try { (*dict)[word]++; } catch (const std::invalid_argument &iv) { dict->insert(word, 1); } } file.close(); return *dict; } bool compare(std::pair<std::string, int> lhs, std::pair<std::string, int> rhs) { if (lhs.second == rhs.second) return lhs.first < rhs.first; return lhs.second < rhs.second; } void listing(const AVLTree<std::string, int> &src) { auto elements = src.get_elements(); std::sort(elements.begin(), elements.end(), compare); for (auto ele : elements) std::cout << ele.first << ": " << ele.second << "\n"; }
18.41195
82
0.523997
gch144
d7777457bca06068d235a8522f6f391f74e9c2ef
873
cpp
C++
Coursework 1/MultiThreading/MultiThreading/main.cpp
BarrySoap/Concurrent-Parallel-Systems
628b84c7a7a8ef01b5f58216e35e74f03d066d95
[ "MIT" ]
1
2018-11-05T15:05:02.000Z
2018-11-05T15:05:02.000Z
Coursework 1/MultiThreading/MultiThreading/main.cpp
BarrySoap/Concurrent-Parallel-Systems
628b84c7a7a8ef01b5f58216e35e74f03d066d95
[ "MIT" ]
null
null
null
Coursework 1/MultiThreading/MultiThreading/main.cpp
BarrySoap/Concurrent-Parallel-Systems
628b84c7a7a8ef01b5f58216e35e74f03d066d95
[ "MIT" ]
null
null
null
#include <chrono> #include <fstream> #include "block_chain.h" using namespace std; using namespace chrono; int main() { block_chain bchain; // Open a file in the root folder, bchain.results.open("MultiThreading.csv", ofstream::out); // And add the headings for average block time and difficulty. bchain.results << "Average Block Time" << "," << "Difficulty" << endl; // Cycle through multiple difficulties on one run, rather than repeated runs. for (uint32_t difficulty = 1; difficulty < 6; difficulty++) { auto start = system_clock::now(); for (uint32_t i = 1; i < 100u; ++i) { bchain.add_block(block(i, string("Block ") + to_string(i) + string(" Data")), difficulty); } auto end = system_clock::now(); duration<double> diff = end - start; bchain.results << diff.count() << "," << difficulty << endl; } bchain.results.close(); return 0; }
26.454545
93
0.672394
BarrySoap
d77d7a87c950369f5b31f1c9220c5f503a2af38d
1,797
hpp
C++
apps/router/api/assfire/router/api/RouteDetails.hpp
Eaglegor/assfire-suite
6c8140e848932b6ce22b6addd07a93abba652c01
[ "MIT" ]
null
null
null
apps/router/api/assfire/router/api/RouteDetails.hpp
Eaglegor/assfire-suite
6c8140e848932b6ce22b6addd07a93abba652c01
[ "MIT" ]
null
null
null
apps/router/api/assfire/router/api/RouteDetails.hpp
Eaglegor/assfire-suite
6c8140e848932b6ce22b6addd07a93abba652c01
[ "MIT" ]
null
null
null
#pragma once #include <utility> #include <vector> #include "assfire/concepts/Location.hpp" #include "RouteInfo.hpp" namespace assfire::router { class RouteDetails { public: using Waypoint = Location; using Waypoints = std::vector<Waypoint>; RouteDetails() : summary(RouteInfo::zero()) {} RouteDetails(const RouteInfo &summary, Waypoints waypoints) : summary(summary), waypoints(std::move(waypoints)) {} RouteDetails(const Distance& distance, const TimeInterval& time_interval, Waypoints waypoints) : summary(distance, time_interval), waypoints(std::move(waypoints)) {} RouteDetails(const RouteDetails &rhs) = default; const RouteInfo &getSummary() const { return summary; } const Distance& getDistance() const { return summary.getDistance(); } const TimeInterval& getDuration() const { return summary.getDuration(); } const Waypoints &getWaypoints() const { return waypoints; } bool isInfinity() const { return summary.isInfinity(); } bool isZero() const { return summary.isZero(); } static const RouteDetails zero(const Location& from, const Location& to) { return RouteDetails(RouteInfo::zero(), {from, to}); } static const RouteDetails infinity(const Location& from, const Location& to) { return RouteDetails(RouteInfo::infinity(), {from, to}); } private: RouteInfo summary; Waypoints waypoints; }; }
26.426471
86
0.554257
Eaglegor
d784cf0da031e7f68610edb83169de9c657102de
9,275
cpp
C++
src/gpre/pat.cpp
aafemt/firebird
6f5617524996a8ef6eb721cc782d7fa3513b7d3b
[ "Condor-1.1" ]
null
null
null
src/gpre/pat.cpp
aafemt/firebird
6f5617524996a8ef6eb721cc782d7fa3513b7d3b
[ "Condor-1.1" ]
null
null
null
src/gpre/pat.cpp
aafemt/firebird
6f5617524996a8ef6eb721cc782d7fa3513b7d3b
[ "Condor-1.1" ]
null
null
null
//____________________________________________________________ // // PROGRAM: Language Preprocessor // MODULE: pat.cpp // DESCRIPTION: Code generator pattern generator // // The contents of this file are subject to the Interbase Public // License Version 1.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.Inprise.com/IPL.html // // Software distributed under the License is distributed on an // "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express // or implied. See the License for the specific language governing // rights and limitations under the License. // // The Original Code was created by Inprise Corporation // and its predecessors. Portions created by Inprise Corporation are // Copyright (C) Inprise Corporation. // // All Rights Reserved. // Contributor(s): ______________________________________. // // //____________________________________________________________ // // #include "firebird.h" #include <stdio.h> #include <string.h> #include "../gpre/gpre.h" #include "../gpre/pat.h" #include "../gpre/gpre_proto.h" #include "../gpre/pat_proto.h" #include "../gpre/lang_proto.h" enum pat_t { NL, RH, RL, RT, RI, RS, // Request handle, level, transaction, ident, length DH, DF, // Database handle, filename TH, // Transaction handle BH, BI, // Blob handle, blob_ident FH, // Form handle V1, V2, // Status vectors I1, I2, // Identifier numbers RF, RE, // OS- and language-dependent REF and REF-end character VF, VE, // OS- and language-dependent VAL and VAL-end character S1, S2, S3, S4, S5, S6, S7, // Arbitrary strings N1, N2, N3, N4, // Arbitrary number (SSHORT) L1, L2, // Arbitrary number (SLONG) PN, PL, PI, // Port number, port length, port ident QN, QL, QI, // Second port number, port length, port ident IF, EL, EN, // If, else, end FR // Field reference }; static const struct ops { pat_t ops_type; TEXT ops_string[3]; } operators[] = { { RH, "RH" }, { RL, "RL" }, { RT, "RT" }, { RI, "RI" }, { RS, "RS" }, { DH, "DH" }, { DF, "DF" }, { TH, "TH" }, { BH, "BH" }, { BI, "BI" }, { FH, "FH" }, { V1, "V1" }, { V2, "V2" }, { I1, "I1" }, { I2, "I2" }, { S1, "S1" }, { S2, "S2" }, { S3, "S3" }, { S4, "S4" }, { S5, "S5" }, { S6, "S6" }, { S7, "S7" }, { N1, "N1" }, { N2, "N2" }, { N3, "N3" }, { N4, "N4" }, { L1, "L1" }, { L2, "L2" }, { PN, "PN" }, { PL, "PL" }, { PI, "PI" }, { QN, "QN" }, { QL, "QL" }, { QI, "QI" }, { IF, "IF" }, { EL, "EL" }, { EN, "EN" }, { RF, "RF" }, { RE, "RE" }, { VF, "VF" }, { VE, "VE" }, { FR, "FR" }, { NL, "" } }; //____________________________________________________________ // // Expand a pattern. // void PATTERN_expand( USHORT column, const TEXT* pattern, PAT* args) { // CVC: kudos to the programmer that had chosen variables with the same // names that structs in gpre.h and with type char* if not enough. // Renamed ref to lang_ref and val to lang_val. const TEXT* lang_ref = ""; const TEXT* refend = ""; const TEXT* lang_val = ""; const TEXT* valend = ""; if ((gpreGlob.sw_language == lang_c) || (isLangCpp(gpreGlob.sw_language))) { lang_ref = "&"; refend = ""; } else if (gpreGlob.sw_language == lang_pascal) { lang_ref = "%%REF "; refend = ""; } else if (gpreGlob.sw_language == lang_cobol) { lang_ref = "BY REFERENCE "; refend = ""; lang_val = "BY VALUE "; valend = ""; } else if (gpreGlob.sw_language == lang_fortran) { #if (defined AIX || defined AIX_PPC) lang_ref = "%REF("; refend = ")"; lang_val = "%VAL("; valend = ")"; #endif } TEXT buffer[512]; TEXT* p = buffer; *p++ = '\n'; bool sw_gen = true; for (USHORT n = column; n; --n) *p++ = ' '; SSHORT value; // value needs to be signed since some of the // values printed out are signed. SLONG long_value; TEXT c; while (c = *pattern++) { if (c != '%') { if (sw_gen) { *p++ = c; if ((c == '\n') && (*pattern)) for (USHORT n = column; n; --n) *p++ = ' '; } continue; } bool sw_ident = false; const TEXT* string = NULL; const ref* reference = NULL; bool handle_flag = false, long_flag = false; const ops* oper_iter; for (oper_iter = operators; oper_iter->ops_type != NL; oper_iter++) { if (oper_iter->ops_string[0] == pattern[0] && oper_iter->ops_string[1] == pattern[1]) { break; } } pattern += 2; switch (oper_iter->ops_type) { case IF: sw_gen = args->pat_condition; continue; case EL: sw_gen = !sw_gen; continue; case EN: sw_gen = true; continue; case RH: handle_flag = true; string = args->pat_request->req_handle; break; case RL: string = args->pat_request->req_request_level; break; case RS: value = args->pat_request->req_length; break; case RT: handle_flag = true; string = args->pat_request->req_trans; break; case RI: long_value = args->pat_request->req_ident; long_flag = true; sw_ident = true; break; case DH: handle_flag = true; string = args->pat_database->dbb_name->sym_string; break; case DF: string = args->pat_database->dbb_filename; break; case PN: value = args->pat_port->por_msg_number; break; case PL: value = args->pat_port->por_length; break; case PI: long_value = args->pat_port->por_ident; long_flag = true; sw_ident = true; break; case QN: value = args->pat_port2->por_msg_number; break; case QL: value = args->pat_port2->por_length; break; case QI: long_value = args->pat_port2->por_ident; long_flag = true; sw_ident = true; break; case BH: long_value = args->pat_blob->blb_ident; long_flag = true; sw_ident = true; break; case I1: long_value = args->pat_ident1; long_flag = true; sw_ident = true; break; case I2: long_value = args->pat_ident2; long_flag = true; sw_ident = true; break; case S1: string = args->pat_string1; break; case S2: string = args->pat_string2; break; case S3: string = args->pat_string3; break; case S4: string = args->pat_string4; break; case S5: string = args->pat_string5; break; case S6: string = args->pat_string6; break; case S7: string = args->pat_string7; break; case V1: string = args->pat_vector1; break; case V2: string = args->pat_vector2; break; case N1: value = args->pat_value1; break; case N2: value = args->pat_value2; break; case N3: value = args->pat_value3; break; case N4: value = args->pat_value4; break; case L1: long_value = args->pat_long1; long_flag = true; break; case L2: long_value = args->pat_long2; long_flag = true; break; case RF: string = lang_ref; break; case RE: string = refend; break; case VF: string = lang_val; break; case VE: string = valend; break; case FR: reference = args->pat_reference; break; default: sprintf(buffer, "Unknown substitution \"%c%c\"", pattern[-2], pattern[-1]); CPR_error(buffer); continue; } if (!sw_gen) continue; if (string) { #ifdef GPRE_ADA if (handle_flag && (gpreGlob.sw_language == lang_ada)) { for (const TEXT* q = gpreGlob.ada_package; *q;) *p++ = *q++; } #endif while (*string) *p++ = *string++; continue; } if (sw_ident) { if (long_flag) sprintf(p, gpreGlob.long_ident_pattern, long_value); else sprintf(p, gpreGlob.ident_pattern, value); } else if (reference) { if (!reference->ref_port) sprintf(p, gpreGlob.ident_pattern, reference->ref_ident); else { TEXT temp1[16], temp2[16]; sprintf(temp1, gpreGlob.ident_pattern, reference->ref_port->por_ident); sprintf(temp2, gpreGlob.ident_pattern, reference->ref_ident); switch (gpreGlob.sw_language) { case lang_fortran: case lang_cobol: strcpy(p, temp2); break; default: sprintf(p, "%s.%s", temp1, temp2); } } } else if (long_flag) { sprintf(p, "%" SLONGFORMAT, long_value); } else { sprintf(p, "%d", value); } while (*p) p++; } *p = 0; #if (defined GPRE_ADA || defined GPRE_COBOL || defined GPRE_FORTRAN) switch (gpreGlob.sw_language) { #ifdef GPRE_ADA // Ada lines can be up to 120 characters long. ADA_print_buffer // handles this problem and ensures that GPRE output is <=120 characters. case lang_ada: ADA_print_buffer(buffer, 0); break; #endif #ifdef GPRE_COBOL // COBOL lines can be up to 72 characters long. COB_print_buffer // handles this problem and ensures that GPRE output is <= 72 characters. case lang_cobol: COB_print_buffer(buffer, true); break; #endif #ifdef GPRE_FORTRAN // In FORTRAN, characters beyond column 72 are ignored. FTN_print_buffer // handles this problem and ensures that GPRE output does not exceed this // limit. case lang_fortran: FTN_print_buffer(buffer); break; #endif default: fprintf(gpreGlob.out_file, "%s", buffer); break; } #else fprintf(gpreGlob.out_file, "%s", buffer); #endif }
19.734043
88
0.612183
aafemt
d78cf77ec801ae1619175bab3bcd12fd09dade2a
10,541
cc
C++
xtcdata/xtcdata/app/amiwriter.cc
AntoineDujardin/lcls2
8b9d2815497fbbabb4d37800fd86a7be1728b552
[ "BSD-3-Clause-LBNL" ]
null
null
null
xtcdata/xtcdata/app/amiwriter.cc
AntoineDujardin/lcls2
8b9d2815497fbbabb4d37800fd86a7be1728b552
[ "BSD-3-Clause-LBNL" ]
null
null
null
xtcdata/xtcdata/app/amiwriter.cc
AntoineDujardin/lcls2
8b9d2815497fbbabb4d37800fd86a7be1728b552
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "xtcdata/xtc/DescData.hh" #include "xtcdata/xtc/Dgram.hh" #include "xtcdata/xtc/VarDef.hh" #include "xtcdata/xtc/NamesLookup.hh" #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> #include <stdint.h> #include <sys/time.h> using namespace XtcData; #define BUFSIZE 0x4000000 class ConfigDef: public VarDef { public: enum index { configIndex }; ConfigDef() {NameVec.push_back({"fakeValue",Name::CHARSTR,1});} } ConfigDef; class LaserDef: public VarDef { public: enum index { laserIndex }; LaserDef() {NameVec.push_back({"laserOn",Name::UINT32});} } LaserDef; class EBeamDef: public VarDef { public: enum index { ebeamIndex }; EBeamDef() {NameVec.push_back({"energy",Name::FLOAT});} } EBeamDef; class HsdDef: public VarDef { public: enum index { hsdIndex }; HsdDef() {NameVec.push_back({"waveform",Name::UINT16,1});} } HsdDef; class CspadDef: public VarDef { public: enum index { cspadIndex }; CspadDef() {NameVec.push_back({"arrayRaw",Name::UINT16,2});} } CspadDef; void addCspad(Xtc& parent, NamesLookup& namesLookup, NamesId& namesId, unsigned value) { CreateData fex(parent, namesLookup, namesId); unsigned shape[MaxRank] = {50,100}; Array<uint16_t> arrayT = fex.allocate<uint16_t>(CspadDef::cspadIndex,shape); unsigned factors[4]; for (unsigned k=0; k<4; k++) factors[k] = (value + k) % 4; for(unsigned i=0; i<shape[0]; i++){ for (unsigned j=0; j<shape[1]; j++) { if (i < shape[0] / 2) { if (j < shape[1] / 2) arrayT(i,j) = value * factors[0]; else arrayT(i,j) = value * factors[1]; } else { if (j < shape[1] / 2) arrayT(i,j) = value * factors[2]; else arrayT(i,j) = value * factors[3]; } } }; } void addConfig(Xtc& parent, NamesLookup& namesLookup, NamesId& namesId, const char* value) { CreateData config(parent, namesLookup, namesId); config.set_string(ConfigDef::configIndex, value); } void addLaser(Xtc& parent, NamesLookup& namesLookup, NamesId& namesId, unsigned value) { CreateData fex(parent, namesLookup, namesId); fex.set_value(LaserDef::laserIndex, (uint32_t)value); } void addEBeam(Xtc& parent, NamesLookup& namesLookup, NamesId& namesId, float value) { CreateData fex(parent, namesLookup, namesId); fex.set_value(EBeamDef::ebeamIndex, value); } void addHsd(Xtc& parent, NamesLookup& namesLookup, NamesId& namesId, unsigned value) { CreateData fex(parent, namesLookup, namesId); unsigned shape[MaxRank] = {50}; Array<uint16_t> arrayT = fex.allocate<uint16_t>(HsdDef::hsdIndex,shape); for(unsigned i=0; i<shape[0]; i++){ arrayT(i) = value; }; } void addCspadNames(Xtc& xtc, NamesLookup& namesLookup, NamesId& namesId, unsigned segment) { Alg cspadAlg("raw",2,3,42); Names& cspadNames = *new(xtc) Names("xppcspad", cspadAlg, "cspad", "serialnum1234", namesId, segment); cspadNames.add(xtc, CspadDef); namesLookup[namesId] = NameIndex(cspadNames); } void addCspadConfigNames(Xtc& xtc, NamesLookup& namesLookup, NamesId& namesId, unsigned segment) { Alg cspadAlg("fakeConfig",0,0,1); Names& cspadNames = *new(xtc) Names("xppcspad", cspadAlg, "cspad", "serialnum1234", namesId, segment); cspadNames.add(xtc, ConfigDef); namesLookup[namesId] = NameIndex(cspadNames); } void addLaserNames(Xtc& xtc, NamesLookup& namesLookup, NamesId& namesId) { Alg laserAlg("raw",2,3,42); Names& laserNames = *new(xtc) Names("xpplaser", laserAlg, "laser", "serialnum1234", namesId, 0); laserNames.add(xtc, LaserDef); namesLookup[namesId] = NameIndex(laserNames); } void addLaserConfigNames(Xtc& xtc, NamesLookup& namesLookup, NamesId& namesId) { Alg laserAlg("fakeConfig",0,0,1); Names& laserNames = *new(xtc) Names("xpplaser", laserAlg, "laser", "serialnum1234", namesId, 0); laserNames.add(xtc, ConfigDef); namesLookup[namesId] = NameIndex(laserNames); } void addEBeamNames(Xtc& xtc, NamesLookup& namesLookup, NamesId& namesId) { Alg ebeamAlg("raw",2,3,42); Names& ebeamNames = *new(xtc) Names("EBeam", ebeamAlg, "ebeam", "serialnum1234", namesId, 0); ebeamNames.add(xtc, EBeamDef); namesLookup[namesId] = NameIndex(ebeamNames); } void addEBeamConfigNames(Xtc& xtc, NamesLookup& namesLookup, NamesId& namesId) { Alg ebeamAlg("fakeConfig",0,0,1); Names& ebeamNames = *new(xtc) Names("EBeam", ebeamAlg, "ebeam", "serialnum1234", namesId, 0); ebeamNames.add(xtc, ConfigDef); namesLookup[namesId] = NameIndex(ebeamNames); } void addHsdNames(Xtc& xtc, NamesLookup& namesLookup, NamesId& namesId) { Alg hsdAlg("raw",2,3,42); Names& hsdNames = *new(xtc) Names("xpphsd", hsdAlg, "hsd", "serialnum1234", namesId, 0); hsdNames.add(xtc, HsdDef); namesLookup[namesId] = NameIndex(hsdNames); } void addHsdConfigNames(Xtc& xtc, NamesLookup& namesLookup, NamesId& namesId) { Alg hsdAlg("fakeConfig",0,0,1); Names& hsdNames = *new(xtc) Names("xpphsd", hsdAlg, "hsd", "serialnum1234", namesId, 0); hsdNames.add(xtc, ConfigDef); namesLookup[namesId] = NameIndex(hsdNames); } void usage(char* progname) { fprintf(stderr, "Usage: %s [-f <filename> -n <numEvents> -t -h]\n", progname); } Dgram& createTransition(TransitionId::Value transId, bool counting_timestamps, unsigned& timestamp_val) { TypeId tid(TypeId::Parent, 0); uint64_t pulseId = 0; uint32_t env = 0; struct timeval tv; void* buf = malloc(BUFSIZE); if (counting_timestamps) { tv.tv_sec = 0; tv.tv_usec = timestamp_val; timestamp_val++; } else { gettimeofday(&tv, NULL); // convert to ns for the Timestamp tv.tv_usec *= 1000; } Sequence seq(Sequence::Event, transId, TimeStamp(tv.tv_sec, tv.tv_usec), PulseId(pulseId,0)); return *new(buf) Dgram(Transition(seq, env), Xtc(tid)); } void save(Dgram& dg, FILE* xtcFile) { if (fwrite(&dg, sizeof(dg) + dg.xtc.sizeofPayload(), 1, xtcFile) != 1) { printf("Error writing to output xtc file.\n"); } } #define MAX_FNAME_LEN 256 int main(int argc, char* argv[]) { int c; int parseErr = 0; unsigned nevents = 2; char xtcname[MAX_FNAME_LEN]; strncpy(xtcname, "ami.xtc2", MAX_FNAME_LEN); unsigned starting_segment = 0; // this is used to create uniform timestamps across files // so we can do offline event-building. bool counting_timestamps = false; bool add_fake_configs = false; while ((c = getopt(argc, argv, "hf:n:s:tc")) != -1) { switch (c) { case 'h': usage(argv[0]); exit(0); case 'n': nevents = atoi(optarg); break; case 'f': strncpy(xtcname, optarg, MAX_FNAME_LEN); break; case 's': starting_segment = atoi(optarg); break; case 't': counting_timestamps = true; break; case 'c': add_fake_configs = true; break; default: parseErr++; } } FILE* xtcFile = fopen(xtcname, "w"); if (!xtcFile) { printf("Error opening output xtc file.\n"); return -1; } struct timeval tv; TypeId tid(TypeId::Parent, 0); uint32_t env = 0; uint64_t pulseId = 0; unsigned timestamp_val = 0; Dgram& config = createTransition(TransitionId::Configure, counting_timestamps, timestamp_val); unsigned nodeId = 1; NamesLookup namesLookup; unsigned nSegments=2; unsigned segmentIndex = starting_segment; NamesId namesIdCspad[] = {NamesId(nodeId,segmentIndex++), NamesId(nodeId,segmentIndex++)}; for (unsigned iseg=0; iseg<nSegments; iseg++) { addCspadNames(config.xtc, namesLookup, namesIdCspad[iseg], iseg); } NamesId namesIdLaser(nodeId,segmentIndex++); addLaserNames(config.xtc, namesLookup, namesIdLaser); NamesId namesIdEBeam(nodeId,segmentIndex++); addEBeamNames(config.xtc, namesLookup, namesIdEBeam); NamesId namesIdHsd(nodeId,segmentIndex++); addHsdNames(config.xtc, namesLookup, namesIdHsd); if (add_fake_configs) { NamesId namesIdCspadConfig[] = {NamesId(nodeId,segmentIndex++), NamesId(nodeId,segmentIndex++)}; for (unsigned iseg=0; iseg<nSegments; iseg++) { addCspadConfigNames(config.xtc, namesLookup, namesIdCspadConfig[iseg], iseg); addConfig(config.xtc, namesLookup, namesIdCspadConfig[iseg], "I am a cspad!"); } NamesId namesIdLaserConfig(nodeId,segmentIndex++); addLaserConfigNames(config.xtc, namesLookup, namesIdLaserConfig); addConfig(config.xtc, namesLookup, namesIdLaserConfig, "I am a laser!"); NamesId namesIdEBeamConfig(nodeId,segmentIndex++); addEBeamConfigNames(config.xtc, namesLookup, namesIdEBeamConfig); addConfig(config.xtc, namesLookup, namesIdEBeamConfig, "I am an ebeam!"); NamesId namesIdHsdConfig(nodeId,segmentIndex++); addHsdConfigNames(config.xtc, namesLookup, namesIdHsdConfig); addConfig(config.xtc, namesLookup, namesIdHsdConfig, "I am an hsd!"); } save(config,xtcFile); void* buf = malloc(BUFSIZE); for (int i = 0; i < nevents; i++) { if (counting_timestamps) { tv.tv_sec = 0; tv.tv_usec = timestamp_val; timestamp_val++; } else { gettimeofday(&tv, NULL); // convert to ns for the Timestamp tv.tv_usec *= 1000; } Sequence seq(Sequence::Event, TransitionId::L1Accept, TimeStamp(tv.tv_sec, tv.tv_usec), PulseId(pulseId,0)); Dgram& dgram = *new(buf) Dgram(Transition(seq, env), Xtc(tid)); for (unsigned iseg=0; iseg<nSegments; iseg++) { addCspad(dgram.xtc, namesLookup, namesIdCspad[iseg], i); } addLaser(dgram.xtc, namesLookup, namesIdLaser, i%2); addEBeam(dgram.xtc, namesLookup, namesIdEBeam, (float)i); if (i%2==0) { addHsd(dgram.xtc, namesLookup, namesIdHsd, i); } save(dgram,xtcFile); } fclose(xtcFile); return 0; }
32.838006
116
0.625652
AntoineDujardin
d78d273df487de6baa7bd73cebfb9d65870e363c
2,317
cpp
C++
test/BytesTest.cpp
TheOsch2/boolinq
5464cf801b046026e8d32cb37d9985fd672a34ec
[ "MIT" ]
473
2015-01-03T03:58:48.000Z
2022-03-18T19:27:09.000Z
test/BytesTest.cpp
TheOsch2/boolinq
5464cf801b046026e8d32cb37d9985fd672a34ec
[ "MIT" ]
58
2015-01-13T14:43:35.000Z
2022-03-02T16:48:55.000Z
test/BytesTest.cpp
TheOsch2/boolinq
5464cf801b046026e8d32cb37d9985fd672a34ec
[ "MIT" ]
71
2015-02-17T20:30:50.000Z
2022-03-21T00:56:54.000Z
#include <vector> #include <string> #include <gtest/gtest.h> #include "CommonTests.h" #include "boolinq.h" using namespace boolinq; ////////////////////////////////////////////////////////////////////////// TEST(Bytes, OneByteDefault) { unsigned char src[] = {0xAA}; int ans[] = {0xAA}; auto rng = from(src); auto dst = rng.bytes(); CheckRangeEqArray(dst, ans); } TEST(Bytes, OneByteFL) { unsigned char src[] = {0xAA}; int ans[] = {0xAA}; auto rng = from(src); auto dst = rng.bytes(BytesFirstToLast); CheckRangeEqArray(dst, ans); } TEST(Bytes, OneByteLF) { unsigned char src[] = {0xAA}; int ans[] = {0xAA}; auto rng = from(src); auto dst = rng.bytes(BytesLastToFirst); CheckRangeEqArray(dst, ans); } ////////////////////////////////////////////////////////////////////////// TEST(Bytes, OneIntDefault) { int src[] = {0x12345678}; int ans[] = {0x78,0x56,0x34,0x12}; auto rng = from(src); auto dst = rng.bytes(); CheckRangeEqArray(dst, ans); } TEST(Bytes, OneIntFL) { int src[] = {0x12345678}; int ans[] = {0x78,0x56,0x34,0x12}; auto rng = from(src); auto dst = rng.bytes(BytesFirstToLast); CheckRangeEqArray(dst, ans); } TEST(Bytes, OneIntLF) { int src[] = {0x12345678}; int ans[] = {0x12,0x34,0x56,0x78}; auto rng = from(src); auto dst = rng.bytes(BytesLastToFirst); CheckRangeEqArray(dst, ans); } ////////////////////////////////////////////////////////////////////////// TEST(Bytes, IntsDefault) { unsigned src[] = {0x12345678, 0xAABBCCDD}; int ans[] = { 0x78,0x56,0x34,0x12, 0xDD,0xCC,0xBB,0xAA, }; auto rng = from(src); auto dst = rng.bytes(BytesFirstToLast); CheckRangeEqArray(dst, ans); } TEST(Bytes, IntsFL) { unsigned src[] = {0x12345678, 0xAABBCCDD}; int ans[] = { 0x78,0x56,0x34,0x12, 0xDD,0xCC,0xBB,0xAA, }; auto rng = from(src); auto dst = rng.bytes(BytesFirstToLast); CheckRangeEqArray(dst, ans); } TEST(Bytes, IntsLF) { unsigned src[] = {0x12345678, 0xAABBCCDD}; int ans[] = { 0x12,0x34,0x56,0x78, 0xAA,0xBB,0xCC,0xDD, }; auto rng = from(src); auto dst = rng.bytes(BytesLastToFirst); CheckRangeEqArray(dst, ans); }
18.244094
74
0.540354
TheOsch2
d78eadf35b3641381ed81b8e9eb92a3a5f3153e8
1,607
cpp
C++
test/metafunctions.cpp
GuapoTaco/Modular-ECS
479114936eba14fa701787d67de147c19bd6ce04
[ "MIT" ]
null
null
null
test/metafunctions.cpp
GuapoTaco/Modular-ECS
479114936eba14fa701787d67de147c19bd6ce04
[ "MIT" ]
null
null
null
test/metafunctions.cpp
GuapoTaco/Modular-ECS
479114936eba14fa701787d67de147c19bd6ce04
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include <ecs/manager.hpp> #define GET_HANA_CONSTANT_VALUE(name) ::std::decay_t<decltype(name)>::value using namespace ecs; BOOST_AUTO_TEST_CASE(get_index_of_first_matching_test) { auto tup = make_type_tuple<int, char, double>; BOOST_TEST( GET_HANA_CONSTANT_VALUE(get_index_of_first_matching(tup, boost::hana::type_c<int>)) == 0); BOOST_TEST( GET_HANA_CONSTANT_VALUE(get_index_of_first_matching(tup, boost::hana::type_c<char>)) == 1); BOOST_TEST(GET_HANA_CONSTANT_VALUE( get_index_of_first_matching(tup, boost::hana::type_c<double>)) == 2); } BOOST_AUTO_TEST_CASE(remove_dups_test1) { auto tup = make_type_tuple<int, int, char, char, double, int>; auto removed = remove_dups(tup); BOOST_TEST(GET_HANA_CONSTANT_VALUE(boost::hana::contains(removed, boost::hana::type_c<int>))); BOOST_TEST(GET_HANA_CONSTANT_VALUE(boost::hana::contains(removed, boost::hana::type_c<char>))); BOOST_TEST( GET_HANA_CONSTANT_VALUE(boost::hana::contains(removed, boost::hana::type_c<double>))); BOOST_TEST(GET_HANA_CONSTANT_VALUE(boost::hana::size(removed)) == 3); } BOOST_AUTO_TEST_CASE(remove_dups_test2) { auto tup = make_type_tuple<int, char, double>; auto removed = remove_dups(tup); BOOST_TEST(GET_HANA_CONSTANT_VALUE(boost::hana::contains(removed, boost::hana::type_c<int>))); BOOST_TEST(GET_HANA_CONSTANT_VALUE(boost::hana::contains(removed, boost::hana::type_c<char>))); BOOST_TEST( GET_HANA_CONSTANT_VALUE(boost::hana::contains(removed, boost::hana::type_c<double>))); BOOST_TEST(GET_HANA_CONSTANT_VALUE(boost::hana::size(removed)) == 3); }
33.479167
96
0.766646
GuapoTaco
d78f71aee3d4008daa43d9d4e16c196dd271b699
3,212
cpp
C++
11. DP 2/Practice/4_Square_brackets.cpp
bhavinvirani/Competitive-Programming-coding-ninjas
5e50ae7ad3fc969a4970f91f8d895c986353bb71
[ "MIT" ]
null
null
null
11. DP 2/Practice/4_Square_brackets.cpp
bhavinvirani/Competitive-Programming-coding-ninjas
5e50ae7ad3fc969a4970f91f8d895c986353bb71
[ "MIT" ]
null
null
null
11. DP 2/Practice/4_Square_brackets.cpp
bhavinvirani/Competitive-Programming-coding-ninjas
5e50ae7ad3fc969a4970f91f8d895c986353bb71
[ "MIT" ]
null
null
null
/* Square Brackets Send Feedback You are given: a positive integer n, an integer k, 1<=k<=n, an increasing sequence of k integers 0 < s1 < s2 < ... < sk <= 2n. What is the number of proper bracket expressions of length 2n with opening brackets appearing in positions s1, s2,...,sk? Illustration Several proper bracket expressions: [[]][[[]][]] [[[][]]][][[]] An improper bracket expression: [[[][]]][]][[]] There is exactly one proper expression of length 8 with opening brackets in positions 2, 5 and 7. Task Write a program which for each data set from a sequence of several data sets: 1. reads integers n, k and an increasing sequence of k integers from input, 2. computes the number of proper bracket expressions of length 2n with opening brackets appearing at positions s1,s2,...,sk, 3. writes the result to output. Note: since result can be pretty large output the answer % mod (10^9 + 7). Input Format: The first line of the input file contains one integer T(number of test cases), each test case follows as. The first line contains two integers n and k separated by single space. The second line contains an increasing sequence of k integers from the interval [1;2n] separated by single spaces. Output Format: For each test case print the number of balanced square bracket sequence % mod (10^9 + 7), that can be formed using the above rules in a new line. Constraints: 1 <= T <= 100 1 <= N <= 100 1 <= K <= N Sample Input 5 1 1 1 1 1 2 2 1 1 3 1 2 4 2 5 7 Sample Output 1 0 2 3 2 */ #include <bits/stdc++.h> using namespace std; int m=pow(10,9)+7; int solve(int o, int c, int n, bool check[], int **dp) { //* imbalance brackets if (o > n || c > n) return 0; //* no more brackets if (o == n && c == n) return 1; //* empty string possible //* work already done if (dp[o][c] != -1) { return dp[o][c]; } //? three possible cases /* 1. can put only opning bracket //* ki == true, o == c(alredy balanced brackets) 2. can put only closing bracket //* opning brackets are over 3. can put both opening and closing bracket //* */ int ans; if (o == c || check[o + c]) { ans = solve(o + 1, c, n, check, dp)%m; } else if (o == n) { ans = solve(o, c + 1, n, check, dp)%m; } else { int op1 = solve(o + 1, c, n, check, dp)%m; int op2 = solve(o, c + 1, n, check, dp)%m; ans = (op1 + op2)%m; } dp[o][c] = ans; return ans; } int main() { // freopen("/home/spy/Desktop/input.txt", "r", stdin); // freopen("/home/spy/Desktop/output.txt", "w", stdout); int t; cin >> t; while (t--) { int n, k; cin >> n >> k; int arr[k]; bool check[2 * n] = {false}; for (int i = 0; i < k; i++) { cin >> arr[i]; check[arr[i] - 1] = true; } int **dp = new int *[n + 1]; for (int i = 0; i <= n; i++) { dp[i] = new int[n + 1]; for (int j = 0; j <= n; j++) { dp[i][j] = -1; } } cout << solve(0, 0, n, check, dp) << endl; } return 0; }
25.291339
146
0.562578
bhavinvirani
d79317ca2c74ce53b6fd74b8d6a2b56ca19e0b1b
13,880
cpp
C++
src/VK/PostProc/BlurPS.cpp
whatevermarch/Cauldron
b3a4f62bf79034240b979d575e67ee51790ab435
[ "MIT" ]
1
2021-10-13T06:15:46.000Z
2021-10-13T06:15:46.000Z
src/VK/PostProc/BlurPS.cpp
whatevermarch/Cauldron
b3a4f62bf79034240b979d575e67ee51790ab435
[ "MIT" ]
null
null
null
src/VK/PostProc/BlurPS.cpp
whatevermarch/Cauldron
b3a4f62bf79034240b979d575e67ee51790ab435
[ "MIT" ]
null
null
null
// AMD Cauldron code // // Copyright(c) 2018 Advanced Micro Devices, Inc.All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "stdafx.h" #include "Base/DynamicBufferRing.h" #include "Base/StaticBufferPool.h" #include "Base/ExtDebugMarkers.h" #include "Base/UploadHeap.h" #include "Base/Texture.h" #include "Base/Helper.h" #include "PostProcPS.h" #include "BlurPS.h" namespace CAULDRON_VK { void BlurPS::OnCreate( Device* pDevice, ResourceViewHeaps *pResourceViewHeaps, DynamicBufferRing *pConstantBufferRing, StaticBufferPool *pStaticBufferPool, VkFormat format ) { m_pDevice = pDevice; m_pResourceViewHeaps = pResourceViewHeaps; m_pConstantBufferRing = pConstantBufferRing; m_outFormat = format; // Create Descriptor Set Layout, the shader needs a uniform dynamic buffer and a texture + sampler // The Descriptor Sets will be created and initialized once we know the input to the shader, that happens in OnCreateWindowSizeDependentResources() { std::vector<VkDescriptorSetLayoutBinding> layoutBindings(2); layoutBindings[0].binding = 0; layoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; layoutBindings[0].descriptorCount = 1; layoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; layoutBindings[0].pImmutableSamplers = NULL; layoutBindings[1].binding = 1; layoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; layoutBindings[1].descriptorCount = 1; layoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; layoutBindings[1].pImmutableSamplers = NULL; VkDescriptorSetLayoutCreateInfo descriptor_layout = {}; descriptor_layout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptor_layout.pNext = NULL; descriptor_layout.bindingCount = (uint32_t)layoutBindings.size(); descriptor_layout.pBindings = layoutBindings.data(); VkResult res = vkCreateDescriptorSetLayout(pDevice->GetDevice(), &descriptor_layout, NULL, &m_descriptorSetLayout); assert(res == VK_SUCCESS); } // Create a Render pass that will discard the contents of the render target. // m_in = SimpleColorWriteRenderPass(pDevice->GetDevice(), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // The sampler we want to use for downsampling, all linear // { VkSamplerCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; info.magFilter = VK_FILTER_LINEAR; info.minFilter = VK_FILTER_LINEAR; info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; info.minLod = -1000; info.maxLod = 1000; info.maxAnisotropy = 1.0f; VkResult res = vkCreateSampler(pDevice->GetDevice(), &info, NULL, &m_sampler); assert(res == VK_SUCCESS); } // Use helper class to create the fullscreen pass // m_directionalBlur.OnCreate(pDevice, m_in, "blur.glsl", "main", "", pStaticBufferPool, pConstantBufferRing, m_descriptorSetLayout); // Allocate descriptors for the mip chain // for (int i = 0; i < BLURPS_MAX_MIP_LEVELS; i++) { // Horizontal pass // m_pResourceViewHeaps->AllocDescriptor(m_descriptorSetLayout, &m_horizontalMip[i].m_descriptorSet); // Vertical pass // m_pResourceViewHeaps->AllocDescriptor(m_descriptorSetLayout, &m_verticalMip[i].m_descriptorSet); } } void BlurPS::OnCreateWindowSizeDependentResources(Device* pDevice, uint32_t Width, uint32_t Height, Texture *pInput, int mipCount) { m_Width = Width; m_Height = Height; m_mipCount = mipCount; // Create a temporary texture to hold the horizontal pass (only now we know the size of the render target we want to downsample, hence we create the temporary render target here) // VkImageCreateInfo image_info = {}; image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.pNext = NULL; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.format = m_outFormat; image_info.extent.width = m_Width; image_info.extent.height = m_Height; image_info.extent.depth = 1; image_info.mipLevels = mipCount; image_info.arrayLayers = 1; image_info.samples = VK_SAMPLE_COUNT_1_BIT; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_info.queueFamilyIndexCount = 0; image_info.pQueueFamilyIndices = NULL; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.usage = (VkImageUsageFlags)(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); //TODO image_info.flags = 0; image_info.tiling = VK_IMAGE_TILING_OPTIMAL; // VK_IMAGE_TILING_LINEAR should never be used and will never be faster m_tempBlur.Init(m_pDevice, &image_info, "BlurHorizontal"); // Create framebuffers and views for the mip chain // for (int i = 0; i < m_mipCount; i++) { // Horizontal pass, from pInput to m_tempBlur // { pInput->CreateSRV(&m_horizontalMip[i].m_SRV, i); // source (pInput) m_tempBlur.CreateRTV(&m_horizontalMip[i].m_RTV, i); // target (m_tempBlur) // Create framebuffer for target // { VkImageView attachments[1] = { m_horizontalMip[i].m_RTV }; VkFramebufferCreateInfo fb_info = {}; fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; fb_info.pNext = NULL; fb_info.renderPass = m_in; fb_info.attachmentCount = 1; fb_info.pAttachments = attachments; fb_info.width = Width >> i; fb_info.height = Height >> i; fb_info.layers = 1; VkResult res = vkCreateFramebuffer(m_pDevice->GetDevice(), &fb_info, NULL, &m_horizontalMip[i].m_frameBuffer); assert(res == VK_SUCCESS); } // Create Descriptor sets (all of them use the same Descriptor Layout) m_pConstantBufferRing->SetDescriptorSet(0, sizeof(BlurPS::cbBlur), m_horizontalMip[i].m_descriptorSet); SetDescriptorSet(m_pDevice->GetDevice(), 1, m_horizontalMip[i].m_SRV, &m_sampler, m_horizontalMip[i].m_descriptorSet); } // Vertical pass, from m_tempBlur back to pInput // { m_tempBlur.CreateSRV(&m_verticalMip[i].m_SRV, i); // source (pInput)(m_tempBlur) pInput->CreateRTV(&m_verticalMip[i].m_RTV, i); // target (pInput) { VkImageView attachments[1] = { m_verticalMip[i].m_RTV }; VkFramebufferCreateInfo fb_info = {}; fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; fb_info.pNext = NULL; fb_info.renderPass = m_in; fb_info.attachmentCount = 1; fb_info.pAttachments = attachments; fb_info.width = Width >> i; fb_info.height = Height >> i; fb_info.layers = 1; VkResult res = vkCreateFramebuffer(m_pDevice->GetDevice(), &fb_info, NULL, &m_verticalMip[i].m_frameBuffer); assert(res == VK_SUCCESS); } // create and update descriptor m_pConstantBufferRing->SetDescriptorSet(0, sizeof(BlurPS::cbBlur), m_verticalMip[i].m_descriptorSet); SetDescriptorSet(m_pDevice->GetDevice(), 1, m_verticalMip[i].m_SRV, &m_sampler, m_verticalMip[i].m_descriptorSet); } } } void BlurPS::OnDestroyWindowSizeDependentResources() { // destroy views and framebuffers of the vertical and horizontal passes // for (int i = 0; i < m_mipCount; i++) { vkDestroyImageView(m_pDevice->GetDevice(), m_horizontalMip[i].m_SRV, NULL); vkDestroyImageView(m_pDevice->GetDevice(), m_horizontalMip[i].m_RTV, NULL); vkDestroyFramebuffer(m_pDevice->GetDevice(), m_horizontalMip[i].m_frameBuffer, NULL); vkDestroyImageView(m_pDevice->GetDevice(), m_verticalMip[i].m_SRV, NULL); vkDestroyImageView(m_pDevice->GetDevice(), m_verticalMip[i].m_RTV, NULL); vkDestroyFramebuffer(m_pDevice->GetDevice(), m_verticalMip[i].m_frameBuffer, NULL); } // Destroy temporary render target used to hold the horizontal pass // m_tempBlur.OnDestroy(); } void BlurPS::OnDestroy() { // destroy views for (int i = 0; i < BLURPS_MAX_MIP_LEVELS; i++) { m_pResourceViewHeaps->FreeDescriptor(m_horizontalMip[i].m_descriptorSet); m_pResourceViewHeaps->FreeDescriptor(m_verticalMip[i].m_descriptorSet); } m_directionalBlur.OnDestroy(); vkDestroyDescriptorSetLayout(m_pDevice->GetDevice(), m_descriptorSetLayout, NULL); vkDestroySampler(m_pDevice->GetDevice(), m_sampler, nullptr); vkDestroyRenderPass(m_pDevice->GetDevice(), m_in, NULL); } void BlurPS::Draw(VkCommandBuffer cmd_buf, int mipLevel) { SetPerfMarkerBegin(cmd_buf, "blur"); SetViewportAndScissor(cmd_buf, 0, 0, m_Width >> mipLevel, m_Height >> mipLevel); // horizontal pass // { VkRenderPassBeginInfo rp_begin = {}; rp_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; rp_begin.pNext = NULL; rp_begin.renderPass = m_in; rp_begin.framebuffer = m_horizontalMip[mipLevel].m_frameBuffer; rp_begin.renderArea.offset.x = 0; rp_begin.renderArea.offset.y = 0; rp_begin.renderArea.extent.width = m_Width >> mipLevel; rp_begin.renderArea.extent.height = m_Height >> mipLevel; rp_begin.clearValueCount = 0; rp_begin.pClearValues = NULL; vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); BlurPS::cbBlur *data; VkDescriptorBufferInfo constantBuffer; m_pConstantBufferRing->AllocConstantBuffer(sizeof(BlurPS::cbBlur), (void **)&data, &constantBuffer); data->dirX = 1.0f / (float)(m_Width >> mipLevel); data->dirY = 0.0f / (float)(m_Height >> mipLevel); data->mipLevel = mipLevel; m_directionalBlur.Draw(cmd_buf, &constantBuffer, m_horizontalMip[mipLevel].m_descriptorSet); vkCmdEndRenderPass(cmd_buf); } // vertical pass // { VkRenderPassBeginInfo rp_begin = {}; rp_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; rp_begin.pNext = NULL; rp_begin.renderPass = m_in; rp_begin.framebuffer = m_verticalMip[mipLevel].m_frameBuffer; rp_begin.renderArea.offset.x = 0; rp_begin.renderArea.offset.y = 0; rp_begin.renderArea.extent.width = m_Width >> mipLevel; rp_begin.renderArea.extent.height = m_Height >> mipLevel; rp_begin.clearValueCount = 0; rp_begin.pClearValues = NULL; vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); BlurPS::cbBlur *data; VkDescriptorBufferInfo constantBuffer; m_pConstantBufferRing->AllocConstantBuffer(sizeof(BlurPS::cbBlur), (void **)&data, &constantBuffer); data->dirX = 0.0f / (float)(m_Width >> mipLevel); data->dirY = 1.0f / (float)(m_Height >> mipLevel); data->mipLevel = mipLevel; m_directionalBlur.Draw(cmd_buf, &constantBuffer, m_verticalMip[mipLevel].m_descriptorSet); vkCmdEndRenderPass(cmd_buf); } SetPerfMarkerEnd(cmd_buf); } void BlurPS::Draw(VkCommandBuffer cmd_buf) { for (int i = 0; i < m_mipCount; i++) { Draw(cmd_buf, i); } } }
45.064935
186
0.637896
whatevermarch
d7965ae5f13da7506c2a6bd89f02667f04f807c9
3,242
cpp
C++
client/include/samp/CActor.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
97
2019-01-13T20:19:19.000Z
2022-02-27T18:47:11.000Z
client/include/samp/CActor.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
92
2019-01-23T23:02:31.000Z
2022-03-23T19:59:40.000Z
client/include/samp/CActor.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
69
2019-01-13T22:01:40.000Z
2022-03-09T00:55:49.000Z
/* This is a SAMP (0.3.7-R1/R3) API project file. Developer: LUCHARE <luchare.dev@gmail.com> See more here https://github.com/LUCHARE/SAMP-API Copyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved. */ #include "CActor.h" #if defined(SAMP_R1) SAMP::CActor::CActor(int nSkin, CVectorSA vPos, float fRotation) { ((void(__thiscall*)(CActor*, int, CVectorSA, float))SAMP_ADDROF(0x97C60))(this, nSkin, vPos, fRotation); } void SAMP::CActor::Destroy() { ((void(__thiscall*)(CActor*))SAMP_ADDROF(0x97DA0))(this); } void SAMP::CActor::PerformAnimation(const char* szAnim, const char* szIFP, float fFramedelta, int bLockA, int bLockX, int bLockY, int bLockF, int nTime) { ((void(__thiscall*)(CActor*, const char*, const char*, float, int, int, int, int, int))SAMP_ADDROF(0x97E00))(this, szAnim, szIFP, fFramedelta, bLockA, bLockX, bLockY, bLockF, nTime); } void SAMP::CActor::SetRotation(float fValue) { ((void(__thiscall*)(CActor*, float))SAMP_ADDROF(0x97F10))(this, fValue); } void SAMP::CActor::SetHealth(float fValue) { ((void(__thiscall*)(CActor*, float))SAMP_ADDROF(0x97F70))(this, fValue); } float SAMP::CActor::GetHealth() { return ((float(__thiscall*)(CActor*))SAMP_ADDROF(0x97F50))(this); } void SAMP::CActor::SetInvulnerable(bool bInv) { ((void(__thiscall*)(CActor*, bool))SAMP_ADDROF(0x980A0))(this, bInv); } void SAMP::CActor::SetArmour(float fValue) { ((void(__thiscall*)(CActor*, float))SAMP_ADDROF(0x97FD0))(this, fValue); } float SAMP::CActor::GetArmour() { return ((float(__thiscall*)(CActor*))SAMP_ADDROF(0x97FB0))(this); } void SAMP::CActor::SetState(int nValue) { ((void(__thiscall*)(CActor*, int))SAMP_ADDROF(0x98000))(this, nValue); } int SAMP::CActor::GetState() { return ((int(__thiscall*)(CActor*))SAMP_ADDROF(0x97FF0))(this); } BOOL SAMP::CActor::IsDead() { return ((BOOL(__thiscall*)(CActor*))SAMP_ADDROF(0x98020))(this); } void SAMP::CActor::SetStatus(int nValue) { ((void(__thiscall*)(CActor*, int))SAMP_ADDROF(0x98060))(this, nValue); } int SAMP::CActor::GetStatus() { return ((int(__thiscall*)(CActor*))SAMP_ADDROF(0x98050))(this); } #elif defined(SAMP_R3) SAMP::CActor::CActor(int nModel, CVectorSA position, float fRotation) { ((void(__thiscall*)(CActor*, int, CVectorSA, float))SAMP_ADDROF(0x9BBA0))(this, nModel, position, fRotation); } void SAMP::CActor::Destroy() { ((void(__thiscall*)(CActor*))SAMP_ADDROF(0x9BCF0))(this); } void SAMP::CActor::PerformAnimation(const char* szAnim, const char* szIFP, float fFramedelta, int bLockA, int bLockX, int bLockY, int bLockF, int nTime) { ((void(__thiscall*)(CActor*, const char*, const char*, float, int, int, int, int, int))SAMP_ADDROF(0x9BD50))(this, szAnim, szIFP, fFramedelta, bLockA, bLockX, bLockY, bLockF, nTime); } void SAMP::CActor::SetRotation(float fAngle) { ((void(__thiscall*)(CActor*, float))SAMP_ADDROF(0x9BE60))(this, fAngle); } float SAMP::CActor::GetHealth() { return ((float(__thiscall*)(CActor*))SAMP_ADDROF(0x9BEA0))(this); } void SAMP::CActor::SetHealth(float fValue) { ((void(__thiscall*)(CActor*, float))SAMP_ADDROF(0x9BEC0))(this, fValue); } void SAMP::CActor::SetInvulnerable(bool bEnable) { ((void(__thiscall*)(CActor*, bool))SAMP_ADDROF(0x9BFF0))(this, bEnable); } #endif
32.09901
183
0.713757
MayconFelipeA
d796fb41d4cb992c1d40777d98cb8b76a56b8d11
619
cpp
C++
Siv3D/src/Siv3D/BoolFormat/SivBoolFormat.cpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/BoolFormat/SivBoolFormat.cpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/BoolFormat/SivBoolFormat.cpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
1
2019-10-06T17:09:26.000Z
2019-10-06T17:09:26.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/BoolFormat.hpp> # include <Siv3D/String.hpp> namespace s3d { String ToString(const bool value, const LetterCase letterCase) { static constexpr const char32 bools[] = U"falsetrueFALSETRUEFalseTrue"; const size_t index = static_cast<size_t>(letterCase) * 9 + value * 5; return String(bools + index, 5 - value); } }
23.807692
73
0.589661
Fuyutsubaki
d798a82e4f7ba69b2133203e210918f14b22002e
1,604
cpp
C++
firmware/src/views/menu.cpp
brianpepin/lpm
969105a6374fa65c2de4e74a119d614b32e6ea2c
[ "MIT" ]
3
2020-06-02T01:23:18.000Z
2022-02-25T22:20:24.000Z
firmware/src/views/menu.cpp
brianpepin/lpm
969105a6374fa65c2de4e74a119d614b32e6ea2c
[ "MIT" ]
null
null
null
firmware/src/views/menu.cpp
brianpepin/lpm
969105a6374fa65c2de4e74a119d614b32e6ea2c
[ "MIT" ]
null
null
null
#include <globals.h> #include <views/menu.h> #include <adc.h> #include <power.h> #include <logger.h> #define MI_CLEAR 0 #define MI_LOGGING 1 #define MI_CALIBRATION 2 #define MI_POWER_OFF 3 const char PROGMEM _menuTitle[] = "Menu"; const char PROGMEM _miClear[] = "Clear"; const char PROGMEM _miLogging[] = "Logging"; const char PROGMEM _miStopLogging[] = "Stop Logging"; const char PROGMEM _miCalibration[] = "Calibration"; const char PROGMEM _miPowerOff[] = "Power Off"; const char * _menuText[] = { _miClear, _miLogging, _miCalibration, _miPowerOff, nullptr }; const char * _loggingMenuText[] = { _miClear, _miStopLogging, _miCalibration, _miPowerOff, nullptr }; void MenuView::init(View *previousView) { MenuBaseView::init(previousView, _menuTitle); } bool MenuView::update(bool newReading) { auto items = Logger::isLogging() ? _loggingMenuText : _menuText; if (getItems() != items) { setItems(items); return true; } return false; } void MenuView::onSelect(int8_t row, View **newView) { switch (row) { case MI_CLEAR: Adc::zero(); break; case MI_POWER_OFF: Power::turnOff(); break; case MI_CALIBRATION: _calibrate.init(this); *newView = &_calibrate; break; case MI_LOGGING: if (Logger::isLogging()) { Logger::stop(); *newView = this; } else { _log.init(this); *newView = &_log; } break; } }
19.095238
68
0.589776
brianpepin
d79e6c7bc79b39e41e70ca3a4aad12d7772a9bfe
1,976
cpp
C++
winshell/src/echo/main.cpp
ZhangShuaiH/demos
8e4926e6fb40de54d9b50b9e36e3e90ea541e719
[ "Apache-2.0" ]
1
2021-05-18T14:07:05.000Z
2021-05-18T14:07:05.000Z
winshell/src/echo/main.cpp
ZhangShuaiH/demos
8e4926e6fb40de54d9b50b9e36e3e90ea541e719
[ "Apache-2.0" ]
null
null
null
winshell/src/echo/main.cpp
ZhangShuaiH/demos
8e4926e6fb40de54d9b50b9e36e3e90ea541e719
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <sstream> #include <ctype.h> using namespace std; char newLine = '\n'; void noNewLine() { newLine = 0; } void help() { string command = "echo "; cout<<command<<"[option].. [msg].."<<endl; cout<<endl; cout<<"options:"<<endl; cout<<'\t'<<"-n --nonewline\tdo not print newline character at end"<<endl; cout<<'\t'<<"-h --help\tprint help message"<<endl; cout<<endl; cout<<"examles:"<<endl; cout<<'\t'<<command<<"msg"<<endl; cout<<'\t'<<command<<"msg1 msg2"<<endl; cout<<'\t'<<command<<"-n msg"<<endl; cout<<'\t'<<command<<"msg -n"<<endl; cout<<'\t'<<command<<"--nonewline msg"<<endl; cout<<'\t'<<command<<"-h"<<endl; cout<<'\t'<<command<<"--help"<<endl; } void error(const stringstream &errMsg) { cout<<"error\t"<<errMsg.str()<<endl; help(); exit(-1); } void parseOptions(const string &option) { stringstream errMsg; errMsg << "parsing "<<option<< " error!"<<endl; if(option[1] == '-') { if(option == "--nonewline") { noNewLine(); }else if(option == "--help") { help(); }else { error(errMsg); } }else{ int i; for(i=1; i<option.size(); i++) { switch(option[i]) { case 'n': noNewLine(); break; case 'h': help(); break; default: error(errMsg); } } if(i == 1) { error(errMsg); } } } int main(int argc, char *argv[]) { if(argc<2) { help(); } for(int i=1; i<argc; i++) { if(argv[i][0] == '-') { parseOptions(argv[i]); }else{ cout<<argv[i]<<" "; } } cout<<newLine; return 0; }
19.564356
78
0.423583
ZhangShuaiH
d79fd6cd08a4cd2b58ea37a6ad691db9fa661f0c
1,750
hpp
C++
consolemgr/include/Client.hpp
maximaximal/piga
54530c208e59eaaf8d44c1f8d640f5ec028d4126
[ "Zlib" ]
2
2015-01-07T18:36:39.000Z
2015-01-08T13:54:43.000Z
consolemgr/include/Client.hpp
maximaximal/piga
54530c208e59eaaf8d44c1f8d640f5ec028d4126
[ "Zlib" ]
null
null
null
consolemgr/include/Client.hpp
maximaximal/piga
54530c208e59eaaf8d44c1f8d640f5ec028d4126
[ "Zlib" ]
null
null
null
#ifndef CLIENT_HPP #define CLIENT_HPP #include <memory> #include <QObject> #include <Player.hpp> namespace NetworkedClient { class PlayerManager; class Client; } class Client : public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) Q_PROPERTY(StatusCode status READ status) Q_PROPERTY(QList<QObject*>* players READ players) public: enum StatusCode { Success, WrongCredentials, ConnectionFailure, LoLoginPossible, NoMoreTries, UserIDNotExisting, UserIDAlreadyActive, _COUNT }; Q_ENUMS(StatusCode) explicit Client(QObject *parent = 0); Client(const Client& other); ~Client(); void connectToConsole(const QString &host, int port); QString name() const; QString address() const; int port() const; void setName(QString name); StatusCode status() const; QList<QObject*>* players(); void setStatus(StatusCode status); std::shared_ptr<NetworkedClient::Client> getNetClient() const; std::shared_ptr<NetworkedClient::PlayerManager> getPlayerManager() const; signals: void clientConnected(); void loginResponse(StatusCode response); void nameChanged(QString name); public slots: bool update(); private: QString m_name; std::shared_ptr<NetworkedClient::Client> m_netClient; std::shared_ptr<NetworkedClient::PlayerManager> m_netPlayerManager; QList<QObject*> m_players; void handshakeCompleted(); }; Q_DECLARE_METATYPE_IMPL(Client) #endif // CLIENT_HPP
25.362319
81
0.633143
maximaximal
d7a8f19b10136dcfc8ebc24eda6273e5e3c66c32
599
cpp
C++
cwsdk/cube.cpp
Andoryuuta/cwsdk
a3672e9c9645e6a0de388e07483e4f8bf22eb7fb
[ "MIT" ]
2
2019-07-08T13:55:13.000Z
2021-05-06T23:35:46.000Z
cwsdk/cube.cpp
Andoryuuta/cwsdk
a3672e9c9645e6a0de388e07483e4f8bf22eb7fb
[ "MIT" ]
4
2018-11-09T12:18:17.000Z
2019-07-08T19:16:24.000Z
cwsdk/cube.cpp
Andoryuuta/cwsdk
a3672e9c9645e6a0de388e07483e4f8bf22eb7fb
[ "MIT" ]
1
2019-07-07T10:05:56.000Z
2019-07-07T10:05:56.000Z
#include "cube.h" #include <iostream> #include <Windows.h> #include "msvc_bincompat.h" #include "cube_funcs.h" #include "globals.h" namespace cube { GameController* BusywaitForGameController() { auto imageBase = (uint32_t)GetModuleHandleA(NULL); GameController** gcp = (GameController**)(imageBase + 0x36B1C8); while (*gcp == nullptr) { Sleep(500); } return *gcp; } GameController* GetGameController() { auto imageBase = (uint32_t)GetModuleHandleA(NULL); GameController* gc = *(GameController**)(imageBase + 0x36B1C8); return gc; } void InitAPI() { InitGlobals(); } };
21.392857
66
0.699499
Andoryuuta
92e4e69ee851faaa71edec6736ccd4fc7cafacd5
3,006
hpp
C++
src/Controller/PhysicsFacade/RigidBody.hpp
MajorArkwolf/Project-Blue-Engine
e5fc6416d0a41a1251f1b369047e0ea1097775da
[ "MIT" ]
1
2021-04-18T09:49:38.000Z
2021-04-18T09:49:38.000Z
src/Controller/PhysicsFacade/RigidBody.hpp
MajorArkwolf/ICT397-Project-Blue
e5fc6416d0a41a1251f1b369047e0ea1097775da
[ "MIT" ]
null
null
null
src/Controller/PhysicsFacade/RigidBody.hpp
MajorArkwolf/ICT397-Project-Blue
e5fc6416d0a41a1251f1b369047e0ea1097775da
[ "MIT" ]
2
2020-06-13T15:24:01.000Z
2021-04-15T20:25:49.000Z
#pragma once #include <glm/gtc/quaternion.hpp> #include <glm/vec3.hpp> namespace Physics { enum class RigidBodyType { Static, Kinematic, Dynamic }; /** * @class RigidBody * A pure virtual class that represents a RigidBody for use within a dynamics world */ class RigidBody { public: RigidBody(){} virtual ~RigidBody(){} /** * @brief Sets the position of the rigid body * @param position THe position to set the rigid body to */ virtual void SetPosition(glm::vec3 position) = 0; /** * @brief Sets the rotation or orientation of the rigid body * @param orientation The orietnation to set the rigid body to */ virtual void SetOrientation(glm::quat orientation) = 0; /** * @brief Sets the position and rotation of the rigid body * @param position The new position * @param orientation The new Orientation */ virtual void SetPositionAndOrientation(glm::vec3 position, glm::quat orientation) = 0; /** * @brief Returns the position of the rigid body within the dynamics world * @return The position of the rigid body */ virtual glm::vec3 GetPosition() = 0; /** * @brief Returns the orientatino of the body relative to the dynamics world * @return The orientation of the body */ virtual glm::quat GetOrientation() = 0; /** * @brief Sets wheter physics should be updated on this body * @param sleeping Set to true if the body should not be updated */ virtual void SetSleeping(bool sleeping) = 0; /** * @brief Returns whether the body is currently not being udpated * @return Whether the body is sleeping */ virtual bool GetSleeping() = 0; /** * @brief Applies a give force to the centre of the object * @param force The amount of force and direction to apply */ virtual void ApplyForceToCentre(glm::vec3 force) = 0; /** * @brief Applies force to a given point of the body * @param force The amount of force to apply * @param point The point to apply the force */ virtual void ApplyForce(glm::vec3 force, glm::vec3 point) = 0; virtual void SetAngularDamping(double damping) = 0; /** * @brief Destroys the rigid body when no longer needed */ virtual void Destroy() = 0; private: }; }
40.08
98
0.50998
MajorArkwolf
92ea347cd955ba757106ded405f52df63d42ac5e
7,158
hpp
C++
ivarp/include/ivarp/bound_dependency_analysis.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
ivarp/include/ivarp/bound_dependency_analysis.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
ivarp/include/ivarp/bound_dependency_analysis.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
// The code is open source under the MIT license. // Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group // https://ibr.cs.tu-bs.de/alg // // 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. // // Created by Phillip Keldenich on 28.01.20. // #pragma once #include "ivarp/math_fn.hpp" namespace ivarp { /** * An enum whose elements identify zero, one or two bounds of an interval. */ enum class BoundID : unsigned { NONE = 0, LB = 1, UB = 2, BOTH = 3, EMPTY = 4 // returned from bound applications if an interval became empty }; template<std::size_t TargetArg> struct LabeledBoundID { static constexpr std::size_t target = TargetArg; BoundID bound_id; }; static inline constexpr bool uses_lb(BoundID b) noexcept { return b == BoundID::LB || b == BoundID::BOTH; } static inline constexpr bool uses_ub(BoundID b) noexcept { return b == BoundID::UB || b == BoundID::BOTH; } /** * @struct BoundDependencies * @brief Contains information about which bound of a given expression may depend on * which bound of an argument. * * Generally speaking, this is an over-approximation * in the sense that the flags in this struct may be set even if * the evaluation sometimes does not actually depend on the argument bound. */ struct BoundDependencies { bool lb_depends_on_lb; bool lb_depends_on_ub; bool ub_depends_on_lb; bool ub_depends_on_ub; template<typename BDepType> static constexpr BoundDependencies from_type() { return BoundDependencies{BDepType::lb_depends_on_lb, BDepType::lb_depends_on_ub, BDepType::ub_depends_on_lb, BDepType::ub_depends_on_ub}; } constexpr bool operator==(const BoundDependencies& o) const noexcept { return lb_depends_on_lb == o.lb_depends_on_lb && lb_depends_on_ub == o.lb_depends_on_ub && ub_depends_on_lb == o.ub_depends_on_lb && ub_depends_on_ub == o.ub_depends_on_ub; } /** * @brief Compute how a computation using the given bounds of its child expression * depends on the target argument. * @param used_bounds The bounds of the child expression that are used. * @param bd How the child bounds depend on the target argument. * @return */ constexpr static bool depends_on_lb(BoundID used_bounds, const BoundDependencies& bd) noexcept { return (uses_lb(used_bounds) && bd.lb_depends_on_lb) || (uses_ub(used_bounds) && bd.ub_depends_on_lb); } /** * @brief Compute how a computation using the given bounds of its child expression * depends on the target argument. * @param used_bounds The bounds of the child expression that are used. * @param bd How the child bounds depend on the target argument. * @return */ constexpr static bool depends_on_ub(BoundID used_bounds, const BoundDependencies& bd) noexcept { return (uses_lb(used_bounds) && bd.lb_depends_on_ub) || (uses_ub(used_bounds) && bd.ub_depends_on_ub); } /** * Compute BoundDependencies for a binary operator such as * or /. * * @param lb_bounds_arg1 The bounds of the first input used in producing the lower bound of the result. * @param ub_bounds_arg1 The bounds of the first input used in producing the upper bound of the result. * @param a1deps The dependencies of the first input on the target argument. * @param lb_bounds_arg2 The bounds of the second input used in producing the lower bound of the result. * @param ub_bounds_arg2 The bounds of the second input used in producing the upper bound of the result. * @param a2deps The dependencies of the second input on the target argument. * @return The resulting bound dependencies. */ constexpr static BoundDependencies computation_uses(BoundID lb_bounds_arg1, BoundID ub_bounds_arg1, BoundDependencies a1deps, BoundID lb_bounds_arg2, BoundID ub_bounds_arg2, BoundDependencies a2deps) noexcept { return BoundDependencies{ depends_on_lb(lb_bounds_arg1, a1deps) || depends_on_lb(lb_bounds_arg2, a2deps), depends_on_ub(lb_bounds_arg1, a1deps) || depends_on_ub(lb_bounds_arg2, a2deps), depends_on_lb(ub_bounds_arg1, a1deps) || depends_on_lb(ub_bounds_arg2, a2deps), depends_on_ub(ub_bounds_arg1, a1deps) || depends_on_ub(ub_bounds_arg2, a2deps) }; } }; /** * @brief Output bound dependencies. * @param o * @param b * @return The output stream. */ inline std::ostream& operator<<(std::ostream& o, const BoundDependencies& b) { o << std::boolalpha << "lb -> lb: " << b.lb_depends_on_lb << ", " << "lb -> ub: " << b.lb_depends_on_ub << ", " << "ub -> lb: " << b.ub_depends_on_lb << ", " << "ub -> ub: " << b.ub_depends_on_ub; return o; } /** * Compute the BoundDependencies for a given, bounded expression or predicate and a given argument index. * * @tparam BoundedMathExprOrPred * @tparam ArgIndex * @return The BoundDependencies for the given expression or predicate. */ template<typename BoundedMathExprOrPred, std::size_t ArgIndex> static inline constexpr BoundDependencies compute_bound_dependencies() noexcept; } // Include implementation headers. #include "bound_dependency_analysis/cbd_simple_deps.hpp" #include "bound_dependency_analysis/cbd_meta_eval_tag.hpp" #include "bound_dependency_analysis/cbd_bounded.hpp" #include "bound_dependency_analysis/cbd_constants.hpp" #include "bound_dependency_analysis/cbd_args.hpp" #include "bound_dependency_analysis/cbd_arithmetic_ops.hpp" #include "bound_dependency_analysis/compute_bound_dependencies.hpp"
44.185185
114
0.674211
phillip-keldenich
92ea4394d365ff9f627d7ee8e30f27b0c7b570c2
4,025
cpp
C++
YareEngine/Source/Utilities/IOHelper.cpp
Resoona/Yare
fc94403575285099ce93ef556f68c77b815577d9
[ "MIT" ]
2
2020-03-01T13:56:45.000Z
2020-03-06T01:41:00.000Z
YareEngine/Source/Utilities/IOHelper.cpp
Riyusuna/Yare
fc94403575285099ce93ef556f68c77b815577d9
[ "MIT" ]
null
null
null
YareEngine/Source/Utilities/IOHelper.cpp
Riyusuna/Yare
fc94403575285099ce93ef556f68c77b815577d9
[ "MIT" ]
null
null
null
#include "Utilities/IOHelper.h" #include "Utilities/Logger.h" #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #define GLM_ENABLE_EXPERIMENTAL #include <tinyobjloader/tiny_obj_loader.h> #include <glm/glm.hpp> #include <glm/gtx/hash.hpp> #include <glm/gtx/string_cast.hpp> #include <unordered_map> namespace std { template <> struct hash<Yare::Vertex> { size_t operator()(Yare::Vertex const& vertex) const { return ((hash<glm::vec3>()(vertex.pos) ^ (hash<glm::vec3>()(vertex.normal) << 1)) >> 1) ^ (hash<glm::vec2>()(vertex.uv) << 1); } }; } // namespace std namespace Yare::Utilities { std::vector<std::string> readFile(const std::string& filename) { std::ifstream file(filename); if (!file) { YZ_ERROR("File '" + filename + "' was unable to open."); throw std::runtime_error("File '" + filename + "' was unable to open."); } // captures lines not separated by whitespace std::vector<std::string> myLines; std::copy(std::istream_iterator<std::string>(file), std::istream_iterator<std::string>(), std::back_inserter(myLines)); return myLines; } void loadMesh(const std::string& filePath, std::vector<Vertex>& vertices, std::vector<uint32_t>& indices) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string warn, err; if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filePath.c_str())) { YZ_ERROR(warn + err); } std::unordered_map<Vertex, uint32_t> uniqueVertices = {}; for (size_t s = 0; s < shapes.size(); s++) { // Loop over faces(polygon) size_t index_offset = 0; for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) { // hardcode loading to triangles int fv = 3; // Loop over vertices in the face. for (size_t v = 0; v < fv; v++) { // access to vertex tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v]; // vertex position tinyobj::real_t vx = attrib.vertices[3 * idx.vertex_index + 0]; tinyobj::real_t vy = attrib.vertices[3 * idx.vertex_index + 1]; tinyobj::real_t vz = attrib.vertices[3 * idx.vertex_index + 2]; // vertex normal tinyobj::real_t nx = attrib.normals[3 * idx.normal_index + 0]; tinyobj::real_t ny = attrib.normals[3 * idx.normal_index + 1]; tinyobj::real_t nz = attrib.normals[3 * idx.normal_index + 2]; tinyobj::real_t ux = attrib.texcoords[2 * idx.texcoord_index + 0]; tinyobj::real_t uy = attrib.texcoords[2 * idx.texcoord_index + 1]; // copy it into our vertex Vertex new_vert; new_vert.pos.x = vx; new_vert.pos.y = vy; new_vert.pos.z = vz; new_vert.normal.x = nx; new_vert.normal.y = ny; new_vert.normal.z = nz; new_vert.uv.x = ux; new_vert.uv.y = uy; // we are setting the vertex color as the vertex normal. This is just for display purposes new_vert.color = new_vert.normal; if (uniqueVertices.count(new_vert) == 0) { uniqueVertices[new_vert] = static_cast<uint32_t>(vertices.size()); vertices.push_back(new_vert); } indices.push_back(uniqueVertices[new_vert]); } index_offset += fv; } } } } // namespace Yare::Utilities
37.616822
111
0.529193
Resoona
92ef8c3f89eb39202e5a05268a98f797da5dd951
8,950
cpp
C++
src/renderer/surface/swapchain.cpp
LwRuan/RainEngine
0bf3c009190e86cf1b81a692ce26eb26646aca3c
[ "MIT" ]
null
null
null
src/renderer/surface/swapchain.cpp
LwRuan/RainEngine
0bf3c009190e86cf1b81a692ce26eb26646aca3c
[ "MIT" ]
null
null
null
src/renderer/surface/swapchain.cpp
LwRuan/RainEngine
0bf3c009190e86cf1b81a692ce26eb26646aca3c
[ "MIT" ]
null
null
null
#include "swapchain.h" #include "device/device.h" namespace Rain { VkResult SwapChain::Init(Device* device, PhysicalDevice* physical_device, GLFWwindow* window, VkSurfaceKHR surface) { device_ = device; VkSurfaceFormatKHR surface_format = physical_device->ChooseSurfaceFormat(); VkPresentModeKHR present_mode = physical_device->ChoosePresentMode(); VkExtent2D extent = physical_device->ChooseSwapExtent(window); uint32_t min_image_count = physical_device->swap_chain_support_details_.capabilities_.minImageCount; uint32_t max_image_count = physical_device->swap_chain_support_details_.capabilities_.maxImageCount; uint32_t image_count = min_image_count + 1; if (max_image_count > 0 && image_count > max_image_count) { image_count = max_image_count; } // spdlog::debug("swap chain image count: {}", image_count); VkSwapchainCreateInfoKHR create_info{}; create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; create_info.surface = surface; create_info.minImageCount = image_count; create_info.imageFormat = surface_format.format; create_info.imageColorSpace = surface_format.colorSpace; create_info.imageExtent = extent; create_info.imageArrayLayers = 1; create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; uint32_t queue_family[2]; physical_device->GetGraphicsPresentQueueFamily(queue_family[0], queue_family[1]); if (queue_family[0] != queue_family[1]) { create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT; create_info.queueFamilyIndexCount = 2; create_info.pQueueFamilyIndices = queue_family; } else { create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; create_info.queueFamilyIndexCount = 0; create_info.pQueueFamilyIndices = nullptr; } create_info.preTransform = physical_device->swap_chain_support_details_ .capabilities_.currentTransform; create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; create_info.presentMode = present_mode; create_info.clipped = VK_TRUE; create_info.oldSwapchain = VK_NULL_HANDLE; VkResult result = vkCreateSwapchainKHR(device->device_, &create_info, nullptr, &swap_chain_); if (result != VK_SUCCESS) { spdlog::error("swap chain creation failed"); return result; } vkGetSwapchainImagesKHR(device->device_, swap_chain_, &image_count, nullptr); images_.resize(image_count); vkGetSwapchainImagesKHR(device->device_, swap_chain_, &image_count, images_.data()); image_format_ = surface_format.format; extent_ = extent; result = CreateImageViews(); if (result != VK_SUCCESS) return result; image_available_semaphores_.resize(MAX_FRAMES_IN_FLIGHT, VK_NULL_HANDLE); render_finished_semaphores_.resize(MAX_FRAMES_IN_FLIGHT, VK_NULL_HANDLE); in_flight_fences_.resize(MAX_FRAMES_IN_FLIGHT, VK_NULL_HANDLE); images_in_flight_.resize(images_.size()); std::fill(images_in_flight_.begin(), images_in_flight_.end(), VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphore_info{}; semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fence_signaled_info{}; fence_signaled_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fence_signaled_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { VkResult result = vkCreateSemaphore(device->device_, &semaphore_info, nullptr, &image_available_semaphores_[i]); if (result != VK_SUCCESS) { spdlog::error("semaphore creation failed"); return result; } result = vkCreateSemaphore(device->device_, &semaphore_info, nullptr, &render_finished_semaphores_[i]); if (result != VK_SUCCESS) { spdlog::error("semaphore creation failed"); return result; } result = vkCreateFence(device->device_, &fence_signaled_info, nullptr, &in_flight_fences_[i]); if (result != VK_SUCCESS) { spdlog::error("fence creation failed"); return result; } } return VK_SUCCESS; } VkResult SwapChain::CreateImageViews() { image_views_.resize(images_.size(), VK_NULL_HANDLE); for (size_t i = 0; i < images_.size(); ++i) { VkImageViewCreateInfo create_info{}; create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; create_info.image = images_[i]; create_info.viewType = VK_IMAGE_VIEW_TYPE_2D; create_info.format = image_format_; create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; create_info.subresourceRange.baseMipLevel = 0; create_info.subresourceRange.levelCount = 1; create_info.subresourceRange.baseArrayLayer = 0; create_info.subresourceRange.layerCount = 1; VkResult result = vkCreateImageView(device_->device_, &create_info, nullptr, &image_views_[i]); if (result != VK_SUCCESS) { spdlog::error("swap chain image view creation failed"); return result; } } return VK_SUCCESS; } uint32_t SwapChain::BeginFrame(bool &resized) { vkWaitForFences(device_->device_, 1, &in_flight_fences_[current_frame_], VK_TRUE, UINT64_MAX); uint32_t image_index; VkResult result = vkAcquireNextImageKHR(device_->device_, swap_chain_, UINT64_MAX, image_available_semaphores_[current_frame_], VK_NULL_HANDLE, &image_index); if(result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { resized = true; return 0; } if (images_in_flight_[image_index] != VK_NULL_HANDLE) { vkWaitForFences(device_->device_, 1, &images_in_flight_[image_index], VK_TRUE, UINT64_MAX); } images_in_flight_[image_index] = in_flight_fences_[current_frame_]; return image_index; } VkResult SwapChain::EndFrame(uint32_t image_index) { VkSubmitInfo submit_info{}; submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore wait_semaphores[] = {image_available_semaphores_[current_frame_]}; VkPipelineStageFlags wait_stages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; submit_info.waitSemaphoreCount = 1; submit_info.pWaitSemaphores = wait_semaphores; submit_info.pWaitDstStageMask = wait_stages; submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &device_->command_buffers_[image_index]; VkSemaphore signal_semaphores[] = { render_finished_semaphores_[current_frame_]}; submit_info.signalSemaphoreCount = 1; submit_info.pSignalSemaphores = signal_semaphores; vkResetFences(device_->device_, 1, &in_flight_fences_[current_frame_]); VkResult result = vkQueueSubmit(device_->graphics_queue_, 1, &submit_info, in_flight_fences_[current_frame_]); if (result != VK_SUCCESS) { spdlog::error("queue submition failed"); return result; } VkPresentInfoKHR present_info{}; present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present_info.waitSemaphoreCount = 1; present_info.pWaitSemaphores = signal_semaphores; VkSwapchainKHR swap_chains[] = {swap_chain_}; present_info.swapchainCount = 1; present_info.pSwapchains = swap_chains; present_info.pImageIndices = &image_index; result = vkQueuePresentKHR(device_->present_queue_, &present_info); if (result != VK_SUCCESS) { spdlog::error("queue presentation failed"); return result; } current_frame_ = (current_frame_ + 1) % MAX_FRAMES_IN_FLIGHT; return VK_SUCCESS; } void SwapChain::Destroy() { for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { if (image_available_semaphores_[i] != VK_NULL_HANDLE) { vkDestroySemaphore(device_->device_, image_available_semaphores_[i], nullptr); } if (render_finished_semaphores_[i] != VK_NULL_HANDLE) { vkDestroySemaphore(device_->device_, render_finished_semaphores_[i], nullptr); } if (in_flight_fences_[i] != VK_NULL_HANDLE) { vkDestroyFence(device_->device_, in_flight_fences_[i], nullptr); } } if (swap_chain_) { for (auto image_view : image_views_) { if (image_view != VK_NULL_HANDLE) vkDestroyImageView(device_->device_, image_view, nullptr); } if (swap_chain_ != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device_->device_, swap_chain_, nullptr); } } } }; // namespace Rain
42.018779
85
0.707039
LwRuan
92efbf827dfc576b2d9a57cc6331941ac50b24ae
488
cpp
C++
1200/00/1209.cpp
actium/timus
6231d9e7fd325cae36daf5ee2ec7e61381f04003
[ "Unlicense" ]
null
null
null
1200/00/1209.cpp
actium/timus
6231d9e7fd325cae36daf5ee2ec7e61381f04003
[ "Unlicense" ]
null
null
null
1200/00/1209.cpp
actium/timus
6231d9e7fd325cae36daf5ee2ec7e61381f04003
[ "Unlicense" ]
null
null
null
#include <iostream> unsigned search(unsigned k) { unsigned lb = 0, ub = 92682; while (lb + 1 < ub) { const unsigned mid = (lb + ub) / 2; const auto x = mid * (mid + 1ull) / 2 + 1; if (x == k) return 1; (x < k ? lb : ub) = mid; } return k == 1; } int main() { unsigned n; std::cin >> n; while (n-- != 0) { unsigned k; std::cin >> k; std::cout << search(k) << ' '; } return 0; }
15.25
50
0.418033
actium
92f26f31af131f2dc41f9a10919861e7af80e1c8
3,701
cpp
C++
prophy_cpp/test/test_generated_unions.cpp
florczakraf/prophy
a42a6151a77b31afa05300fc2e1f52cc15a298cf
[ "MIT" ]
14
2015-02-19T22:00:37.000Z
2020-11-30T03:03:55.000Z
prophy_cpp/test/test_generated_unions.cpp
florczakraf/prophy
a42a6151a77b31afa05300fc2e1f52cc15a298cf
[ "MIT" ]
31
2015-06-22T11:11:10.000Z
2021-05-12T06:35:47.000Z
prophy_cpp/test/test_generated_unions.cpp
florczakraf/prophy
a42a6151a77b31afa05300fc2e1f52cc15a298cf
[ "MIT" ]
16
2015-06-12T06:48:06.000Z
2019-11-26T22:48:13.000Z
#include <vector> #include <gtest/gtest.h> #include "Unions.ppf.hpp" #include "util.hpp" using namespace testing; using namespace prophy::generated; TEST(generated_unions, Union) { std::vector<char> data(1024); Union x{Union::discriminator_a_t, 1}; size_t size = x.encode(data.data()); /// encoding EXPECT_EQ(12, size); EXPECT_EQ(size, x.get_byte_size()); EXPECT_EQ(bytes( "\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00"), bytes(data.data(), size)); x = {Union::discriminator_b_t, 1}; size = x.encode(data.data()); EXPECT_EQ(12, size); EXPECT_EQ(bytes( "\x02\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00"), bytes(data.data(), size)); x = {Union::discriminator_c_t, {{{1, 2}}}}; size = x.encode(data.data()); EXPECT_EQ(12, size); EXPECT_EQ(bytes( "\x03\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00"), bytes(data.data(), size)); /// decoding EXPECT_TRUE(x.decode(bytes( "\x01\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00"))); EXPECT_EQ(Union::discriminator_a, x.discriminator); EXPECT_EQ(4, x.a); EXPECT_EQ(std::string( "a: 4\n"), x.print()); EXPECT_TRUE(x.decode(bytes( "\x02\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00"))); EXPECT_EQ(Union::discriminator_b, x.discriminator); EXPECT_EQ(8, x.b); EXPECT_EQ(std::string( "b: 8\n"), x.print()); EXPECT_TRUE(x.decode(bytes( "\x03\x00\x00\x00" "\x01\x00\x00\x00\x02\x00\x00\x00"))); EXPECT_EQ(Union::discriminator_c, x.discriminator); EXPECT_EQ(1, x.c.x[0]); EXPECT_EQ(2, x.c.x[1]); EXPECT_EQ(std::string( "c {\n" " x: 1\n" " x: 2\n" "}\n"), x.print()); } TEST(generated_unions, BuiltinOptional) { std::vector<char> data(1024); BuiltinOptional x{}; size_t size = x.encode(data.data()); /// encoding EXPECT_EQ(8, size); EXPECT_EQ(size, x.get_byte_size()); EXPECT_EQ(bytes( "\x00\x00\x00\x00\x00\x00\x00\x00"), bytes(data.data(), size)); x = {2}; size = x.encode(data.data()); EXPECT_EQ(8, size); EXPECT_EQ(bytes( "\x01\x00\x00\x00\x02\x00\x00\x00"), bytes(data.data(), size)); /// decoding EXPECT_TRUE(x.decode(bytes( "\x00\x00\x00\x00\x00\x00\x00\x00"))); EXPECT_FALSE(x.x); EXPECT_EQ(std::string( ""), x.print()); EXPECT_TRUE(x.decode(bytes( "\x01\x00\x00\x00\x05\x00\x00\x00"))); EXPECT_TRUE(x.x); EXPECT_EQ(5, *x.x); EXPECT_EQ(std::string( "x: 5\n"), x.print()); } TEST(generated_unions, FixcompOptional) { std::vector<char> data(1024); FixcompOptional x{}; size_t size = x.encode(data.data()); /// encoding EXPECT_EQ(8, size); EXPECT_EQ(size, x.get_byte_size()); EXPECT_EQ(bytes( "\x00\x00\x00\x00\x00\x00\x00\x00"), bytes(data.data(), size)); x = {{{3, 4}}}; size = x.encode(data.data()); EXPECT_EQ(8, size); EXPECT_EQ(bytes( "\x01\x00\x00\x00\x03\x00\x04\x00"), bytes(data.data(), size)); /// decoding EXPECT_TRUE(x.decode(bytes( "\x00\x00\x00\x00\x00\x00\x00\x00"))); EXPECT_FALSE(x.x); EXPECT_EQ(std::string( ""), x.print()); EXPECT_TRUE(x.decode(bytes( "\x01\x00\x00\x00\x07\x00\x08\x00"))); EXPECT_TRUE(x.x); EXPECT_EQ(7, x.x->x); EXPECT_EQ(8, x.x->y); EXPECT_EQ(std::string( "x {\n" " x: 7\n" " y: 8\n" "}\n"), x.print()); }
25.701389
66
0.546339
florczakraf
92f7f0a9398dc2e0219401564a70be07672b339f
1,087
hpp
C++
Programming Guide/Headers/Siv3D/Spline.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
38
2016-01-14T13:51:13.000Z
2021-12-29T01:49:30.000Z
Programming Guide/Headers/Siv3D/Spline.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
null
null
null
Programming Guide/Headers/Siv3D/Spline.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
16
2016-01-15T11:07:51.000Z
2021-12-29T01:49:37.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2016 Ryo Suzuki // // Licensed under the MIT License. // //----------------------------------------------- # pragma once namespace s3d { /// <summary> /// スプライン /// </summary> namespace Spline { template <class Type> inline constexpr Type CalculateTangent(const Type& p0, const Type& p1, const Type& p2, const double a = 0.0, const double b = 0.0) { return ((1 - a)*(1 + b)) / 2 * (p1 - p0) + ((1 - a)*(1 - b)) / 2 * (p2 - p1); } template <class Type> inline constexpr Type Hermite(const Type& p0, const Type& p1, const Type& m0, const Type& m1, const double t) { return (2 * (t*t*t) - 3 * (t*t) + 1)*p0 + ((t*t*t) - 2 * (t*t) + t)*m0 + ((t*t*t) - (t*t))*m1 + (-2 * (t*t*t) + 3 * (t*t))*p1; } template <class Type> inline constexpr Type CatmullRom(const Type& p0, const Type& p1, const Type& p2, const Type& p3, const double t) { return Hermite(p1, p2, CalculateTangent(p0, p1, p2), CalculateTangent(p1, p2, p3), t); } } }
27.871795
132
0.533579
Reputeless
92f8015caf1e67ea934f7faf81467cc17cd343b9
3,000
cpp
C++
src/old/src/pmca.cpp
anupgp/astron
5ef1b113b5025f5e0477a1fb2b5202fadbc5335c
[ "MIT" ]
null
null
null
src/old/src/pmca.cpp
anupgp/astron
5ef1b113b5025f5e0477a1fb2b5202fadbc5335c
[ "MIT" ]
null
null
null
src/old/src/pmca.cpp
anupgp/astron
5ef1b113b5025f5e0477a1fb2b5202fadbc5335c
[ "MIT" ]
null
null
null
// Time-stamp: <2017-09-21 17:59:25 anup> // Units: all SI units - seconds, Volts, Ampere, Meters, Simenes, Farads // Ref:bartol2015 #include <vector> #include <iostream> #include <cmath> #include "insilico/core.hpp" #include "data_types.hpp" #include "physical_constants.hpp" #include "pmca.hpp" namespace consts=astron::phy_const; void pmca::current(state_type &variables, state_type &dxdt, const double t, unsigned index) { // Get all variable indices int ca_cyt_index = newinsilico::get_neuron_index(index, "ca_cyt"); int pmca0_index = newinsilico::get_neuron_index(index, "pmca0"); int pmca1_index = newinsilico::get_neuron_index(index, "pmca1"); int pmca2_index = newinsilico::get_neuron_index(index, "pmca2"); // Set lower limits on variable values const double kf1 = newinsilico::neuron_value(index, "pmca_kf1"); const double kb1 = newinsilico::neuron_value(index, "pmca_kb1"); const double kf2 = newinsilico::neuron_value(index, "pmca_kf2"); const double kf3 = newinsilico::neuron_value(index, "pmca_kf3"); const double kl = newinsilico::neuron_value(index, "pmca_kl"); const double pmca_density = newinsilico::neuron_value(index, "pmca_density"); const double area_volume_ratio_cyt = newinsilico::neuron_value(index, "area_volume_ratio_cyt"); const double volume_cyt = newinsilico::neuron_value(index, "volume_cyt"); // volume_cyt (m^3) const double area_cyt = volume_cyt * area_volume_ratio_cyt; // Initialize pmca values at the start of the simulation from the pmca density const double pmca_init_check = newinsilico::neuron_value(index, "pmca_init_check"); if (pmca_init_check <= 0){ variables[pmca0_index] = variables[pmca0_index] * (pmca_density * area_cyt)/(astron::phy_const::Av * volume_cyt * 1000); variables[pmca1_index] = variables[pmca1_index] * (pmca_density * area_cyt)/(astron::phy_const::Av * volume_cyt * 1000); variables[pmca2_index] = variables[pmca2_index] * (pmca_density * area_cyt)/(astron::phy_const::Av * volume_cyt * 1000); newinsilico::neuron_value(index, "pmca_init_check", 1); } // Set lower limits on variable values variables[pmca0_index] = std::max<double>(variables[pmca0_index],0.0); variables[pmca1_index] = std::max<double>(variables[pmca1_index],0.0); variables[pmca2_index] = std::max<double>(variables[pmca2_index],0.0); variables[ca_cyt_index] = std::max<double>(variables[ca_cyt_index],0.0); // Get variable values double ca_cyt = variables[ca_cyt_index]; double pmca0 = variables[pmca0_index]; double pmca1 = variables[pmca1_index]; double pmca2 = variables[pmca2_index]; dxdt[pmca0_index] = (-ca_cyt * pmca0 * kf1) + (pmca1 * kb1) + (pmca2 * kf3); dxdt[pmca1_index] = (-pmca1 * kb1) + (pmca0 * ca_cyt * kf1) + (-pmca1 * kf2); dxdt[pmca2_index] = (-pmca2 * kf3) + (pmca1 * kf2); double pmca_ca_cyt_flux = ((-ca_cyt * pmca0 * kf1) + (pmca1 * kb1) + (kl * pmca0)); newinsilico::neuron_value(index, "pmca_ca_cyt_flux", pmca_ca_cyt_flux); };
44.117647
124
0.726333
anupgp
92f808d6eaf2f84a6521df39b1e29a9b335ca967
3,762
hpp
C++
proj/KSP/src/SerialComs.hpp
bananu7/Arduino
56769c0850a6da873c29a0ac78fa2e1133bb7cc7
[ "MIT" ]
1
2020-02-24T09:14:02.000Z
2020-02-24T09:14:02.000Z
proj/KSP/src/SerialComs.hpp
bananu7/Arduino
56769c0850a6da873c29a0ac78fa2e1133bb7cc7
[ "MIT" ]
2
2016-11-20T18:43:59.000Z
2016-11-20T18:44:11.000Z
proj/KSP/src/SerialComs.hpp
bananu7/Arduino
56769c0850a6da873c29a0ac78fa2e1133bb7cc7
[ "MIT" ]
null
null
null
#pragma once #include "Structure.h" class SerialComs { public: struct ReadResult { bool status; enum class TypeOfPacket { HandShakePacket, VesselData } typeOfPacket; union { HandShakePacket handShakePacket; VesselData vesselData; }; ReadResult() : status(false) { } }; private: uint8_t rx_len; byte buffer[256]; //address for temporary storage and parsing buffer uint8_t structSize; uint8_t rx_array_inx; //index for RX parsing buffer uint8_t calc_CS; //calculated Chacksum int id; ReadResult::TypeOfPacket typeOfPacketProcessed; public: //This shit contains stuff borrowed from EasyTransfer lib inline ReadResult KSPBoardReceiveData() { ReadResult result; if ((rx_len == 0)&&(Serial.available()>3)){ while(Serial.read()!= 0xBE) { if (Serial.available() == 0) return result; } if (Serial.read() == 0xEF){ rx_len = Serial.read(); id = Serial.read(); rx_array_inx = 1; switch(id) { case 0: typeOfPacketProcessed = ReadResult::TypeOfPacket::HandShakePacket; structSize = sizeof(HandShakePacket); break; case 1: typeOfPacketProcessed = ReadResult::TypeOfPacket::VesselData; structSize = sizeof(VesselData); break; } } //make sure the binary structs on both Arduinos are the same size. if(rx_len != structSize){ rx_len = 0; return result; } } if(rx_len != 0){ while(Serial.available() && rx_array_inx <= rx_len){ buffer[rx_array_inx++] = Serial.read(); } buffer[0] = id; if(rx_len == (rx_array_inx-1)){ //seem to have got whole message //last uint8_t is CS calc_CS = rx_len; for (int i = 0; i<rx_len; i++){ calc_CS^=buffer[i]; } if(calc_CS == buffer[rx_array_inx-1]){//CS good uint16_t * address; switch(typeOfPacketProcessed) { case ReadResult::TypeOfPacket::HandShakePacket: address = reinterpret_cast<uint16_t*>(&result.handShakePacket); break; case ReadResult::TypeOfPacket::VesselData: address = reinterpret_cast<uint16_t*>(&result.vesselData); break; } memcpy(address, buffer, structSize); rx_len = 0; rx_array_inx = 1; // Success result.status = true; result.typeOfPacket = typeOfPacketProcessed; return result; } else { //failed checksum, need to clear this out anyway rx_len = 0; rx_array_inx = 1; return result; } } } return result; } inline void KSPBoardSendData(uint8_t * address, uint8_t len){ uint8_t CS = len; Serial.write(0xBE); Serial.write(0xEF); Serial.write(len); for(int i = 0; i<len; i++){ CS^=*(address+i); Serial.write(*(address+i)); } Serial.write(CS); } };
28.938462
87
0.468634
bananu7
92f8c60874f25595b4cdfb3e210a9ed34e23604d
5,960
cc
C++
test/intersectionface.cc
untaugh/geotree
4600a1cb4115094ed5c4c1500c6221a458e68be8
[ "MIT" ]
2
2018-07-27T00:58:07.000Z
2021-11-20T22:26:10.000Z
test/intersectionface.cc
untaugh/geotree
4600a1cb4115094ed5c4c1500c6221a458e68be8
[ "MIT" ]
null
null
null
test/intersectionface.cc
untaugh/geotree
4600a1cb4115094ed5c4c1500c6221a458e68be8
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <Eigen/Core> #include <vector> #include "MeshIntersection.h" #include "IntersectionFace.h" #include "MeshFactory.h" #include "Face.h" namespace { using namespace Geotree; class IntersectionFaceTest : public ::testing::Test { }; TEST_F(IntersectionFaceTest, basic) { //Mesh mesh; Verticies V(3,3); Faces F(1,3); V << 0,0,0, 1,0,0, 0,1,0; F << 0,1,2; //mesh.V = V; //mesh.F = F; Mesh mesh(V,F); IntersectionFace face = mesh.getFaceT(0); PathX<FacePoint> path(mesh); path.add(FacePoint(mesh, Vector(0.5, 0, 0), SEGMENT, 0)); path.add(FacePoint(mesh, Vector(0, 0.5, 0), SEGMENT, 2)); face.cut(path); EXPECT_EQ(face.numberOfPaths(), 0); EXPECT_EQ(face.numberOfEdgePoints(), 5); face.completePaths(); EXPECT_EQ(face.numberOfPaths(), 2); EXPECT_TRUE(face.pathSize(0) == 4 || face.pathSize(0) == 3); EXPECT_TRUE(face.pathSize(1) == 4 || face.pathSize(1) == 3); PathT p1(mesh); p1.addExisting(3); p1.addExisting(4); p1.addExisting(0); PathT p2(mesh); p2.addExisting(3); p2.addExisting(4); p2.addExisting(2); p2.addExisting(1); std::cout << face.getPath(0) << std::endl; std::cout << face.getPath(1) << std::endl; EXPECT_TRUE(face.getPath(0) == p1 || face.getPath(0) == p2); EXPECT_TRUE(face.getPath(1) == p1 || face.getPath(1) == p2); face.triangulate(); for (int j=0; j<2; j++) { std::set<int> area = face.getArea(j); std::cout << "area: "; for (int i : area) { std::cout << i << ", "; } std::cout << std::endl; } } TEST_F(IntersectionFaceTest, twoCuts) { //Mesh mesh; Verticies V(3,3); Faces F(1,3); V << 0,0,0, 1,0,0, 0,1,0; F << 0,1,2; Mesh mesh(V,F); //mesh.V = V; //mesh.F = F; IntersectionFace face = mesh.getFaceT(0); PathX<FacePoint> path(mesh); PathX<FacePoint> path2(mesh); path.add(FacePoint(mesh, Vector(0.5, 0, 0), SEGMENT, 0)); path2.add(FacePoint(mesh, Vector(0.7, 0, 0), SEGMENT, 0)); path.add(FacePoint(mesh, Vector(0, 0.5, 0), SEGMENT, 2)); path2.add(FacePoint(mesh, Vector(0, 0.7, 0), SEGMENT, 2)); face.cut(path); face.cut(path2); EXPECT_EQ(face.numberOfPaths(), 0); EXPECT_EQ(face.numberOfEdgePoints(), 7); face.completePaths(); EXPECT_EQ(face.numberOfPaths(), 3); std::cout << face.getPath(0) << std::endl; std::cout << face.getPath(1) << std::endl; EXPECT_TRUE(face.pathSize(0) == 4 || face.pathSize(0) == 3); EXPECT_TRUE(face.pathSize(1) == 4 || face.pathSize(1) == 3); EXPECT_TRUE(face.pathSize(2) == 4 || face.pathSize(2) == 3); PathT p1(mesh); p1.addExisting(3); p1.addExisting(5); p1.addExisting(0); PathT p2(mesh); p2.addExisting(3); p2.addExisting(5); p2.addExisting(6); p2.addExisting(4); EXPECT_TRUE(face.getPath(0) == p1 || face.getPath(0) == p2); EXPECT_TRUE(face.getPath(1) == p1 || face.getPath(1) == p2); face.triangulate(); for (int j=0; j<3; j++) { std::set<int> area = face.getArea(j); std::cout << "area: "; for (int i : area) { std::cout << i << ", "; } std::cout << std::endl; } } TEST_F(IntersectionFaceTest, longer) { Verticies V(3,3); Faces F(1,3); V << 0,0,0, 1,0,0, 0,1,0; F << 0,1,2; Mesh mesh(V,F); IntersectionFace face = mesh.getFaceT(0); PathX<FacePoint> path(mesh); path.add(FacePoint(mesh, Vector(0.5, 0, 0), SEGMENT, 0)); path.add(FacePoint(mesh, Vector(0.5, 0.1, 0), FACE, 0)); path.add(FacePoint(mesh, Vector(0.5, 0.2, 0), FACE, 0)); path.add(FacePoint(mesh, Vector(0.5, 0.3, 0), FACE, 0)); path.add(FacePoint(mesh, Vector(0.0, 0.5, 0), SEGMENT, 2)); face.cut(path); EXPECT_EQ(face.numberOfPaths(), 0); EXPECT_EQ(face.numberOfEdgePoints(), 5); face.completePaths(); EXPECT_EQ(face.numberOfPaths(), 2); std::cout << face.getPath(0) << std::endl; std::cout << face.getPath(1) << std::endl; EXPECT_TRUE(face.pathSize(0) == 6 || face.pathSize(0) == 7); EXPECT_TRUE(face.pathSize(1) == 6 || face.pathSize(1) == 7); face.triangulate(); for (int j=0; j<2; j++) { std::set<int> area = face.getArea(j); std::cout << "area: "; for (int i : area) { std::cout << i << ", "; } std::cout << std::endl; } } TEST_F(IntersectionFaceTest, noEdge) { Verticies V(3, 3); Faces F(1, 3); V << 0, 0, 0, 1, 0, 0, 0, 1, 0; F << 0, 1, 2; Mesh mesh(V,F); IntersectionFace face = mesh.getFaceT(0); PathX<FacePoint> path(mesh); path.add(FacePoint(mesh, Vector(0.1, 0.1, 0), FACE, 0)); path.add(FacePoint(mesh, Vector(0.5, 0.1, 0), FACE, 0)); path.add(FacePoint(mesh, Vector(0.1, 0.5, 0), FACE, 0)); face.cut(path); EXPECT_EQ(face.numberOfPaths(), 0); EXPECT_EQ(face.numberOfEdgePoints(), 3); face.completePaths(); EXPECT_EQ(face.numberOfPaths(), 2); face.triangulate(); for (int j=0; j<2; j++) { std::set<int> area = face.getArea(j); std::cout << "area: "; for (int i : area) { std::cout << i << ", "; } std::cout << std::endl; } } }
25.147679
68
0.500168
untaugh
92fb903178035aa80b5092cd78999ddcaf4d2e15
3,773
cpp
C++
arcc/Listing.cpp
zethon/yarc
37bd8d780689f262315f590d3dc354a9a147d296
[ "MIT" ]
5
2017-12-17T19:21:20.000Z
2022-02-26T01:11:18.000Z
arcc/Listing.cpp
zethon/yarc
37bd8d780689f262315f590d3dc354a9a147d296
[ "MIT" ]
22
2017-12-13T10:51:32.000Z
2019-11-28T16:20:26.000Z
arcc/Listing.cpp
zethon/yarc
37bd8d780689f262315f590d3dc354a9a147d296
[ "MIT" ]
null
null
null
// Another Reddit Console Client // Copyright (c) 2017-2019, Adalid Claure <aclaure@gmail.com> #include <boost/algorithm/string.hpp> #include <nlohmann/json.hpp> #include "RedditSession.h" #include "Listing.h" namespace arcc { Listing::Listing(RedditSessionPtr session, const std::string& endpoint, std::size_t limit) : Listing(session, endpoint, limit, Params{}) {} Listing::Listing(RedditSessionPtr session, const std::string& endpoint, std::size_t limit, const Params& params) : _sessionPtr{ session }, _endpoint{ endpoint }, _limit{ limit }, _params{ params } {} Listing::Listing(const Listing& other) : _sessionPtr{ other._sessionPtr }, _endpoint{ other.endpoint() }, _limit{ other.limit() }, _params{ other.params() } { } Listing::Page Listing::processResponse(nlohmann::json response) { Listing::Page retval; const auto& data = response.at("data"); if (data.find("before") != data.end() && !data["before"].is_null()) { _before = data["before"]; } if (data.find("after") != data.end() && !data["after"].is_null()) { _after = data["after"]; } return data.value("children", Page{}); } Listing::Page Listing::getFirstPage() { if (auto session = _sessionPtr.lock(); session) { Params params{ _params }; params.insert_or_assign("limit", std::to_string(_limit)); const auto jsontext = session->doGetRequest(_endpoint, params); if (!jsontext.empty()) { const auto reply = nlohmann::json::parse(jsontext); if (reply.find("data") == reply.end()) { throw std::runtime_error("the listing response was malformed"); } return processResponse(reply); } } return Listing::Page{}; } Listing::Page Listing::getNextPage() { if (_after.empty()) { // no more posts return Listing::Page{}; } if (auto session = _sessionPtr.lock(); session) { _before.clear(); _count += _limit; Params params{ _params }; params.insert_or_assign("limit", std::to_string(_limit)); params.insert_or_assign("count", std::to_string(_count)); params.insert_or_assign("after", _after); const auto jsontext = session->doGetRequest(_endpoint, params); if (!jsontext.empty()) { const auto reply = nlohmann::json::parse(jsontext); if (reply.find("data") == reply.end()) { throw std::runtime_error("the listing response was malformed"); } return processResponse(reply); } } return Listing::Page{}; } Listing::Page Listing::getPreviousPage() { if (_before.empty() || (_count - _limit) <= 0) { // we're at the first page, so no more pages return Listing::Page{}; } if (auto session = _sessionPtr.lock(); session) { _after.clear(); _count -= (_limit - 1); Params params{ _params }; params.insert_or_assign("limit", std::to_string(_limit)); params.insert_or_assign("before", _before); if (_count > 0) { params.insert_or_assign("count", std::to_string(_count)); } const auto jsontext = session->doGetRequest(_endpoint, params); if (!jsontext.empty()) { const auto reply = nlohmann::json::parse(jsontext); if (reply.find("data") == reply.end()) { throw std::runtime_error("the listing response was malformed"); } return processResponse(reply); } } return Listing::Page{}; } }
24.5
112
0.572754
zethon
92fcd40c24decc57806b41372a0eb24b1b9ffe72
11,907
hpp
C++
include/codegen/include/UnityEngine/ProBuilder/PreferenceDictionary.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/ProBuilder/PreferenceDictionary.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/ProBuilder/PreferenceDictionary.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:21 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: UnityEngine.ScriptableObject #include "UnityEngine/ScriptableObject.hpp" // Including type: UnityEngine.ISerializationCallbackReceiver #include "UnityEngine/ISerializationCallbackReceiver.hpp" // Including type: UnityEngine.ProBuilder.IHasDefault #include "UnityEngine/ProBuilder/IHasDefault.hpp" // Including type: UnityEngine.Color #include "UnityEngine/Color.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: Dictionary`2<TKey, TValue> template<typename TKey, typename TValue> class Dictionary_2; // Forward declaring type: Dictionary`2<TKey, TValue> template<typename TKey, typename TValue> class Dictionary_2; // Forward declaring type: Dictionary`2<TKey, TValue> template<typename TKey, typename TValue> class Dictionary_2; // Forward declaring type: Dictionary`2<TKey, TValue> template<typename TKey, typename TValue> class Dictionary_2; // Forward declaring type: Dictionary`2<TKey, TValue> template<typename TKey, typename TValue> class Dictionary_2; // Forward declaring type: Dictionary`2<TKey, TValue> template<typename TKey, typename TValue> class Dictionary_2; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Material class Material; } // Completed forward declares // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // Autogenerated type: UnityEngine.ProBuilder.PreferenceDictionary class PreferenceDictionary : public UnityEngine::ScriptableObject, public UnityEngine::ISerializationCallbackReceiver, public UnityEngine::ProBuilder::IHasDefault { public: // private System.Collections.Generic.Dictionary`2<System.String,System.Boolean> m_Bool // Offset: 0x18 System::Collections::Generic::Dictionary_2<::Il2CppString*, bool>* m_Bool; // private System.Collections.Generic.Dictionary`2<System.String,System.Int32> m_Int // Offset: 0x20 System::Collections::Generic::Dictionary_2<::Il2CppString*, int>* m_Int; // private System.Collections.Generic.Dictionary`2<System.String,System.Single> m_Float // Offset: 0x28 System::Collections::Generic::Dictionary_2<::Il2CppString*, float>* m_Float; // private System.Collections.Generic.Dictionary`2<System.String,System.String> m_String // Offset: 0x30 System::Collections::Generic::Dictionary_2<::Il2CppString*, ::Il2CppString*>* m_String; // private System.Collections.Generic.Dictionary`2<System.String,UnityEngine.Color> m_Color // Offset: 0x38 System::Collections::Generic::Dictionary_2<::Il2CppString*, UnityEngine::Color>* m_Color; // private System.Collections.Generic.Dictionary`2<System.String,UnityEngine.Material> m_Material // Offset: 0x40 System::Collections::Generic::Dictionary_2<::Il2CppString*, UnityEngine::Material*>* m_Material; // private System.Collections.Generic.List`1<System.String> m_Bool_keys // Offset: 0x48 System::Collections::Generic::List_1<::Il2CppString*>* m_Bool_keys; // private System.Collections.Generic.List`1<System.String> m_Int_keys // Offset: 0x50 System::Collections::Generic::List_1<::Il2CppString*>* m_Int_keys; // private System.Collections.Generic.List`1<System.String> m_Float_keys // Offset: 0x58 System::Collections::Generic::List_1<::Il2CppString*>* m_Float_keys; // private System.Collections.Generic.List`1<System.String> m_String_keys // Offset: 0x60 System::Collections::Generic::List_1<::Il2CppString*>* m_String_keys; // private System.Collections.Generic.List`1<System.String> m_Color_keys // Offset: 0x68 System::Collections::Generic::List_1<::Il2CppString*>* m_Color_keys; // private System.Collections.Generic.List`1<System.String> m_Material_keys // Offset: 0x70 System::Collections::Generic::List_1<::Il2CppString*>* m_Material_keys; // private System.Collections.Generic.List`1<System.Boolean> m_Bool_values // Offset: 0x78 System::Collections::Generic::List_1<bool>* m_Bool_values; // private System.Collections.Generic.List`1<System.Int32> m_Int_values // Offset: 0x80 System::Collections::Generic::List_1<int>* m_Int_values; // private System.Collections.Generic.List`1<System.Single> m_Float_values // Offset: 0x88 System::Collections::Generic::List_1<float>* m_Float_values; // private System.Collections.Generic.List`1<System.String> m_String_values // Offset: 0x90 System::Collections::Generic::List_1<::Il2CppString*>* m_String_values; // private System.Collections.Generic.List`1<UnityEngine.Color> m_Color_values // Offset: 0x98 System::Collections::Generic::List_1<UnityEngine::Color>* m_Color_values; // private System.Collections.Generic.List`1<UnityEngine.Material> m_Material_values // Offset: 0xA0 System::Collections::Generic::List_1<UnityEngine::Material*>* m_Material_values; // public System.Boolean HasKey(System.String key) // Offset: 0x101C094 bool HasKey(::Il2CppString* key); // public System.Boolean HasKey(System.String key) // Offset: 0xE4E1AC // ABORTED: conflicts with another method. bool HasKey(::Il2CppString* key) // public System.Void DeleteKey(System.String key) // Offset: 0x101C1B0 void DeleteKey(::Il2CppString* key); // public T Get(System.String key, T fallback) // Offset: 0xD3AE4C template<class T> T Get(::Il2CppString* key, T fallback) { return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<T>(this, "Get", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, key, fallback)); } // public System.Void Set(System.String key, T value) // Offset: 0xC4D178 template<class T> void Set(::Il2CppString* key, T value) { CRASH_UNLESS(il2cpp_utils::RunGenericMethod(this, "Set", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, key, value)); } // public System.Boolean GetBool(System.String key, System.Boolean fallback) // Offset: 0x101C374 bool GetBool(::Il2CppString* key, bool fallback); // public System.Int32 GetInt(System.String key, System.Int32 fallback) // Offset: 0x101C40C int GetInt(::Il2CppString* key, int fallback); // public System.Single GetFloat(System.String key, System.Single fallback) // Offset: 0x101C498 float GetFloat(::Il2CppString* key, float fallback); // public System.String GetString(System.String key, System.String fallback) // Offset: 0x101C52C ::Il2CppString* GetString(::Il2CppString* key, ::Il2CppString* fallback); // public UnityEngine.Color GetColor(System.String key, UnityEngine.Color fallback) // Offset: 0x101C5B8 UnityEngine::Color GetColor(::Il2CppString* key, UnityEngine::Color fallback); // public UnityEngine.Material GetMaterial(System.String key, UnityEngine.Material fallback) // Offset: 0x101C670 UnityEngine::Material* GetMaterial(::Il2CppString* key, UnityEngine::Material* fallback); // public System.Void SetBool(System.String key, System.Boolean value) // Offset: 0x101C6FC void SetBool(::Il2CppString* key, bool value); // public System.Void SetInt(System.String key, System.Int32 value) // Offset: 0x101C7B8 void SetInt(::Il2CppString* key, int value); // public System.Void SetFloat(System.String key, System.Single value) // Offset: 0x101C874 void SetFloat(::Il2CppString* key, float value); // public System.Void SetString(System.String key, System.String value) // Offset: 0x101C93C void SetString(::Il2CppString* key, ::Il2CppString* value); // public System.Void SetColor(System.String key, UnityEngine.Color value) // Offset: 0x101C9F8 void SetColor(::Il2CppString* key, UnityEngine::Color value); // public System.Void SetMaterial(System.String key, UnityEngine.Material value) // Offset: 0x101CAF0 void SetMaterial(::Il2CppString* key, UnityEngine::Material* value); // public System.Collections.Generic.Dictionary`2<System.String,System.Boolean> GetBoolDictionary() // Offset: 0x101CBAC System::Collections::Generic::Dictionary_2<::Il2CppString*, bool>* GetBoolDictionary(); // public System.Collections.Generic.Dictionary`2<System.String,System.Int32> GetIntDictionary() // Offset: 0x101CBB4 System::Collections::Generic::Dictionary_2<::Il2CppString*, int>* GetIntDictionary(); // public System.Collections.Generic.Dictionary`2<System.String,System.Single> GetFloatDictionary() // Offset: 0x101CBBC System::Collections::Generic::Dictionary_2<::Il2CppString*, float>* GetFloatDictionary(); // public System.Collections.Generic.Dictionary`2<System.String,System.String> GetStringDictionary() // Offset: 0x101CBC4 System::Collections::Generic::Dictionary_2<::Il2CppString*, ::Il2CppString*>* GetStringDictionary(); // public System.Collections.Generic.Dictionary`2<System.String,UnityEngine.Color> GetColorDictionary() // Offset: 0x101CBCC System::Collections::Generic::Dictionary_2<::Il2CppString*, UnityEngine::Color>* GetColorDictionary(); // public System.Collections.Generic.Dictionary`2<System.String,UnityEngine.Material> GetMaterialDictionary() // Offset: 0x101CBD4 System::Collections::Generic::Dictionary_2<::Il2CppString*, UnityEngine::Material*>* GetMaterialDictionary(); // public System.Void Clear() // Offset: 0x101CBDC void Clear(); // public System.Void OnBeforeSerialize() // Offset: 0x101B924 // Implemented from: UnityEngine.ISerializationCallbackReceiver // Base method: System.Void ISerializationCallbackReceiver::OnBeforeSerialize() void OnBeforeSerialize(); // Creating proxy method: UnityEngine_ISerializationCallbackReceiver_OnBeforeSerialize // Maps to method: OnBeforeSerialize void UnityEngine_ISerializationCallbackReceiver_OnBeforeSerialize(); // public System.Void OnAfterDeserialize() // Offset: 0x101BC08 // Implemented from: UnityEngine.ISerializationCallbackReceiver // Base method: System.Void ISerializationCallbackReceiver::OnAfterDeserialize() void OnAfterDeserialize(); // Creating proxy method: UnityEngine_ISerializationCallbackReceiver_OnAfterDeserialize // Maps to method: OnAfterDeserialize void UnityEngine_ISerializationCallbackReceiver_OnAfterDeserialize(); // public System.Void SetDefaultValues() // Offset: 0x101BFC4 // Implemented from: UnityEngine.ProBuilder.IHasDefault // Base method: System.Void IHasDefault::SetDefaultValues() void SetDefaultValues(); // public System.Void .ctor() // Offset: 0x101CC94 // Implemented from: UnityEngine.ScriptableObject // Base method: System.Void ScriptableObject::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static PreferenceDictionary* New_ctor(); }; // UnityEngine.ProBuilder.PreferenceDictionary } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::PreferenceDictionary*, "UnityEngine.ProBuilder", "PreferenceDictionary"); #pragma pack(pop)
51.103004
166
0.738809
Futuremappermydud