hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
475c6b2d3279c433fdf8b7adeaa360ee3671a805
661
cpp
C++
cses/graph-algorithms/flight-discount.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
cses/graph-algorithms/flight-discount.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
cses/graph-algorithms/flight-discount.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> #include <cpplib/graph/shortest-path/dijkstra.hpp> int32_t main(){ // https://cses.fi/problemset/task/1195 desync(); int n, m; cin >> n >> m; vvii adj(n+1), adjinv(n+1); for(int i=0; i<m; ++i){ int a, b, c; cin >> a >> b >> c; adj[a].pb({b, c}); adjinv[b].pb({a, c}); } vi from = dijkstra(1, adj, INF*INF), to = dijkstra(n, adjinv, INF*INF); int ans = from[n]; for(int u=1; u<=n; ++u){ for(ii vw:adj[u]){ int v = vw.ff, w = vw.ss; ans = min(ans, from[u] + w/2 + to[v]); } } cout << ans << endl; return 0; }
24.481481
75
0.465961
tysm
47614d5c08eaa65b87512ced2d003ab1dd8dc524
21,690
cpp
C++
Extensions/ZilchShaders/LibraryTranslator.cpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
52
2018-09-11T17:18:35.000Z
2022-03-13T15:28:21.000Z
Extensions/ZilchShaders/LibraryTranslator.cpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
1,409
2018-09-19T18:03:43.000Z
2021-06-09T08:33:33.000Z
Extensions/ZilchShaders/LibraryTranslator.cpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
26
2018-09-11T17:16:32.000Z
2021-11-22T06:21:19.000Z
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2015, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" namespace Zero { //-------------------------------------------------------------------MemberAccessResolverWrapper FunctionCallResolverWrapper::FunctionCallResolverWrapper() : mFnCall(nullptr), mConstructorCallResolver(nullptr) { } FunctionCallResolverWrapper::FunctionCallResolverWrapper(FunctionCallResolverFn fnCall) : mFnCall(fnCall), mConstructorCallResolver(nullptr) { } FunctionCallResolverWrapper::FunctionCallResolverWrapper(ConstructorCallResolverFn constructorCall) : mFnCall(nullptr), mConstructorCallResolver(constructorCall) { } FunctionCallResolverWrapper::FunctionCallResolverWrapper(StringParam str) : mFnCall(nullptr), mConstructorCallResolver(nullptr) { mBackupString = str; } void FunctionCallResolverWrapper::Translate(ZilchShaderTranslator* translator, Zilch::FunctionCallNode* fnCallNode, Zilch::MemberAccessNode* memberAccessNode, ZilchShaderTranslatorContext* context) { // Call the function pointer if we have it, otherwise use the backup string if(mFnCall != nullptr) mFnCall(translator, fnCallNode, memberAccessNode, context); else context->GetBuilder() << mBackupString; } void FunctionCallResolverWrapper::Translate(ZilchShaderTranslator* translator, Zilch::FunctionCallNode* fnCallNode, Zilch::StaticTypeNode* staticTypeNode, ZilchShaderTranslatorContext* context) { // Call the function pointer if we have it, otherwise use the backup string if(mConstructorCallResolver != nullptr) mConstructorCallResolver(translator, fnCallNode, staticTypeNode, context); else context->GetBuilder() << mBackupString; } void FunctionCallResolverWrapper::Translate(ZilchShaderTranslator* translator, ZilchShaderTranslatorContext* context) { context->GetBuilder() << mBackupString; } //-------------------------------------------------------------------MemberAccessResolverWrapper MemberAccessResolverWrapper::MemberAccessResolverWrapper() : mResolverFn(nullptr) { } MemberAccessResolverWrapper::MemberAccessResolverWrapper(MemberAccessResolverFn resolverFn) : mResolverFn(resolverFn) { } MemberAccessResolverWrapper::MemberAccessResolverWrapper(StringParam replacementStr) : mResolverFn(nullptr), mNameReplacementString(replacementStr) { } void MemberAccessResolverWrapper::Translate(ZilchShaderTranslator* translator, Zilch::MemberAccessNode* memberAccessNode, ZilchShaderTranslatorContext* context) { // Call the function pointer if we have it, otherwise use the backup string if(mResolverFn != nullptr) mResolverFn(translator, memberAccessNode, context); else context->GetBuilder() << mNameReplacementString; } //-------------------------------------------------------------------BinaryOpResolverWrapper BinaryOpResolverWrapper::BinaryOpResolverWrapper() : mResolverFn(nullptr) { } BinaryOpResolverWrapper::BinaryOpResolverWrapper(BinaryOpResolver resolverFn) : mResolverFn(resolverFn) { } BinaryOpResolverWrapper::BinaryOpResolverWrapper(StringParam replacementFnCallStr) : mResolverFn(nullptr), mReplacementFnCallStr(replacementFnCallStr) { } void BinaryOpResolverWrapper::Translate(ZilchShaderTranslator* translator, Zilch::BinaryOperatorNode* node, ZilchShaderTranslatorContext* context) { // Call the function pointer if we have it, otherwise use the backup string if(mResolverFn != nullptr) mResolverFn(translator, node, context); else { ScopedShaderCodeBuilder subBuilder(context); subBuilder << mReplacementFnCallStr << "("; context->Walker->Walk(translator, node->LeftOperand, context); subBuilder.Write(", "); context->Walker->Walk(translator, node->RightOperand, context); subBuilder.Write(")"); subBuilder.PopFromStack(); context->GetBuilder().Write(subBuilder.ToString()); } } //-------------------------------------------------------------------LibraryTranslator LibraryTranslator::LibraryTranslator() { Reset(); } void LibraryTranslator::Reset() { mNativeLibraryParser = nullptr; mTemplateTypeResolver = nullptr; mFunctionCallResolvers.Clear(); mBackupConstructorResolvers.Clear(); mMemberAccessFieldResolvers.Clear(); mMemberAccessPropertyResolvers.Clear(); mMemberAccessFunctionResolvers.Clear(); mBackupMemberAccessResolvers.Clear(); mBinaryOpResolvers.Clear(); mIntializerResolvers.Clear(); mRegisteredTemplates.Clear(); } void LibraryTranslator::RegisterNativeLibraryParser(NativeLibraryParser nativeLibraryParser) { mNativeLibraryParser = nativeLibraryParser; } void LibraryTranslator::ParseNativeLibrary(ZilchShaderTranslator* translator, ZilchShaderLibrary* shaderLibrary) { ErrorIf(mNativeLibraryParser == nullptr, "No native library parser registered"); (*mNativeLibraryParser)(translator, shaderLibrary); } void LibraryTranslator::RegisterFunctionCallResolver(Zilch::Function* fn, const FunctionCallResolverWrapper& wrapper) { ErrorIf(fn == nullptr, "Cannot register a null function. Many things will break in this case."); mFunctionCallResolvers[fn] = wrapper; } void LibraryTranslator::RegisterFunctionCallResolver(Zilch::Function* fn, FunctionCallResolverFn resolver) { ErrorIf(fn == nullptr, "Cannot register a null function. Many things will break in this case."); RegisterFunctionCallResolver(fn, FunctionCallResolverWrapper(resolver)); } void LibraryTranslator::RegisterFunctionCallResolver(Zilch::Function* fn, ConstructorCallResolverFn resolver) { ErrorIf(fn == nullptr, "Cannot register a null function. Many things will break in this case."); RegisterFunctionCallResolver(fn, FunctionCallResolverWrapper(resolver)); } void LibraryTranslator::RegisterFunctionCallResolver(Zilch::Function* fn, StringParam replacementStr) { ErrorIf(fn == nullptr, "Cannot register a null function. Many things will break in this case."); RegisterFunctionCallResolver(fn, FunctionCallResolverWrapper(replacementStr)); } void LibraryTranslator::RegisterBackupConstructorResolver(Zilch::Type* type, ConstructorCallResolverFn resolver) { mBackupConstructorResolvers[type] = FunctionCallResolverWrapper(resolver); } bool LibraryTranslator::ResolveFunctionCall(ZilchShaderTranslator* translator, Zilch::FunctionCallNode* fnCallNode, ZilchShaderTranslatorContext* context) { // Check and see if the left node is a static type node. This happens when constructing a type, such as Real2(); Zilch::StaticTypeNode* staticTypeNode = Zilch::Type::DynamicCast<Zilch::StaticTypeNode*>(fnCallNode->LeftOperand); if(staticTypeNode != nullptr) { FunctionCallResolverWrapper* wrapper = mFunctionCallResolvers.FindPointer(staticTypeNode->ConstructorFunction); if(wrapper != nullptr) { wrapper->Translate(translator, fnCallNode, staticTypeNode, context); return true; } wrapper = mBackupConstructorResolvers.FindPointer(staticTypeNode->ResultType); if(wrapper != nullptr) { wrapper->Translate(translator, fnCallNode, staticTypeNode, context); return true; } if(staticTypeNode->ConstructorFunction != nullptr && !translator->IsInOwningLibrary(staticTypeNode->ConstructorFunction->GetOwningLibrary())) { String msg = String::Format("Constructor of type '%s' is not able to be translated.", staticTypeNode->ResultType->ToString().c_str()); translator->SendTranslationError(staticTypeNode->Location, msg); } } // Otherwise try a member access node. This happens on both static and instance function calls. Zilch::MemberAccessNode* memberAccessNode = Zilch::Type::DynamicCast<Zilch::MemberAccessNode*>(fnCallNode->LeftOperand); if(memberAccessNode != nullptr) { FunctionCallResolverWrapper* wrapper = mFunctionCallResolvers.FindPointer(memberAccessNode->AccessedFunction); if(wrapper != nullptr) { wrapper->Translate(translator, fnCallNode, memberAccessNode, context); return true; } // If we are calling an extension function then mark the class with the extension function as a dependency. // There's no need to alter the translation though as the member access node and function translation should be the same as normal. ShaderFunction* extensionFunction = mTranslator->mCurrentLibrary->FindExtension(memberAccessNode->AccessedFunction); if(extensionFunction != nullptr) { context->mCurrentType->AddDependency(extensionFunction->mOwner); return false; } // Don't make it an error to not translate a function here. Since this is a member // access node we'll have another chance to translate it when we resolve MemberAccessNode. // This location allows a simpler replacement of just the function name (eg. Math.Dot -> dot). // If we can't translate it by the time we get there then it'll be an error. } // Otherwise we didn't have a special translation for this function, let the normal translation happen. return false; } bool LibraryTranslator::ResolveDefaultConstructor(ZilchShaderTranslator* translator, Zilch::Type* type, Zilch::Function* constructorFn, ZilchShaderTranslatorContext* context) { FunctionCallResolverWrapper* wrapper = mFunctionCallResolvers.FindPointer(constructorFn); if(wrapper != nullptr) { wrapper->Translate(translator, context); return true; } if(constructorFn != nullptr && !translator->IsInOwningLibrary(constructorFn->GetOwningLibrary())) { String msg = String::Format("Default constructor of type '%s' is not able to be translated", type->ToString().c_str()); translator->SendTranslationError(constructorFn->Location, msg); } return false; } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Field* field, const MemberAccessResolverWrapper& wrapper) { mMemberAccessFieldResolvers[field] = wrapper; } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Field* field, MemberAccessResolverFn resolverFn) { RegisterMemberAccessResolver(field, MemberAccessResolverWrapper(resolverFn)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Field* field, StringParam replacementStr) { RegisterMemberAccessResolver(field, MemberAccessResolverWrapper(replacementStr)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Property* prop, const MemberAccessResolverWrapper& wrapper) { ErrorIf(prop == nullptr, "Cannot register a null property. Many things will break in this case."); mMemberAccessPropertyResolvers[prop] = wrapper; } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Property* prop, MemberAccessResolverFn resolverFn) { RegisterMemberAccessResolver(prop, MemberAccessResolverWrapper(resolverFn)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Property* prop, StringParam replacementStr) { RegisterMemberAccessResolver(prop, MemberAccessResolverWrapper(replacementStr)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Function* function, const MemberAccessResolverWrapper& wrapper) { mMemberAccessFunctionResolvers[function] = wrapper; } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Function* function, MemberAccessResolverFn resolverFn) { RegisterMemberAccessResolver(function, MemberAccessResolverWrapper(resolverFn)); } void LibraryTranslator::RegisterMemberAccessResolver(Zilch::Function* function, StringParam replacementStr) { RegisterMemberAccessResolver(function, MemberAccessResolverWrapper(replacementStr)); } void LibraryTranslator::RegisterMemberAccessBackupResolver(Zilch::Type* type, MemberAccessResolverFn resolverFn) { mBackupMemberAccessResolvers[type] = MemberAccessResolverWrapper(resolverFn); } bool LibraryTranslator::ResolveMemberAccess(ZilchShaderTranslator* translator, Zilch::MemberAccessNode* memberAccessNode, ZilchShaderTranslatorContext* context) { if(memberAccessNode->AccessedField != nullptr) { Zilch::Field* field = memberAccessNode->AccessedField; MemberAccessResolverWrapper* wrapper = mMemberAccessFieldResolvers.FindPointer(field); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } // Get the bound type (converts indirection types to bound types) Zilch::Type* resultType = Zilch::BoundType::GetBoundType(memberAccessNode->LeftOperand->ResultType); wrapper = mBackupMemberAccessResolvers.FindPointer(resultType); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } else if(!mTranslator->IsInOwningLibrary(field->GetOwningLibrary())) { String msg = String::Format("Member Field '%s' is not able to be translated.", memberAccessNode->Name.c_str()); translator->SendTranslationError(memberAccessNode->Location, msg); } } if(memberAccessNode->AccessedProperty != nullptr) { Zilch::Property* prop = memberAccessNode->AccessedProperty; // If this is actually a get/set property then mark a dependency on the type that actually implements the extension function Zilch::GetterSetter* getSet = memberAccessNode->AccessedGetterSetter; if(getSet != nullptr) { if(memberAccessNode->IoUsage == Zilch::IoMode::ReadRValue) { ShaderFunction* extensionFunction = mTranslator->mCurrentLibrary->FindExtension(getSet->Get); if(extensionFunction != nullptr) { context->mCurrentType->AddDependency(extensionFunction->mOwner); return false; } // See if this function has been implemented by another class ShaderFunction* implementsFunction = mTranslator->mCurrentLibrary->FindImplements(getSet->Get); if(implementsFunction != nullptr) { // Mark the implementing class as a dependency of this one context->mCurrentType->AddDependency(implementsFunction->mOwner); // Instead of printing the function's name from zilch, replace it with the name of the implementing function context->GetBuilder() << implementsFunction->mShaderName; // Since we replaced a member with a function we have to manually add the function call parenthesis context->GetBuilder() << "("; // If this is an instance function then we have to pass through and translate 'this' if(!implementsFunction->IsStatic()) context->Walker->Walk(translator, memberAccessNode->LeftOperand, context); context->GetBuilder() << ")"; // Return that we replaced this member access return true; } } } MemberAccessResolverWrapper* wrapper = mMemberAccessPropertyResolvers.FindPointer(prop); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } // Check backup resolvers last, after we've tried all other options wrapper = mBackupMemberAccessResolvers.FindPointer(memberAccessNode->LeftOperand->ResultType); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } else if(!mTranslator->IsInOwningLibrary(prop->GetOwningLibrary())) { String resultType = memberAccessNode->LeftOperand->ResultType->ToString(); String propertyResultType = memberAccessNode->ResultType->ToString(); String msg = String::Format("Member property '%s:%s' on type '%s' is not able to be translated.", memberAccessNode->Name.c_str(), propertyResultType.c_str(), resultType.c_str()); translator->SendTranslationError(memberAccessNode->Location, msg); } } if(memberAccessNode->AccessedFunction != nullptr) { Zilch::Function* fn = memberAccessNode->AccessedFunction; // See if this function has been implemented by another class ShaderFunction* implementsFunction = mTranslator->mCurrentLibrary->FindImplements(fn); if(implementsFunction != nullptr) { // Mark the implementing class as a dependency of this one context->mCurrentType->AddDependency(implementsFunction->mOwner); // Instead of printing the function's name from zilch, replace it with the name of the implementing function context->GetBuilder() << implementsFunction->mShaderName; // Return that we replaced this function name return true; } MemberAccessResolverWrapper* wrapper = mMemberAccessFunctionResolvers.FindPointer(fn); if(wrapper != nullptr) { wrapper->Translate(translator, memberAccessNode, context); return true; } // For now just mark that extension functions are not errors (let translation happen as normal) // @JoshD: Cleanup and merge somehow with the function call portion! ShaderFunction* extensionFunction = mTranslator->mCurrentLibrary->FindExtension(fn); if(extensionFunction != nullptr) { return false; } else if(!mTranslator->IsInOwningLibrary(fn->GetOwningLibrary())) { String fnName = GetFunctionDescription(memberAccessNode->Name, memberAccessNode->AccessedFunction); String msg = String::Format("Member function '%s' is not able to be translated.", fnName.c_str()); translator->SendTranslationError(memberAccessNode->Location, msg); } } // Otherwise we didn't have a special translation for this member, let the normal translation happen. return false; } void LibraryTranslator::RegisterBinaryOpResolver(Zilch::Type* typeA, Zilch::Grammar::Enum op, Zilch::Type* typeB, const BinaryOpResolverWrapper wrapper) { String key = BuildString(typeA->ToString(), Zilch::Grammar::GetKeywordOrSymbol(op), typeB->ToString()); RegisterBinaryOpResolver(key, wrapper); } void LibraryTranslator::RegisterBinaryOpResolver(Zilch::Type* typeA, Zilch::Grammar::Enum op, Zilch::Type* typeB, StringParam replacementFnCallStr) { RegisterBinaryOpResolver(typeA, op, typeB, BinaryOpResolverWrapper(replacementFnCallStr)); } void LibraryTranslator::RegisterBinaryOpResolver(Zilch::Type* typeA, Zilch::Grammar::Enum op, Zilch::Type* typeB, BinaryOpResolver resolverFn) { RegisterBinaryOpResolver(typeA, op, typeB, BinaryOpResolverWrapper(resolverFn)); } void LibraryTranslator::RegisterBinaryOpResolver(StringParam key, const BinaryOpResolverWrapper wrapper) { mBinaryOpResolvers[key] = wrapper; } void LibraryTranslator::RegisterBinaryOpResolver(StringParam key, StringParam replacementFnCallStr) { RegisterBinaryOpResolver(key, BinaryOpResolverWrapper(replacementFnCallStr)); } void LibraryTranslator::RegisterBinaryOpResolver(StringParam key, BinaryOpResolver resolverFn) { RegisterBinaryOpResolver(key, BinaryOpResolverWrapper(resolverFn)); } bool LibraryTranslator::ResolveBinaryOp(ZilchShaderTranslator* translator, Zilch::BinaryOperatorNode* node, ZilchShaderTranslatorContext* context) { // Build the key for this operator which is (type)(operator)(type) and use that to lookup a replacement String operatorSignature = BuildString(node->LeftOperand->ResultType->ToString(), node->Operator->Token, node->RightOperand->ResultType->ToString()); BinaryOpResolverWrapper* resolverWrapper = mBinaryOpResolvers.FindPointer(operatorSignature); if(resolverWrapper != nullptr) resolverWrapper->Translate(translator, node, context); return resolverWrapper != nullptr; } void LibraryTranslator::RegisterTemplateTypeResolver(TemplateTypeResolver resolver) { mTemplateTypeResolver = resolver; } void LibraryTranslator::RegisterInitializerNodeResolver(Zilch::Type* type, InitializerResolver resolver) { mIntializerResolvers[type] = resolver; } bool LibraryTranslator::ResolveInitializerNode(ZilchShaderTranslator* translator, Zilch::Type* type, Zilch::ExpressionInitializerNode* initializerNode, ZilchShaderTranslatorContext* context) { InitializerResolver resolver = mIntializerResolvers.FindValue(type, nullptr); if(resolver == nullptr) return false; (*resolver)(translator, type, initializerNode, context); return true; } String LibraryTranslator::GetFunctionDescription(StringParam fnName, Zilch::Function* fn) { StringBuilder builder; builder.Append(fnName); fn->FunctionType->BuildSignatureString(builder, false); return builder.ToString(); } bool LibraryTranslator::IsUserLibrary(Zilch::Library* library) { //@JoshD: Fix! Array<ZilchShaderLibrary*> libraryStack; libraryStack.PushBack(mTranslator->mCurrentLibrary); while(!libraryStack.Empty()) { ZilchShaderLibrary* testLibrary = libraryStack.Back(); libraryStack.PopBack(); Zilch::Library* testZilchLibrary = testLibrary->mZilchLibrary; // If the library is the same and it's user code // (as in we compiled zilch scripts, not C++) then this is a user library if(testZilchLibrary == library && testLibrary->mIsUserCode) return true; // Add all dependencies of this library ZilchShaderModule* dependencies = testLibrary->mDependencies; if(dependencies != nullptr) { for(size_t i = 0; i < dependencies->Size(); ++i) libraryStack.PushBack((*dependencies)[i]); } } return false; } }//namespace Zero
41.235741
198
0.734071
RachelWilSingh
4766675bb3b3c49968239efc5d6e18f6cda280fd
6,022
hpp
C++
src/alignment.hpp
h-2/vaquita
8ec97df9be7ff50166bc724065be6a49575f7d48
[ "BSD-3-Clause" ]
11
2017-06-14T06:17:40.000Z
2021-02-10T11:24:42.000Z
src/alignment.hpp
h-2/vaquita
8ec97df9be7ff50166bc724065be6a49575f7d48
[ "BSD-3-Clause" ]
11
2017-06-15T11:53:17.000Z
2020-12-16T08:57:56.000Z
src/alignment.hpp
h-2/vaquita
8ec97df9be7ff50166bc724065be6a49575f7d48
[ "BSD-3-Clause" ]
2
2017-06-13T15:31:34.000Z
2018-10-16T13:30:41.000Z
// ========================================================================== // Vaquita // ========================================================================== // Copyright (c) 2017, Jongkyu Kim, MPI-MolGen/FU-Berlin // 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 Jongkyu Kim or the FU Berlin 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 JONGKYU KIM OR THE FU BERLIN 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. // // ========================================================================== // Author: Jongkyu Kim <j.kim@fu-berlin.de> // ========================================================================== #ifndef APP_ALIGNMENT_H_ #define APP_ALIGNMENT_H_ #include "calloption.hpp" #include "candidate.hpp" // ========================================================================== // Tags, Classes, Enums // ========================================================================== typedef std::pair<int32_t, BamAlignmentRecord> TInsBamRecordPair; class AlignmentManager { private : static unsigned const PRINT_READ_NUMBER_PER = 100000000; //static unsigned const PRINT_READ_NUMBER_PER = 10000000; static unsigned const INS_SIZE_ESTIMATION_SAMPLE_SIZE = 100000; double K = 1.4826; // option CallOptionManager* optionManager; // bam record BamFileIn bamFileIn; BamHeader bamHeader; BamIndex<Bai> baiIndex; BamFileOut* pBamFileOut; // breakpoint candidates BreakpointCandidate* splitRead; BreakpointCandidate* pairedEndRead; BreakpointCandidate* clippedRead; BreakpointCandidate* readDepth; // information of a dataset std::map<TTemplateID, TPosition> templateLength; std::vector<TInsBamRecordPair> readsForMedInsEst; std::vector<BamAlignmentRecord> readsBuffer; double insertMedian; double insertDev; // median absolute deviation double minAbInsSize; double maxAbInsSize; int32_t totalRecordNum; int32_t splitReadCount; int32_t pairedReadCount; int32_t clippedReadCount; void calcInsertSize(); //bool isAbnormalInsertion(unsigned ins) { return ( (ins < this->minAbInsSize) || (ins > this->maxAbInsSize) ); } bool isAbnormalInsertion(unsigned ins) { return (ins > this->maxAbInsSize); } double getMaxAbInsSize(void) { return this->maxAbInsSize; } double getMinAbInsSize(void) { return this->minAbInsSize; } static bool pairCompare(const TInsBamRecordPair& e1, const TInsBamRecordPair& e2) { return e1.first < e2.first; } public : AlignmentManager() : optionManager(NULL) {} AlignmentManager(CallOptionManager & op) { init(op); } ~AlignmentManager() { close(bamFileIn); close(*pBamFileOut); } void init(CallOptionManager & op) { optionManager = &op; insertMedian = 0; insertDev = 0.0; minAbInsSize = std::numeric_limits<double>::min(); maxAbInsSize = std::numeric_limits<double>::max(); splitReadCount = 0; pairedReadCount = 0; clippedReadCount = 0; } void setBreakpointCandidate(BreakpointCandidate* s, BreakpointCandidate* p, BreakpointCandidate* e, BreakpointCandidate* r) { splitRead = s; pairedEndRead = p; clippedRead = e; readDepth = r; } // [start, end) void getSequenceAndDepth(CharString&, std::vector<int32_t>&, TTemplateID, TPosition, TPosition); void getSequence(CharString&, TTemplateID, TPosition, TPosition); void getDepth(std::vector<int32_t>&, TTemplateID, TPosition, TPosition); int32_t getSplitReadCount(void) { return splitReadCount; } int32_t getPairedReadCount(void) { return pairedReadCount; } int32_t getClippedReadCount(void) { return clippedReadCount; } int32_t getTotalRecordNum() { return totalRecordNum; } double getInsMedian() { return insertMedian; } double getInsSD() { return insertDev; } double getAbInsParam() { return optionManager->getAbInsParam(); } CharString getRefName(int32_t id); int32_t getRefCount(); std::map<TTemplateID, TPosition>* getTemplateLength(void) { return &templateLength; } CallOptionManager* getOptionManager(void) { return this->optionManager; } void printRecord(BamAlignmentRecord &); bool load(void); }; #endif // APP_ALIGNMENT_H_
44.279412
131
0.62089
h-2
47684729576dfa76505d3551eec1f5544e4b1749
325
cc
C++
common/buffer/buffer_error.cc
changchengx/ReplicWBCache
f0a8ef3108513fcac3a2291dafaebfb52cacfcac
[ "Apache-2.0" ]
null
null
null
common/buffer/buffer_error.cc
changchengx/ReplicWBCache
f0a8ef3108513fcac3a2291dafaebfb52cacfcac
[ "Apache-2.0" ]
null
null
null
common/buffer/buffer_error.cc
changchengx/ReplicWBCache
f0a8ef3108513fcac3a2291dafaebfb52cacfcac
[ "Apache-2.0" ]
null
null
null
/* * SPDX-License-Identifier: Apache-2.0 * Copyright(c) 2020 Liu, Changcheng <changcheng.liu@aliyun.com> */ #include <iostream> #include "buffer/buffer_error.h" std::ostream& spec::buffer::operator<<(std::ostream& out, const spec::buffer::error& berror) { const char* info = berror.what(); return out << info; }
25
94
0.683077
changchengx
4769e3dac92d306980461b3534ecb870f1dff916
682
hpp
C++
src/include/migraphx/time.hpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
72
2018-12-06T18:31:17.000Z
2022-03-30T15:01:02.000Z
src/include/migraphx/time.hpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
1,006
2018-11-30T16:32:33.000Z
2022-03-31T22:43:39.000Z
src/include/migraphx/time.hpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
36
2019-05-07T10:41:46.000Z
2022-03-28T15:59:56.000Z
#ifndef MIGRAPHX_GUARD_RTGLIB_TIME_HPP #define MIGRAPHX_GUARD_RTGLIB_TIME_HPP #include <chrono> #include <migraphx/config.hpp> namespace migraphx { inline namespace MIGRAPHX_INLINE_NS { struct timer { std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now(); template <class Duration> auto record() const { auto finish = std::chrono::steady_clock::now(); return std::chrono::duration_cast<Duration>(finish - start).count(); } }; template <class Duration, class F> auto time(F f) { timer t{}; f(); return t.record<Duration>(); } } // namespace MIGRAPHX_INLINE_NS } // namespace migraphx #endif
20.666667
96
0.696481
raramakr
476c479cdfcd3cbd35ea8f9f9d6f33c1e5e24777
338
cc
C++
lib/AST/OutputPort.cc
rawatamit/scheme
2c5e121fa873a2fb7762b69027480e28686bbb87
[ "MIT" ]
null
null
null
lib/AST/OutputPort.cc
rawatamit/scheme
2c5e121fa873a2fb7762b69027480e28686bbb87
[ "MIT" ]
null
null
null
lib/AST/OutputPort.cc
rawatamit/scheme
2c5e121fa873a2fb7762b69027480e28686bbb87
[ "MIT" ]
null
null
null
#include "AST/OutputPort.h" Scheme::OutputPort::OutputPort(FILE* out) : Scheme::SchemeObject(Scheme::SchemeObject::OUTPUT_PORT_TY), out_(out) {} Scheme::OutputPort::~OutputPort() {} FILE* Scheme::OutputPort::getOutputStream() const { return out_; } int Scheme::OutputPort::closeOutputStream() { return fclose(out_); }
19.882353
77
0.707101
rawatamit
476dafc7c493d911796401bf107e152777f5ee12
4,959
cpp
C++
pj_tensorrt_depth_stereo_hitnet/image_processor/image_processor.cpp
Pandinosaurus/play_with_tensorrt
250bfaef2f880ea3131d6ddfcc4870140cc9964e
[ "Apache-2.0" ]
null
null
null
pj_tensorrt_depth_stereo_hitnet/image_processor/image_processor.cpp
Pandinosaurus/play_with_tensorrt
250bfaef2f880ea3131d6ddfcc4870140cc9964e
[ "Apache-2.0" ]
null
null
null
pj_tensorrt_depth_stereo_hitnet/image_processor/image_processor.cpp
Pandinosaurus/play_with_tensorrt
250bfaef2f880ea3131d6ddfcc4870140cc9964e
[ "Apache-2.0" ]
null
null
null
/*** Include ***/ /* for general */ #include <cstdint> #include <cstdlib> #include <cmath> #include <cstring> #include <string> #include <vector> #include <array> #include <algorithm> #include <chrono> #include <fstream> #include <memory> /* for OpenCV */ #include <opencv2/opencv.hpp> /* for My modules */ #include "common_helper.h" #include "common_helper_cv.h" #include "depth_stereo_engine.h" #include "image_processor.h" /*** Macro ***/ #define TAG "ImageProcessor" #define PRINT(...) COMMON_HELPER_PRINT(TAG, __VA_ARGS__) #define PRINT_E(...) COMMON_HELPER_PRINT_E(TAG, __VA_ARGS__) /*** Global variable ***/ std::unique_ptr<DepthStereoEngine> s_engine; /*** Function ***/ static void DrawFps(cv::Mat& mat, double time_inference, cv::Point pos, double font_scale, int32_t thickness, cv::Scalar color_front, cv::Scalar color_back, bool is_text_on_rect = true) { char text[64]; static auto time_previous = std::chrono::steady_clock::now(); auto time_now = std::chrono::steady_clock::now(); double fps = 1e9 / (time_now - time_previous).count(); time_previous = time_now; snprintf(text, sizeof(text), "FPS: %.1f, Inference: %.1f [ms]", fps, time_inference); CommonHelper::DrawText(mat, text, cv::Point(0, 0), 0.5, 2, CommonHelper::CreateCvColor(0, 0, 0), CommonHelper::CreateCvColor(180, 180, 180), true); } int32_t ImageProcessor::Initialize(const InputParam& input_param) { if (s_engine) { PRINT_E("Already initialized\n"); return -1; } s_engine.reset(new DepthStereoEngine()); if (s_engine->Initialize(input_param.work_dir, input_param.num_threads) != DepthStereoEngine::kRetOk) { s_engine->Finalize(); s_engine.reset(); return -1; } return 0; } int32_t ImageProcessor::Finalize(void) { if (!s_engine) { PRINT_E("Not initialized\n"); return -1; } if (s_engine->Finalize() != DepthStereoEngine::kRetOk) { return -1; } return 0; } int32_t ImageProcessor::Command(int32_t cmd) { if (!s_engine) { PRINT_E("Not initialized\n"); return -1; } switch (cmd) { case 0: default: PRINT_E("command(%d) is not supported\n", cmd); return -1; } } static cv::Mat ConvertDisparity2Depth(const cv::Mat& mat_disparity, float fov, float baseline, float mag = 1.0f) { cv::Mat mat_depth(mat_disparity.size(), CV_8UC1); const float scale = mag * fov * baseline; #pragma omp parallel for for (int32_t i = 0; i < mat_disparity.total(); i++) { if (mat_disparity.at<float>(i) > 0) { float Z = scale / mat_disparity.at<float>(i); // [meter] if (Z <= 255.0f) { mat_depth.at<uint8_t>(i) = static_cast<uint8_t>(Z); } else { mat_depth.at<uint8_t>(i) = 255; } } else { mat_depth.at<uint8_t>(i) = 255; } } return mat_depth; } static cv::Mat NormalizeDisparity(const cv::Mat& mat_disparity, float max_disparity, float mag = 1.0f) { cv::Mat mat_depth(mat_disparity.size(), CV_8UC1); const float scale = mag * 255.0f / max_disparity; #pragma omp parallel for for (int32_t i = 0; i < mat_disparity.total(); i++) { mat_depth.at<uint8_t>(i) = static_cast<uint8_t>(mat_disparity.at<float>(i) * scale); } return mat_depth; } int32_t ImageProcessor::Process(cv::Mat& mat_left, cv::Mat& mat_right, cv::Mat& mat_result, Result& result) { if (!s_engine) { PRINT_E("Not initialized\n"); return -1; } DepthStereoEngine::Result ss_result; if (s_engine->Process(mat_left, mat_right, ss_result) != DepthStereoEngine::kRetOk) { return -1; } /* Convert to colored depth map */ //cv::Mat mat_depth = ConvertDisparity2Depth(ss_result.image, 500.0f, 0.2f, 50); cv::Mat mat_depth = NormalizeDisparity(ss_result.image, s_engine->GetMaxDisparity(), 1.0f); cv::applyColorMap(mat_depth, mat_depth, cv::COLORMAP_MAGMA); /* Create result image */ cv::Mat mat_depth_orgsize = cv::Mat::zeros(mat_left.size(), CV_8UC3); cv::Mat mat_depth_orgsize_cropped = mat_depth_orgsize(cv::Rect(ss_result.crop.x, ss_result.crop.y, ss_result.crop.w, ss_result.crop.h)); cv::resize(mat_depth, mat_depth_orgsize_cropped, mat_depth_orgsize_cropped.size()); cv::vconcat(mat_left, mat_depth_orgsize, mat_result); if (mat_result.rows > 1080) {// just to fit to my display cv::resize(mat_result, mat_result, cv::Size(), 960.0f / mat_result.rows, 960.0f / mat_result.rows); } DrawFps(mat_result, ss_result.time_inference, cv::Point(0, 0), 0.5, 2, CommonHelper::CreateCvColor(0, 0, 0), CommonHelper::CreateCvColor(180, 180, 180), true); /* Return the results */ result.time_pre_process = ss_result.time_pre_process; result.time_inference = ss_result.time_inference; result.time_post_process = ss_result.time_post_process; return 0; }
31.386076
185
0.655576
Pandinosaurus
476e156b97f8e3552d02104d5edbe3c0bde6a514
9,400
cpp
C++
BesImage/appConfig.cpp
BensonLaur/BesImage
63e32cc35db093fbe3f3033c32837ee6595d8c49
[ "MIT" ]
2
2019-10-17T06:13:13.000Z
2020-05-24T12:39:47.000Z
BesImage/appConfig.cpp
BensonLaur/BesImage
63e32cc35db093fbe3f3033c32837ee6595d8c49
[ "MIT" ]
null
null
null
BesImage/appConfig.cpp
BensonLaur/BesImage
63e32cc35db093fbe3f3033c32837ee6595d8c49
[ "MIT" ]
3
2019-06-30T02:31:42.000Z
2021-11-30T02:14:24.000Z
#include "appConfig.h" AppConfig& AppConfig::GetInstance() { static AppConfig* instance = nullptr; if(instance == nullptr) instance = new AppConfig(); return *instance; } //获得打数 (如果未加载自动去文件读取,已加载则使用已载入的参数。bForceLoadFromFile 强制从文件获得最新参数) bool AppConfig::GetAppParameter(AppConfigParameter& param, bool bForceLoadFromFile) { if(!m_hasLoad || bForceLoadFromFile) { QString confPath; if(!MakeSureConfigPathAvailable(confPath)) //获得路径 return false; if(!QFile::exists(confPath)) //不存在,自动创建配置,并提示 { param = AppConfigParameter(); if(SetAppParameter(param)) QMessageBox::information(nullptr,tr("提示"),tr("配置文件不存在,已自动创建")+":" + confPath, QMessageBox::Yes,QMessageBox::Yes); else QMessageBox::information(nullptr,tr("提示"),tr("配置文件不存在,自动创建失败")+":" + confPath, QMessageBox::Yes,QMessageBox::Yes); m_param = param; } else //存在,读取配置 { if(!LoadAppConfig()) QMessageBox::information(nullptr,tr("提示"),tr("载入配置文件失败")+":" + confPath, QMessageBox::Yes,QMessageBox::Yes); } m_hasLoad = true; } param = m_param; return true; } //设置参数 bool AppConfig::SetAppParameter(const AppConfigParameter& param) { m_param = param; return SaveAppConfig(); } //判断当前配置是否是有效的“只显示一张图片” bool AppConfig::IsValidOnlyShowOneImage() { if(m_param.onlyShowOneImage) //有设置onluyShowOneImage { if(m_param.initPath.size() != 0) { QFileInfo fi(m_param.initPath); if(fi.isFile()) //传入的路径确实是一个文件 return true; } } return false; } //从默认路径中加载打印参数 bool AppConfig::LoadAppConfig() { QString confPath; if(!MakeSureConfigPathAvailable(confPath)) //确保配置路径可用,并获得了路径 return false; //打开文件 QFile file(confPath); if (!file.open(QFile::ReadOnly | QFile::Text)) { // 只读模式打开文件 qDebug() << QString("Cannot read file %1(%2).").arg(confPath).arg(file.errorString()); return false; } AppConfigParameter param; //读取示例参考: https://blog.csdn.net/liang19890820/article/details/52808829 //将配置从xml文件读出 QXmlStreamReader reader(&file); QString strElementName = ""; // 解析 XML,直到结束 while (!reader.atEnd()) { // 读取下一个元素 QXmlStreamReader::TokenType nType = reader.readNext(); if (nType == QXmlStreamReader::StartElement) { strElementName = reader.name().toString(); if (QString::compare(strElementName, "appConfig") == 0) // 根元素 { parseConfig(reader, param); //解析 printConfig } } } if (reader.hasError()) { // 解析出错 qDebug() << QObject::tr("错误信息:%1 行号:%2 列号:%3 字符位移:%4").arg(reader.errorString()).arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.characterOffset()); } file.close(); // 关闭文件 m_param = param; return true; } //解析config void AppConfig::parseConfig(QXmlStreamReader &reader, AppConfigParameter &param) { while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { // 开始元素 QString strElementName = reader.name().toString(); if(strElementName == "user") { parseUser(reader, param); } else if(strElementName == "default") { parseDefault(reader, param); } } else if(reader.isEndElement()) { QString strElementName = reader.name().toString(); if (QString::compare(strElementName, "appConfig") == 0) { break; // 跳出 } } } } //解析user void AppConfig::parseUser(QXmlStreamReader &reader, AppConfigParameter &param) { while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { // 开始元素 QString strElementName = reader.name().toString(); if(strElementName == "functionMode") { param.functionMode = (FunctionMode)reader.readElementText().toInt(); } else if(strElementName == "appTitle") { param.appTitle = reader.readElementText(); } else if(strElementName == "iconPath") { param.iconPath = reader.readElementText(); } else if(strElementName == "backgroundImagePath") { param.backgroundImagePath = reader.readElementText(); } else if(strElementName == "initPath") { param.initPath = reader.readElementText(); } else if(strElementName == "onlyShowOneImage") { param.onlyShowOneImage = reader.readElementText().toInt()== 0 ? false:true; } else if(strElementName == "closeDirTreeOnOpen") { param.closeDirTreeOnOpen = reader.readElementText().toInt() == 0 ? false:true; } } else if(reader.isEndElement()) { QString strElementName = reader.name().toString(); if (QString::compare(strElementName, "user") == 0) { break; // 跳出 } } } } //解析default void AppConfig::parseDefault(QXmlStreamReader &reader, AppConfigParameter &param) { while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { // 开始元素 QString strElementName = reader.name().toString(); if(strElementName == "defaultBackgroundPath") { param.defaultBackgroundPath = reader.readElementText(); } else if(strElementName == "besimageBlackIcon") { param.besimageBlackIcon = reader.readElementText(); } else if(strElementName == "besimageWhiteIcon") { param.besimageWhiteIcon = reader.readElementText(); } else if(strElementName == "isWindowHeaderColorBlack") { param.isWindowHeaderColorBlack = reader.readElementText().toInt()== 0 ? false:true; } else if(strElementName == "bgFillMode") { param.bgFillMode = (BGFillMode)reader.readElementText().toInt(); } } else if(reader.isEndElement()) { QString strElementName = reader.name().toString(); if (QString::compare(strElementName, "default") == 0) { break; // 跳出 } } } } //保存到打印参数 bool AppConfig::SaveAppConfig() { QString confPath; if(!MakeSureConfigPathAvailable(confPath)) //确保配置路径可用,并获得了路径 return false; //打开文件 QFile file(confPath); if (!file.open(QFile::WriteOnly | QFile::Text)) { // 只写模式打开文件 qDebug() << QString("Cannot write file %1(%2).").arg(confPath).arg(file.errorString()); return false; } //将配置写入xml文件 QXmlStreamWriter writer(&file); writer.setAutoFormatting(true); // 自动格式化 writer.writeStartDocument("1.0", true); // 开始文档(XML 声明) writer.writeStartElement("appConfig"); // 开始元素<appConfig> writer.writeStartElement("user"); // 开始元素<user> writer.writeTextElement("functionMode", QString::number((int)m_param.functionMode)); writer.writeTextElement("appTitle", m_param.appTitle); writer.writeTextElement("iconPath", m_param.iconPath); writer.writeTextElement("backgroundImagePath", m_param.backgroundImagePath); writer.writeTextElement("initPath", m_param.initPath); writer.writeTextElement("onlyShowOneImage", QString::number(m_param.onlyShowOneImage ? 1 : 0)); writer.writeTextElement("closeDirTreeOnOpen", QString::number(m_param.closeDirTreeOnOpen? 1 : 0)); writer.writeEndElement(); // 结束子元素 </user> writer.writeStartElement("default"); // 开始元素<default> writer.writeTextElement("defaultBackgroundPath", m_param.defaultBackgroundPath); writer.writeTextElement("besimageBlackIcon", m_param.besimageBlackIcon); writer.writeTextElement("besimageWhiteIcon", m_param.besimageWhiteIcon); writer.writeTextElement("isWindowHeaderColorBlack", QString::number(m_param.isWindowHeaderColorBlack ? 1 : 0)); writer.writeTextElement("bgFillMode", QString::number((int)m_param.bgFillMode)); writer.writeEndElement(); // 结束子元素 </default> writer.writeEndElement(); // 结束子元素 </appConfig> writer.writeEndDocument(); // 结束文档 file.close(); // 关闭文件 return true; } //确保配置路径可用,返回配置路径 bool AppConfig::MakeSureConfigPathAvailable(QString &path) { QString StrSettingsDir = QCoreApplication::applicationDirPath() + "/settings"; //如果settings 目录不存在则创建目录 QDir SettingDir(StrSettingsDir); if(!SettingDir.exists()) { if(!SettingDir.mkpath(StrSettingsDir)) { QMessageBox::information(nullptr,tr("提示"),tr("无法为配置创建目录")+":" + StrSettingsDir, QMessageBox::Yes,QMessageBox::Yes); return false; } } //得到目标路径 path = StrSettingsDir + "/app.config"; return true; }
29.936306
177
0.58266
BensonLaur
4778a51eccb0064ff5353bb11892d0feff6d2070
1,710
cpp
C++
Compiler/ErrorHandler.cpp
davidov541/MiniC
d3b16a1568b97a4d801880b110a8be04fe848adb
[ "Apache-2.0" ]
null
null
null
Compiler/ErrorHandler.cpp
davidov541/MiniC
d3b16a1568b97a4d801880b110a8be04fe848adb
[ "Apache-2.0" ]
null
null
null
Compiler/ErrorHandler.cpp
davidov541/MiniC
d3b16a1568b97a4d801880b110a8be04fe848adb
[ "Apache-2.0" ]
null
null
null
#include "ErrorHandler.h" #include "stdafx.h" namespace MiniC { ErrorHandler* ErrorHandler::instance = NULL; ErrorHandler::ErrorHandler(int debugCode) { this->debugCode = debugCode; } ErrorHandler::~ErrorHandler() { } bool ErrorHandler::CheckFlag() { bool flag = this->FlagRaised; this->FlagRaised = false; return flag; } void ErrorHandler::SetFlag() { this->FlagRaised = true; } ErrorHandler* ErrorHandler::GetInstance() { return GetInstance(0); } ErrorHandler* ErrorHandler::GetInstance(int debugCode) { if (instance == NULL) { instance = new ErrorHandler(debugCode); } return instance; } void ErrorHandler::ClearErrors() { instance = NULL; } void ErrorHandler::RegisterError(std::wstring message) { this->ErrorList.push_back(Error(this->currFunc, message)); } bool ErrorHandler::IsEmpty() { return this->ErrorList.size() == 0; } std::wstring ErrorHandler::PrintErrors() { int errorCount = 0; std::wstringstream errorMsgs; BOOST_FOREACH(Error e, this->ErrorList) { errorMsgs << L"Error "; errorMsgs << ++errorCount; errorMsgs << L" in "; errorMsgs << e.GetLocation(); errorMsgs << L": "; errorMsgs << e.GetMessage(); errorMsgs << std::endl; } return errorMsgs.str(); } void ErrorHandler::EnterFunc(std::wstring function) { this->currFunc = function; } int ErrorHandler::GetDebugCode() { return this->debugCode; } Error::Error(std::wstring function, std::wstring message) { this->function = function; this->message = message; } Error::~Error() { } std::wstring Error::GetMessage() { return this->message; } std::wstring Error::GetLocation() { return this->function; } }
17.1
60
0.669006
davidov541
47796a9a1dbf55676661038472e0926a913caf1b
820
cpp
C++
CorrelationApp/CheckCorrelation/main.cpp
zkbreeze/KunPBR
9f545a4e589998691b469bbcadb65a63ac826ebd
[ "BSD-3-Clause" ]
null
null
null
CorrelationApp/CheckCorrelation/main.cpp
zkbreeze/KunPBR
9f545a4e589998691b469bbcadb65a63ac826ebd
[ "BSD-3-Clause" ]
null
null
null
CorrelationApp/CheckCorrelation/main.cpp
zkbreeze/KunPBR
9f545a4e589998691b469bbcadb65a63ac826ebd
[ "BSD-3-Clause" ]
null
null
null
// // main.cpp // // // Created by Kun Zhao on 2015-12-11 15:22:50. // // #include <iostream> #include <fstream> #include "Correlation.h" // Load test csv data int main( int argc, char** argv ) { std::ifstream ifs( argv[1], std::ifstream::in ); char* buf = new char[256]; ifs.getline( buf, 256 ); // Skip ifs.getline( buf, 256 ); // Skip kvs::ValueArray<float> sequences1; sequences1.allocate( 27 ); kvs::ValueArray<float> sequences2; sequences2.allocate( 27 ); for( size_t i = 0; i < 27; i++ ) { ifs.getline( buf, 256 ); std::sscanf( buf, "%f,%f", &sequences1.data()[i], &sequences2.data()[i] ); std::cout << sequences1.data()[i] << ", " << sequences2.data()[i] <<std::endl; } float correlation = kun::Correlation::calculate( sequences1, sequences2 ); std::cout << correlation << std::endl; }
23.428571
80
0.62439
zkbreeze
47796f2012760298993adf0f73bdbf77d162e967
3,064
cpp
C++
higan/sfc/coprocessor/icd2/interface/interface.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
3
2016-03-23T01:17:36.000Z
2019-10-25T06:41:09.000Z
higan/sfc/coprocessor/icd2/interface/interface.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
higan/sfc/coprocessor/icd2/interface/interface.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
auto ICD2::lcdScanline() -> void { if(GameBoy::ppu.status.ly > 143) return; //Vblank if((GameBoy::ppu.status.ly & 7) == 0) { write_bank = (write_bank + 1) & 3; write_addr = 0; } } auto ICD2::lcdOutput(uint2 color) -> void { uint y = write_addr / 160; uint x = write_addr % 160; uint addr = write_bank * 512 + y * 2 + x / 8 * 16; output[addr + 0] = (output[addr + 0] << 1) | (bool)(color & 1); output[addr + 1] = (output[addr + 1] << 1) | (bool)(color & 2); write_addr = (write_addr + 1) % 1280; } auto ICD2::joypWrite(bool p15, bool p14) -> void { //joypad handling if(p15 == 1 && p14 == 1) { if(joyp15lock == 0 && joyp14lock == 0) { joyp15lock = 1; joyp14lock = 1; joyp_id = (joyp_id + 1) & 3; } } if(p15 == 0 && p14 == 1) joyp15lock = 0; if(p15 == 1 && p14 == 0) joyp14lock = 0; //packet handling if(p15 == 0 && p14 == 0) { //pulse pulselock = false; packetoffset = 0; bitoffset = 0; strobelock = true; packetlock = false; return; } if(pulselock) return; if(p15 == 1 && p14 == 1) { strobelock = false; return; } if(strobelock) { if(p15 == 1 || p14 == 1) { //malformed packet packetlock = false; pulselock = true; bitoffset = 0; packetoffset = 0; } else { return; } } //p15:1, p14:0 = 0 //p15:0, p14:1 = 1 bool bit = (p15 == 0); strobelock = true; if(packetlock) { if(p15 == 1 && p14 == 0) { if((joyp_packet[0] >> 3) == 0x11) { mlt_req = joyp_packet[1] & 3; if(mlt_req == 2) mlt_req = 3; joyp_id = 0; } if(packetsize < 64) packet[packetsize++] = joyp_packet; packetlock = false; pulselock = true; } return; } bitdata = (bit << 7) | (bitdata >> 1); if(++bitoffset < 8) return; bitoffset = 0; joyp_packet[packetoffset] = bitdata; if(++packetoffset < 16) return; packetlock = true; } auto ICD2::videoColor(uint source, uint16 red, uint16 green, uint16 blue) -> uint32 { return source; } auto ICD2::videoRefresh(const uint32* data, uint pitch, uint width, uint height) -> void { } auto ICD2::audioSample(int16 left, int16 right) -> void { audio.coprocessor_sample(left, right); } auto ICD2::inputPoll(uint port, uint device, uint id) -> int16 { GameBoy::cpu.status.mlt_req = joyp_id & mlt_req; uint data = 0x00; switch(joyp_id & mlt_req) { case 0: data = ~r6004; break; case 1: data = ~r6005; break; case 2: data = ~r6006; break; case 3: data = ~r6007; break; } switch((GameBoy::Input)id) { case GameBoy::Input::Start: return (bool)(data & 0x80); case GameBoy::Input::Select: return (bool)(data & 0x40); case GameBoy::Input::B: return (bool)(data & 0x20); case GameBoy::Input::A: return (bool)(data & 0x10); case GameBoy::Input::Down: return (bool)(data & 0x08); case GameBoy::Input::Up: return (bool)(data & 0x04); case GameBoy::Input::Left: return (bool)(data & 0x02); case GameBoy::Input::Right: return (bool)(data & 0x01); } return 0; }
24.910569
90
0.574739
ameer-bauer
477a2dce24aedf16869dd3b5bd5701dc2f7b277c
5,374
hh
C++
src/Damage/ScalarDamageModel.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Damage/ScalarDamageModel.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Damage/ScalarDamageModel.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // ScalarDamageModel -- Base class for the scalar damage physics models. // This class does not know how to seed the flaw distribution -- that is // required of descendant classes. // // Created by JMO, Sun Oct 10 17:22:05 PDT 2004 //----------------------------------------------------------------------------// #ifndef __Spheral_ScalarDamageModel_hh__ #define __Spheral_ScalarDamageModel_hh__ #include "Geometry/GeomPlane.hh" #include "NodeList/FluidNodeList.hh" #include "DamageModel.hh" #include <vector> // Forward declarations. namespace Spheral { template<typename Dimension> class State; template<typename Dimension> class StateDerivatives; template<typename Dimension> class GeomPlane; template<typename Dimension> class FluidNodeList; template<typename Dimension> class SolidNodeList; template<typename Dimension> class DataBase; template<typename Dimension, typename DataType> class Field; template<typename Dimension, typename DataType> class FieldList; } namespace Spheral { template<typename Dimension> class ScalarDamageModel: public DamageModel<Dimension> { public: //--------------------------- Public Interface ---------------------------// // Useful typedefs. typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::Tensor Tensor; typedef typename Dimension::SymTensor SymTensor; typedef GeomPlane<Dimension> Plane; typedef typename Physics<Dimension>::TimeStepType TimeStepType; typedef typename Physics<Dimension>::ConstBoundaryIterator ConstBoundaryIterator; typedef Field<Dimension, std::vector<double> > FlawStorageType; // Constructors, destructor. ScalarDamageModel(SolidNodeList<Dimension>& nodeList, FluidNodeList<Dimension>& damagedNodeList, const double kernelExtent, const double crackGrowthMultiplier, const FlawStorageType& flaws); virtual ~ScalarDamageModel(); //........................................................................... // Provide the required physics package interface. // Compute the derivatives. virtual void evaluateDerivatives(const Scalar time, const Scalar dt, const DataBase<Dimension>& dataBase, const State<Dimension>& state, StateDerivatives<Dimension>& derivatives) const; // Vote on a time step. virtual TimeStepType dt(const DataBase<Dimension>& dataBase, const State<Dimension>& state, const StateDerivatives<Dimension>& derivs, const Scalar currentTime) const; // Register our state. virtual void registerState(DataBase<Dimension>& dataBase, State<Dimension>& state); // Register the derivatives/change fields for updating state. virtual void registerDerivatives(DataBase<Dimension>& dataBase, StateDerivatives<Dimension>& derivs); //........................................................................... // Finalize method, called at the end of a time step. virtual void finalize(const Scalar time, const Scalar dt, DataBase<Dimension>& db, State<Dimension>& state, StateDerivatives<Dimension>& derivs); // Access the damaged NodeList. const FluidNodeList<Dimension>& damagedNodeList() const; // Specify whether to split or refine fully failed nodes. bool splitFailedNodes() const; void splitFailedNodes(const bool x); // Provide access to the state fields we maintain. const Field<Dimension, Scalar>& strain() const; const Field<Dimension, Scalar>& damage() const; const Field<Dimension, Scalar>& DdamageDt() const; // Return a vector of undamged -> damaged node indicies. std::vector<int> undamagedToDamagedNodeIndicies() const; // The set of boundary planes to respect if creating new nodes. std::vector<Plane>& boundPlanes(); // Determine if the given position violates any of the specified boundary // planes. bool positionOutOfBounds(const Vector& r) const; //************************************************************************** // Restart methods. virtual void dumpState(FileIO& file, const std::string& pathName) const; virtual void restoreState(const FileIO& file, const std::string& pathName); //************************************************************************** private: //--------------------------- Private Interface ---------------------------// FluidNodeList<Dimension>* mDamagedNodeListPtr; bool mSplitFailedNodes; Field<Dimension, Scalar> mStrain; Field<Dimension, Scalar> mDamage; Field<Dimension, Scalar> mDdamageDt; Field<Dimension, Scalar> mMass0; Field<Dimension, int> mUndamagedToDamagedIndex; std::vector<Plane> mBoundPlanes; // No default constructor, copying or assignment. ScalarDamageModel(); ScalarDamageModel(const ScalarDamageModel&); ScalarDamageModel& operator=(const ScalarDamageModel&); }; } #else // Forward declaration. namespace Spheral { template<typename Dimension> class ScalarDamageModel; } #endif
36.557823
83
0.628768
jmikeowen
477b0bf7314789f5b8525cd0a59d12ed95a22d03
5,941
cc
C++
flecsi/execution/test/index_subspaces.cc
manopapad/flecsi
8bb06e4375f454a0680564c76df2c60ffe49c770
[ "Unlicense" ]
null
null
null
flecsi/execution/test/index_subspaces.cc
manopapad/flecsi
8bb06e4375f454a0680564c76df2c60ffe49c770
[ "Unlicense" ]
null
null
null
flecsi/execution/test/index_subspaces.cc
manopapad/flecsi
8bb06e4375f454a0680564c76df2c60ffe49c770
[ "Unlicense" ]
null
null
null
/*~-------------------------------------------------------------------------~~* * Copyright (c) 2014 Los Alamos National Security, LLC * All rights reserved. *~-------------------------------------------------------------------------~~*/ #include <cinchdevel.h> #include <flecsi/execution/context.h> #include <flecsi/execution/execution.h> #include <flecsi/supplemental/coloring/add_colorings.h> #define FLECSI_TEST_MESH_INDEX_SUBSPACES 1 #include <flecsi/supplemental/mesh/test_mesh_2d.h> #include <flecsi/data/dense_accessor.h> clog_register_tag(devel_handle); namespace flecsi { namespace execution { //----------------------------------------------------------------------------// // Type definitions //----------------------------------------------------------------------------// using point_t = flecsi::supplemental::point_t; using mesh_t = flecsi::supplemental::test_mesh_2d_t; template<size_t PS> using mesh = data_client_handle_u<mesh_t, PS>; template<size_t EP, size_t SP, size_t GP> using field = dense_accessor<double, EP, SP, GP>; //----------------------------------------------------------------------------// // Variable registration //----------------------------------------------------------------------------// flecsi_register_data_client(mesh_t, clients, m); flecsi_register_field(mesh_t, data, pressure, double, dense, 1, index_spaces::cells); //----------------------------------------------------------------------------// // Initialize pressure //----------------------------------------------------------------------------// void initialize_pressure(mesh<ro> m, field<rw, rw, ro> p) { size_t count{0}; auto & context{execution::context_t::instance()}; for(auto c : m.cells(owned)) { p(c) = (context.color() + 1) * 1000.0 + count++; } // for } // initialize_pressure flecsi_register_task(initialize_pressure, flecsi::execution, loc, index); //----------------------------------------------------------------------------// // Update pressure //----------------------------------------------------------------------------// void update_pressure(mesh<ro> m, field<rw, rw, ro> p) { size_t count{0}; for(auto c : m.cells(owned)) { p(c) = 2.0 * p(c); } // for for(auto v : m.subentities<0>()) { std::cout << "subentity id: " << v->id() << std::endl; } } // initialize_pressure flecsi_register_task(update_pressure, flecsi::execution, loc, index); //----------------------------------------------------------------------------// // Print task //----------------------------------------------------------------------------// void print_mesh(mesh<ro> m, field<ro, ro, ro> p) { { clog_tag_guard(devel_handle); clog(info) << "print_mesh task" << std::endl; } // scope auto & context = execution::context_t::instance(); auto & vertex_map = context.index_map(index_spaces::vertices); auto & cell_map = context.index_map(index_spaces::cells); for(auto c : m.cells(owned)) { const size_t cid = c->template id<0>(); { clog_tag_guard(devel_handle); clog(trace) << "color: " << context.color() << " cell id: (" << cid << ", " << cell_map[cid] << ")" << std::endl; clog(trace) << "color: " << context.color() << " pressure: " << p(c) << std::endl; } // scope size_t vcount(0); for(auto v : m.vertices(c)) { const size_t vid = v->template id<0>(); { clog_tag_guard(devel_handle); clog(trace) << "color: " << context.color() << " vertex id: (" << vid << ", " << vertex_map[vid] << ") " << vcount << std::endl; point_t coord = v->coordinates(); clog(trace) << "color: " << context.color() << " coordinates: (" << coord[0] << ", " << coord[1] << ")" << std::endl; } // scope vcount++; } // for } // for } // print_mesh flecsi_register_task(print_mesh, flecsi::execution, loc, index); //----------------------------------------------------------------------------// // Top-Level Specialization Initialization //----------------------------------------------------------------------------// void specialization_tlt_init(int argc, char ** argv) { { clog_tag_guard(devel_handle); clog(info) << "specialization_tlt_init function" << std::endl; } // scope supplemental::do_test_mesh_2d_coloring(); auto & context{execution::context_t::instance()}; context.add_index_subspace(0, 1024); } // specialization_tlt_init //----------------------------------------------------------------------------// // SPMD Specialization Initialization //----------------------------------------------------------------------------// void specialization_spmd_init(int argc, char ** argv) { { clog_tag_guard(devel_handle); clog(info) << "specialization_spmd_init function" << std::endl; } // scope auto mh = flecsi_get_client_handle(mesh_t, clients, m); flecsi_execute_task(initialize_mesh, flecsi::supplemental, index, mh); } // specialization_spmd_ini //----------------------------------------------------------------------------// // User driver. //----------------------------------------------------------------------------// void driver(int argc, char ** argv) { auto mh = flecsi_get_client_handle(mesh_t, clients, m); auto ph = flecsi_get_handle(mh, data, pressure, double, dense, 0); flecsi_execute_task(initialize_pressure, flecsi::execution, index, mh, ph); flecsi_execute_task(update_pressure, flecsi::execution, index, mh, ph); flecsi_execute_task(print_mesh, flecsi::execution, index, mh, ph); } // driver } // namespace execution } // namespace flecsi DEVEL(index_subspaces) {} /*~------------------------------------------------------------------------~--* * Formatting options for vim. * vim: set tabstop=2 shiftwidth=2 expandtab : *~------------------------------------------------------------------------~--*/
31.433862
80
0.479717
manopapad
477f6910f6b332be8565a1020006d12339e9f4d7
1,693
cpp
C++
src/lib/slo/SloInfo.cpp
MarkLeone/PostHaste
56083e30a58489338e39387981029488d7af2390
[ "MIT" ]
4
2015-05-07T03:29:52.000Z
2016-08-29T17:30:15.000Z
src/lib/slo/SloInfo.cpp
MarkLeone/PostHaste
56083e30a58489338e39387981029488d7af2390
[ "MIT" ]
1
2018-05-14T04:41:04.000Z
2018-05-14T04:41:04.000Z
src/lib/slo/SloInfo.cpp
MarkLeone/PostHaste
56083e30a58489338e39387981029488d7af2390
[ "MIT" ]
null
null
null
// Copyright 2009 Mark Leone (markleone@gmail.com). All rights reserved. // Licensed under the terms of the MIT License. // See http://www.opensource.org/licenses/mit-license.php. #include "slo/SloInfo.h" #include "slo/SloInputFile.h" #include "slo/SloOutputFile.h" #include <string.h> int SloInfo::Read(SloInputFile* in) { if (const char* line = in->ReadLine()) { // Extract name. size_t delimIndex = strcspn(line, " \t"); mName = std::string(line, delimIndex); line += delimIndex; // Extract remaining fields. mOptUnknown = -1; int shaderType; int numFields = sscanf(line, " %i %i %i %i %i %i %i %i %i %i %i %i", &mNumSyms, &mNumConstants, &mNumStrings, &mUnknown3, &mNumInsts, &mUnknown1, &mNumInits, &mNumInits2, &mUnknown2, &mBeginPC, &shaderType, &mOptUnknown); mType = static_cast<SloShaderType>(shaderType); if (!SloIsKnown(mType)) in->Report(kUtWarning, "Unknown shader type %i", mType); if (numFields == 11 || numFields == 12) return 0; } in->Report(kUtError, "Error reading SLO info"); return 1; } void SloInfo::Write(SloOutputFile* file) const { file->Write("%s %i %i %i %i %i %i %i %i %i %i %i", mName.c_str(), mNumSyms, mNumConstants, mNumStrings, mUnknown3, mNumInsts, mUnknown1, mNumInits, mNumInits2, mUnknown2, mBeginPC, mType, mOptUnknown); if (mOptUnknown != -1) file->Write(" %i\n", mOptUnknown); else file->Write("\n"); }
33.86
79
0.558771
MarkLeone
477f7069f85a04f13aa7fea995156ed92eca4669
25,605
cpp
C++
randitem/obri_effects.cpp
uesp/obranditem
4869f96bb9eda7b3a2369815c5f225050d28c445
[ "MIT" ]
null
null
null
randitem/obri_effects.cpp
uesp/obranditem
4869f96bb9eda7b3a2369815c5f225050d28c445
[ "MIT" ]
null
null
null
randitem/obri_effects.cpp
uesp/obranditem
4869f96bb9eda7b3a2369815c5f225050d28c445
[ "MIT" ]
null
null
null
/*=========================================================================== * * File: Obri_Effects.CPP * Author: Dave Humphrey (uesp@sympatico.ca) * Created On: 21 April 2006 * * Description * *=========================================================================*/ /* Include Files */ #include "obri_effects.h" /*=========================================================================== * * Begin Local Definitions * *=========================================================================*/ /*=========================================================================== * End of Local Definitions *=========================================================================*/ /*=========================================================================== * * Begin Value String Arrays * *=========================================================================*/ /*=========================================================================== * End of Value String Arrays *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Constructor * *=========================================================================*/ CObriEffects::CObriEffects () { m_InputLine = 0; } /*=========================================================================== * End of Class CObriEffects Constructor *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - void Destroy (void); * *=========================================================================*/ void CObriEffects::Destroy (void) { /* Clear the arrays and unallocate contents */ m_Prefixes.Destroy(); m_Suffixes.Destroy(); m_InputLine = 0; } /*=========================================================================== * End of Class Method CObriEffects::Destroy() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - obri_effect_t* FindEffect (pName); * * Searches the suffix and prefix arrays for an effect with the matching * name ID (not case sensitive). Returns NULL on any error. * *=========================================================================*/ obri_effect_t* CObriEffects::FindEffect (const SSCHAR* pName) { obri_effect_t* pEffect; dword Index; /* Ignore invalid input */ if (pName == NULL) return (NULL); /* Search the prefix array */ for (Index = 0; Index < m_Prefixes.GetSize(); ++Index) { pEffect = m_Prefixes.GetAt(Index); if (stricmp(pEffect->NameID, pName) == 0) return (pEffect); } /* Search the suffix array */ for (Index = 0; Index < m_Suffixes.GetSize(); ++Index) { pEffect = m_Suffixes.GetAt(Index); if (stricmp(pEffect->NameID, pName) == 0) return (pEffect); } return (NULL); } /*=========================================================================== * End of Class Method CObriEffects::FindEffect() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool ReadEffect (File, pNewEffect); * * Inputs a new record from the current position in the given file, storing * the data in the given object. Protected class method. Returns false on * any error. * *=========================================================================*/ bool CObriEffects::ReadEffect (CObFile& File, obri_effect_t* pNewEffect) { CSString LineBuffer; CSString Variable; CSString Value; bool IsReading = true; bool ParseResult; bool Result; /* Input until end of file or end of effect */ while (!File.IsEOF() && IsReading) { /* Input a single line of text from the file */ Result = File.ReadLine(LineBuffer); if (!Result) return (false); ++m_InputLine; /* Parse input, ignore comments, whitespace trim, etc... */ ParseResult = LineBuffer.SeperateVarValue(Variable, Value); /* Determine input action */ if (Variable.CompareNoCase("End") == 0) { IsReading = false; } /* Input an enchantment section */ else if (Variable.CompareNoCase("Enchant") == 0) { Result = ReadEnchant(File, pNewEffect); if (!Result) return (false); } else if (ParseResult) { Result = SetEffectParam(pNewEffect, Variable, Value); if (!Result) return (false); } } return (true); } /*=========================================================================== * End of Class Method CObriEffects::ReadEffect() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool ReadEffectFile (pFilename); * * Attempts to input effect data from the given file. Returns false on any error. * *=========================================================================*/ bool CObriEffects::ReadEffectFile (const SSCHAR* pFilename) { CSString LineBuffer; CSString Variable; CSString Value; CObFile File; long Filesize; bool IsReading = true; bool Result; /* Attempt to open the file for reading */ Result = File.Open(pFilename, "rt"); if (!Result) return (false); Filesize = File.GetFileSize(); /* Input until end of file or end of effect */ while (!File.IsEOF() && File.Tell() < Filesize) { /* Input a single line of text from the file */ Result = File.ReadLine(LineBuffer); if (!Result) return (false); ++m_InputLine; /* Parse input, ignore comments, whitespace trim, etc... */ LineBuffer.SeperateVarValue(Variable, Value); /* Start of effect sections */ if (Variable.CompareNoCase("Suffix") == 0) { Result = ReadSuffix(File); if (!Result) return (false); } else if (Variable.CompareNoCase("Prefix") == 0) { Result = ReadPrefix(File); if (!Result) return (false); } } SystemLog.Printf("Loaded %d prefixes", m_Prefixes.GetSize()); SystemLog.Printf("Loaded %d suffixes", m_Suffixes.GetSize()); return (true); } /*=========================================================================== * End of Class Method CObriEffects::ReadEffectFile() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool ReadEnchant (File, pNewEffect); * * Protected class method to input an enchantment block starting at the * current position in the given file. Returns false on any error. * *=========================================================================*/ bool CObriEffects::ReadEnchant (CObFile& File, obri_effect_t* pNewEffect) { CSString LineBuffer; CSString Variable; CSString Value; bool IsReading = true; bool ParseResult; bool Result; /* Input until end of file or end of effect */ while (!File.IsEOF() && IsReading) { /* Input a single line of text from the file */ Result = File.ReadLine(LineBuffer); if (!Result) return (false); ++m_InputLine; /* Parse input, ignore comments, whitespace trim, etc... */ ParseResult = LineBuffer.SeperateVarValue(Variable, Value); /* Determine input action */ if (Variable.CompareNoCase("End") == 0) { IsReading = false; } /* Input an effect section */ else if (Variable.CompareNoCase("Effect") == 0) { /* Ensure we don't exceed the effect array size */ if (pNewEffect->Enchantment.NumEffects < OBRI_MAX_ENCHEFFECTS) { DefaultObriEnchEffect(pNewEffect->Enchantment.Effects[pNewEffect->Enchantment.NumEffects]); ++pNewEffect->Enchantment.NumEffects; Result = ReadEnchantEffect(File, pNewEffect); if (!Result) return (false); } else { AddObUserError(OBERR_USER_MAXINDEX, "Exceeded the effect array size of %d!", OBRI_MAX_ENCHEFFECTS); return (false); } } else if (ParseResult) { Result = SetEnchantParam(pNewEffect, Variable, Value); if (!Result) return (false); } } return (true); } /*=========================================================================== * End of Class Method CObriEffects::ReadEnchant() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool ReadEnchantEffect (File, pNewEffect); * * Protected class method to input an effect enchantment block starting at the * current position in the given file. Returns false on any error. * *=========================================================================*/ bool CObriEffects::ReadEnchantEffect (CObFile& File, obri_effect_t* pNewEffect) { CSString LineBuffer; CSString Variable; CSString Value; bool IsReading = true; bool ParseResult; bool Result; /* Input until end of file or end of effect */ while (!File.IsEOF() && IsReading) { /* Input a single line of text from the file */ Result = File.ReadLine(LineBuffer); if (!Result) return (false); ++m_InputLine; /* Parse input, ignore comments, whitespace trim, etc... */ ParseResult = LineBuffer.SeperateVarValue(Variable, Value); /* Determine input action */ if (Variable.CompareNoCase("End") == 0) { IsReading = false; } else if (ParseResult) { Result = SetEnchantEffectParam(pNewEffect, Variable, Value); if (!Result) return (false); } } return (true); } /*=========================================================================== * End of Class Method CObriEffects::ReadEnchantEffect() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool ReadPrefix (File); * * Input effect data from the current position in the given file. Protected * class method. Assumes that the 'Prefix' line has already been input. * Returns false on any error. * *=========================================================================*/ bool CObriEffects::ReadPrefix (CObFile& File) { obri_effect_t* pNewPrefix; /* Create and initialize the new effect object */ pNewPrefix = new obri_effect_t; m_Prefixes.Add(pNewPrefix); DefaultObriEffect(*pNewPrefix); return ReadEffect(File, pNewPrefix); } /*=========================================================================== * End of Class Method CObriEffects::ReadPrefix() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool ReadSuffix (File); * * Input effect data from the current position in the given file. Protected * class method. Assumes that the 'Suffix' line has already been input. * Returns false on any error. * *=========================================================================*/ bool CObriEffects::ReadSuffix (CObFile& File) { obri_effect_t* pNewSuffix; /* Create and initialize the new effect object */ pNewSuffix = new obri_effect_t; m_Suffixes.Add(pNewSuffix); DefaultObriEffect(*pNewSuffix); return ReadEffect(File, pNewSuffix); } /*=========================================================================== * End of Class Method CObriEffects::ReadSuffix() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool ParseNameMask (pNewEffect, pString); * *=========================================================================*/ bool CObriEffects::ParseNameMask (obri_effect_t* pNewEffect, const SSCHAR* pString) { CSString* pNewMask; SSCHAR Buffer[512]; SSCHAR* pParse; /* Create a temporary working copy */ strnncpy(Buffer, pString, 511); pParse = strtok(Buffer, "|"); while (pParse != NULL) { pParse = trim(pParse); if (*pParse != NULL_CHAR) { pNewMask = pNewEffect->NameMasks.AddNew(); *pNewMask = pParse; } pParse = strtok(NULL, "|"); } return (true); } /*=========================================================================== * End of Class Method CObriEffects::ParseNameMask() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool ParseCustomTypes (pNewEffect, pString); * *=========================================================================*/ bool CObriEffects::ParseCustomTypes (obri_effect_t* pNewEffect, const SSCHAR* pString) { CSString* pNewMask; SSCHAR Buffer[512]; SSCHAR* pParse; /* Create a temporary working copy */ strnncpy(Buffer, pString, 511); pParse = strtok(Buffer, "|"); while (pParse != NULL) { pParse = trim(pParse); if (*pParse != NULL_CHAR) { pNewMask = pNewEffect->CustomTypes.AddNew(); *pNewMask = pParse; } pParse = strtok(NULL, "|"); } return (true); } /*=========================================================================== * End of Class Method CObriEffects::ParseCustomTypes() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool SetEffectParam (pNewEffect, pVariable, pValue); * * Sets the input effect parameter according to the value of the variable * and value strings. Returns false on any error. Protected class method. * *=========================================================================*/ bool CObriEffects::SetEffectParam (obri_effect_t* pNewEffect, const SSCHAR* pVariable, const SSCHAR* pValue) { bool Result; if (stricmp(pVariable, "Name") == 0) { strnncpy(pNewEffect->Name, pValue, OBRI_MAX_NAMESIZE); if (pNewEffect->NameID[0] == NULL_CHAR) { strnncpy(pNewEffect->NameID, pValue, OBRI_MAX_NAMESIZE); } } else if (stricmp(pVariable, "NameID") == 0) { strnncpy(pNewEffect->NameID, pValue, OBRI_MAX_NAMESIZE); } else if (stricmp(pVariable, "NameMask") == 0) { ParseNameMask(pNewEffect, pValue); } else if (stricmp(pVariable, "CustomTypes") == 0) { ParseCustomTypes(pNewEffect, pValue); } else if (stricmp(pVariable, "Script") == 0) { strnncpy(pNewEffect->Script, pValue, OBRI_MAX_NAMESIZE); } else if (stricmp(pVariable, "Cursed") == 0) { Result = StringToBoolean(pNewEffect->Cursed, pValue); if (!Result) AddObGeneralError("%5ld: Unknown boolean value '%s'!", m_InputLine, pValue); } else if (stricmp(pVariable, "EffectType") == 0) { Result = StringToObriEffectType(pNewEffect->EffectType, pValue); if (!Result) AddObGeneralError("%5ld: Unknown effect type '%s'!", m_InputLine, pValue); } else if (stricmp(pVariable, "ItemLevel") == 0) { pNewEffect->ItemLevel = atoi(pValue); } else if (stricmp(pVariable, "ItemMask") == 0) { pNewEffect->ItemMask = StringToObriItemMask(pValue); } else if (stricmp(pVariable, "MinEffect") == 0) { pNewEffect->MinEffect = (float) atof(pValue); } else if (stricmp(pVariable, "MaxEffect") == 0) { pNewEffect->MaxEffect = (float) atof(pValue); } else if (stricmp(pVariable, "MinQuality") == 0) { pNewEffect->MinQuality = atoi(pValue); } else if (stricmp(pVariable, "MaxQuality") == 0) { pNewEffect->MaxQuality = atoi(pValue); } else if (stricmp(pVariable, "Multiplier") == 0) { pNewEffect->Multiplier = atoi(pValue); } else { AddObGeneralError ("%5ld: Unknown effect variable '%s'!", m_InputLine, pVariable); } return (true); } /*=========================================================================== * End of Class Method CObriEffects::SetEffectParam() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool SetEnchantParam (pNewEffect, pVariable, pValue); * * Sets the input enchantment parameter according to the value of the variable * and value strings. Returns false on any error. Protected class method. * *=========================================================================*/ bool CObriEffects::SetEnchantParam (obri_effect_t* pNewEffect, const SSCHAR* pVariable, const SSCHAR* pValue) { bool Result; if (stricmp(pVariable, "MinCharge") == 0) { pNewEffect->Enchantment.MinCharge = atoi(pValue); } else if (stricmp(pVariable, "MaxCharge") == 0) { pNewEffect->Enchantment.MaxCharge = atoi(pValue); } else if (stricmp(pVariable, "MinCost") == 0) { pNewEffect->Enchantment.MinCost = atoi(pValue); } else if (stricmp(pVariable, "MaxCost") == 0) { pNewEffect->Enchantment.MaxCost = atoi(pValue); } else if (stricmp(pVariable, "EnchantType") == 0) { //Result = StringToObriEnchantType(pNewEffect->Enchantment.EnchantType, pValue); Result = GetObEnchantTypeValue(pNewEffect->Enchantment.EnchantType, pValue); if (!Result) AddObGeneralError ("%5ld: Unknown enchant type '%s'!", m_InputLine, pValue); } else if (stricmp(pVariable, "AutoCalc") == 0) { Result = StringToBoolean(pNewEffect->Enchantment.AutoCalc, pValue); if (!Result) AddObGeneralError ("%5ld: Unknown boolean value '%s'!", m_InputLine, pValue); } else { AddObGeneralError ("%5ld: Unknown enchantment variable '%s'!", m_InputLine, pVariable); } return (true); } /*=========================================================================== * End of Class Method CObriEffects::SetEnchantParam() *=========================================================================*/ /*=========================================================================== * * Class CObriEffects Method - bool SetEnchantEffectParam (pNewEffect, pVariable, pValue); * * Sets the input enchantment effect parameter according to the value * of the variable and value strings. Returns false on any error. * Protected class method. * *=========================================================================*/ bool CObriEffects::SetEnchantEffectParam (obri_effect_t* pNewEffect, const SSCHAR* pVariable, const SSCHAR* pValue) { const obeffectdata_t* pEffect; bool Result; int EffectIndex; int OutputValue; /* Ensure a valid effect index */ EffectIndex = pNewEffect->Enchantment.NumEffects - 1; if (EffectIndex < 0 || EffectIndex >= OBRI_MAX_ENCHEFFECTS) return (false); if (stricmp(pVariable, "EffectID") == 0) { pEffect = FindObEffectData(pValue); if (pEffect == NULL) AddObGeneralError ("%5ld: Unknown effect ID '%s'!", m_InputLine, pValue); else pNewEffect->Enchantment.Effects[EffectIndex].pEffectID = pEffect->pName; } else if (stricmp(pVariable, "ActorValue") == 0) { Result = GetObActorValueValue(OutputValue, pValue); if (!Result) AddObGeneralError ("%5ld: Unknown skill ID '%s'!", m_InputLine, pValue); else pNewEffect->Enchantment.Effects[EffectIndex].ActorValue = OutputValue; } else if (stricmp(pVariable, "RangeType") == 0) { Result = GetObEnchantRangeValue(OutputValue, pValue); if (!Result) AddObGeneralError ("%5ld: Unknown enchant range type '%s'!", m_InputLine, pValue); else pNewEffect->Enchantment.Effects[EffectIndex].RangeType = OutputValue; } else if (stricmp(pVariable, "MinArea") == 0) { pNewEffect->Enchantment.Effects[EffectIndex].MinArea = atoi(pValue); } else if (stricmp(pVariable, "MaxArea") == 0) { pNewEffect->Enchantment.Effects[EffectIndex].MaxArea = atoi(pValue); } else if (stricmp(pVariable, "MinDuration") == 0) { pNewEffect->Enchantment.Effects[EffectIndex].MinDuration = atoi(pValue); } else if (stricmp(pVariable, "MaxDuration") == 0) { pNewEffect->Enchantment.Effects[EffectIndex].MaxDuration = atoi(pValue); } else if (stricmp(pVariable, "MinMagnitude") == 0) { pNewEffect->Enchantment.Effects[EffectIndex].MinMagnitude = atoi(pValue); } else if (stricmp(pVariable, "MaxMagnitude") == 0) { pNewEffect->Enchantment.Effects[EffectIndex].MaxMagnitude = atoi(pValue); } else if (stricmp(pVariable, "VisualEffectID") == 0) { pEffect = FindObEffectData(pValue); if (pEffect == NULL) AddObGeneralError ("%5ld: Unknown visual effect ID '%s'!", m_InputLine, pValue); else pNewEffect->Enchantment.Effects[EffectIndex].pVisualEffectID = pEffect->pName; } else if (stricmp(pVariable, "Script") == 0) { strnncpy(pNewEffect->Enchantment.Effects[EffectIndex].Script, pValue, OBRI_MAX_NAMESIZE); } else if (stricmp(pVariable, "EffectName") == 0) { strnncpy(pNewEffect->Enchantment.Effects[EffectIndex].EffectName, pValue, OBRI_MAX_NAMESIZE); } else if (stricmp(pVariable, "School") == 0) { Result = GetObSpellSchoolValue(pNewEffect->Enchantment.Effects[EffectIndex].School, pValue); if (!Result) AddObGeneralError ("%5ld: Invalid spell school '%s'!", m_InputLine, pValue); } else if (stricmp(pVariable, "Hostile") == 0) { Result = StringToBoolean(pNewEffect->Enchantment.Effects[EffectIndex].IsHostile, pValue); if (!Result) AddObGeneralError ("%5ld: Invalid boolean value '%s'!", m_InputLine, pValue); } else { AddObGeneralError ("%5ld: Unknown enchantment effect variable '%s'!", m_InputLine, pVariable); } return (true); } /*=========================================================================== * End of Class Method CObriEffects::SetEnchantEffectParam() *=========================================================================*/ /*=========================================================================== * * Function - void DefaultObriEffect (Effect); * *=========================================================================*/ void DefaultObriEffect (obri_effect_t& Effect) { Effect.Cursed = false; Effect.EffectType = OBRI_EFFTYPE_NONE; Effect.ItemLevel = 1; Effect.ItemMask = OBRI_ITEMTYPE_ALL; Effect.MinEffect = 1; Effect.MaxEffect = 10; Effect.MinQuality = 10; Effect.MaxQuality = 100; Effect.Multiplier = 1; Effect.Name[0] = NULL_CHAR; Effect.NameID[0] = NULL_CHAR; Effect.Script[0] = NULL_CHAR; Effect.NameMasks.Empty(); Effect.CustomTypes.Empty(); DefaultObriEnchant(Effect.Enchantment); } /*=========================================================================== * End of Function DefaultObriEffect() *=========================================================================*/ /*=========================================================================== * * Function - void DefaultObriEnchant (Enchant); * *=========================================================================*/ void DefaultObriEnchant (obri_enchant_t& Enchant) { Enchant.NumEffects = 0; Enchant.MinCharge = 100; Enchant.MaxCharge = 100; Enchant.MinCost = 10; Enchant.MaxCost = 10; Enchant.EnchantType = OB_ENCHTYPE_SCROLL; Enchant.AutoCalc = false; } /*=========================================================================== * End of Function DefaultObriEnchant() *=========================================================================*/ /*=========================================================================== * * Function - void DefaultObriEnchEffect (EnchEffect); * *=========================================================================*/ void DefaultObriEnchEffect (obri_encheff_t& EnchEffect) { EnchEffect.MinArea = 0; EnchEffect.MaxArea = 0; EnchEffect.MinDuration = 10; EnchEffect.MaxDuration = 10; EnchEffect.RangeType = 0; EnchEffect.MinMagnitude = 1; EnchEffect.MaxMagnitude = 5; EnchEffect.ActorValue = OB_ACTORVALUE_NONE; EnchEffect.pEffectID = &OB_NAME_NULL; EnchEffect.pVisualEffectID = &OB_NAME_NULL; EnchEffect.Script[0] = NULL_CHAR; EnchEffect.School = 0; EnchEffect.IsHostile = true; EnchEffect.EffectName[0] = NULL_CHAR; } /*=========================================================================== * End of Function DefaultObriEnchEffect() *=========================================================================*/
36.216407
108
0.49588
uesp
477f9c9b2104983abe33713e3d572ea630c4aea1
632
cpp
C++
Creational Patterns/bridge/AbstractionImp.cpp
lijiansong/design-pattern
64f6be452c1af2c0098b0255adacaf828f765e8f
[ "MIT" ]
1
2021-03-26T06:07:27.000Z
2021-03-26T06:07:27.000Z
Creational Patterns/bridge/AbstractionImp.cpp
lijiansong/design-pattern
64f6be452c1af2c0098b0255adacaf828f765e8f
[ "MIT" ]
null
null
null
Creational Patterns/bridge/AbstractionImp.cpp
lijiansong/design-pattern
64f6be452c1af2c0098b0255adacaf828f765e8f
[ "MIT" ]
2
2020-06-03T08:48:45.000Z
2021-09-14T12:16:04.000Z
#include "AbstractionImp.h" #include <iostream> using namespace std; AbstractionImp::AbstractionImp() {} AbstractionImp::~AbstractionImp() {} void AbstractionImp::Operation() { cout << "Abstraction... imp..." <<endl; } ConcreteAbstractionImpA::ConcreteAbstractionImpA() {} ConcreteAbstractionImpA::~ConcreteAbstractionImpA() {} void ConcreteAbstractionImpA::Operation() { cout << "ConcreteAbstractionImpA..." << endl; } ConcreteAbstractionImpB::ConcreteAbstractionImpB() {} ConcreteAbstractionImpB::~ConcreteAbstractionImpB() {} void ConcreteAbstractionImpB::Operation() { cout << "ConcreteAbstractionImpB..." << endl; }
17.555556
51
0.754747
lijiansong
4784403837a3640e1fa74c8ff40704737246c70f
3,593
cpp
C++
sample/gl/kalmanfilter/main.cpp
sanko-shoko/simplesp
6a71022dbb9a304e5a68d60885a04906dc78913a
[ "MIT" ]
24
2017-09-07T16:08:33.000Z
2022-02-26T16:32:48.000Z
sample/gl/kalmanfilter/main.cpp
sanko-shoko/simplesp
6a71022dbb9a304e5a68d60885a04906dc78913a
[ "MIT" ]
null
null
null
sample/gl/kalmanfilter/main.cpp
sanko-shoko/simplesp
6a71022dbb9a304e5a68d60885a04906dc78913a
[ "MIT" ]
8
2018-11-30T02:53:24.000Z
2021-05-18T06:30:42.000Z
#include "simplesp.h" #include "spex/spgl.h" using namespace sp; class KalmanfilterGUI : public BaseWindow { private: void help() { printf("\n"); } virtual void init() { help(); } virtual void display() { glClearColor(0.10f, 0.12f, 0.12f, 0.00f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Mem2<Col3> img(320, 240); static int cnt = 0; // delta time const double dt = 0.1; // observation noise (sigma) const double onoize = 5.0; // system noize (sigma) const double snoize = 0.1; // observation Mat Z(2, 1); { // circle radius const double radius = 100.0; const double time = cnt * dt; const double angle = time * SP_PI / 180.0; const Vec2 pos = getVec2(::cos(angle), ::sin(angle)) * radius + getVec2(img.dsize[0] - 1, img.dsize[1] - 1) * 0.5; Z(0, 0) = pos.x + randg() * onoize; Z(1, 0) = pos.y + randg() * onoize; } static Mat X, Q, P, R, F, H; if (cnt == 0) { // initialize state // X (position 2d & velocity 2d) { double m[]{ Z(0, 0), Z(1, 0), 0.0, 0.0 }; X.resize(4, 1, m); } // Q (system noize covariance) { const double a = sq(dt * dt / 2.0); const double b = (dt * dt / 2.0) * dt; const double c = dt * dt; double m[]{ a, 0.0, b, 0.0, 0.0, a, 0.0, b, b, 0.0, c, 0.0, 0.0, b, 0.0, c }; Q.resize(4, 4, m); Q *= sq(snoize); } // P (state covariance) P = Q; // R (observation noize covariance) { double m[]{ 1.0, 0.0, 0.0, 1.0 }; R.resize(2, 2, m); R *= sq(onoize); } // F (prediction matrix) { double m[]{ 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; F.resize(4, 4, m); } // H (observation matrix) { double m[]{ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, }; H.resize(2, 4, m); } } else { // predict X = F * X; P = F * P * trnMat(F) + Q; // kalman gain const Mat K = P * trnMat(H) * invMat(H * P * trnMat(H) + R); // update X = X + K * (Z - H * X); P = (eyeMat(4, 4) - K * H) * P; } setElm(img, getCol3(255, 255, 255)); renderPoint(img, getVec2(Z[0], Z[1]), getCol3(0, 0, 0), 3); renderPoint(img, getVec2(X[0], X[1]), getCol3(0, 0, 255), 5); glLoadView2D(img.dsize[0], img.dsize[1], m_viewPos, m_viewScale); glTexImg(img); //char path[256]; //sprintf(path, "img%03d.bmp", cnt); //saveBMP(img, path); cnt++; } }; int main(){ KalmanfilterGUI win; win.execute("kalmanfilter", 800, 600); return 0; }
23.180645
126
0.367659
sanko-shoko
47883c640e13051e023540983403195e1dca9627
820
cpp
C++
docs/mfc/codesnippet/CPP/ccolordialog-class_5.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
14
2018-01-28T18:10:55.000Z
2021-11-16T13:21:18.000Z
docs/mfc/codesnippet/CPP/ccolordialog-class_5.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
null
null
null
docs/mfc/codesnippet/CPP/ccolordialog-class_5.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
2
2018-11-01T12:33:08.000Z
2021-11-16T13:21:19.000Z
// Override OnColorOK to validate the color entered to the // Red, Green, and Blue edit controls. If the color // is BLACK (i.e. RGB(0, 0,0)), then force the current color // selection to be the color initially selected when the // dialog box is created. The color dialog won't close so // user can enter a new color. BOOL CMyColorDlg::OnColorOK() { // Value in Red edit control. COLORREF clrref = GetColor(); if (RGB(0, 0, 0) == clrref) { AfxMessageBox(_T("BLACK is not an acceptable color. ") _T("Please enter a color again")); // GetColor() returns initially selected color. SetCurrentColor(GetColor()); // Won't dismiss color dialog. return TRUE; } // OK to dismiss color dialog. return FALSE; }
32.8
60
0.614634
jmittert
478b8065eb80f55e29466001e75deb52edbbb88c
1,900
cpp
C++
Ch04/comp3.cpp
rzotya0327/UDProg-Introduction
c64244ee541d4ad0c85645385ef4f0c2e1886621
[ "CC0-1.0" ]
null
null
null
Ch04/comp3.cpp
rzotya0327/UDProg-Introduction
c64244ee541d4ad0c85645385ef4f0c2e1886621
[ "CC0-1.0" ]
null
null
null
Ch04/comp3.cpp
rzotya0327/UDProg-Introduction
c64244ee541d4ad0c85645385ef4f0c2e1886621
[ "CC0-1.0" ]
null
null
null
#include "std_lib_facilities.h" int main() { double number = 0, smallest = 0, largest = 0, convert = 0; string unit; const double m_to_cm = 100; const double in_to_cm = 2.54; const double ft_to_in = 12; const double cm_to_m = 0.01; vector<double> distances; //értékek eltárolása a vectorban cout << "Please enter a number and a measurement unit (cm, m, in, ft)!" << endl; while (cin >> number >> unit) { if (unit != "cm" && unit != "ft" && unit != "in" && unit != "m") { cout << "This is an invalid unit. Please enter a number and a valid unit!" << endl; } else { cout << "You entered this: " << number << unit << endl; if (unit == "m") { convert = number; } else if (unit == "in") { convert = (number * in_to_cm) * cm_to_m; } else if (unit == "ft") { convert = (number * ft_to_in) * in_to_cm * cm_to_m; } else if (unit == "cm") { convert = number * cm_to_m; } distances.push_back(convert); //a méterré alakított értékek hozzáadása a vectorhoz if (largest == 0 && smallest == 0) { largest = number; smallest = number; cout << "The smallest so far: " << smallest << unit << endl; cout << "The largest so far: " << largest << unit <<endl; } else if (convert > smallest) { largest = number; cout << "The smallest so far: " << smallest << unit << endl; cout << "The largest so far: " << largest << unit << endl; } } } sort(distances); //a vector elemeinek rendezése double sum = 0; for(double distance : distances) { sum += distance; cout << distance << endl; } cout << "The sum of the values: " << sum << endl; cout << "The smallest value: " << distances[0] << endl; //első (0.) elem kiírása cout << "The largest value: " << distances[distances.size()-1] << endl; //utolsó elem kiírása return 0; }
23.75
96
0.568947
rzotya0327
478bee93f76c8091bdb6bc47ba42943eab8ef293
16,272
cpp
C++
led/CQLFontEd.cpp
colinw7/CVFont
7ff7eb85425e756d46f9461071400fecfca4cceb
[ "MIT" ]
2
2021-09-03T01:49:54.000Z
2021-12-23T02:23:03.000Z
led/CQLFontEd.cpp
colinw7/CVFont
7ff7eb85425e756d46f9461071400fecfca4cceb
[ "MIT" ]
null
null
null
led/CQLFontEd.cpp
colinw7/CVFont
7ff7eb85425e756d46f9461071400fecfca4cceb
[ "MIT" ]
null
null
null
#include <CQLFontEd.h> #include <CFile.h> #include <QStatusBar> #include <QLabel> int main(int argc, char **argv) { CQApp qapp(argc, argv); Application *app = new Application("lfont"); app->init(); app->show(); return qapp.exec(); } Application:: Application(const std::string &name) : CQMainWindow(), fontData_('Q') { setObjectName(name.c_str()); } QWidget * Application:: createCentralWidget() { canvas_ = new Canvas(this, "canvas"); return canvas_; } void Application:: createStatusBar() { stateLabel_ = new QLabel; posLabel_ = new QLabel; statusBar()->addPermanentWidget(stateLabel_, 1); statusBar()->addPermanentWidget(posLabel_); stateLabel_->setText(" "); posLabel_ ->setText(" "); updateState(); } void Application:: createMenus() { CQMenu *fileMenu = new CQMenu(this, "&File"); CQMenuItem *quitItem = new CQMenuItem(fileMenu, "&Quit"); quitItem->setShortcut("Ctrl+Q"); quitItem->setStatusTip("Quit the application"); quitItem->connect(this, SLOT(close())); CQMenuItem *printItem = new CQMenuItem(fileMenu, "&Print"); printItem->setShortcut("Ctrl+P"); printItem->setStatusTip("Print the current character"); printItem->connect(this, SLOT(print())); CQMenuItem *printAllItem = new CQMenuItem(fileMenu, "&Print All"); printAllItem->connect(this, SLOT(printAll())); CQMenuItem *helpItem = new CQMenuItem(fileMenu, "&Help"); helpItem->setShortcut("Ctrl+H"); helpItem->setStatusTip("Help"); //helpItem->connect(this, SLOT(help())); //--- CQMenu *viewMenu = new CQMenu(this, "&View"); CQMenuItem *previewItem = new CQMenuItem(viewMenu, "&Preview"); previewItem->setStatusTip("Preview font with example text"); previewItem->connect(this, SLOT(preview())); CQMenuItem *increaseLineWidthItem = new CQMenuItem(viewMenu, "&Increase Line Width"); increaseLineWidthItem->connect(this, SLOT(increaseLineWidth())); CQMenuItem *decreaseLineWidthItem = new CQMenuItem(viewMenu, "&Decrease Line Width"); decreaseLineWidthItem->connect(this, SLOT(decreaseLineWidth())); //--- CQMenu *editMenu = new CQMenu(this, "&Edit"); editMenu->startGroup(); CQMenuItem *moveItem = new CQMenuItem(editMenu, "&Move" , CQMenuItem::CHECKED); CQMenuItem *addItem = new CQMenuItem(editMenu, "&Add" , CQMenuItem::CHECKABLE); CQMenuItem *deleteItem = new CQMenuItem(editMenu, "&Delete", CQMenuItem::CHECKABLE); editMenu->endGroup(); moveItem ->connect(this, SLOT(moveState())); addItem ->connect(this, SLOT(addState())); deleteItem->connect(this, SLOT(deleteState())); } void Application:: print() { CFile file("/tmp/CLFontDef.h"); if (! file.open(CFile::Mode::WRITE)) return; printChar(file, fontData_.c(), fontData_.fontDef()); file.close(); } void Application:: printAll() { CFile file("/tmp/CLFontDef.h"); if (! file.open(CFile::Mode::WRITE)) return; for (char c = ' '; c <= '~'; ++c) { const CLFontDef &fontDef = CLFont::getFontDef(c); printChar(file, c, fontDef); } file.close(); } void Application:: printChar(CFile &file, char c, const CLFontDef &fontDef) { int charNum = c - ' '; //--- bool lineFound = false; for (const auto &line : fontDef.lines()) { if (! lineFound) { file.writef("static CLFontLine lines%02d[] = { /* %c */\n", charNum, c); lineFound = true; } file.writef(" {{% 6.4f,% 6.4f},{% 6.4f,% 6.4f}},\n", line->start().x, line->start().y, line->end().x, line->end().y); } if (lineFound) file.write("};\n"); //--- file.writef("/* %c */\n", c); file.writef("static std::string lines%02d = \"\\\n", charNum); for (const auto &line : fontDef.lines()) { file.writef(" L %6.4f %6.4f %6.4f %6.4f \\\n", line->start().x, line->start().y, line->end().x, line->end().y); } file.write("\";\n"); //--- file.close(); } void Application:: draw(QPainter *painter) { QPen pen; pen.setWidth(1); pen.setCosmetic(true); pen.setColor(Qt::green); painter->setPen(pen); double x1 = 0.0; double x2 = CLFont::charWidth; double y1 = -CLFont::charDescent; double y2 = 0.0; double y3 = y2 + CLFont::charAscent; painter->drawLine(QPointF(x1, y1), QPointF(x2, y1)); painter->drawLine(QPointF(x2, y1), QPointF(x2, y3)); painter->drawLine(QPointF(x2, y3), QPointF(x1, y3)); painter->drawLine(QPointF(x1, y3), QPointF(x1, y1)); pen.setColor(QColor(40,40,40)); painter->setPen(pen); double dx = 0.0625; double dy = 0.0625; for (double x = x1 + dx; x <= x2 - dx; x += dx) { painter->drawLine(QPointF(x, y1), QPointF(x, y3)); } for (double y = y1 + dy; y <= y3 - dy; y += dy) { painter->drawLine(QPointF(x1, y), QPointF(x2, y)); } pen.setColor(Qt::blue); painter->setPen(pen); painter->drawLine(QPointF(x1, y2), QPointF(x2, y2)); drawChar(painter, CPoint2D(0, 0), fontData_.fontDef()); drawPreviewPoint(painter); drawSelected(painter); //--- if (state_ == State::ADD && moving_ && ! mouseState_.escape) { pen.setColor(Qt::yellow); painter->setPen(pen); painter->drawLine(CQUtil::toQPoint(mouseState_.pressPoint), CQUtil::toQPoint(mouseState_.movePoint)); } } void Application:: drawText(QPainter *painter, const CPoint2D &p, const std::string &str) { CPoint2D p1 = p; for (std::size_t i = 0; i < str.size(); ++i) { const CLFontDef &fontDef = CLFont::getFontDef(str[i]); drawChar(painter, p1, fontDef); p1 += CPoint2D(1, 0); } } void Application:: drawChar(QPainter *painter, const CPoint2D &p, const CLFontDef &fontDef) { QPen pen; pen.setWidth(lineWidth()); pen.setCosmetic(true); pen.setColor(Qt::white); painter->setPen(pen); int lastXInd = -1; int lastYInd = -1; int firstXInd = -1; int firstYInd = -1; QPainterPath path; for (const auto &line : fontDef.lines()) { QPointF p1(p.x + line->start().x, p.y + line->start().y); QPointF p2(p.x + line->end ().x, p.y + line->end ().y); int xind1 = line->startXInd(); int yind1 = line->startYInd(); int xind2 = line->endXInd(); int yind2 = line->endYInd(); if (xind1 != lastXInd || yind1 != lastYInd) { if (xind2 == firstXInd && yind2 == firstYInd) path.closeSubpath(); firstXInd = xind1; firstYInd = yind1; path.moveTo(p1); } path.lineTo(p2); lastXInd = xind2; lastYInd = yind2; } painter->strokePath(path, pen); } void Application:: drawSelected(QPainter *painter) { if (! selectedPoint_.isSet()) return; const CLFontLine *line = fontData_.fontDef().lines()[selectedPoint_.ind()]; QPen pen; pen.setWidth(1); pen.setCosmetic(true); pen.setColor(Qt::gray); pen.setStyle(Qt::DotLine); painter->setPen(pen); drawCrossPoint(painter, CQUtil::toQPoint(line->start()), Qt::gray); drawCrossPoint(painter, CQUtil::toQPoint(line->end ()), Qt::gray); drawPointData(painter, selectedPoint_, Qt::red); } void Application:: drawPreviewPoint(QPainter *painter) { drawPointData(painter, previewPoint_, Qt::yellow); } void Application:: drawPointData(QPainter *painter, const PointData &pointData, const QColor &c) { if (pointData.isSet()) { const CLFontLine *line = fontData_.fontDef().lines()[pointData.ind()]; if (pointData.subInd() == 0) drawCrossPoint(painter, CQUtil::toQPoint(line->start()), c); else if (pointData.subInd() == 1) drawCrossPoint(painter, CQUtil::toQPoint(line->end ()), c); } } void Application:: drawCrossPoint(QPainter *painter, const QPointF &p, const QColor &c) { QPen pen; pen.setWidth(1); pen.setCosmetic(true); pen.setColor(c); painter->setPen(pen); double s = 0.02; painter->drawLine(p - QPointF( s, s), p + QPointF( s, s)); painter->drawLine(p - QPointF(-s, s), p + QPointF(-s, s)); } void Application:: setKey(char c) { fontData_.setChar(c); selectedPoint_.reset(); previewPoint_ .reset(); updateAll(); } void Application:: mousePress(const CPoint2D &p) { mouseState_.pressed = true; mouseState_.pressPoint = CLFont::snapPoint(p); mouseState_.moving = false; mouseState_.escape = false; if (state_ == State::MOVE) { selectAt(mouseState_.pressPoint); selectPoint_ = pointDataPos(selectedPoint_); } else if (state_ == State::DELETE) { selectAt(mouseState_.pressPoint); deleteSelected(); } } void Application:: mouseMove(const CPoint2D &p) { mouseState_.movePoint = CLFont::snapPoint(p); posLabel_->setText(QString("%1,%2").arg(mouseState_.movePoint.x).arg(mouseState_.movePoint.y)); if (mouseState_.pressed) { mouseState_.moving = true; if (mouseState_.escape) return; if (state_ == State::MOVE) moveTo(p); else if (state_ == State::ADD) updateAll(); } else { previewPoint_ = nearestPoint(mouseState_.movePoint); updateAll(); } } void Application:: mouseRelease(const CPoint2D &p) { mouseState_.pressed = false; mouseState_.releasePoint = CLFont::snapPoint(p); mouseState_.moving = false; mouseState_.escape = false; if (state_ == State::ADD) { if (mouseState_.escape) return; int ind = fontData_.fontDef().addLine(mouseState_.pressPoint, mouseState_.releasePoint); selectedPoint_ = PointData(ind, 0); updateFontDef(); updateAll(); } } void Application:: selectAt(const CPoint2D &p) { selectedPoint_ = nearestPoint(p); std::cerr << pointDataPos(selectedPoint_) << std::endl; updateAll(); } void Application:: escape() { mouseState_.escape = true; if (mouseState_.moving && state_ == State::MOVE) moveTo(selectPoint_); } void Application:: nextChar() { int charNum = fontData_.charNum(); if (charNum < 94) { ++charNum; setKey(charNum + ' '); updateAll(); } } void Application:: prevChar() { int charNum = fontData_.charNum(); if (charNum > 0) { --charNum; setKey(charNum + ' '); updateAll(); } } void Application:: moveTo(const CPoint2D &p) { move(MoveType::TO, p); } void Application:: moveBy(const CPoint2D &p) { move(MoveType::BY, p); } void Application:: move(const MoveType &moveType, const CPoint2D &p) { CPoint2D p1 = CLFont::snapPoint(p); if (selectedPoint_.isSet()) { CLFontLine *line = fontData_.fontDef_.lines()[selectedPoint_.ind()]; if (selectedPoint_.subInd() == 0) { if (moveType == MoveType::TO) line->setStart(p1); else if (moveType == MoveType::BY) line->setStart(line->start() + p1); } else if (selectedPoint_.subInd() == 1) { if (moveType == MoveType::TO) line->setEnd(p1); else if (moveType == MoveType::BY) line->setEnd(line->end() + p1); } updateFontDef(); updateAll(); } } void Application:: deleteSelected() { if (selectedPoint_.isSet()) { fontData_.fontDef_.deleteLine(selectedPoint_.ind()); selectedPoint_.reset(); previewPoint_ .reset(); updateFontDef(); } } PointData Application:: nearestPoint(const CPoint2D &p) const { class MinDist { public: MinDist(const CPoint2D &p) : p_(p) { } double minDist() const { return minD_; } const PointData &minPoint() const { return minPoint_; } bool update(const PointData &pointData, const CPoint2D &p) { double d = std::hypot(p_.x - p.x, p_.y - p.y); if (! minPoint_.isSet() || d < minD_) { minD_ = d; minPoint_ = pointData; minP_ = p; } return (minD_ < 1E-5); } private: CPoint2D p_; double minD_ { 1E50 }; PointData minPoint_; CPoint2D minP_; }; //--- MinDist minDist(p); int i = 0; for (const auto &line : fontData_.fontDef_.lines()) { if (minDist.update(PointData(i, 0), line->start())) break; if (minDist.update(PointData(i, 1), line->end ())) break; ++i; } if (minDist.minDist() > 1E-5) return PointData(); return minDist.minPoint(); } CPoint2D Application:: pointDataPos(const PointData &pointData) const { if (selectedPoint_.isSet()) { const CLFontLine *line = fontData_.fontDef_.lines()[selectedPoint_.ind()]; if (pointData.subInd() == 0) return line->start(); else if (pointData.subInd() == 1) return line->end (); } return CPoint2D(0, 0); } void Application:: updateFontDef() { CLFont::setFontDef(fontData_.c(), fontData_.fontDef()); updateAll(); } void Application:: preview() { if (! preview_) preview_ = new Preview(this, "Preview"); preview_->show(); } void Application:: increaseLineWidth() { lineWidth_ += 1; updateAll(); } void Application:: decreaseLineWidth() { if (lineWidth_ > 1) { lineWidth_ -= 1; updateAll(); } } void Application:: moveState() { state_ = State::MOVE; updateState(); } void Application:: addState() { state_ = State::ADD; updateState(); } void Application:: deleteState() { state_ = State::DELETE; updateState(); } void Application:: updateAll() { update(); if (preview_) preview_->update(); updateState(); } void Application:: updateState() { QString str; if (state_ == State::MOVE) str += "Move"; else if (state_ == State::ADD) str += "Add"; else if (state_ == State::DELETE) str += "Delete"; str += QString(" : Char %1 (#%2)").arg(fontData_.c()).arg(fontData_.charNum()); stateLabel_->setText(str); } //--------- Canvas:: Canvas(Application *app, const std::string &name) : QWidget(app), app_(app) { setObjectName(name.c_str()); double margin = CLFont::charWidth/2.0; range_.setWindowRange(-margin, -margin - CLFont::charDescent, CLFont::charWidth + margin, CLFont::charAscent + margin); setFocusPolicy(Qt::StrongFocus); setMouseTracking(true); } void Canvas:: paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing); painter.fillRect(rect(), QBrush(QColor(0,0,0))); painter.setWorldMatrix(CQUtil::toQMatrix(range_.getMatrix())); app_->draw(&painter); } void Canvas:: resizeEvent(QResizeEvent *) { range_.setPixelRange(0, 0, width() - 1, height() - 1); } void Canvas:: keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Left) app_->moveBy(CPoint2D(-CLFont::delta, 0)); else if (e->key() == Qt::Key_Right) app_->moveBy(CPoint2D( CLFont::delta, 0)); else if (e->key() == Qt::Key_Down) app_->moveBy(CPoint2D(0, -CLFont::delta)); else if (e->key() == Qt::Key_Up) app_->moveBy(CPoint2D(0, CLFont::delta)); else if (e->key() == Qt::Key_Escape) app_->escape(); else if (e->key() == Qt::Key_PageDown) app_->prevChar(); else if (e->key() == Qt::Key_PageUp) app_->nextChar(); else { QString text = e->text(); if (text.length()) app_->setKey(text[0].toLatin1()); } update(); } void Canvas:: mousePressEvent(QMouseEvent *e) { CPoint2D p; range_.pixelToWindow(CPoint2D(e->x(), e->y()), p); app_->mousePress(p); } void Canvas:: mouseMoveEvent(QMouseEvent *e) { CPoint2D p; range_.pixelToWindow(CPoint2D(e->x(), e->y()), p); app_->mouseMove(p); } void Canvas:: mouseReleaseEvent(QMouseEvent *e) { CPoint2D p; range_.pixelToWindow(CPoint2D(e->x(), e->y()), p); app_->mouseRelease(p); } //--------- Preview:: Preview(Application *app, const std::string &name) : QWidget(), app_(app) { setObjectName(name.c_str()); range_.setWindowRange(0, 0, 30, 20); setFocusPolicy(Qt::StrongFocus); } void Preview:: paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing); painter.fillRect(rect(), QBrush(QColor(0,0,0))); painter.setWorldMatrix(CQUtil::toQMatrix(range_.getMatrix())); double y = 20; double dy = CLFont::charHeight; y -= dy; app_->drawText(&painter, CPoint2D(0, y), "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); y -= dy; app_->drawText(&painter, CPoint2D(0, y), "abcdefghijklmnopqrstuvwxyz"); y -= dy; app_->drawText(&painter, CPoint2D(0, y), "1234567890!\"£$%^&*()-_=+\\|"); y -= dy; app_->drawText(&painter, CPoint2D(0, y), "'~[]{}:;@#<>?,./"); } void Preview:: resizeEvent(QResizeEvent *) { range_.setPixelRange(0, 0, width() - 1, height() - 1); }
18.724971
97
0.631207
colinw7
478ed2e73e827ab55a48aadc2eae9190dcdb2147
2,302
cpp
C++
src/ZJGUIDataExchange.cpp
sowicm/mb-savedata-editor
73dfb1c906ea651c0a9eb21b71702af895a3589c
[ "MIT" ]
null
null
null
src/ZJGUIDataExchange.cpp
sowicm/mb-savedata-editor
73dfb1c906ea651c0a9eb21b71702af895a3589c
[ "MIT" ]
null
null
null
src/ZJGUIDataExchange.cpp
sowicm/mb-savedata-editor
73dfb1c906ea651c0a9eb21b71702af895a3589c
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "ZJGUIDataExchange.h" #include "ZJ_Algorithm.h" void DDX_Text(CDataExchange* pDX, CZJGUI& gui, UINT iView, int nIDC, CString& value) { CZJGUIView *pView = gui.GetView(iView); for (int i = 0; i < pView->GetNumControls(); ++i) { if (pView->GetControl(i)->GetID() == nIDC) { if (pDX->m_bSaveAndValidate) { value = pView->GetControl(i)->GetText(); } else { pView->GetControl(i)->SetText(value.GetBuffer()); } break; } } } void DDX_Text(CDataExchange* pDX, CZJGUI& gui, UINT iView, int nIDC, DWORD& value) { CZJGUIView *pView = gui.GetView(iView); for (int i = 0; i < pView->GetNumControls(); ++i) { if (pView->GetControl(i)->GetID() == nIDC) { if (pDX->m_bSaveAndValidate) { value = wtou(pView->GetControl(i)->GetText()); } else { pView->GetControl(i)->SetTextDirectly(utow(value)); } break; } } } void DDX_Text(CDataExchange* pDX, CZJGUI& gui, UINT iView, int nIDC, int& value) { CZJGUIView *pView = gui.GetView(iView); for (int i = 0; i < pView->GetNumControls(); ++i) { if (pView->GetControl(i)->GetID() == nIDC) { if (pDX->m_bSaveAndValidate) { value = wtoi(pView->GetControl(i)->GetText()); } else { pView->GetControl(i)->SetTextDirectly(itow(value)); } break; } } } void DDX_Check(CDataExchange* pDX, CZJGUI& gui, UINT iView, int nIDC, bool& value) { CZJGUIView *pView = gui.GetView(iView); for (int i = 0; i < pView->GetNumControls(); ++i) { if (pView->GetControl(i)->GetID() == nIDC) { if (pDX->m_bSaveAndValidate) { value = ((CZJGUICheckBox*)pView->GetControl(i))->GetChecked(); } else { ((CZJGUICheckBox*)pView->GetControl(i))->SetChecked(value); } break; } } }
28.419753
85
0.470026
sowicm
4794f526217319dbb03ce885bc3d8c28f20184cc
1,857
cpp
C++
LaplacianSmoother/src/MeshLaplacianData.cpp
tody411/MayaPluginSamples
785f1b1425e202f42d77622290c3faf80d7bd06f
[ "MIT" ]
2
2016-06-16T14:48:42.000Z
2018-06-28T20:12:09.000Z
LaplacianSmoother/src/MeshLaplacianData.cpp
tody411/MayaPluginSamples
785f1b1425e202f42d77622290c3faf80d7bd06f
[ "MIT" ]
null
null
null
LaplacianSmoother/src/MeshLaplacianData.cpp
tody411/MayaPluginSamples
785f1b1425e202f42d77622290c3faf80d7bd06f
[ "MIT" ]
null
null
null
#include "MeshLaplacianData.h" #include <maya/MIntArray.h> //! Get Laplacian data. const Eigen::SparseMatrix<double> MeshLaplacianData::GetLaplacianMatrix(int numFunctions) { if ( _geometryPath.hasFn(MFn::kMesh) ) { MFnMesh meshFn( _geometryPath ); return getLaplacianMatrix(meshFn, numFunctions); } if ( _geometryObject.hasFn(MFn::kMesh)) { MFnMesh meshFn( _geometryObject ); return getLaplacianMatrix(meshFn, numFunctions); } Eigen::SparseMatrix<double> zeroMat; return zeroMat; } //! Vertex iterator for the target geometry. MItMeshVertex MeshLaplacianData::vertIter() { if ( _geometryPath.hasFn(MFn::kMesh) ) { return MItMeshVertex(_geometryPath); } if ( _geometryObject.hasFn(MFn::kMesh) ) { return MItMeshVertex(_geometryObject); } return MItMeshVertex( _geometryObject); } //! Get Laplacian data. const Eigen::SparseMatrix<double> MeshLaplacianData::getLaplacianMatrix(MFnMesh& meshFn, int numFunctions) { int numVertices = meshFn.numVertices(); int numRows = numFunctions * numVertices; int numCols = numRows; Eigen::SparseMatrix<double> LaplacianMatrix(numRows, numCols); LaplacianMatrix.reserve(Eigen::VectorXi::Constant(numCols,8)); MItMeshVertex vertIt = vertIter(); MIntArray cvIDs; int iterVerts = 0; while ( !vertIt.isDone() ) { int vID = vertIt.index(); vertIt.getConnectedVertices( cvIDs ); if ( cvIDs.length() > 0) { for(int i = 0; i < numFunctions; ++i) { LaplacianMatrix.insert(numFunctions*vID+i,numFunctions*vID+i) = (float) cvIDs.length(); } for (int vi = 0; vi < cvIDs.length(); ++vi) { int cvID = cvIDs[vi]; for(int i = 0; i < numFunctions; ++i) { LaplacianMatrix.insert(numFunctions*vID+i, numFunctions*cvID+i) = -1.0f; } } } vertIt.next(); iterVerts++; } LaplacianMatrix.makeCompressed(); return LaplacianMatrix; }
21.847059
106
0.705439
tody411
4796a51b0812e1f9b09a9121f7572f0d11bd228b
7,078
cpp
C++
samples/openNI2_2d-icp-slam/test.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
2
2017-03-25T18:09:17.000Z
2017-05-22T08:14:48.000Z
samples/openNI2_2d-icp-slam/test.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
null
null
null
samples/openNI2_2d-icp-slam/test.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
1
2021-08-16T11:50:47.000Z
2021-08-16T11:50:47.000Z
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include <mrpt/hwdrivers/COpenNI2Sensor.h> #include <mrpt/gui.h> #include <mrpt/utils/CTicTac.h> #include <mrpt/opengl.h> #include <mrpt/opengl/CPlanarLaserScan.h> // This class is in mrpt-maps using namespace mrpt; using namespace mrpt::obs; using namespace mrpt::opengl; using namespace mrpt::utils; using namespace mrpt::hwdrivers; using namespace std; const float vert_FOV = DEG2RAD( 4.0 ); // This demo records from an OpenNI2 device, convert observations to 2D scans // and runs 2d-icp-slam with them. int main ( int argc, char** argv ) { try { if (argc>2) { cerr << "Usage: " << argv[0] << " <sensor_id/sensor_serial\n"; cerr << "Example: " << argv[0] << " 0 \n"; return 1; } //const unsigned sensor_id = 0; COpenNI2Sensor rgbd_sensor; //rgbd_sensor.loadConfig_sensorSpecific(const mrpt::utils::CConfigFileBase &configSource, const std::string &iniSection ); unsigned sensor_id_or_serial = 0; if(argc == 2) { sensor_id_or_serial = atoi(argv[1]); if(sensor_id_or_serial > 10) rgbd_sensor.setSerialToOpen(sensor_id_or_serial); else rgbd_sensor.setSensorIDToOpen(sensor_id_or_serial); } // Open: //cout << "Calling COpenNI2Sensor::initialize()..."; rgbd_sensor.initialize(); if(rgbd_sensor.getNumDevices() == 0) return 0; cout << "OK " << rgbd_sensor.getNumDevices() << " available devices." << endl; cout << "\nUse device " << sensor_id_or_serial << endl << endl; // Create window and prepare OpenGL object in the scene: // -------------------------------------------------------- mrpt::gui::CDisplayWindow3D win3D("OpenNI2 3D view",800,600); win3D.setCameraAzimuthDeg(140); win3D.setCameraElevationDeg(20); win3D.setCameraZoom(8.0); win3D.setFOV(90); win3D.setCameraPointingToPoint(2.5,0,0); mrpt::opengl::CPointCloudColouredPtr gl_points = mrpt::opengl::CPointCloudColoured::Create(); gl_points->setPointSize(2.5); // The 2D "laser scan" OpenGL object: mrpt::opengl::CPlanarLaserScanPtr gl_2d_scan = mrpt::opengl::CPlanarLaserScan::Create(); gl_2d_scan->enablePoints(true); gl_2d_scan->enableLine(true); gl_2d_scan->enableSurface(true); gl_2d_scan->setSurfaceColor(0,0,1, 0.3); // RGBA opengl::COpenGLViewportPtr viewInt; // Extra viewports for the RGB images. { mrpt::opengl::COpenGLScenePtr &scene = win3D.get3DSceneAndLock(); // Create the Opengl object for the point cloud: scene->insert( gl_points ); scene->insert( mrpt::opengl::CGridPlaneXY::Create() ); scene->insert( mrpt::opengl::stock_objects::CornerXYZ() ); scene->insert( gl_2d_scan ); const double aspect_ratio = 480.0 / 640.0; const int VW_WIDTH = 400; // Size of the viewport into the window, in pixel units. const int VW_HEIGHT = aspect_ratio*VW_WIDTH; // Create an extra opengl viewport for the RGB image: viewInt = scene->createViewport("view2d_int"); viewInt->setViewportPosition(5, 30, VW_WIDTH,VW_HEIGHT ); win3D.addTextMessage(10, 30+VW_HEIGHT+10,"Intensity data",TColorf(1,1,1), 2, MRPT_GLUT_BITMAP_HELVETICA_12 ); win3D.addTextMessage(5,5, format("'o'/'i'-zoom out/in, ESC: quit"), TColorf(0,0,1), 110, MRPT_GLUT_BITMAP_HELVETICA_18 ); win3D.unlockAccess3DScene(); win3D.repaint(); } // Grab frames continuously and show //======================================================================================== bool bObs = false, bError = true; mrpt::system::TTimeStamp last_obs_tim = INVALID_TIMESTAMP; while (!win3D.keyHit()) //Push any key to exit // win3D.isOpen() { // cout << "Get new observation\n"; CObservation3DRangeScanPtr newObs = CObservation3DRangeScan::Create(); rgbd_sensor.getNextObservation(*newObs, bObs, bError); CObservation2DRangeScanPtr obs_2d; // The equivalent 2D scan if (bObs && !bError && newObs && newObs->timestamp!=INVALID_TIMESTAMP && newObs->timestamp!=last_obs_tim ) { // It IS a new observation: last_obs_tim = newObs->timestamp; // Convert ranges to an equivalent 2D "fake laser" scan: if (newObs->hasRangeImage ) { // Convert to scan: obs_2d = CObservation2DRangeScan::Create(); T3DPointsTo2DScanParams p2s; p2s.angle_sup = .5f*vert_FOV; p2s.angle_inf = .5f*vert_FOV; p2s.sensorLabel = "KINECT_2D_SCAN"; newObs->convertTo2DScan(*obs_2d, p2s); } // Update visualization --------------------------------------- win3D.get3DSceneAndLock(); // Estimated grabbing rate: win3D.addTextMessage(-350,-13, format("Timestamp: %s", mrpt::system::dateTimeLocalToString(last_obs_tim).c_str()), TColorf(0.6,0.6,0.6),"mono",10,mrpt::opengl::FILL, 100); // Show intensity image: if (newObs->hasIntensityImage ) { viewInt->setImageView(newObs->intensityImage); // This is not "_fast" since the intensity image may be needed later on. } win3D.unlockAccess3DScene(); // ------------------------------------------------------- // Create 3D points from RGB+D data // // There are several methods to do this. // Switch the #if's to select among the options: // See also: http://www.mrpt.org/Generating_3D_point_clouds_from_RGB_D_observations // ------------------------------------------------------- if (newObs->hasRangeImage) { // Pathway: RGB+D --> XYZ+RGB opengl win3D.get3DSceneAndLock(); newObs->project3DPointsFromDepthImageInto(*gl_points, false /* without obs.sensorPose */); win3D.unlockAccess3DScene(); } // And load scan in the OpenGL object: gl_2d_scan->setScan(*obs_2d); win3D.repaint(); } // end update visualization: } cout << "\nClosing RGBD sensor...\n"; return 0; } catch (std::exception &e) { std::cout << "MRPT exception caught: " << e.what() << std::endl; return -1; } catch (...) { printf("Untyped exception!!"); return -1; } }
35.747475
182
0.567816
yhexie
4799f417e923c2b78dc497746a1dd3e6c2a2f1ec
762
cpp
C++
MrGimmick/BaseEnemySound.cpp
CodingC1402/SpaghettiEngine
80fddf7c68ae7476a5880aae8fd0eac5bbf6ad1a
[ "MIT" ]
1
2021-06-02T09:31:15.000Z
2021-06-02T09:31:15.000Z
MrGimmick/BaseEnemySound.cpp
CornyCodingCorn/SpaghettiEngine
80fddf7c68ae7476a5880aae8fd0eac5bbf6ad1a
[ "MIT" ]
1
2021-07-13T13:56:18.000Z
2021-07-13T13:56:18.000Z
MrGimmick/BaseEnemySound.cpp
CodingC1402/SpaghettiEngine
80fddf7c68ae7476a5880aae8fd0eac5bbf6ad1a
[ "MIT" ]
2
2021-04-25T02:08:42.000Z
2021-04-29T04:18:34.000Z
#include "BaseEnemySound.h" #include "FieldNames.h" REGISTER_FINISH(BaseEnemySound, BaseSoundScript) {} void BaseEnemySound::OnStart() { _health = GET_FIRST_SCRIPT_OF_TYPE(HealthScript); _health->AddToHealthEvent([&](const int& health, const int& delta) { this->Play(health, delta); }); BaseSoundScript::OnStart(); } void BaseEnemySound::PlayDeadSound() { _soundManager->Play(Fields::SoundManager::_explode); } void BaseEnemySound::StopDeadSound() { _soundManager->Stop(Fields::SoundManager::_explode); } void BaseEnemySound::Play(const int& health, const int& delta) { if (health <= 0) { PlayDeadSound(); } } ScriptBase* BaseEnemySound::Clone() const { auto clone = dynamic_cast<BaseEnemySound*>(ScriptBase::Clone()); return clone; }
18.585366
69
0.730971
CodingC1402
479c8c6bdcf1594041d33deddb256f189d88cc6e
9,743
cpp
C++
KeyWords/DX10AsmKeyWords.cpp
GPUOpen-Tools/common-src-ShaderUtils
545195d74ff0758f74ebf9a8b4c541f9390a1df7
[ "MIT" ]
18
2017-01-28T14:18:44.000Z
2020-04-29T00:05:10.000Z
KeyWords/DX10AsmKeyWords.cpp
GPUOpen-Archive/common-src-ShaderUtils
545195d74ff0758f74ebf9a8b4c541f9390a1df7
[ "MIT" ]
1
2019-02-09T18:00:53.000Z
2019-02-09T18:00:53.000Z
KeyWords/DX10AsmKeyWords.cpp
GPUOpen-Tools/common-src-ShaderUtils
545195d74ff0758f74ebf9a8b4c541f9390a1df7
[ "MIT" ]
5
2018-04-29T09:46:06.000Z
2019-11-01T23:11:27.000Z
//===================================================================== // // Author: AMD Developer Tools Team // Graphics Products Group // Developer Tools // AMD, Inc. // // DX10AsmKeywords.cpp // File contains <Seth file description here> // //===================================================================== // $Id: //devtools/main/Common/Src/ShaderUtils/KeyWords/DX10AsmKeyWords.cpp#3 $ // // Last checkin: $DateTime: 2016/04/14 04:43:34 $ // Last edited by: $Author: AMD Developer Tools Team //===================================================================== // ( C ) AMD, Inc. 2009,2010 All rights reserved. //===================================================================== #include "DX10AsmKeywords.h" #include <tchar.h> #include <boost/foreach.hpp> #include <boost/format.hpp> #include "D3D10ShaderUtils.h" #include "Swizzles.h" using namespace D3D10ShaderUtils; using boost::format; bool ShaderUtils::GetDX10InstKeyWords(ShaderUtils::KeyWordsList& keyWords, const D3D10ShaderObject::CD3D10ShaderObject& shader) { // Ops KeyWords opKeyWords; opKeyWords.type = KW_Op; opKeyWords.strKeywords = "constant linear centroid linearCentroid linearNoperspective linearNoperspectiveCentroid dynamicIndexed immediateIndexed mode_default float noperspective position refactoringAllowed " "ClipDistance CullDistance Coverage Depth IsFrontFace Position RenderTargetArrayIndex SampleIndex Target ViewportArrayIndex InstanceID PrimitiveID VertexID " "Buffer Texture1D Texture1DArray Texture2D Texture2DArray Texture3D TextureCube Texture2DMS Texture2DMSArray TextureCubeArray " "buffer texture1d texture1darray texture2d texture2darray texture3d texturecube texture2dms texture2dmsarray texturecubearray " "UNORM SNORM SINT UINT FLOAT unorm snorm sint uint float default mode_default comparison mode_comparison mono mode_mono "; KeyWords texOpKeyWords; texOpKeyWords.type = KW_TextureOp; texOpKeyWords.strKeywords = ""; KeyWords intOpKeyWords; intOpKeyWords.type = KW_IntOp; intOpKeyWords.strKeywords = ""; KeyWords doubleOpKeyWords; doubleOpKeyWords.type = KW_DoubleOp; doubleOpKeyWords.strKeywords = ""; D3D10ShaderUtils::ShaderType shaderType = D3D10ShaderUtils::None; switch (shader.GetShaderType()) { case D3D10_SB_VERTEX_SHADER: opKeyWords.strKeywords += "vs_4_0 vs_4_1 vs_5_0 dcl_input_vertexID dcl_input_instanceID instance_id "; shaderType = VS; break; case D3D10_SB_GEOMETRY_SHADER: opKeyWords.strKeywords += "gs_4_0 gs_4_1 gs_5_0 dcl_input_primitiveID dcl_output_primitiveID dcl_output_isFrontFace dcl_maxout rendertarget_array_index "; shaderType = GS; break; case D3D10_SB_PIXEL_SHADER: opKeyWords.strKeywords += "ps_4_0 ps_4_1 ps_5_0 dcl_input_ps dcl_input_primitiveID dcl_input_isFrontFace dcl_input_clipDistance dcl_input_cullDistance dcl_input_position dcl_input_renderTargetArrayIndex dcl_input_viewportArrayIndex "; shaderType = PS; break; case D3D11_SB_HULL_SHADER: opKeyWords.strKeywords += "hs_5_0 "; shaderType = HS; break; case D3D11_SB_DOMAIN_SHADER: opKeyWords.strKeywords += "ds_5_0 "; shaderType = DS; break; case D3D11_SB_COMPUTE_SHADER: opKeyWords.strKeywords += "cs_4_0 cs_4_1 cs_5_0 "; shaderType = CS; break; } const OpCodeInfo* pOpCodeInfo = GetOpCodeInfoTable(); for (DWORD i = 0; i < GetOpCodeInfoCount(); i++) { if ((pOpCodeInfo[i].shaderTypes & shaderType) != 0) { switch (pOpCodeInfo[i].instructionType) { case IT_Integer: // Fall-through case IT_Atomic: intOpKeyWords.strKeywords += pOpCodeInfo[i].pszKeyWords; intOpKeyWords.strKeywords += _T(" "); break; case IT_Double: doubleOpKeyWords.strKeywords += pOpCodeInfo[i].pszKeyWords; doubleOpKeyWords.strKeywords += _T(" "); break; case IT_Load: // Fall-through case IT_Store: texOpKeyWords.strKeywords += pOpCodeInfo[i].pszKeyWords; texOpKeyWords.strKeywords += _T(" "); break; case IT_Declaration: // Fall-through case IT_ALU: // Fall-through case IT_FlowControl: // Fall-through case IT_Other: // Fall-through default: opKeyWords.strKeywords += pOpCodeInfo[i].pszKeyWords; opKeyWords.strKeywords += _T(" "); break; } } } keyWords.push_back(opKeyWords); keyWords.push_back(texOpKeyWords); keyWords.push_back(intOpKeyWords); keyWords.push_back(doubleOpKeyWords); return !keyWords.empty(); } const std::string GenerateRegKeyWords(const TCHAR* pszFormat, DWORD dwCount) { std::string strRegKeyWords; for (DWORD i = 0; i < dwCount; i++) { strRegKeyWords += str(format(pszFormat) % i); } return strRegKeyWords; } const std::string GenerateArrayRegKeyWords(const TCHAR* pszFormat, DWORD dwRegIndex, DWORD dwArraySize) { std::string strRegKeyWords; for (DWORD i = 0; i < dwArraySize; i++) { strRegKeyWords += str(format(pszFormat) % dwRegIndex % i); } return strRegKeyWords; } const std::string GenerateRegKeyWords(const TCHAR* pszFormat, DWORD dwStart, DWORD dwCount) { std::string strRegKeyWords; for (DWORD i = dwStart; i < dwStart + dwCount; i++) { strRegKeyWords += str(format(pszFormat) % i); } return strRegKeyWords; } bool ShaderUtils::GetDX10RegKeyWords(ShaderUtils::KeyWordsList& keyWords, const D3D10ShaderObject::CD3D10ShaderObject& shader) { KeyWords regKeyWords; regKeyWords.type = KW_Reg; regKeyWords.strKeywords = _T("null l icb ") + GenerateRegKeyWords(_T("icb%i "), shader.GetImmediateConstantCount()) + GenerateRegKeyWords(_T("r%i "), shader.GetStats().TempRegisterCount); if (shader.GetShaderModel() >= SM_5_0) { regKeyWords.strKeywords += "this "; } if (shader.GetShaderType() == D3D11_SB_COMPUTE_SHADER) { regKeyWords.strKeywords += "vThreadID vThreadGroupID vThreadIDInGroupFlattened vThreadIDInGroup "; } BOOST_FOREACH(D3D10ShaderObject::D3D10_ResourceBinding resource, shader.GetBoundResources()) { if (resource.Type == D3D10_SIT_CBUFFER) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("cb%i "), resource.dwBindPoint, resource.dwBindCount); } else if (resource.Type == D3D10_SIT_SAMPLER) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("s%i "), resource.dwBindPoint, resource.dwBindCount); } else if (resource.Type == D3D10_SIT_TBUFFER || resource.Type == D3D10_SIT_TEXTURE || resource.Type == D3D11_SIT_STRUCTURED || resource.Type == D3D11_SIT_BYTEADDRESS || resource.Type == D3D11_SIT_UAV_CONSUME_STRUCTURED) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("t%i "), resource.dwBindPoint, resource.dwBindCount); } else if (resource.Type == D3D11_SIT_UAV_RWTYPED || resource.Type == D3D11_SIT_UAV_RWSTRUCTURED || resource.Type == D3D11_SIT_UAV_RWBYTEADDRESS || resource.Type == D3D11_SIT_UAV_APPEND_STRUCTURED || resource.Type == D3D11_SIT_UAV_RWSTRUCTURED_WITH_COUNTER) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("t%i "), resource.dwBindPoint, resource.dwBindCount) + GenerateRegKeyWords(_T("u%i "), resource.dwBindPoint, resource.dwBindCount); } else if (resource.Type == D3D11_SIT_STRUCTURED) { regKeyWords.strKeywords += GenerateRegKeyWords(_T("g%i "), resource.dwBindPoint, resource.dwBindCount); } else { regKeyWords.strKeywords += GenerateRegKeyWords(_T("u%i "), resource.dwBindPoint, resource.dwBindCount); } } regKeyWords.strKeywords += "v "; BOOST_FOREACH(D3D10ShaderObject::D3D10_Signature inputSignature, shader.GetInputSignatures()) { regKeyWords.strKeywords += str(format(_T("v%i ")) % inputSignature.dwRegister); } BOOST_FOREACH(std::string strInputSemanticName, shader.GetInputSemanticNames()) { regKeyWords.strKeywords += strInputSemanticName + " "; } BOOST_FOREACH(D3D10ShaderObject::D3D10_Signature outputSignature, shader.GetOutputSignatures()) { regKeyWords.strKeywords += str(format(_T("o%i ")) % outputSignature.dwRegister); } // Just hack in oDepth & oMask for all pixel shaders for now if (shader.GetShaderType() == D3D10_SB_PIXEL_SHADER) { regKeyWords.strKeywords += "oDepth oMask "; } BOOST_FOREACH(std::string strOutputSemanticName, shader.GetOutputSemanticNames()) { regKeyWords.strKeywords += strOutputSemanticName + " "; } BOOST_FOREACH(D3D10ShaderObject::D3D10_IndexableTempRegister indexableTempRegister, shader.GetIndexableTempRegisters()) { regKeyWords.strKeywords += str(format(_T("x%i ")) % indexableTempRegister.dwIndex); } BOOST_FOREACH(D3D10ShaderObject::D3D10_GlobalMemoryRegister globalMemoryRegister, shader.GetGlobalMemoryRegisters()) { regKeyWords.strKeywords += str(format(_T("g%i ")) % globalMemoryRegister.dwIndex); } regKeyWords.strKeywords += GetRGBASwizzles() + GetXYZWSwizzles(); keyWords.push_back(regKeyWords); return true; }
39.445344
248
0.655548
GPUOpen-Tools
479db04fb3008cba1e3ec58ea4e97fd851c6c5b7
3,044
cc
C++
day-10/ten.cc
JoBoCl/advent-of-code-2018
536bcd422a8289a8944d847c7806a81a1044442d
[ "MIT" ]
null
null
null
day-10/ten.cc
JoBoCl/advent-of-code-2018
536bcd422a8289a8944d847c7806a81a1044442d
[ "MIT" ]
null
null
null
day-10/ten.cc
JoBoCl/advent-of-code-2018
536bcd422a8289a8944d847c7806a81a1044442d
[ "MIT" ]
null
null
null
#include <algorithm> #include <fstream> #include <functional> #include <iostream> #include <limits> #include <list> #include <map> #include <numeric> #include <queue> #include <regex> #include <set> #include <string> #include <utility> #include <vector> using namespace std; struct Star { int x; int y; int u; int v; }; struct Box { int x0; int x1; int y0; int y1; }; int area(struct Box *b) { return (b->x1 - b->x0) * (b->y1 - b->y0); } int perimeter(struct Box *b) { return (b->x1 - b->x0) + (b->y1 - b->y0); } bool lessThan(struct Box *l, struct Box *r) { return perimeter(l) < perimeter(r); } vector<struct Star> readSequence() { vector<struct Star> stars; std::ifstream myfile("10.input"); string line; regex matcher("position=<\\s*(-?\\d+),\\s*(-?\\d+)> " "velocity=<\\s*(-?\\d+),\\s*(-?\\d+)>"); if (myfile.is_open()) { while (getline(myfile, line)) { struct Star star; smatch match; if (regex_match(line, match, matcher)) { struct Star star; star.x = stoi(match[1].str()); star.y = stoi(match[2].str()); star.u = stoi(match[3].str()); star.v = stoi(match[4].str()); stars.push_back(star); } } } return stars; } Box maxSize(vector<Star> *stars) { struct Box box; box.x0 = numeric_limits<int>::max(); box.y0 = numeric_limits<int>::max(); box.x1 = numeric_limits<int>::min(); box.y1 = numeric_limits<int>::min(); for (Star &star : *stars) { if (star.x < box.x0) box.x0 = star.x; if (star.y < box.y0) box.y0 = star.y; if (star.x > box.x1) box.x1 = star.x; if (star.y > box.y1) box.y1 = star.y; } return box; } void advance(Star *star) { star->x += star->u; star->y += star->v; } void retreat(Star *star) { star->x -= star->u; star->y -= star->v; } void partOne(vector<Star> stars) { struct Box oldBounds; struct Box newBounds = maxSize(&stars); int iterations = 0; do { oldBounds = newBounds; for (auto &star : stars) { advance(&star); } newBounds = maxSize(&stars); iterations++; } while (lessThan(&newBounds, &oldBounds)); cout << "Current bounds: " << oldBounds.x1 - oldBounds.x0 << ", " << oldBounds.y1 - oldBounds.y0 << " after " << iterations - 1 << " iterations. Print [y/N]?"; char print = 'Y'; // cin >> print; for (auto &star : stars) { retreat(&star); } if (toupper(print) == 'Y') { for (int j = oldBounds.y0; j <= oldBounds.y1; j++) { for (int i = oldBounds.x0; i <= oldBounds.x1; i++) { bool print = false; for (auto &star : stars) { if (star.x == i && star.y == j) { print = true; break; } } cout << (print ? '#' : ' '); } cout << "\n"; } } } void partTwo(vector<Star> stars) {} int main() { vector<struct Star> node = readSequence(); cout << "==== Part One ====\n"; partOne(node); cout << "\n==== Part Two ====\n"; partTwo(node); }
20.993103
74
0.538436
JoBoCl
47a41b1dff642d2d8441b83a3b1f3f79aa7397b4
2,990
cpp
C++
demo/dataflow/pipeline.cpp
DanieleDeSensi/Nornir
60587824d6b0a6e61b8fc75bdea37c9fc69199c7
[ "MIT" ]
2
2018-10-31T08:09:03.000Z
2021-01-18T19:23:54.000Z
demo/dataflow/pipeline.cpp
DanieleDeSensi/Nornir
60587824d6b0a6e61b8fc75bdea37c9fc69199c7
[ "MIT" ]
1
2020-02-02T11:58:22.000Z
2020-02-02T11:58:22.000Z
demo/dataflow/pipeline.cpp
DanieleDeSensi/Nornir
60587824d6b0a6e61b8fc75bdea37c9fc69199c7
[ "MIT" ]
1
2019-04-13T09:54:49.000Z
2019-04-13T09:54:49.000Z
/* * pipeline.cpp * * Created on: 04/05/2016 * * ========================================================================= * Copyright (C) 2015-, Daniele De Sensi (d.desensi.software@gmail.com) * * This file is part of nornir. * * nornir is free software: you can redistribute it and/or * modify it under the terms of the Lesser GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * nornir is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Lesser GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public * License along with nornir. * If not, see <http://www.gnu.org/licenses/>. * * ========================================================================= */ #include <iostream> #include <stdlib.h> #include <nornir/nornir.hpp> using namespace nornir::dataflow; #define MAX_SIZE 10; class DemoInputStream: public nornir::dataflow::InputStream{ private: size_t _currentElem; size_t _streamSize; bool _eos; public: explicit inline DemoInputStream(size_t streamSize): _currentElem(0), _streamSize(streamSize), _eos(false){ srand(time(NULL)); } inline void* next(){ if(_currentElem < _streamSize){ int* x; ++_currentElem; x = new int(); *x = rand() % 1000; std::cout << "Generated: " << *x << std::endl; std::cout << "ExpectedOutput: " << ((*x + 3) * 4) + 1 << std::endl; return (void*) x; }else{ _eos = true; return NULL; } } inline bool hasNext(){ return !_eos; } }; class DemoOutputStream: public nornir::dataflow::OutputStream{ public: void put(void* a){ int* x = (int*) a; std::cout << "Result: " << *x << std::endl; delete x; } }; int* fun1(int* x){ *x = *x + 3; return (int*) x; } int* fun2(int* x){ *x = *x * 4; return (int*) x; } class LastStage: public Computable{ public: void compute(Data* d){ int* in = (int*) d->getInput(); *in = *in + 1; d->setOutput((void*) in); } }; int main(int argc, char** argv){ if(argc < 2){ std::cerr << "Usage: " << argv[0] << " streamSize" << std::endl; return -1; } /* Create streams. */ DemoInputStream inp(atoi(argv[1])); DemoOutputStream out; Computable* pipeTmp = createStandardPipeline<int, int, int, fun1, fun2>(); Computable* lastStage = new LastStage(); Pipeline* pipe = new Pipeline(pipeTmp, lastStage); nornir::Parameters p("parameters.xml"); nornir::dataflow::Interpreter m(&p, pipe, &inp, &out); m.start(); m.wait(); delete pipe; delete lastStage; }
25.338983
79
0.563211
DanieleDeSensi
47a839414bbddb9f1dfcfcf391b5a446432faaad
1,420
hpp
C++
test_funcs.hpp
wagavulin/ropencv2
c57b8611ccc241e0953eb04451bb21cc4d589611
[ "Apache-2.0" ]
null
null
null
test_funcs.hpp
wagavulin/ropencv2
c57b8611ccc241e0953eb04451bb21cc4d589611
[ "Apache-2.0" ]
6
2021-05-24T14:29:40.000Z
2021-07-04T15:31:46.000Z
test_funcs.hpp
wagavulin/ropencv2
c57b8611ccc241e0953eb04451bb21cc4d589611
[ "Apache-2.0" ]
null
null
null
#include "opencv2/core.hpp" namespace cv { CV_EXPORTS_W double bindTest1(int a, CV_IN_OUT Point& b, CV_OUT int* c, int d=10, RNG* rng=0, double e=1.2); CV_EXPORTS_W void bindTest2(int a); CV_EXPORTS_W int bindTest3(int a); CV_EXPORTS_W void bindTest4(int a, CV_IN_OUT Point& pt); CV_EXPORTS_W void bindTest5(int a, CV_IN_OUT Point& pt, CV_OUT int* x); CV_EXPORTS_W bool bindTest6(int a, CV_IN_OUT Point& pt, CV_OUT int* x); CV_EXPORTS_W double bindTest_overload(Point a, Point b, double c); CV_EXPORTS_W double bindTest_overload(RotatedRect a); CV_EXPORTS_W void bindTest_InOut_Mat(CV_IN_OUT Mat& a); CV_EXPORTS_W void bindTest_InOut_bool(CV_IN_OUT bool& a); CV_EXPORTS_W void bindTest_InOut_uchar(CV_IN_OUT uchar& a); CV_EXPORTS_W void bindTest_InOut_int(CV_IN_OUT int& a); CV_EXPORTS_W void bindTest_Out_intp(CV_OUT int* a); CV_EXPORTS_W void bindTest_InOut_size_t(CV_IN_OUT size_t& a); CV_EXPORTS_W void bindTest_InOut_float(CV_IN_OUT float& a); CV_EXPORTS_W void bindTest_InOut_double(CV_IN_OUT double& a); CV_EXPORTS_W void bindTest_InOut_Size(CV_IN_OUT Size& a); CV_EXPORTS_W void bindTest_InOut_Size2f(CV_IN_OUT Size2f& a); CV_EXPORTS_W void bindTest_InOut_Point(CV_IN_OUT Point& a); CV_EXPORTS_W void bindTest_InOut_Point2f(CV_IN_OUT Point2f& a); CV_EXPORTS_W void bindTest_InOut_RotatedRect(CV_IN_OUT RotatedRect& a); CV_EXPORTS_W void bindTest_InOut_vector_Point(CV_IN_OUT std::vector<Point>& a); } // cv
44.375
108
0.814789
wagavulin
47aa9aa21f0b3b47d9eea9921357eae0dc2e60cb
2,578
hpp
C++
include/amtrs/.driver/win32-api-gdi_bitmap.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
1
2019-12-10T02:12:49.000Z
2019-12-10T02:12:49.000Z
include/amtrs/.driver/win32-api-gdi_bitmap.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
include/amtrs/.driver/win32-api-gdi_bitmap.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. * * Use of this source code is governed by a BSD-style license that * * can be found in the LICENSE file. */ #ifndef __libamtrs__os__win32__gdi_bitmap__hpp #define __libamtrs__os__win32__gdi_bitmap__hpp #include "win32-api-windows.hpp" #include "../graphics.hpp" AMTRS_OS_WIN32_NAMESPACE_BEGIN struct bitmap { template<class ST = unsigned int> static HBITMAP create_compatible(HDC _dc, size2<ST> _size) { HBITMAP bmp = CreateCompatibleBitmap(_dc, _size.width, _size.height); if (bmp == nullptr) { throw std::system_error(make_last_error_code()); } return bmp; } template<class ST> static void get_dibits(HDC _dc, HBITMAP _bmp, size2<ST> _size, rgba<uint8_t>* _buffer) { ::BITMAPINFOHEADER bmih = {}; bmih.biSize = sizeof(bmih); bmih.biWidth = (DWORD)_size.width; bmih.biHeight = (DWORD)_size.height; bmih.biPlanes = 1; bmih.biBitCount = 32; bmih.biSizeImage = bmih.biBitCount * bmih.biWidth * bmih.biHeight / 8; if (!GetDIBits(_dc, _bmp, 0, bmih.biHeight, _buffer, (LPBITMAPINFO)&bmih, DIB_RGB_COLORS)) { throw std::system_error(make_last_error_code()); } } static size2<unsigned int> get_size(HBITMAP /*_bmp*/) { ::BITMAP bmp; return {(unsigned int)bmp.bmWidth, (unsigned int)bmp.bmHeight}; } template<class PixelT, class BufferT, class ST = unsigned int> static void create_bitmap(basic_bitmap<PixelT, BufferT>& _dest, HDC _dc, HBITMAP _bmp, size2<ST> _size) { _dest = basic_bitmap<PixelT, BufferT>(_size.cast_to<unsigned int>()); basic_bitmap<PixelT, BufferT> tmp = _dest; get_dibits(_dc, _bmp, _size, tmp.pixels().data()); auto f = tmp.subimg({{0, 0}, tmp.size()}).flip_vertical(); _dest.assign(f.begin(), f.end()); for (auto& c : _dest) { std::swap(c.r, c.b); c.a = 255; } } template<class PixelT, class BufferT = std::vector<PixelT>, class ST = unsigned int> static basic_bitmap<PixelT, BufferT> create_bitmap(HDC _dc, HBITMAP _bmp, size2<ST> _size) { basic_bitmap<PixelT, BufferT> retval(_size.cast_to<unsigned int>()); create_bitmap(retval, _dc, _bmp, _size); return retval; } template<class PixelT, class BufferT = std::vector<PixelT>, class ST = unsigned int> static basic_bitmap<PixelT, BufferT> create_bitmap(HDC _dc, HBITMAP _bmp) { auto bmpSize = get_size(_bmp); basic_bitmap<PixelT, BufferT> retval(bmpSize.cast_to<unsigned int>()); create_bitmap(retval, _dc, _bmp, bmpSize); return retval; } }; AMTRS_OS_WIN32_NAMESPACE_END #endif
31.060241
104
0.70287
isaponsoft
47aaad505c523dbf9a61dde609f519c82c5c0414
6,339
cpp
C++
buffer_stream/buffer_stream_test.cpp
churuxu/codesnippets
9d01c53a5bd7be29168e3c8bfb27ebacc5164f03
[ "MIT" ]
4
2018-11-05T03:21:02.000Z
2021-09-25T15:33:52.000Z
buffer_stream/buffer_stream_test.cpp
churuxu/codesnippets
9d01c53a5bd7be29168e3c8bfb27ebacc5164f03
[ "MIT" ]
null
null
null
buffer_stream/buffer_stream_test.cpp
churuxu/codesnippets
9d01c53a5bd7be29168e3c8bfb27ebacc5164f03
[ "MIT" ]
2
2021-01-28T08:14:07.000Z
2021-09-25T15:33:54.000Z
#include "gtest.h" #include "buffer_stream.h" //默认模式基本测试 TEST(buffer_stream, test_default){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //写入两次,一次读取 buffer_stream_push(s, "hello", 5); buffer_stream_push(s, "world", 5); data = buffer_stream_fetch(s, &len); EXPECT_EQ(10, len); EXPECT_TRUE(data); EXPECT_TRUE(0==memcmp(data, "helloworld", 10)); buffer_stream_pop(s, len); //无数据时,预期获取到NULL data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入两次,一次读取 buffer_stream_push(s, "hello1", 6); buffer_stream_push(s, "world1", 6); data = buffer_stream_fetch(s, &len); EXPECT_EQ(12, len); EXPECT_TRUE(data); EXPECT_TRUE(0==memcmp(data, "hello1world1", 10)); buffer_stream_pop(s, len); buffer_stream_destroy(s); } //fix模式基本测试 TEST(buffer_stream, test_fix){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //每次固定读4字节 buffer_stream_set_fix_mode(s, 4); //写入数据 buffer_stream_push(s, "hello", 5); buffer_stream_push(s, "world", 5); //读第1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(4, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "hell", 4)); buffer_stream_pop(s, len); //读第2次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(4, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "owor", 4)); buffer_stream_pop(s, len); //读第3次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //再写一次 buffer_stream_push(s, "hello", 5); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(4, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "ldhe", 4)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); buffer_stream_destroy(s); } //计算动态长度,例如AT+5hello static int calc_testat_length(void* data, int len){ char* str = (char*)data; if(len<4)return 0; //数据不足 if(str[0] == 'A' && str[1] == 'T' && str[2] == '+'){ //数据足够 return 4 + (str[3] - '0'); } //数据有误 return -1; } //dynamic模式基本测试 TEST(buffer_stream, test_dynamic){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //每次读动态长度 buffer_stream_set_dynamic_mode(s, calc_testat_length); //写入数据 buffer_stream_push(s, "AT+5helloAT+6world!A", 20); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(9, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "AT+5hello", 9)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(10, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "AT+6world!", 10)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入数据 buffer_stream_push(s, "T+3bye", 6); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(7, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "AT+3bye", 7)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入错误数据 buffer_stream_push(s, "T+3bye", 6); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入数据 buffer_stream_push(s, "AT+3bye", 7); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(7, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "AT+3bye", 7)); buffer_stream_pop(s, len); buffer_stream_destroy(s); } //split模式基本测试 TEST(buffer_stream, test_split){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //每次读取一行 buffer_stream_set_split_mode(s, '\n'); //写入数据 buffer_stream_push(s, "hello\nworld\nhaha", 16); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(6, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "hello\n", 6)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(6, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "world\n", 6)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); //写入数据 buffer_stream_push(s, " bye\n", 6); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(9, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "haha bye\n", 9)); buffer_stream_pop(s, len); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(0, len); EXPECT_TRUE(data == NULL); buffer_stream_destroy(s); } //模式切换测试 TEST(buffer_stream, test_change_mode){ int len; void* data; buffer_stream* s = buffer_stream_create(64); ASSERT_TRUE(s); //写入数据 buffer_stream_push(s, "recv 5\nhellorecv 6\nworld!aaa", 26); //读取一行 buffer_stream_set_split_mode(s, '\n'); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(7, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "recv 5\n", 7)); buffer_stream_pop(s, len); //读取固定长度 buffer_stream_set_fix_mode(s, 5); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(5, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "hello", 5)); buffer_stream_pop(s, len); //读取一行 buffer_stream_set_split_mode(s, '\n'); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(7, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "recv 6\n", 7)); buffer_stream_pop(s, len); //读取固定长度 buffer_stream_set_fix_mode(s, 6); //读1次 data = buffer_stream_fetch(s, &len); EXPECT_EQ(6, len); EXPECT_TRUE(data); EXPECT_TRUE(0 == memcmp(data, "world!", 6)); buffer_stream_pop(s, len); buffer_stream_destroy(s); }
25.560484
65
0.589525
churuxu
47ace847e2d274e60f2f7f77dbbfabf7e2094d83
5,951
cpp
C++
buildpng.cpp
iggyvolz/GDD1-Assets
80449c6860f63460db589727bbc6655537236f73
[ "MIT" ]
null
null
null
buildpng.cpp
iggyvolz/GDD1-Assets
80449c6860f63460db589727bbc6655537236f73
[ "MIT" ]
null
null
null
buildpng.cpp
iggyvolz/GDD1-Assets
80449c6860f63460db589727bbc6655537236f73
[ "MIT" ]
null
null
null
#include <png++/png.hpp> #include "buildpng.h" #include<cmath> #include <ft2build.h> #include<iostream> using namespace std; #include FT_FREETYPE_H bool about(double a, double b, double delta) { if(a>b) { return (a-b)<delta; } return (b-a)<delta; } void red(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(255,0,0); } } } void green(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,255,0); } } } void blue(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,255); } } } void yellow(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(255,255,0); } } } // Draw moneybag on image void moneybag(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { // Circle if((x-28)*(x-28)+(y-28)*(y-28)<=15*15-5) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(219, 138, 67); } // Lines else if(about(y,5,1) && x>=17 && x<=39) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,0); } else if(y>=5&&y<=28 && about(x,(y+12), 1)) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,0); } else if(y>=5 && y<=28 && about(x,TILE_SIZE-(y+12), 1)) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,0); } else if(y>=5 && y<=28 && x>=(y+12) && x<=(44-y)) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(219, 138, 67); } // Border else if((x-28)*(x-28)+(y-28)*(y-28)<=16*16-5) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(0,0,0); } } } } void lightblue_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE*2; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX]=png::rgb_pixel(135,206,250); } } } void yellow_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=TILE_SIZE*2; y < TILE_SIZE*3; y++) { for (png::uint_32 x = 0; x < TILE_SIZE*5; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX]=png::rgb_pixel(255,255,0); } } for(png::uint_32 y=0; y < TILE_SIZE*5; y++) { for (png::uint_32 x = TILE_SIZE*2; x < TILE_SIZE*3; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX]=png::rgb_pixel(255,255,0); } } } void green_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0;y<TILE_SIZE*3;y++) { for(png::uint_32 x=0;x<TILE_SIZE;x++) { markXY(x+startX,y+startY);image[y+startY][x+startX]=png::rgb_pixel(0,255,0); } } } void orange_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(255,165,0); } } } void purple_piece(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < TILE_SIZE*2; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(128,0,128); } } for(png::uint_32 y=0; y<TILE_SIZE*6;y++) { for (png::uint_32 x = TILE_SIZE; x < TILE_SIZE*2; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(128,0,128); } } } void door(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < 2*TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(139,69,19); } } } void laser(Image& image, png::uint_32 startX, png::uint_32 startY) { for(png::uint_32 y=0; y < TILE_SIZE; y++) { for (png::uint_32 x = 0; x < 3*TILE_SIZE; x++) { markXY(x+startX,y+startY);image[y+startY][x+startX] = png::rgb_pixel(255,0,0); } } } template<typename T> T square(T val) { return val*val; } png::uint_32 maxX=0; png::uint_32 maxY=0; void markXY(png::uint_32 x, png::uint_32 y) { if(x>maxX) maxX=x; if(y>maxY) maxY=y; } void printMax() { cout << "x: " << maxX << ", y: " << maxY << endl; } void reverse(Image& source, Image& dest) { for(png::uint_32 y=0; y < source.get_height(); y++) { for (png::uint_32 x = 0; x < source.get_width(); x++) { dest[y][source.get_width()-x-1] = source[y][x]; } } }
27.298165
99
0.524282
iggyvolz
47ae79401ad2ce538b80529b0a0e3f1b09e06d1c
155,326
cc
C++
avida/avida-core/source/cpu/cHardwareBCR.cc
FergusonAJ/plastic-evolvability-avida
441a91f1cafa2a0883f8f3ce09c8894efa963e7c
[ "MIT" ]
2
2021-09-16T14:47:43.000Z
2021-10-31T04:55:16.000Z
avida/avida-core/source/cpu/cHardwareBCR.cc
FergusonAJ/plastic-evolvability-avida
441a91f1cafa2a0883f8f3ce09c8894efa963e7c
[ "MIT" ]
null
null
null
avida/avida-core/source/cpu/cHardwareBCR.cc
FergusonAJ/plastic-evolvability-avida
441a91f1cafa2a0883f8f3ce09c8894efa963e7c
[ "MIT" ]
2
2020-08-19T20:01:14.000Z
2020-12-21T21:24:12.000Z
/* * cHardwareBCR.cc * Avida * * Created by David on 11/2/2012 based on cHardwareMBE.cc * Copyright 1999-2013 Michigan State University. All rights reserved. * * * This file is part of Avida. * * Avida is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Avida is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with Avida. * If not, see <http://www.gnu.org/licenses/>. * * Authors: David M. Bryson <david@programerror.com>, Aaron P. Wagner <apwagner@msu.edu> * */ #include "cHardwareBCR.h" #include "avida/core/Feedback.h" #include "avida/core/WorldDriver.h" #include "avida/output/File.h" #include "cAvidaContext.h" #include "cHardwareManager.h" #include "cHardwareTracer.h" #include "cInstSet.h" #include "cOrganism.h" #include "cPhenotype.h" #include "cPopulation.h" #include "cStateGrid.h" #include "cWorld.h" #include "tInstLibEntry.h" #include <climits> #include <fstream> #include <iomanip> using namespace std; using namespace Avida; using namespace AvidaTools; tInstLib<cHardwareBCR::tMethod>* cHardwareBCR::s_inst_slib = cHardwareBCR::initInstLib(); tInstLib<cHardwareBCR::tMethod>* cHardwareBCR::initInstLib(void) { struct cNOPEntry { cString name; int nop_mod; cNOPEntry(const cString &name, int nop_mod) : name(name), nop_mod(nop_mod) {} }; static const cNOPEntry s_n_array[] = { cNOPEntry("nop-A", rAX), cNOPEntry("nop-B", rBX), cNOPEntry("nop-C", rCX), cNOPEntry("nop-D", rDX), cNOPEntry("nop-E", rEX), cNOPEntry("nop-F", rFX), cNOPEntry("nop-G", rGX), cNOPEntry("nop-H", rHX), cNOPEntry("nop-I", rIX), cNOPEntry("nop-J", rJX), cNOPEntry("nop-K", rKX), cNOPEntry("nop-L", rLX), }; static const tInstLibEntry<tMethod> s_f_array[] = { /* Note: all entries of cNOPEntryCPU s_n_array must have corresponding in the same order in tInstLibEntry<tMethod> s_f_array, and these entries must be the first elements of s_f_array. */ tInstLibEntry<tMethod>("nop-A", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-B", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-C", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-D", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-E", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-F", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-G", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-H", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-I", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-J", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-K", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("nop-L", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, nInstFlag::NOP, "No-operation; modifies other instructions"), tInstLibEntry<tMethod>("NULL", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, 0, "True no-operation instruction: does nothing"), tInstLibEntry<tMethod>("nop-X", &cHardwareBCR::Inst_Nop, INST_CLASS_NOP, 0, "True no-operation instruction: does nothing"), // Threading tInstLibEntry<tMethod>("thread-create", &cHardwareBCR::Inst_ThreadCreate, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), tInstLibEntry<tMethod>("thread-cancel", &cHardwareBCR::Inst_ThreadCancel, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), tInstLibEntry<tMethod>("thread-id", &cHardwareBCR::Inst_ThreadID, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), tInstLibEntry<tMethod>("yield", &cHardwareBCR::Inst_Yield, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), tInstLibEntry<tMethod>("regulate-pause", &cHardwareBCR::Inst_RegulatePause, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), tInstLibEntry<tMethod>("regulate-pause-sp", &cHardwareBCR::Inst_RegulatePauseSP, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), tInstLibEntry<tMethod>("regulate-resume", &cHardwareBCR::Inst_RegulateResume, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), tInstLibEntry<tMethod>("regulate-resume-sp", &cHardwareBCR::Inst_RegulateResumeSP, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), tInstLibEntry<tMethod>("regulate-reset", &cHardwareBCR::Inst_RegulateReset, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), tInstLibEntry<tMethod>("regulate-reset-sp", &cHardwareBCR::Inst_RegulateResetSP, INST_CLASS_OTHER, 0, "", BEHAV_CLASS_NONE), // Standard Conditionals tInstLibEntry<tMethod>("if-n-equ", &cHardwareBCR::Inst_IfNEqu, INST_CLASS_CONDITIONAL, 0, "Execute next instruction if ?BX?!=?CX?, else skip it"), tInstLibEntry<tMethod>("if-less", &cHardwareBCR::Inst_IfLess, INST_CLASS_CONDITIONAL, 0, "Execute next instruction if ?BX? < ?CX?, else skip it"), tInstLibEntry<tMethod>("if-not-0", &cHardwareBCR::Inst_IfNotZero, INST_CLASS_CONDITIONAL, 0, "Execute next instruction if ?BX? != 0, else skip it"), tInstLibEntry<tMethod>("if-equ-0", &cHardwareBCR::Inst_IfEqualZero, INST_CLASS_CONDITIONAL, 0, "Execute next instruction if ?BX? == 0, else skip it"), tInstLibEntry<tMethod>("if-gtr-0", &cHardwareBCR::Inst_IfGreaterThanZero, INST_CLASS_CONDITIONAL, 0, "Execute next instruction if ?BX? > 0, else skip it"), tInstLibEntry<tMethod>("if-less-0", &cHardwareBCR::Inst_IfLessThanZero, INST_CLASS_CONDITIONAL, 0, "Execute next instruction if ?BX? < 0, else skip it"), tInstLibEntry<tMethod>("if-gtr-x", &cHardwareBCR::Inst_IfGtrX, INST_CLASS_CONDITIONAL), tInstLibEntry<tMethod>("if-equ-x", &cHardwareBCR::Inst_IfEquX, INST_CLASS_CONDITIONAL), // Core ALU Operations tInstLibEntry<tMethod>("pop", &cHardwareBCR::Inst_Pop, INST_CLASS_DATA, 0, "Remove top number from stack and place into ?BX?"), tInstLibEntry<tMethod>("push", &cHardwareBCR::Inst_Push, INST_CLASS_DATA, 0, "Copy number from ?BX? and place it into the stack"), tInstLibEntry<tMethod>("pop-all", &cHardwareBCR::Inst_PopAll, INST_CLASS_DATA, 0, "Remove top numbers from stack and place into ?BX?"), tInstLibEntry<tMethod>("push-all", &cHardwareBCR::Inst_PushAll, INST_CLASS_DATA, 0, "Copy number from all registers and place into the stack"), tInstLibEntry<tMethod>("swap-stk", &cHardwareBCR::Inst_SwitchStack, INST_CLASS_DATA, 0, "Toggle which stack is currently being used"), tInstLibEntry<tMethod>("swap-stk-top", &cHardwareBCR::Inst_SwapStackTop, INST_CLASS_DATA, 0, "Swap the values at the top of both stacks"), tInstLibEntry<tMethod>("swap", &cHardwareBCR::Inst_Swap, INST_CLASS_DATA, 0, "Swap the contents of ?BX? with ?CX?"), tInstLibEntry<tMethod>("copy-val", &cHardwareBCR::Inst_CopyVal, INST_CLASS_DATA, 0, "Put the contents of ?BX? in ?CX?"), tInstLibEntry<tMethod>("shift-r", &cHardwareBCR::Inst_ShiftR, INST_CLASS_ARITHMETIC_LOGIC, 0, "Shift bits in ?BX? right by one (divide by two)"), tInstLibEntry<tMethod>("shift-l", &cHardwareBCR::Inst_ShiftL, INST_CLASS_ARITHMETIC_LOGIC, 0, "Shift bits in ?BX? left by one (multiply by two)"), tInstLibEntry<tMethod>("inc", &cHardwareBCR::Inst_Inc, INST_CLASS_ARITHMETIC_LOGIC, 0, "Increment ?BX? by one"), tInstLibEntry<tMethod>("dec", &cHardwareBCR::Inst_Dec, INST_CLASS_ARITHMETIC_LOGIC, 0, "Decrement ?BX? by one"), tInstLibEntry<tMethod>("zero", &cHardwareBCR::Inst_Zero, INST_CLASS_ARITHMETIC_LOGIC, 0, "Set ?BX? to 0"), tInstLibEntry<tMethod>("one", &cHardwareBCR::Inst_One, INST_CLASS_ARITHMETIC_LOGIC, 0, "Set ?BX? to 0"), tInstLibEntry<tMethod>("rand", &cHardwareBCR::Inst_Rand, INST_CLASS_ARITHMETIC_LOGIC, 0, "Set ?BX? to rand number"), tInstLibEntry<tMethod>("add", &cHardwareBCR::Inst_Add, INST_CLASS_ARITHMETIC_LOGIC, 0, "Add BX to CX and place the result in ?BX?"), tInstLibEntry<tMethod>("sub", &cHardwareBCR::Inst_Sub, INST_CLASS_ARITHMETIC_LOGIC, 0, "Subtract CX from BX and place the result in ?BX?"), tInstLibEntry<tMethod>("nand", &cHardwareBCR::Inst_Nand, INST_CLASS_ARITHMETIC_LOGIC, 0, "Nand BX by CX and place the result in ?BX?"), tInstLibEntry<tMethod>("IO", &cHardwareBCR::Inst_TaskIO, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "Output ?BX?, and input new number back into ?BX?", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("input", &cHardwareBCR::Inst_TaskInput, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "Input new number into ?BX?", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("output", &cHardwareBCR::Inst_TaskOutput, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "Output ?BX?", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("mult", &cHardwareBCR::Inst_Mult, INST_CLASS_ARITHMETIC_LOGIC, 0, "Multiple BX by CX and place the result in ?BX?"), tInstLibEntry<tMethod>("div", &cHardwareBCR::Inst_Div, INST_CLASS_ARITHMETIC_LOGIC, 0, "Divide BX by CX and place the result in ?BX?"), tInstLibEntry<tMethod>("mod", &cHardwareBCR::Inst_Mod, INST_CLASS_ARITHMETIC_LOGIC), // Flow Control Instructions tInstLibEntry<tMethod>("label", &cHardwareBCR::Inst_Label, INST_CLASS_FLOW_CONTROL, nInstFlag::LABEL), tInstLibEntry<tMethod>("search-lbl-direct-s", &cHardwareBCR::Inst_Search_Label_Direct_S, INST_CLASS_FLOW_CONTROL, 0, "Find direct label from genome start and move the flow head"), tInstLibEntry<tMethod>("search-lbl-direct-f", &cHardwareBCR::Inst_Search_Label_Direct_F, INST_CLASS_FLOW_CONTROL, 0, "Find direct label forward and move the flow head"), tInstLibEntry<tMethod>("search-lbl-direct-b", &cHardwareBCR::Inst_Search_Label_Direct_B, INST_CLASS_FLOW_CONTROL, 0, "Find direct label backward and move the flow head"), tInstLibEntry<tMethod>("search-lbl-direct-d", &cHardwareBCR::Inst_Search_Label_Direct_D, INST_CLASS_FLOW_CONTROL, 0, "Find direct label backward and move the flow head"), tInstLibEntry<tMethod>("search-seq-comp-s", &cHardwareBCR::Inst_Search_Seq_Comp_S, INST_CLASS_FLOW_CONTROL, 0, "Find complement template from genome start and move the flow head"), tInstLibEntry<tMethod>("search-seq-comp-f", &cHardwareBCR::Inst_Search_Seq_Comp_F, INST_CLASS_FLOW_CONTROL, 0, "Find complement template forward and move the flow head"), tInstLibEntry<tMethod>("search-seq-comp-b", &cHardwareBCR::Inst_Search_Seq_Comp_B, INST_CLASS_FLOW_CONTROL, 0, "Find complement template backward and move the flow head"), tInstLibEntry<tMethod>("search-seq-comp-d", &cHardwareBCR::Inst_Search_Seq_Comp_D, INST_CLASS_FLOW_CONTROL, 0, "Find complement template backward and move the flow head"), tInstLibEntry<tMethod>("mov-head", &cHardwareBCR::Inst_MoveHead, INST_CLASS_FLOW_CONTROL, 0, "Move head ?IP? to the flow head"), tInstLibEntry<tMethod>("mov-head-if-n-equ", &cHardwareBCR::Inst_MoveHeadIfNEqu, INST_CLASS_FLOW_CONTROL, 0, "Move head ?IP? to the flow head if ?BX? != ?CX?"), tInstLibEntry<tMethod>("mov-head-if-less", &cHardwareBCR::Inst_MoveHeadIfLess, INST_CLASS_FLOW_CONTROL, 0, "Move head ?IP? to the flow head if ?BX? != ?CX?"), tInstLibEntry<tMethod>("jmp-head", &cHardwareBCR::Inst_JumpHead, INST_CLASS_FLOW_CONTROL, 0, "Move head ?Flow? by amount in ?CX? register"), tInstLibEntry<tMethod>("get-head", &cHardwareBCR::Inst_GetHead, INST_CLASS_FLOW_CONTROL, 0, "Copy the position of the ?IP? head into ?CX?"), tInstLibEntry<tMethod>("set-memory", &cHardwareBCR::Inst_SetMemory, INST_CLASS_FLOW_CONTROL, 0, "Set ?mem_space_label? of the ?Flow? head."), tInstLibEntry<tMethod>("promoter", &cHardwareBCR::Inst_Nop, INST_CLASS_FLOW_CONTROL, nInstFlag::PROMOTER, "True no-operation instruction: does nothing"), tInstLibEntry<tMethod>("terminator", &cHardwareBCR::Inst_Nop, INST_CLASS_FLOW_CONTROL, nInstFlag::TERMINATOR, "True no-operation instruction: does nothing"), // Replication Instructions tInstLibEntry<tMethod>("divide", &cHardwareBCR::Inst_Divide, INST_CLASS_LIFECYCLE, nInstFlag::STALL, "Divide code between read and write heads.", BEHAV_CLASS_COPY), tInstLibEntry<tMethod>("divide-memory", &cHardwareBCR::Inst_DivideMemory, INST_CLASS_LIFECYCLE, nInstFlag::STALL, "Divide memory space.", BEHAV_CLASS_COPY), tInstLibEntry<tMethod>("h-copy", &cHardwareBCR::Inst_HeadCopy, INST_CLASS_LIFECYCLE, 0, "Copy from read-head to write-head; advance both", BEHAV_CLASS_COPY), tInstLibEntry<tMethod>("h-read", &cHardwareBCR::Inst_HeadRead, INST_CLASS_LIFECYCLE, 0, "Read instruction from ?read-head? to ?AX?; advance the head.", BEHAV_CLASS_COPY), tInstLibEntry<tMethod>("h-write", &cHardwareBCR::Inst_HeadWrite, INST_CLASS_LIFECYCLE, 0, "Write to ?write-head? instruction from ?AX?; advance the head.", BEHAV_CLASS_COPY), tInstLibEntry<tMethod>("if-copied-lbl-comp", &cHardwareBCR::Inst_IfCopiedCompLabel, INST_CLASS_CONDITIONAL, 0, "Execute next if we copied complement of attached label"), tInstLibEntry<tMethod>("if-copied-lbl-direct", &cHardwareBCR::Inst_IfCopiedDirectLabel, INST_CLASS_CONDITIONAL, 0, "Execute next if we copied direct match of the attached label"), tInstLibEntry<tMethod>("if-copied-seq-comp", &cHardwareBCR::Inst_IfCopiedCompSeq, INST_CLASS_CONDITIONAL, 0, "Execute next if we copied complement of attached sequence"), tInstLibEntry<tMethod>("if-copied-seq-direct", &cHardwareBCR::Inst_IfCopiedDirectSeq, INST_CLASS_CONDITIONAL, 0, "Execute next if we copied direct match of the attached sequence"), tInstLibEntry<tMethod>("did-copy-lbl-comp", &cHardwareBCR::Inst_DidCopyCompLabel, INST_CLASS_OTHER, 0, "Execute next if we copied complement of attached label"), tInstLibEntry<tMethod>("did-copy-lbl-direct", &cHardwareBCR::Inst_DidCopyDirectLabel, INST_CLASS_OTHER, 0, "Execute next if we copied direct match of the attached label"), tInstLibEntry<tMethod>("did-copy-seq-comp", &cHardwareBCR::Inst_DidCopyCompSeq, INST_CLASS_OTHER, 0, "Execute next if we copied complement of attached sequence"), tInstLibEntry<tMethod>("did-copy-seq-direct", &cHardwareBCR::Inst_DidCopyDirectSeq, INST_CLASS_OTHER, 0, "Execute next if we copied direct match of the attached sequence"), tInstLibEntry<tMethod>("repro", &cHardwareBCR::Inst_Repro, INST_CLASS_LIFECYCLE, nInstFlag::STALL, "Instantly reproduces the organism", BEHAV_CLASS_COPY), tInstLibEntry<tMethod>("die", &cHardwareBCR::Inst_Die, INST_CLASS_LIFECYCLE, nInstFlag::STALL, "Instantly kills the organism", BEHAV_CLASS_COPY), // Thread Execution Control tInstLibEntry<tMethod>("wait-cond-equ", &cHardwareBCR::Inst_WaitCondition_Equal, INST_CLASS_OTHER, nInstFlag::STALL, ""), tInstLibEntry<tMethod>("wait-cond-less", &cHardwareBCR::Inst_WaitCondition_Less, INST_CLASS_OTHER, nInstFlag::STALL, ""), tInstLibEntry<tMethod>("wait-cond-gtr", &cHardwareBCR::Inst_WaitCondition_Greater, INST_CLASS_OTHER, nInstFlag::STALL, ""), // State Grid instructions tInstLibEntry<tMethod>("sg-move", &cHardwareBCR::Inst_SGMove, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("sg-rotate-l", &cHardwareBCR::Inst_SGRotateL, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("sg-rotate-r", &cHardwareBCR::Inst_SGRotateR, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("sg-sense", &cHardwareBCR::Inst_SGSense, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_INPUT), // Movement and Navigation instructions tInstLibEntry<tMethod>("move", &cHardwareBCR::Inst_Move, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("juv-move", &cHardwareBCR::Inst_JuvMove, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("get-north-offset", &cHardwareBCR::Inst_GetNorthOffset, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("get-position-offset", &cHardwareBCR::Inst_GetPositionOffset, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("get-northerly", &cHardwareBCR::Inst_GetNortherly, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("get-easterly", &cHardwareBCR::Inst_GetEasterly, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("zero-easterly", &cHardwareBCR::Inst_ZeroEasterly, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("zero-northerly", &cHardwareBCR::Inst_ZeroNortherly, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("zero-position-offset", &cHardwareBCR::Inst_ZeroPosOffset, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_INPUT), // Rotation tInstLibEntry<tMethod>("rotate-home", &cHardwareBCR::Inst_RotateHome, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("rotate-to-unoccupied-cell", &cHardwareBCR::Inst_RotateUnoccupiedCell, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("rotate-x", &cHardwareBCR::Inst_RotateX, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("rotate-org-id", &cHardwareBCR::Inst_RotateOrgID, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("rotate-away-org-id", &cHardwareBCR::Inst_RotateAwayOrgID, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), // Resource and Topography Sensing tInstLibEntry<tMethod>("sense-resource-id", &cHardwareBCR::Inst_SenseResourceID, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("sense-nest", &cHardwareBCR::Inst_SenseNest, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("sense-faced-habitat", &cHardwareBCR::Inst_SenseFacedHabitat, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-ahead", &cHardwareBCR::Inst_LookAhead, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-ahead-intercept", &cHardwareBCR::Inst_LookAheadIntercept, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-ahead-ex", &cHardwareBCR::Inst_LookAheadEX, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-again-ex", &cHardwareBCR::Inst_LookAgainEX, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-ahead-ftx", &cHardwareBCR::Inst_LookAheadFTX, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-again-ftx", &cHardwareBCR::Inst_LookAgainFTX, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-around", &cHardwareBCR::Inst_LookAround, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-around-intercept", &cHardwareBCR::Inst_LookAroundIntercept, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-ft", &cHardwareBCR::Inst_LookFT, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("look-around-ft", &cHardwareBCR::Inst_LookAroundFT, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("set-forage-target", &cHardwareBCR::Inst_SetForageTarget, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("set-ft-once", &cHardwareBCR::Inst_SetForageTargetOnce, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("set-rand-ft-once", &cHardwareBCR::Inst_SetRandForageTargetOnce, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("get-forage-target", &cHardwareBCR::Inst_GetForageTarget, INST_CLASS_ENVIRONMENT, 0, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("collect-specific", &cHardwareBCR::Inst_CollectSpecific, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("get-res-stored", &cHardwareBCR::Inst_GetResStored, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), // Opinion instructions. tInstLibEntry<tMethod>("set-opinion", &cHardwareBCR::Inst_SetOpinion, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("get-opinion", &cHardwareBCR::Inst_GetOpinion, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), // Grouping instructions tInstLibEntry<tMethod>("join-group", &cHardwareBCR::Inst_JoinGroup, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("get-group-id", &cHardwareBCR::Inst_GetGroupID, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), // Org Interaction instructions tInstLibEntry<tMethod>("get-faced-org-id", &cHardwareBCR::Inst_GetFacedOrgID, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("teach-offspring", &cHardwareBCR::Inst_TeachOffspring, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("learn-parent", &cHardwareBCR::Inst_LearnParent, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("modify-simp-display", &cHardwareBCR::Inst_ModifySimpDisplay, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("read-simp-display", &cHardwareBCR::Inst_ReadLastSimpDisplay, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), tInstLibEntry<tMethod>("kill-display", &cHardwareBCR::Inst_KillDisplay, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("attack-prey", &cHardwareBCR::Inst_AttackPrey, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), tInstLibEntry<tMethod>("attack-ft-prey", &cHardwareBCR::Inst_AttackFTPrey, INST_CLASS_ENVIRONMENT, nInstFlag::STALL, "", BEHAV_CLASS_ACTION), // Control-type Instructions tInstLibEntry<tMethod>("scramble-registers", &cHardwareBCR::Inst_ScrambleReg, INST_CLASS_DATA, nInstFlag::STALL, "", BEHAV_CLASS_INPUT), }; const int n_size = sizeof(s_n_array)/sizeof(cNOPEntry); static cString n_names[n_size]; static int nop_mods[n_size]; for (int i = 0; i < n_size && i < NUM_REGISTERS; i++) { n_names[i] = s_n_array[i].name; nop_mods[i] = s_n_array[i].nop_mod; } const int f_size = sizeof(s_f_array)/sizeof(tInstLibEntry<tMethod>); static tMethod functions[f_size]; for (int i = 0; i < f_size; i++) functions[i] = s_f_array[i].GetFunction(); const int def = 0; const int null_inst = 12; return new tInstLib<tMethod>(f_size, s_f_array, n_names, nop_mods, functions, def, null_inst); } cHardwareBCR::cHardwareBCR(cAvidaContext& ctx, cWorld* world, cOrganism* in_organism, cInstSet* in_inst_set) : cHardwareBase(world, in_organism, in_inst_set), m_genes(0), m_mem_array(1), m_sensor(world, in_organism), m_sensor_sessions(NUM_NOPS) { m_functions = s_inst_slib->GetFunctions(); m_spec_die = false; m_no_cpu_cycle_time = m_world->GetConfig().NO_CPU_CYCLE_TIME.Get(); m_slip_read_head = !m_world->GetConfig().SLIP_COPY_MODE.Get(); const Genome& in_genome = in_organism->GetGenome(); ConstInstructionSequencePtr in_seq_p; in_seq_p.DynamicCastFrom(in_genome.Representation()); const InstructionSequence& in_seq = *in_seq_p; m_mem_array[0] = in_seq; // Initialize memory... m_use_avatar = m_world->GetConfig().USE_AVATARS.Get(); Reset(ctx); // Setup the rest of the hardware... } void cHardwareBCR::internalReset() { m_spec_stall = false; m_cycle_count = 0; m_last_output = 0; m_sensor.Reset(); for (int i = 0; i < m_sensor_sessions.GetSize(); i++) m_sensor_sessions[i].Clear(); // Stack m_global_stack.Clear(m_inst_set->GetStackSize()); // Threads m_threads.Resize(0); m_waiting_threads = 0; m_running_threads = 0; // Memory m_mem_array.Resize(1); for (int i = 1; i < MAX_MEM_SPACES; i++) m_mem_ids[i] = -1; m_mem_ids[0] = 0; // Genes m_genes.Resize(0); setupGenes(); } void cHardwareBCR::internalResetOnFailedDivide() { internalReset(); } void cHardwareBCR::setupGenes() { Head cur_promoter(this, 0, 0, false); do { if (m_inst_set->IsPromoter(cur_promoter.GetInst())) { // Flag the promoter as executed cur_promoter.SetFlagExecuted(); // Create the gene data structure int gene_id = m_genes.GetSize(); m_genes.Resize(gene_id + 1); // Start reading gene content, including the label if specified Head gene_content_start(cur_promoter); readLabel(gene_content_start, m_genes[gene_id].label); // Copy the specified genome segment Head seghead(gene_content_start); seghead.Advance(); int gene_idx = 0; cCPUMemory& gene = m_genes[gene_id].memory; while (!m_inst_set->IsTerminator(seghead.GetInst()) && seghead != gene_content_start) { if (gene.GetSize() <= gene_idx) gene.Resize(gene.GetSize() + 1); gene[gene_idx] = seghead.GetInst(); seghead.SetFlagExecuted(); gene_idx++; seghead.Advance(); } // Ignore zero length genes if (gene.GetSize() == 0) { m_genes.Resize(gene_id); continue; } // Create the gene thread Head thread_start(this, 0, gene_id, true); threadCreate(m_genes[gene_id].label, thread_start); } cur_promoter.Advance(); } while (!cur_promoter.AtEnd()); // If no valid genes where identified, create default gene from the whole genome if (m_genes.GetSize() == 0) { m_genes.Resize(1); m_genes[0].memory = m_mem_array[0]; for (int i = 0; i < m_mem_array[0].GetSize(); i++) m_mem_array[0].SetFlagExecuted(i); Head thread_start(this, 0, 0, true); threadCreate(m_genes[0].label, thread_start); } ResizeCostArrays(m_threads.GetSize()); } void cHardwareBCR::Thread::Reset(cHardwareBCR* in_hardware, const Head& start_pos) { // Clear registers for (int i = 0; i < NUM_REGISTERS; i++) reg[i].Clear(); // Reset the heads (read/write in genome, others at start_pos) heads[hREAD].Reset(in_hardware, 0, 0, false); heads[hWRITE].Reset(in_hardware, 0, 0, false); heads[hIP] = start_pos; for (int i = hFLOW; i < NUM_HEADS; i++) heads[i] = start_pos; // Clear the stack stack.Clear(in_hardware->GetInstSet().GetStackSize()); cur_stack = 0; // Clear other flags and values reading_label = false; reading_seq = false; running = true; active = true; read_label.Clear(); next_label.Clear(); sensor_session.Clear(); } bool cHardwareBCR::SingleProcess(cAvidaContext& ctx, bool speculative) { // If speculatively stalled, stay that way until a real instruction comes if (speculative && m_spec_stall) return false; // Mark this organism as running... m_organism->SetRunning(true); // Handle if this organism died while speculatively executing if (!speculative && m_spec_die) { m_organism->Die(ctx); m_organism->SetRunning(false); return false; } cPhenotype& phenotype = m_organism->GetPhenotype(); if (m_spec_stall) { m_spec_stall = false; } else { // Update cycle counts m_cycle_count++; phenotype.IncCPUCyclesUsed(); if (!m_no_cpu_cycle_time) phenotype.IncTimeUsed(); // Wake any stalled threads for (int i = 0; i < m_threads.GetSize(); i++) { if (!m_threads[i].active && m_threads[i].wait_reg == -1) m_threads[i].active = true; } // Reset behavioral class m_behav_class_used[0] = false; m_behav_class_used[1] = false; m_behav_class_used[2] = false; // Reset execution state m_cur_uop = 0; m_cur_thread = 0; } // Execute specified number of micro ops per cpu cycle on each thread in a round robin fashion const int uop_ratio = m_inst_set->GetUOpsPerCycle(); for (; m_cur_uop < uop_ratio; m_cur_uop++) { for (m_cur_thread = (m_cur_thread < m_threads.GetSize()) ? m_cur_thread : 0; m_cur_thread < m_threads.GetSize(); m_cur_thread++) { // Setup the hardware for the next instruction to be executed. // If the currently selected thread is inactive, proceed to the next thread if (!m_threads[m_cur_thread].running || !m_threads[m_cur_thread].active) continue; m_advance_ip = true; Head& ip = m_threads[m_cur_thread].heads[hIP]; ip.Adjust(); // Print the status of this CPU at each step... if (m_tracer) m_tracer->TraceHardware(ctx, *this); // Find the instruction to be executed const Instruction cur_inst = ip.GetInst(); if (speculative && (m_spec_die || m_inst_set->ShouldStall(cur_inst))) { // Speculative instruction stall, flag it and halt the thread m_spec_stall = true; m_organism->SetRunning(false); return false; } // Print the short form status of this CPU at each step... if (m_tracer) m_tracer->TraceHardware(ctx, *this, false, true); bool exec = true; int exec_success = 0; BehavClass behav_class = m_inst_set->GetInstLib()->Get(m_inst_set->GetLibFunctionIndex(ip.GetInst())).GetBehavClass(); // Check if this instruction class has been used and should cause the thread to stall? if (behav_class < BEHAV_CLASS_NONE && m_behav_class_used[behav_class]) { m_threads[m_cur_thread].active = false; m_threads[m_cur_thread].wait_reg = -1; if (m_tracer) m_tracer->TraceHardware(ctx, *this, false, true, exec_success); continue; } // Test if costs have been paid and it is okay to execute this now... // record any failure due to costs being paid // before we try to execute the instruction, is this org currently paying precosts for it bool on_pause = IsPayingActiveCost(ctx, m_cur_thread); if (m_has_any_costs) exec = SingleProcess_PayPreCosts(ctx, cur_inst, m_cur_thread); if (!exec) exec_success = -1; // Now execute the instruction... bool rand_fail = false; if (exec == true) { // NOTE: This call based on the cur_inst must occur prior to instruction // execution, because this instruction reference may be invalid after // certain classes of instructions (namely divide instructions) @DMB const int addl_time_cost = m_inst_set->GetAddlTimeCost(cur_inst); // Prob of exec (moved from SingleProcess_PayCosts so that we advance IP after a fail) if ( m_inst_set->GetProbFail(cur_inst) > 0.0 ) { exec = !( ctx.GetRandom().P(m_inst_set->GetProbFail(cur_inst)) ); rand_fail = !exec; } if (exec == true) { if (SingleProcess_ExecuteInst(ctx, cur_inst)) { SingleProcess_PayPostResCosts(ctx, cur_inst); SingleProcess_SetPostCPUCosts(ctx, cur_inst, m_cur_thread); // record execution success exec_success = 1; } } // Check if the instruction just executed caused premature death, break out of execution if so if (phenotype.GetToDelete()) { if (m_tracer) m_tracer->TraceHardware(ctx, *this, false, true, exec_success); break; } // Some instruction (such as jump) may turn m_advance_ip off. Usually // we now want to move to the next instruction in the memory. if (m_advance_ip == true) ip.Advance(); // Pay the additional death_cost of the instruction now phenotype.IncTimeUsed(addl_time_cost); // mark behavior class as used, when appropriate if (behav_class < BEHAV_CLASS_NONE) m_behav_class_used[behav_class] = true; } // if using mini traces, report success or failure of execution if (m_tracer) m_tracer->TraceHardware(ctx, *this, false, true, exec_success); bool do_record = false; // record exec failed if the org just now started paying precosts if (exec_success == -1 && !on_pause) do_record = true; // if exec succeeded but was on pause before this execution, we already recorded it // otherwise we record what the org did else if (exec_success == 1 && !on_pause) do_record = true; // if random failure, we record 'what the org was trying to do' else if (rand_fail) do_record = true; // if exec failed because of something inside the instruction itself, record the attempt else if (exec_success == 0) do_record = true; if (do_record) { // this will differ from time used phenotype.IncNumExecs(); if (m_microtrace || m_topnavtrace) { RecordMicroTrace(cur_inst); if (m_topnavtrace) RecordNavTrace(m_use_avatar); } } if (phenotype.GetToDelete()) { if (m_tracer) m_tracer->TraceHardware(ctx, *this, false, true, exec_success); break; } } if (phenotype.GetToDelete()) break; } // Kill creatures who have reached their max num of instructions executed const int max_executed = m_organism->GetMaxExecuted(); if ((max_executed > 0 && phenotype.GetTimeUsed() >= max_executed) || phenotype.GetToDie() == true) { if (speculative) m_spec_die = true; else m_organism->Die(ctx); } if (!speculative && phenotype.GetToDelete()) m_spec_die = true; m_organism->SetRunning(false); CheckImplicitRepro(ctx); return !m_spec_die && !m_spec_stall; } bool cHardwareBCR::SingleProcess_ExecuteInst(cAvidaContext& ctx, const Instruction& cur_inst) { // Copy Instruction locally to handle stochastic effects Instruction actual_inst = cur_inst; // Get a pointer to the corrisponding method... int inst_idx = m_inst_set->GetLibFunctionIndex(actual_inst); // Mark the instruction as executed getIP().SetFlagExecuted(); // instruction execution count incremeneted m_organism->GetPhenotype().IncCurInstCount(actual_inst.GetOp()); // And execute it. const bool exec_success = (this->*(m_functions[inst_idx]))(ctx); // decremenet if the instruction was not executed successfully if (exec_success == false) { m_organism->GetPhenotype().DecCurInstCount(actual_inst.GetOp()); } return exec_success; } void cHardwareBCR::ProcessBonusInst(cAvidaContext& ctx, const Instruction& inst) { // Mark this organism as running... bool prev_run_state = m_organism->IsRunning(); m_organism->SetRunning(true); if (m_tracer) m_tracer->TraceHardware(ctx, *this, true); SingleProcess_ExecuteInst(ctx, inst); m_organism->SetRunning(prev_run_state); } void cHardwareBCR::PrintStatus(ostream& fp) { fp << "CPU CYCLE:" << m_organism->GetPhenotype().GetCPUCyclesUsed() << "." << m_cur_uop << " "; fp << "THREAD:" << m_cur_thread << " "; fp << "IP:" << getIP().Position() << " (" << GetInstSet().GetName(getIP().GetInst()) << ")" << endl; for (int i = 0; i < NUM_REGISTERS; i++) { DataValue& reg = m_threads[m_cur_thread].reg[i]; fp << static_cast<char>('A' + i) << "X:" << getRegister(i) << " "; fp << setbase(16) << "[0x" << reg.value << "] " << setbase(10); fp << "(" << reg.from_env << " " << reg.env_component << " " << reg.originated << " " << reg.oldest_component << ") "; } // Add some extra information if additional time costs are used for instructions, // leave this out if there are no differences to keep it cleaner if ( m_organism->GetPhenotype().GetTimeUsed() != m_organism->GetPhenotype().GetCPUCyclesUsed() ) { fp << " EnergyUsed:" << m_organism->GetPhenotype().GetTimeUsed(); } fp << endl; fp << " R-Head:" << getHead(hREAD).Position() << " " << "W-Head:" << getHead(hWRITE).Position() << " " << "F-Head:" << getHead(hFLOW).Position() << " " << "RL:" << GetReadLabel().AsString() << " " << "Ex:" << m_last_output << endl; int number_of_stacks = GetNumStacks(); for (int stack_id = 0; stack_id < number_of_stacks; stack_id++) { fp << ((m_threads[m_cur_thread].cur_stack == stack_id) ? '*' : ' ') << " Stack " << stack_id << ":" << setbase(16) << setfill('0'); for (int i = 0; i < m_inst_set->GetStackSize(); i++) fp << " Ox" << setw(8) << GetStack(i, stack_id, 0); fp << setfill(' ') << setbase(10) << endl; } for (int i = 0; i < m_mem_array.GetSize(); i++) { const cCPUMemory& mem = m_mem_array[i]; fp << " Mem " << i << " (" << mem.GetSize() << "): " << mem.AsString() << endl; } for (int i = 0; i < m_genes.GetSize(); i++) { const cCPUMemory& mem = m_genes[i].memory; fp << " Gene " << i << " (" << mem.GetSize() << "): " << mem.AsString() << endl; } fp.flush(); } void cHardwareBCR::SetupMiniTraceFileHeader(Avida::Output::File& df, const int gen_id, const Apto::String& genotype) { const Genome& in_genome = m_organism->GetGenome(); ConstInstructionSequencePtr in_seq_p; in_seq_p.DynamicCastFrom(in_genome.Representation()); const InstructionSequence& in_seq = *in_seq_p; df.WriteTimeStamp(); cString org_dat(""); df.WriteComment(org_dat.Set("Update Born: %d", m_world->GetStats().GetUpdate())); df.WriteComment(org_dat.Set("Org ID: %d", m_organism->GetID())); df.WriteComment(org_dat.Set("Genotype ID: %d", gen_id)); df.WriteComment(org_dat.Set("Genotype: %s", (const char*) genotype)); df.WriteComment(org_dat.Set("Genome Length: %d", in_seq.GetSize())); df.WriteComment(" "); df.WriteComment("Exec Stats Columns:"); df.WriteComment("CPU Cycle"); df.WriteComment("MicroOp"); df.WriteComment("Current Update"); df.WriteComment("Register Contents (CPU Cycle Origin of Contents)"); df.WriteComment("Current Thread"); df.WriteComment("IP Position"); df.WriteComment("RH Position"); df.WriteComment("WH Position"); df.WriteComment("FH Position"); df.WriteComment("CPU Cycle of Last Output"); df.WriteComment("Current Merit"); df.WriteComment("Current Bonus"); df.WriteComment("Forager Type"); df.WriteComment("Group ID (opinion)"); df.WriteComment("Current Cell"); df.WriteComment("Avatar Cell"); df.WriteComment("Faced Direction"); df.WriteComment("Faced Cell Occupied?"); df.WriteComment("Faced Cell Has Hill?"); df.WriteComment("Faced Cell Has Wall?"); df.WriteComment("Queued Instruction"); df.WriteComment("Trailing NOPs"); df.WriteComment("Did Queued Instruction Execute (-1=no, paying cpu costs; 0=failed; 1=yes)"); df.Endl(); } void cHardwareBCR::PrintMiniTraceStatus(cAvidaContext& ctx, ostream& fp) { // basic status info fp << m_cycle_count << " "; fp << m_cur_uop << " "; fp << m_world->GetStats().GetUpdate() << " "; for (int i = 0; i < NUM_REGISTERS; i++) { DataValue& reg = m_threads[m_cur_thread].reg[i]; fp << getRegister(i) << " "; fp << "(" << reg.originated << ") "; } // genome loc info fp << m_cur_thread << " "; fp << getIP().Position() << " "; fp << getHead(hREAD).Position() << " "; fp << getHead(hWRITE).Position() << " "; fp << getHead(hFLOW).Position() << " "; // last output fp << m_last_output << " "; // phenotype/org status info fp << m_organism->GetPhenotype().GetMerit().GetDouble() << " "; fp << m_organism->GetPhenotype().GetCurBonus() << " "; fp << m_organism->GetForageTarget() << " "; if (m_organism->HasOpinion()) fp << m_organism->GetOpinion().first << " "; else fp << -99 << " "; // environment info / things that affect movement fp << m_organism->GetOrgInterface().GetCellID() << " "; if (m_use_avatar) fp << m_organism->GetOrgInterface().GetAVCellID() << " "; if (!m_use_avatar) fp << m_organism->GetOrgInterface().GetFacedDir() << " "; else fp << m_organism->GetOrgInterface().GetAVFacing() << " "; if (!m_use_avatar) fp << m_organism->IsNeighborCellOccupied() << " "; else fp << m_organism->GetOrgInterface().FacedHasAV() << " "; const cResourceLib& resource_lib = m_world->GetEnvironment().GetResourceLib(); Apto::Array<double> cell_resource_levels; if (!m_use_avatar) cell_resource_levels = m_organism->GetOrgInterface().GetFacedCellResources(ctx); else cell_resource_levels = m_organism->GetOrgInterface().GetAVFacedResources(ctx); int wall = 0; int hill = 0; for (int i = 0; i < cell_resource_levels.GetSize(); i++) { if (resource_lib.GetResource(i)->GetHabitat() == 2 && cell_resource_levels[i] > 0) wall = 1; if (resource_lib.GetResource(i)->GetHabitat() == 1 && cell_resource_levels[i] > 0) hill = 1; if (hill == 1 && wall == 1) break; } fp << hill << " "; fp << wall << " "; // instruction about to be executed cString next_name(GetInstSet().GetName(getIP().GetInst())); fp << next_name << " "; // any trailing nops (up to NUM_REGISTERS) cCPUMemory& memory = getIP().MemSpaceIsGene() ? m_genes[getIP().MemSpaceIndex()].memory : m_mem_array[getIP().MemSpaceIndex()]; int pos = getIP().Position(); Apto::Array<int, Apto::Smart> seq; seq.Resize(0); for (int i = 0; i < NUM_REGISTERS; i++) { pos += 1; if (pos >= memory.GetSize()) pos = 0; if (m_inst_set->IsNop(memory[pos])) seq.Push(m_inst_set->GetNopMod(memory[pos])); else break; } cString mod_string; for (int j = 0; j < seq.GetSize(); j++) { mod_string += (char) seq[j] + 'A'; } if (mod_string.GetSize() != 0) fp << mod_string << " "; else fp << "NoMods" << " "; } void cHardwareBCR::PrintMiniTraceSuccess(ostream& fp, const int exec_sucess) { fp << exec_sucess; fp << endl; fp.flush(); } void cHardwareBCR::FindLabelStart(Head& head, Head& default_pos, bool mark_executed) { const cCodeLabel& search_label = GetLabel(); // Make sure the label is of size > 0. if (search_label.GetSize() == 0) { head.Set(default_pos); return; } cCPUMemory& memory = head.GetMemory(); int pos = 0; while (pos < memory.GetSize()) { if (m_inst_set->IsLabel(memory[pos])) { // starting label found pos++; // Check for direct matched label pattern, can be substring of 'label'ed target // - must match all NOPs in search_label // - extra NOPs in 'label'ed target are ignored int size_matched = 0; while (size_matched < search_label.GetSize() && pos < memory.GetSize()) { if (!m_inst_set->IsNop(memory[pos]) || search_label[size_matched] != m_inst_set->GetNopMod(memory[pos])) break; size_matched++; pos++; } // Check that the label matches and has examined the full sequence of nops following the 'label' instruction if (size_matched == search_label.GetSize()) { // Return Head pointed at last NOP of label sequence if (mark_executed) { size_matched++; // Increment size matched so that it includes the label instruction const int start = pos - size_matched; const int max = m_world->GetConfig().MAX_LABEL_EXE_SIZE.Get() + 1; // Max label + 1 for the label instruction itself for (int i = 0; i < size_matched && i < max; i++) memory.SetFlagExecuted(start + i); } head.SetPosition(pos - 1); return; } continue; } pos++; } // Return start point if not found head.Set(default_pos); } void cHardwareBCR::FindNopSequenceStart(Head& head, Head& default_pos, bool mark_executed) { const cCodeLabel& search_label = GetLabel(); // Make sure the label is of size > 0. if (search_label.GetSize() == 0) { head.Set(default_pos); return; } cCPUMemory& memory = head.GetMemory(); int pos = 0; while (pos < memory.GetSize()) { if (m_inst_set->IsNop(memory[pos])) { // start of sequence found // Check for direct matched label pattern, can be substring of 'label'ed target // - must match all NOPs in search_label // - extra NOPs in 'label'ed target are ignored int size_matched = 0; while (size_matched < search_label.GetSize() && pos < memory.GetSize()) { if (!m_inst_set->IsNop(memory[pos]) || search_label[size_matched] != m_inst_set->GetNopMod(memory[pos])) break; size_matched++; pos++; } // Check that the label matches and has examined the full sequence of nops following the 'label' instruction if (size_matched == search_label.GetSize()) { // Return Head pointed at last NOP of label sequence if (mark_executed) { const int start = pos - size_matched; const int max = m_world->GetConfig().MAX_LABEL_EXE_SIZE.Get(); for (int i = 0; i < size_matched && i < max; i++) memory.SetFlagExecuted(start + i); } head.SetPosition(pos - 1); return; } } pos++; } // Return start point if not found head.Set(default_pos); } void cHardwareBCR::FindLabelForward(Head& head, Head& default_pos, bool mark_executed) { const cCodeLabel& search_label = GetLabel(); // Make sure the label is of size > 0. if (search_label.GetSize() == 0) { head.Set(default_pos); return; } head.Adjust(); Head pos(head); pos++; while (pos.Position() != head.Position()) { if (m_inst_set->IsLabel(pos.GetInst())) { // starting label found const int label_start = pos.Position(); pos++; // Check for direct matched label pattern, can be substring of 'label'ed target // - must match all NOPs in search_label // - extra NOPs in 'label'ed target are ignored int size_matched = 0; while (size_matched < search_label.GetSize() && pos.Position() != head.Position()) { if (!m_inst_set->IsNop(pos.GetInst()) || search_label[size_matched] != m_inst_set->GetNopMod(pos.GetInst())) break; size_matched++; pos++; } // Check that the label matches and has examined the full sequence of nops following the 'label' instruction if (size_matched == search_label.GetSize()) { pos--; const int found_pos = pos.Position(); if (mark_executed) { pos.SetPosition(label_start); const int max = m_world->GetConfig().MAX_LABEL_EXE_SIZE.Get() + 1; // Max label + 1 for the label instruction itself for (int i = 0; i < size_matched && i < max; i++, pos++) pos.SetFlagExecuted(); } // Return Head pointed at last NOP of label sequence head.SetPosition(found_pos); return; } continue; } pos++; } // Return start point if not found head.Set(default_pos); } void cHardwareBCR::FindLabelBackward(Head& head, Head& default_pos, bool mark_executed) { const cCodeLabel& search_label = GetLabel(); // Make sure the label is of size > 0. if (search_label.GetSize() == 0) { head.Set(default_pos); return; } head.Adjust(); Head lpos(head); Head pos(head); lpos--; while (pos.Position() != head.Position()) { if (m_inst_set->IsLabel(lpos.GetInst())) { // starting label found pos.SetPosition(lpos.Position()); pos++; // Check for direct matched label pattern, can be substring of 'label'ed target // - must match all NOPs in search_label // - extra NOPs in 'label'ed target are ignored int size_matched = 0; while (size_matched < search_label.GetSize() && pos.Position() != head.Position()) { if (!m_inst_set->IsNop(pos.GetInst()) || search_label[size_matched] != m_inst_set->GetNopMod(pos.GetInst())) break; size_matched++; pos++; } // Check that the label matches and has examined the full sequence of nops following the 'label' instruction if (size_matched == search_label.GetSize()) { pos--; const int found_pos = pos.Position(); if (mark_executed) { const int max = m_world->GetConfig().MAX_LABEL_EXE_SIZE.Get() + 1; // Max label + 1 for the label instruction itself for (int i = 0; i < size_matched && i < max; i++, lpos++) lpos.SetFlagExecuted(); } // Return Head pointed at last NOP of label sequence head.SetPosition(found_pos); return; } } lpos--; } // Return start point if not found head.Set(default_pos); } void cHardwareBCR::FindNopSequenceForward(Head& head, Head& default_pos, bool mark_executed) { const cCodeLabel& search_label = GetLabel(); // Make sure the label is of size > 0. if (search_label.GetSize() == 0) { head.Set(default_pos); return; } head.Adjust(); Head pos(head); pos++; while (pos.Position() != head.Position()) { if (m_inst_set->IsNop(pos.GetInst())) { // starting label found const int label_start = pos.Position(); // Check for direct matched nop sequence, can be substring of target // - must match all NOPs in search_label // - extra NOPs in target are ignored int size_matched = 0; while (size_matched < search_label.GetSize() && pos.Position() != head.Position()) { if (!m_inst_set->IsNop(pos.GetInst()) || search_label[size_matched] != m_inst_set->GetNopMod(pos.GetInst())) break; size_matched++; pos++; } // Check that the label matches and has examined the full sequence of nops if (size_matched == search_label.GetSize()) { pos--; const int found_pos = pos.Position(); if (mark_executed) { pos.SetPosition(label_start); const int max = m_world->GetConfig().MAX_LABEL_EXE_SIZE.Get(); for (int i = 0; i < size_matched && i < max; i++, pos++) pos.SetFlagExecuted(); } // Return Head pointed at last NOP of label sequence head.SetPosition(found_pos); return; } } if (pos.Position() == head.Position()) break; pos++; } // Return start point if not found head.Set(default_pos); } void cHardwareBCR::FindNopSequenceBackward(Head& head, Head& default_pos, bool mark_executed) { const cCodeLabel& search_label = GetLabel(); // Make sure the label is of size > 0. if (search_label.GetSize() == 0) { head.Set(default_pos); return; } head.Adjust(); Head lpos(head); Head pos(head); lpos--; while (pos.Position() != head.Position()) { if (m_inst_set->IsNop(pos.GetInst())) { // starting label found pos.SetPosition(lpos.Position()); // Check for direct matched nop sequence, can be substring of target // - must match all NOPs in search_label // - extra NOPs in target are ignored int size_matched = 0; while (size_matched < search_label.GetSize() && pos.Position() != head.Position()) { if (!m_inst_set->IsNop(pos.GetInst()) || search_label[size_matched] != m_inst_set->GetNopMod(pos.GetInst())) break; size_matched++; pos++; } // Check that the label matches and has examined the full sequence of nops if (size_matched == search_label.GetSize()) { pos--; const int found_pos = pos.Position(); if (mark_executed) { const int max = m_world->GetConfig().MAX_LABEL_EXE_SIZE.Get(); for (int i = 0; i < size_matched && i < max; i++, lpos++) lpos.SetFlagExecuted(); } // Return Head pointed at last NOP of label sequence head.SetPosition(found_pos); return; } continue; } lpos--; } // Return start point if not found head.Set(default_pos); } void cHardwareBCR::ReadInst(Instruction in_inst) { bool is_nop = m_inst_set->IsNop(in_inst); if (m_inst_set->IsLabel(in_inst)) { GetReadLabel().Clear(); m_threads[m_cur_thread].reading_label = true; } else if (m_threads[m_cur_thread].reading_label && is_nop) { GetReadLabel().AddNop(in_inst.GetOp()); } else { GetReadLabel().Clear(); m_threads[m_cur_thread].reading_label = false; } if (!m_threads[m_cur_thread].reading_seq && is_nop) { GetReadSequence().AddNop(in_inst.GetOp()); m_threads[m_cur_thread].reading_seq = true; } else if (m_threads[m_cur_thread].reading_seq && is_nop) { GetReadSequence().AddNop(in_inst.GetOp()); } else { GetReadSequence().Clear(); m_threads[m_cur_thread].reading_seq = false; } } // This function looks at the current position in the info of the organism and sets the next_label to be the sequence of nops // which follows. The instruction pointer is left on the last line of the label found. void cHardwareBCR::readLabel(Head& head, cCodeLabel& label, int max_size) { int count = 0; label.Clear(); while (m_inst_set->IsNop(head.NextInst()) && (count < max_size)) { count++; head.Advance(); label.AddNop(m_inst_set->GetNopMod(head.GetInst())); // If this is the first line of the template, mark it executed. if (label.GetSize() <= m_world->GetConfig().MAX_LABEL_EXE_SIZE.Get()) head.SetFlagExecuted(); } } void cHardwareBCR::threadCreate(const cCodeLabel& thread_label, const Head& start_pos) { // Check for existing thread if (thread_label.GetSize() > 0) { for (int thread_idx = 0; thread_idx < m_threads.GetSize(); thread_idx++) { if (m_threads[thread_idx].thread_label == thread_label) { if (!m_threads[thread_idx].running) { m_threads[thread_idx].Reset(this, start_pos); m_running_threads++; } return; } } } // Create new thread int thread_id = m_threads.GetSize(); m_threads.Resize(thread_id + 1); m_threads[thread_id].thread_label = thread_label; m_threads[thread_id].Reset(this, start_pos); m_running_threads++; m_organism->GetPhenotype().SetIsMultiThread(); } // Instruction Helpers // -------------------------------------------------------------------------------------------------------------- inline int cHardwareBCR::FindModifiedRegister(int default_register) { assert(default_register < NUM_REGISTERS); // Reg ID too high. if (m_inst_set->IsNop(getIP().NextInst())) { getIP().Advance(); default_register = m_inst_set->GetNopMod(getIP().GetInst()); getIP().SetFlagExecuted(); } return default_register; } inline int cHardwareBCR::FindModifiedNextRegister(int default_register) { assert(default_register < NUM_REGISTERS); // Reg ID too high. if (m_inst_set->IsNop(getIP().NextInst())) { getIP().Advance(); default_register = m_inst_set->GetNopMod(getIP().GetInst()); getIP().SetFlagExecuted(); } else { default_register = (default_register + 1) % NUM_REGISTERS; } return default_register; } inline int cHardwareBCR::FindModifiedPreviousRegister(int default_register) { assert(default_register < NUM_REGISTERS); // Reg ID too high. if (m_inst_set->IsNop(getIP().NextInst())) { getIP().Advance(); default_register = m_inst_set->GetNopMod(getIP().GetInst()); getIP().SetFlagExecuted(); } else { default_register = (default_register + NUM_REGISTERS - 1) % NUM_REGISTERS; } return default_register; } inline int cHardwareBCR::FindModifiedHead(int default_head) { assert(default_head < NUM_HEADS); // Head ID too high. if (m_inst_set->IsNop(getIP().NextInst())) { getIP().Advance(); default_head = m_inst_set->GetNopMod(getIP().GetInst()); getIP().SetFlagExecuted(); } return default_head; } inline int cHardwareBCR::FindNextRegister(int base_reg) { return (base_reg + 1) % NUM_REGISTERS; } inline int cHardwareBCR::FindUpstreamModifiedRegister(int offset, int default_register) { assert(default_register < NUM_REGISTERS); // Reg ID too high. assert(offset >= 0); Head location = getIP(); location.Jump(-offset - 1); if (m_inst_set->IsNop(location.GetInst())) { default_register = m_inst_set->GetNopMod(location.GetInst()); location.SetFlagExecuted(); } return default_register; } int cHardwareBCR::calcCopiedSize(const int parent_size, const int child_size) { int copied_size = 0; const cCPUMemory& memory = m_mem_array[m_cur_offspring]; for (int i = 0; i < memory.GetSize(); i++) { if (memory.FlagCopied(i)) copied_size++; } return copied_size; } bool cHardwareBCR::Divide_Main(cAvidaContext& ctx, int mem_space_used, int write_head_pos, double mut_multiplier) { // Make sure the memory space we're using exists if (m_mem_array.GetSize() <= mem_space_used) return false; // Make sure this divide will produce a viable offspring. m_cur_offspring = mem_space_used; // save current child memory space for use by dependent functions (e.g. calcCopiedSize()) if (!Divide_CheckViable(ctx, m_mem_array[0].GetSize(), write_head_pos)) return false; // Since the divide will now succeed, set up the information to be sent to the new organism m_mem_array[mem_space_used].Resize(write_head_pos); InstructionSequencePtr offspring_seq(new InstructionSequence(m_mem_array[mem_space_used])); HashPropertyMap props; cHardwareManager::SetupPropertyMap(props, (const char*)m_inst_set->GetInstSetName()); Genome offspring(GetType(), props, offspring_seq); m_organism->OffspringGenome() = offspring; // Handle Divide Mutations... Divide_DoMutations(ctx, mut_multiplier); // Many tests will require us to run the offspring through a test CPU; // this is, for example, to see if mutations need to be reverted or if // lineages need to be updated. Divide_TestFitnessMeasures(ctx); // reset first time instruction costs for (int i = 0; i < m_inst_ft_cost.GetSize(); i++) { m_inst_ft_cost[i] = m_inst_set->GetFTCost(Instruction(i)); } bool parent_alive = m_organism->ActivateDivide(ctx); //reset the memory of the memory space that has been divided off m_mem_array[mem_space_used] = InstructionSequence("a"); // Division Methods: // 0 - DIVIDE_METHOD_OFFSPRING - Create a child, leave parent state untouched. // 1 - DIVIDE_METHOD_SPLIT - Create a child, completely reset state of parent. // 2 - DIVIDE_METHOD_BIRTH - Create a child, reset state of parent's current thread. if (parent_alive) { // If the parent is no longer alive, all of this is moot switch (m_world->GetConfig().DIVIDE_METHOD.Get()) { case DIVIDE_METHOD_SPLIT: Reset(ctx); // This will wipe out all parasites on a divide. break; case DIVIDE_METHOD_BIRTH: // Reset only the calling thread's state for(int x = 0; x < NUM_HEADS; x++) getHead(x).Reset(this, 0, 0, false); for(int x = 0; x < NUM_REGISTERS; x++) setRegister(x, 0, false); if (m_world->GetConfig().INHERIT_MERIT.Get() == 0) m_organism->GetPhenotype().ResetMerit(); break; case DIVIDE_METHOD_OFFSPRING: default: break; } m_advance_ip = false; } return true; } void cHardwareBCR::checkWaitingThreads(int cur_thread, int reg_num) { for (int i = 0; i < m_threads.GetSize(); i++) { if (i != cur_thread && !m_threads[i].active && int(m_threads[i].wait_reg) == reg_num) { int wait_value = m_threads[i].wait_value; int check_value = m_threads[cur_thread].reg[reg_num].value; if ((m_threads[i].wait_greater && check_value > wait_value) || (m_threads[i].wait_equal && check_value == wait_value) || (m_threads[i].wait_less && check_value < wait_value)) { // Wake up the thread with matched condition m_threads[i].active = true; m_waiting_threads--; // Set destination register to be the check value DataValue& dest = m_threads[i].reg[m_threads[i].wait_dst]; dest.value = check_value; dest.from_env = false; dest.originated = m_cycle_count; dest.oldest_component = m_threads[cur_thread].reg[reg_num].oldest_component; dest.env_component = m_threads[cur_thread].reg[reg_num].env_component; // Cascade check if (m_waiting_threads) checkWaitingThreads(i, m_threads[i].wait_dst); } } } } // Instructions // -------------------------------------------------------------------------------------------------------------- // Multi-threading. bool cHardwareBCR::Inst_ThreadCreate(cAvidaContext&) { if (m_threads.GetSize() >= m_world->GetConfig().MAX_CPU_THREADS.Get()) { m_organism->Fault(FAULT_LOC_THREAD_FORK, FAULT_TYPE_FORK_TH); return false; } readLabel(getIP(), GetLabel()); threadCreate(GetLabel(), m_threads[m_cur_thread].heads[hFLOW]); return true; } bool cHardwareBCR::Inst_ThreadCancel(cAvidaContext& ctx) { if (m_running_threads > 1) { m_threads[m_cur_thread].running = false; m_running_threads--; } return true; } bool cHardwareBCR::Inst_ThreadID(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); setRegister(reg_used, m_cur_thread, false); return true; } bool cHardwareBCR::Inst_Yield(cAvidaContext&) { m_threads[m_cur_thread].active = false; m_threads[m_cur_thread].wait_reg = -1; return true; } bool cHardwareBCR::Inst_RegulatePause(cAvidaContext&) { readLabel(getIP(), m_threads[m_cur_thread].next_label); if (m_threads[m_cur_thread].next_label.GetSize() == 0) return false; for (ThreadLabelIterator it(this, m_threads[m_cur_thread].next_label, false); it.Next() >= 0;) { m_threads[it.Get()].running = false; } return true; } bool cHardwareBCR::Inst_RegulatePauseSP(cAvidaContext&) { readLabel(getIP(), m_threads[m_cur_thread].next_label); if (m_threads[m_cur_thread].next_label.GetSize() == 0) return false; for (ThreadLabelIterator it(this, m_threads[m_cur_thread].next_label); it.Next() >= 0;) { m_threads[it.Get()].running = false; } return true; } bool cHardwareBCR::Inst_RegulateResume(cAvidaContext&) { readLabel(getIP(), m_threads[m_cur_thread].next_label); if (m_threads[m_cur_thread].next_label.GetSize() == 0) return false; for (ThreadLabelIterator it(this, m_threads[m_cur_thread].next_label, false); it.Next() >= 0;) { m_threads[it.Get()].running = true; } return true; } bool cHardwareBCR::Inst_RegulateResumeSP(cAvidaContext&) { readLabel(getIP(), m_threads[m_cur_thread].next_label); if (m_threads[m_cur_thread].next_label.GetSize() == 0) return false; for (ThreadLabelIterator it(this, m_threads[m_cur_thread].next_label); it.Next() >= 0;) { m_threads[it.Get()].running = true; } return true; } bool cHardwareBCR::Inst_RegulateReset(cAvidaContext&) { readLabel(getIP(), m_threads[m_cur_thread].next_label); if (m_threads[m_cur_thread].next_label.GetSize() == 0) return false; for (ThreadLabelIterator it(this, m_threads[m_cur_thread].next_label, false); it.Next() >= 0;) { Head& thread_hIP = m_threads[it.Get()].heads[hIP]; Head thread_start(this, 0, thread_hIP.MemSpaceIndex(), thread_hIP.MemSpaceIsGene()); m_threads[it.Get()].Reset(this, thread_start); } return true; } bool cHardwareBCR::Inst_RegulateResetSP(cAvidaContext&) { readLabel(getIP(), m_threads[m_cur_thread].next_label); if (m_threads[m_cur_thread].next_label.GetSize() == 0) return false; for (ThreadLabelIterator it(this, m_threads[m_cur_thread].next_label); it.Next() >= 0;) { Head& thread_hIP = m_threads[it.Get()].heads[hIP]; Head thread_start(this, 0, thread_hIP.MemSpaceIndex(), thread_hIP.MemSpaceIsGene()); m_threads[it.Get()].Reset(this, thread_start); } return true; } bool cHardwareBCR::Inst_Label(cAvidaContext&) { readLabel(getIP(), GetLabel()); return true; } bool cHardwareBCR::Inst_IfNEqu(cAvidaContext&) // Execute next if bx != ?cx? { const int op1 = FindModifiedRegister(rBX); const int op2 = FindModifiedNextRegister(op1); if (getRegister(op1) == getRegister(op2)) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfLess(cAvidaContext&) // Execute next if ?bx? < ?cx? { const int op1 = FindModifiedRegister(rBX); const int op2 = FindModifiedNextRegister(op1); if (getRegister(op1) >= getRegister(op2)) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfNotZero(cAvidaContext&) // Execute next if ?bx? != 0 { const int op1 = FindModifiedRegister(rBX); if (getRegister(op1) == 0) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfEqualZero(cAvidaContext&) // Execute next if ?bx? == 0 { const int op1 = FindModifiedRegister(rBX); if (getRegister(op1) != 0) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfGreaterThanZero(cAvidaContext&) // Execute next if ?bx? > 0 { const int op1 = FindModifiedRegister(rBX); if (getRegister(op1) <= 0) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfLessThanZero(cAvidaContext&) // Execute next if ?bx? < 0 { const int op1 = FindModifiedRegister(rBX); if (getRegister(op1) >= 0) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfGtrX(cAvidaContext&) // Execute next if BX > X; X value set according to NOP label { // Compares value in BX to a specific value. The value to compare to is determined by the nop label as follows: // no nop label (default): valueToCompare = 1; // nop-A: toggles valueToCompare sign-bit // nop-B: valueToCompare left-shift by 1-bit // nop-C: valueToCompare left-shift by 2-bits // nop-D: valueToCompare left-shift by 3-bits, etc. int valueToCompare = 1; readLabel(getIP(), GetLabel()); const cCodeLabel& shift_label = GetLabel(); for (int i = 0; i < shift_label.GetSize(); i++) { if (shift_label[i] == rAX) { valueToCompare *= -1; } else { valueToCompare <<= shift_label[i]; } } if (getRegister(rBX) <= valueToCompare) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfEquX(cAvidaContext&) // Execute next if BX == X; X value set according to NOP label { // Compares value in BX to a specific value. The value to compare to is determined by the nop label as follows: // no nop label (default): valueToCompare = 1; // nop-A: toggles valueToCompare sign-bit // nop-B: valueToCompare left-shift by 1-bit // nop-C: valueToCompare left-shift by 2-bits // nop-D: valueToCompare left-shift by 3-bits, etc. int valueToCompare = 1; readLabel(getIP(), GetLabel()); const cCodeLabel& shift_label = GetLabel(); for (int i = 0; i < shift_label.GetSize(); i++) { if (shift_label[i] == rAX) { valueToCompare *= -1; } else { valueToCompare <<= shift_label[i]; } } if (getRegister(rBX) != valueToCompare) getIP().Advance(); return true; } bool cHardwareBCR::Inst_Pop(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); DataValue pop = stackPop(); setRegister(reg_used, pop.value, pop); return true; } bool cHardwareBCR::Inst_Push(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); getStack(m_threads[m_cur_thread].cur_stack).Push(m_threads[m_cur_thread].reg[reg_used]); return true; } bool cHardwareBCR::Inst_PopAll(cAvidaContext&) { int reg_used = FindModifiedRegister(rBX); for (int i = 0; i < NUM_REGISTERS; i++) { DataValue pop = stackPop(); setRegister(reg_used, pop.value, pop); reg_used++; if (reg_used == NUM_REGISTERS) reg_used = 0; } return true; } bool cHardwareBCR::Inst_PushAll(cAvidaContext&) { int reg_used = FindModifiedRegister(rBX); for (int i = 0; i < NUM_REGISTERS; i++) { getStack(m_threads[m_cur_thread].cur_stack).Push(m_threads[m_cur_thread].reg[reg_used]); reg_used++; if (reg_used == NUM_REGISTERS) reg_used = 0; } return true; } bool cHardwareBCR::Inst_SwitchStack(cAvidaContext&) { switchStack(); return true; } bool cHardwareBCR::Inst_SwapStackTop(cAvidaContext&) { DataValue v0 = getStack(0).Pop(); DataValue v1 = getStack(1).Pop(); getStack(0).Push(v1); getStack(1).Push(v0); return true; } bool cHardwareBCR::Inst_Swap(cAvidaContext&) { const int op1 = FindModifiedRegister(rBX); const int op2 = FindModifiedNextRegister(op1); DataValue v1 = m_threads[m_cur_thread].reg[op1]; m_threads[m_cur_thread].reg[op1] = m_threads[m_cur_thread].reg[op2]; m_threads[m_cur_thread].reg[op2] = v1; return true; } bool cHardwareBCR::Inst_CopyVal(cAvidaContext&) { const int op1 = FindModifiedRegister(rBX); const int op2 = FindModifiedNextRegister(op1); m_threads[m_cur_thread].reg[op2] = m_threads[m_cur_thread].reg[op1]; return true; } bool cHardwareBCR::Inst_ShiftR(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); setRegister(reg_used, m_threads[m_cur_thread].reg[reg_used].value >> 1, m_threads[m_cur_thread].reg[reg_used]); return true; } bool cHardwareBCR::Inst_ShiftL(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); setRegister(reg_used, m_threads[m_cur_thread].reg[reg_used].value << 1, m_threads[m_cur_thread].reg[reg_used]); return true; } bool cHardwareBCR::Inst_Inc(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); setRegister(reg_used, m_threads[m_cur_thread].reg[reg_used].value + 1, m_threads[m_cur_thread].reg[reg_used]); return true; } bool cHardwareBCR::Inst_Dec(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); setRegister(reg_used, m_threads[m_cur_thread].reg[reg_used].value - 1, m_threads[m_cur_thread].reg[reg_used]); return true; } bool cHardwareBCR::Inst_Zero(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); setRegister(reg_used, 0, false); return true; } bool cHardwareBCR::Inst_One(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); setRegister(reg_used, 1, false); return true; } bool cHardwareBCR::Inst_Rand(cAvidaContext& ctx) { const int reg_used = FindModifiedRegister(rBX); int randsign = ctx.GetRandom().GetUInt(0,2) ? -1 : 1; setRegister(reg_used, ctx.GetRandom().GetInt(INT_MAX) * randsign, false); return true; } bool cHardwareBCR::Inst_Add(cAvidaContext&) { const int dst = FindModifiedRegister(rBX); const int op1 = FindModifiedRegister(dst); const int op2 = FindModifiedNextRegister(op1); DataValue& r1 = m_threads[m_cur_thread].reg[op1]; DataValue& r2 = m_threads[m_cur_thread].reg[op2]; setRegister(dst, r1.value + r2.value, r1, r2); return true; } bool cHardwareBCR::Inst_Sub(cAvidaContext&) { const int dst = FindModifiedRegister(rBX); const int op1 = FindModifiedRegister(dst); const int op2 = FindModifiedNextRegister(op1); DataValue& r1 = m_threads[m_cur_thread].reg[op1]; DataValue& r2 = m_threads[m_cur_thread].reg[op2]; setRegister(dst, r1.value - r2.value, r1, r2); return true; } bool cHardwareBCR::Inst_Mult(cAvidaContext&) { const int dst = FindModifiedRegister(rBX); const int op1 = FindModifiedRegister(dst); const int op2 = FindModifiedNextRegister(op1); DataValue& r1 = m_threads[m_cur_thread].reg[op1]; DataValue& r2 = m_threads[m_cur_thread].reg[op2]; setRegister(dst, r1.value * r2.value, r1, r2); return true; } bool cHardwareBCR::Inst_Div(cAvidaContext&) { const int dst = FindModifiedRegister(rBX); const int op1 = FindModifiedRegister(dst); const int op2 = FindModifiedNextRegister(op1); DataValue& r1 = m_threads[m_cur_thread].reg[op1]; DataValue& r2 = m_threads[m_cur_thread].reg[op2]; if (r2.value != 0) { if (0 - INT_MAX > r1.value && r2.value == -1) m_organism->Fault(FAULT_LOC_MATH, FAULT_TYPE_ERROR, "div: Float exception"); else setRegister(dst, r1.value / r2.value, r1, r2); } else { m_organism->Fault(FAULT_LOC_MATH, FAULT_TYPE_ERROR, "div: dividing by 0"); return false; } return true; } bool cHardwareBCR::Inst_Mod(cAvidaContext&) { const int dst = FindModifiedRegister(rBX); const int op1 = FindModifiedRegister(dst); const int op2 = FindModifiedNextRegister(op1); DataValue& r1 = m_threads[m_cur_thread].reg[op1]; DataValue& r2 = m_threads[m_cur_thread].reg[op2]; if (r2.value != 0) { setRegister(dst, r1.value % r2.value, r1, r2); } else { m_organism->Fault(FAULT_LOC_MATH, FAULT_TYPE_ERROR, "mod: modding by 0"); return false; } return true; } bool cHardwareBCR::Inst_Nand(cAvidaContext&) { const int dst = FindModifiedRegister(rBX); const int op1 = FindModifiedRegister(dst); const int op2 = FindModifiedNextRegister(op1); DataValue& r1 = m_threads[m_cur_thread].reg[op1]; DataValue& r2 = m_threads[m_cur_thread].reg[op2]; setRegister(dst, ~(r1.value & r2.value), r1, r2); return true; } bool cHardwareBCR::Inst_SetMemory(cAvidaContext& ctx) { int mem_label = FindModifiedRegister(rBX); int mem_id = m_mem_ids[mem_label]; // Check for existing mem_space if (mem_id < 0) { mem_id = m_mem_array.GetSize(); m_mem_array.Resize(mem_id + 1); m_mem_ids[mem_label] = mem_id; } m_threads[m_cur_thread].heads[hWRITE].Set(0, mem_id, false); return true; } bool cHardwareBCR::Inst_TaskIO(cAvidaContext& ctx) { const int reg_used = FindModifiedRegister(rBX); DataValue& reg = m_threads[m_cur_thread].reg[reg_used]; // Do the "put" component m_organism->DoOutput(ctx, reg.value); // Check for tasks completed. m_last_output = m_cycle_count; // Do the "get" component const int value_in = m_organism->GetNextInput(); setRegister(reg_used, value_in, true); m_organism->DoInput(value_in); return true; } bool cHardwareBCR::Inst_TaskInput(cAvidaContext&) { const int reg_used = FindModifiedRegister(rBX); // Do the "get" component const int value_in = m_organism->GetNextInput(); setRegister(reg_used, value_in, true); m_organism->DoInput(value_in); return true; } bool cHardwareBCR::Inst_TaskOutput(cAvidaContext& ctx) { const int reg_used = FindModifiedRegister(rBX); DataValue& reg = m_threads[m_cur_thread].reg[reg_used]; // Do the "put" component m_organism->DoOutput(ctx, reg.value); // Check for tasks completed. m_last_output = m_cycle_count; return true; } bool cHardwareBCR::Inst_SGMove(cAvidaContext&) { assert(m_ext_mem.GetSize() > 3); const cStateGrid& sg = m_organism->GetStateGrid(); int& x = m_ext_mem[0]; int& y = m_ext_mem[1]; const int facing = m_ext_mem[2]; // State grid is treated as a 2-dimensional toroidal grid with size [0, width) and [0, height) switch (facing) { case 0: // N if (++y == sg.GetHeight()) y = 0; break; case 1: // NE if (++x == sg.GetWidth()) x = 0; if (++y == sg.GetHeight()) y = 0; break; case 2: // E if (++x == sg.GetWidth()) x = 0; break; case 3: // SE if (++x == sg.GetWidth()) x = 0; if (--y == -1) y = sg.GetHeight() - 1; break; case 4: // S if (--y == -1) y = sg.GetHeight() - 1; break; case 5: // SW if (--x == -1) x = sg.GetWidth() - 1; if (--y == -1) y = sg.GetHeight() - 1; break; case 6: // W if (--x == -1) x = sg.GetWidth() - 1; break; case 7: // NW if (--x == -1) x = sg.GetWidth() - 1; if (++y == sg.GetHeight()) y = 0; break; default: assert(facing >= 0 && facing <= 7); } // Increment state observed count m_ext_mem[3 + sg.GetStateAt(x, y)]++; // Save this location in the movement history m_ext_mem.Push(sg.GetIDFor(x, y)); return true; } bool cHardwareBCR::Inst_SGRotateL(cAvidaContext&) { assert(m_ext_mem.GetSize() > 3); if (--m_ext_mem[2] < 0) m_ext_mem[2] = 7; return true; } bool cHardwareBCR::Inst_SGRotateR(cAvidaContext&) { assert(m_ext_mem.GetSize() > 3); if (++m_ext_mem[2] > 7) m_ext_mem[2] = 0; return true; } bool cHardwareBCR::Inst_SGSense(cAvidaContext&) { const cStateGrid& sg = m_organism->GetStateGrid(); const int reg_used = FindModifiedRegister(rBX); setRegister(reg_used, sg.SenseStateAt(m_ext_mem[0], m_ext_mem[1])); return true; } bool cHardwareBCR::Inst_MoveHead(cAvidaContext&) { const int head_used = FindModifiedHead(hIP); int target = FindModifiedHead(hFLOW); // Cannot move to the read/write heads, acts as move to flow head instead if (target == hWRITE && head_used != hREAD) target = hFLOW; if (target == hREAD && head_used != hWRITE) target = hFLOW; getHead(head_used).Set(getHead(target)); if (head_used == hIP) m_advance_ip = false; return true; } bool cHardwareBCR::Inst_MoveHeadIfNEqu(cAvidaContext&) { const int op1 = FindModifiedRegister(rBX); const int op2 = FindModifiedNextRegister(op1); const int head_used = FindModifiedHead(hIP); int target = FindModifiedHead(hFLOW); // Cannot move to the read/write heads, acts as move to flow head instead if (target == hWRITE && head_used != hREAD) target = hFLOW; if (target == hREAD && head_used != hWRITE) target = hFLOW; if (m_threads[m_cur_thread].reg[op1].value != m_threads[m_cur_thread].reg[op2].value) { getHead(head_used).Set(getHead(target)); if (head_used == hIP) m_advance_ip = false; } return true; } bool cHardwareBCR::Inst_MoveHeadIfLess(cAvidaContext&) { const int op1 = FindModifiedRegister(rBX); const int op2 = FindModifiedNextRegister(op1); const int head_used = FindModifiedHead(hIP); int target = FindModifiedHead(hFLOW); // Cannot move to the read/write heads, acts as move to flow head instead if (target == hWRITE && head_used != hREAD) target = hFLOW; if (target == hREAD && head_used != hWRITE) target = hFLOW; if (m_threads[m_cur_thread].reg[op1].value < m_threads[m_cur_thread].reg[op2].value) { getHead(head_used).Set(getHead(target)); if (head_used == hIP) m_advance_ip = false; } return true; } bool cHardwareBCR::Inst_JumpHead(cAvidaContext&) { const int head_used = FindModifiedHead(hIP); const int reg = FindModifiedRegister(rCX); getHead(head_used).Jump(m_threads[m_cur_thread].reg[reg].value); if (head_used == hIP) m_advance_ip = false; return true; } bool cHardwareBCR::Inst_GetHead(cAvidaContext&) { const int head_used = FindModifiedHead(hIP); const int reg = FindModifiedRegister(rCX); setRegister(reg, getHead(head_used).Position()); return true; } bool cHardwareBCR::Inst_IfCopiedCompLabel(cAvidaContext&) { readLabel(getIP(), GetLabel()); GetLabel().Rotate(1, NUM_NOPS); if (GetLabel() != GetReadLabel()) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfCopiedDirectLabel(cAvidaContext&) { readLabel(getIP(), GetLabel()); if (GetLabel() != GetReadLabel()) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfCopiedCompSeq(cAvidaContext&) { readLabel(getIP(), GetLabel()); GetLabel().Rotate(1, NUM_NOPS); if (GetLabel() != GetReadSequence()) getIP().Advance(); return true; } bool cHardwareBCR::Inst_IfCopiedDirectSeq(cAvidaContext&) { readLabel(getIP(), GetLabel()); if (GetLabel() != GetReadSequence()) getIP().Advance(); return true; } bool cHardwareBCR::Inst_DidCopyCompLabel(cAvidaContext&) { readLabel(getIP(), GetLabel()); GetLabel().Rotate(1, NUM_NOPS); setRegister(rBX, (GetLabel() == GetReadLabel()), false); return true; } bool cHardwareBCR::Inst_DidCopyDirectLabel(cAvidaContext&) { readLabel(getIP(), GetLabel()); setRegister(rBX, (GetLabel() == GetReadLabel()), false); return true; } bool cHardwareBCR::Inst_DidCopyCompSeq(cAvidaContext&) { readLabel(getIP(), GetLabel()); GetLabel().Rotate(1, NUM_NOPS); setRegister(rBX, (GetLabel() == GetReadSequence()), false); return true; } bool cHardwareBCR::Inst_DidCopyDirectSeq(cAvidaContext&) { readLabel(getIP(), GetLabel()); setRegister(rBX, (GetLabel() == GetReadSequence()), false); return true; } bool cHardwareBCR::Inst_Divide(cAvidaContext& ctx) { if (getHead(hWRITE).MemSpaceIsGene()) return false; getHead(hWRITE).Adjust(); const int mem_space_used = getHead(hWRITE).MemSpaceIndex(); const int write_head_pos = getHead(hWRITE).Position(); return Divide_Main(ctx, mem_space_used, write_head_pos, 1.0); } bool cHardwareBCR::Inst_DivideMemory(cAvidaContext& ctx) { int mem_space_used = FindModifiedRegister(rBX); if (mem_space_used < rBX || m_mem_ids[mem_space_used] < 0) return false; mem_space_used = m_mem_ids[mem_space_used]; int end_of_memory = m_mem_array[mem_space_used].GetSize() - 1; return Divide_Main(ctx, mem_space_used, end_of_memory, 1.0); } bool cHardwareBCR::Inst_HeadRead(cAvidaContext& ctx) { const int head_id = FindModifiedHead(hREAD); const int dst = FindModifiedRegister(rAX); getHead(head_id).Adjust(); // Mutations only occur on the read, for the moment. Instruction read_inst; if (m_organism->TestCopyMut(ctx)) { read_inst = m_inst_set->GetRandomInst(ctx); } else { read_inst = getHead(head_id).GetInst(); } setRegister(dst, read_inst.GetOp()); ReadInst(read_inst); if (m_slip_read_head && m_organism->TestCopySlip(ctx)) getHead(head_id).SetPosition(ctx.GetRandom().GetInt(getHead(head_id).GetMemory().GetSize())); getHead(head_id).Advance(); return true; } bool cHardwareBCR::Inst_HeadWrite(cAvidaContext& ctx) { const int head_id = FindModifiedHead(hWRITE); const int src = FindModifiedRegister(rAX); Head& active_head = getHead(head_id); cCPUMemory& memory = active_head.GetMemory(); if (active_head.Position() >= memory.GetSize() - 1) { memory.Resize(memory.GetSize() + 1); memory.Copy(memory.GetSize() - 1, memory.GetSize() - 2); } active_head.Adjust(); int value = m_threads[m_cur_thread].reg[src].value; if (value < 0 || value >= m_inst_set->GetSize()) value = 0; active_head.SetInst(Instruction(value)); active_head.SetFlagCopied(); if (m_organism->TestCopyIns(ctx)) active_head.InsertInst(m_inst_set->GetRandomInst(ctx)); if (m_organism->TestCopyDel(ctx)) active_head.RemoveInst(); // if (m_organism->TestCopyUniform(ctx)) doUniformCopyMutation(ctx, active_head); if (!m_slip_read_head && m_organism->TestCopySlip(ctx)) doSlipMutation(ctx, active_head.GetMemory(), active_head.Position()); // Advance the head after write... active_head++; return true; } bool cHardwareBCR::Inst_HeadCopy(cAvidaContext& ctx) { // For the moment, this cannot be nop-modified. Head& read_head = getHead(hREAD); Head& write_head = getHead(hWRITE); cCPUMemory& memory = write_head.GetMemory(); if (write_head.Position() >= memory.GetSize() - 1) { memory.Resize(memory.GetSize() + 1); memory.Copy(memory.GetSize() - 1, memory.GetSize() - 2); } read_head.Adjust(); write_head.Adjust(); // Do mutations. Instruction read_inst = read_head.GetInst(); ReadInst(read_inst); if (m_organism->TestCopyMut(ctx)) { read_inst = m_inst_set->GetRandomInst(ctx); write_head.SetFlagMutated(); write_head.SetFlagCopyMut(); } write_head.SetInst(read_inst); write_head.SetFlagCopied(); // Set the copied flag... if (m_organism->TestCopyIns(ctx)) write_head.InsertInst(m_inst_set->GetRandomInst(ctx)); if (m_organism->TestCopyDel(ctx)) write_head.RemoveInst(); // if (m_organism->TestCopyUniform(ctx)) doUniformCopyMutation(ctx, write_head); if (m_organism->TestCopySlip(ctx)) { if (m_slip_read_head) { read_head.SetPosition(ctx.GetRandom().GetInt(read_head.GetMemory().GetSize())); } else doSlipMutation(ctx, write_head.GetMemory(), write_head.Position()); } read_head.Advance(); write_head.Advance(); return true; } bool cHardwareBCR::Inst_Search_Label_Direct_S(cAvidaContext&) { readLabel(getIP(), GetLabel()); FindLabelStart(getHead(hFLOW), getIP(), true); getHead(hFLOW).Advance(); return true; } bool cHardwareBCR::Inst_Search_Label_Direct_F(cAvidaContext&) { readLabel(getIP(), GetLabel()); FindLabelForward(getHead(hFLOW), getIP(), true); getHead(hFLOW).Advance(); return true; } bool cHardwareBCR::Inst_Search_Label_Direct_B(cAvidaContext&) { readLabel(getIP(), GetLabel()); FindLabelBackward(getHead(hFLOW), getIP(), true); getHead(hFLOW).Advance(); return true; } bool cHardwareBCR::Inst_Search_Label_Direct_D(cAvidaContext&) { readLabel(getIP(), GetLabel()); int direction = m_threads[m_cur_thread].reg[rBX].value; if (direction == 0) { FindLabelStart(getHead(hFLOW), getIP(), true); } else if (direction < 0) { FindLabelBackward(getHead(hFLOW), getIP(), true); } else { FindLabelForward(getHead(hFLOW), getIP(), true); } getHead(hFLOW).Advance(); return true; } bool cHardwareBCR::Inst_Search_Seq_Comp_S(cAvidaContext&) { readLabel(getIP(), GetLabel()); GetLabel().Rotate(1, NUM_NOPS); FindNopSequenceStart(getHead(hFLOW), getIP(), true); getHead(hFLOW).Advance(); return true; } bool cHardwareBCR::Inst_Search_Seq_Comp_F(cAvidaContext&) { readLabel(getIP(), GetLabel()); GetLabel().Rotate(1, NUM_NOPS); FindNopSequenceForward(getHead(hFLOW), getIP(), true); getHead(hFLOW).Advance(); return true; } bool cHardwareBCR::Inst_Search_Seq_Comp_B(cAvidaContext&) { readLabel(getIP(), GetLabel()); GetLabel().Rotate(1, NUM_NOPS); FindNopSequenceBackward(getHead(hFLOW), getIP(), true); getHead(hFLOW).Advance(); return true; } bool cHardwareBCR::Inst_Search_Seq_Comp_D(cAvidaContext&) { readLabel(getIP(), GetLabel()); GetLabel().Rotate(1, NUM_NOPS); int direction = m_threads[m_cur_thread].reg[rBX].value; if (direction == 0) { FindNopSequenceStart(getHead(hFLOW), getIP(), true); } else if (direction < 0) { FindNopSequenceBackward(getHead(hFLOW), getIP(), true); } else { FindNopSequenceForward(getHead(hFLOW), getIP(), true); } getHead(hFLOW).Advance(); return true; } bool cHardwareBCR::Inst_WaitCondition_Equal(cAvidaContext&) { const int wait_value = FindModifiedRegister(rBX); const int check_reg = FindModifiedRegister(rLX); const int wait_dst = FindModifiedRegister(wait_value); // Check if condition has already been met for (int i = 0; i < m_threads.GetSize(); i++) { if (i != m_cur_thread && m_threads[i].reg[check_reg].value == m_threads[m_cur_thread].reg[wait_value].value) { setRegister(wait_dst, m_threads[i].reg[check_reg].value, m_threads[i].reg[check_reg]); return true; } } // Fail to sleep if this is the last thread awake if (m_waiting_threads == m_running_threads) return false; // Put thread to sleep with appropriate wait condition m_threads[m_cur_thread].active = false; m_waiting_threads++; m_threads[m_cur_thread].wait_equal = true; m_threads[m_cur_thread].wait_less = false; m_threads[m_cur_thread].wait_greater = false; m_threads[m_cur_thread].wait_reg = check_reg; m_threads[m_cur_thread].wait_value = m_threads[m_cur_thread].reg[wait_value].value; m_threads[m_cur_thread].wait_dst = wait_dst; return true; } bool cHardwareBCR::Inst_WaitCondition_Less(cAvidaContext&) { const int wait_value = FindModifiedRegister(rBX); const int check_reg = FindModifiedRegister(rLX); const int wait_dst = FindModifiedRegister(wait_value); // Check if condition has already been met for (int i = 0; i < m_threads.GetSize(); i++) { if (i != m_cur_thread && m_threads[i].reg[check_reg].value < m_threads[m_cur_thread].reg[wait_value].value) { setRegister(wait_dst, m_threads[i].reg[check_reg].value, m_threads[i].reg[check_reg]); return true; } } // Fail to sleep if this is the last thread awake if (m_waiting_threads == m_running_threads) return false; // Put thread to sleep with appropriate wait condition m_threads[m_cur_thread].active = false; m_waiting_threads++; m_threads[m_cur_thread].wait_equal = false; m_threads[m_cur_thread].wait_less = true; m_threads[m_cur_thread].wait_greater = false; m_threads[m_cur_thread].wait_reg = check_reg; m_threads[m_cur_thread].wait_value = m_threads[m_cur_thread].reg[wait_value].value; m_threads[m_cur_thread].wait_dst = wait_dst; return true; } bool cHardwareBCR::Inst_WaitCondition_Greater(cAvidaContext&) { const int wait_value = FindModifiedRegister(rBX); const int check_reg = FindModifiedRegister(rLX); const int wait_dst = FindModifiedRegister(wait_value); // Check if condition has already been met for (int i = 0; i < m_threads.GetSize(); i++) { if (i != m_cur_thread && m_threads[i].reg[check_reg].value > m_threads[m_cur_thread].reg[wait_value].value) { setRegister(wait_dst, m_threads[i].reg[check_reg].value, m_threads[i].reg[check_reg]); return true; } } // Fail to sleep if this is the last thread awake if (m_waiting_threads == m_running_threads) return false; // Put thread to sleep with appropriate wait condition m_threads[m_cur_thread].active = false; m_waiting_threads++; m_threads[m_cur_thread].wait_equal = false; m_threads[m_cur_thread].wait_less = false; m_threads[m_cur_thread].wait_greater = true; m_threads[m_cur_thread].wait_reg = check_reg; m_threads[m_cur_thread].wait_value = m_threads[m_cur_thread].reg[wait_value].value; m_threads[m_cur_thread].wait_dst = wait_dst; return true; } bool cHardwareBCR::Inst_Repro(cAvidaContext& ctx) { // these checks should be done, but currently they make some assumptions // that crash when evaluating this kind of organism -- JEB cCPUMemory& memory = m_mem_array[0]; if (m_organism->GetPhenotype().GetCurBonus() < m_world->GetConfig().REQUIRED_BONUS.Get()) return false; // Since the divide will now succeed, set up the information to be sent // to the new organism InstructionSequencePtr offspring_seq(new InstructionSequence(memory)); HashPropertyMap props; cHardwareManager::SetupPropertyMap(props, (const char*)m_inst_set->GetInstSetName()); Genome offspring(GetType(), props, offspring_seq); m_organism->OffspringGenome() = offspring; m_organism->GetPhenotype().SetLinesCopied(memory.GetSize()); int lines_executed = 0; for (int i = 0; i < memory.GetSize(); i++) if (memory.FlagExecuted(i)) lines_executed++; m_organism->GetPhenotype().SetLinesExecuted(lines_executed); const Genome& org = m_organism->GetGenome(); ConstInstructionSequencePtr org_seq_p; org_seq_p.DynamicCastFrom(org.Representation()); const InstructionSequence& org_genome = *org_seq_p; Genome& child = m_organism->OffspringGenome(); InstructionSequencePtr child_seq_p; child_seq_p.DynamicCastFrom(child.Representation()); InstructionSequence& child_seq = *child_seq_p; // Perform Copy Mutations... if (m_organism->GetCopyMutProb() > 0) { // Skip this if no mutations.... for (int i = 0; i < child_seq.GetSize(); i++) { // for (int i = 0; i < m_memory.GetSize(); i++) { if (m_organism->TestCopyMut(ctx)) child_seq[i] = m_inst_set->GetRandomInst(ctx); } } // Handle Divide Mutations... Divide_DoMutations(ctx); const bool viable = Divide_CheckViable(ctx, org_genome.GetSize(), child_seq.GetSize(), 1); if (viable == false) return false; // Many tests will require us to run the offspring through a test CPU; // this is, for example, to see if mutations need to be reverted or if // lineages need to be updated. Divide_TestFitnessMeasures(ctx); // reset first time instruction costs for (int i = 0; i < m_inst_ft_cost.GetSize(); i++) { m_inst_ft_cost[i] = m_inst_set->GetFTCost(Instruction(i)); } if (m_world->GetConfig().DIVIDE_METHOD.Get() == DIVIDE_METHOD_SPLIT) { m_advance_ip = false; } // Activate the child bool parent_alive = m_organism->ActivateDivide(ctx); // Do more work if the parent lives through the birth of the offspring if (parent_alive) { if (m_world->GetConfig().DIVIDE_METHOD.Get() == DIVIDE_METHOD_SPLIT) Reset(ctx); } return true; } bool cHardwareBCR::Inst_Die(cAvidaContext& ctx) { m_organism->Die(ctx); return true; } bool cHardwareBCR::Inst_Move(cAvidaContext& ctx) { // In TestCPU, movement fails... if (m_organism->GetOrgInterface().GetCellID() == -1) return false; bool move_success = false; if (!m_use_avatar) move_success = m_organism->Move(ctx); else if (m_use_avatar) move_success = m_organism->MoveAV(ctx); const int out_reg = FindModifiedRegister(rBX); setRegister(out_reg, move_success, true); return true; } bool cHardwareBCR::Inst_JuvMove(cAvidaContext& ctx) { // In TestCPU, movement fails... if (m_organism->GetOrgInterface().GetCellID() == -1) return false; if (m_organism->GetPhenotype().GetTimeUsed() < m_world->GetConfig().JUV_PERIOD.Get()) return false; bool move_success = false; if (!m_use_avatar) move_success = m_organism->Move(ctx); else if (m_use_avatar) move_success = m_organism->MoveAV(ctx); const int out_reg = FindModifiedRegister(rBX); setRegister(out_reg, move_success, true); return true; } bool cHardwareBCR::Inst_GetNorthOffset(cAvidaContext& ctx) { const int out_reg = FindModifiedRegister(rBX); int compass_dir = m_organism->GetOrgInterface().GetFacedDir(); if (m_use_avatar) compass_dir = m_organism->GetOrgInterface().GetAVFacing(); setRegister(out_reg, compass_dir, true); return true; } bool cHardwareBCR::Inst_GetPositionOffset(cAvidaContext&) { const int out_reg = FindModifiedRegister(rBX); setRegister(out_reg, m_organism->GetNortherly(), true); setRegister(FindModifiedNextRegister(out_reg), m_organism->GetEasterly(), true); return true; } bool cHardwareBCR::Inst_GetNortherly(cAvidaContext&) { const int out_reg = FindModifiedRegister(rBX); setRegister(out_reg, m_organism->GetNortherly(), true); return true; } bool cHardwareBCR::Inst_GetEasterly(cAvidaContext&) { const int out_reg = FindModifiedRegister(rBX); setRegister(out_reg, m_organism->GetEasterly(), true); return true; } bool cHardwareBCR::Inst_ZeroEasterly(cAvidaContext&) { m_organism->ClearEasterly(); return true; } bool cHardwareBCR::Inst_ZeroNortherly(cAvidaContext&) { m_organism->ClearNortherly(); return true; } bool cHardwareBCR::Inst_ZeroPosOffset(cAvidaContext&) { const int offset = getRegister(FindModifiedRegister(rBX)) % 3; if (offset == 0) { m_organism->ClearEasterly(); m_organism->ClearNortherly(); } else if (offset == 1) m_organism->ClearEasterly(); else if (offset == 2) m_organism->ClearNortherly(); return true; } bool cHardwareBCR::Inst_RotateHome(cAvidaContext& ctx) { // Will rotate organism to face birth cell if org never used zero-easterly or zero-northerly. Otherwise will rotate org // to face the 'marked' spot where those instructions were executed. int easterly = m_organism->GetEasterly(); int northerly = m_organism->GetNortherly(); int correct_facing = 0; if (northerly > 0 && easterly == 0) correct_facing = 0; // rotate N else if (northerly > 0 && easterly < 0) correct_facing = 1; // rotate NE else if (northerly == 0 && easterly < 0) correct_facing = 2; // rotate E else if (northerly < 0 && easterly < 0) correct_facing = 3; // rotate SE else if (northerly < 0 && easterly == 0) correct_facing = 4; // rotate S else if (northerly < 0 && easterly > 0) correct_facing = 5; // rotate SW else if (northerly == 0 && easterly > 0) correct_facing = 6; // rotate W else if (northerly > 0 && easterly > 0) correct_facing = 7; // rotate NW int rotates = m_organism->GetNeighborhoodSize(); if (m_use_avatar == 2) rotates = m_organism->GetOrgInterface().GetAVNumNeighbors(); for (int i = 0; i < rotates; i++) { m_organism->Rotate(ctx, 1); if (!m_use_avatar && m_organism->GetOrgInterface().GetFacedDir() == correct_facing) break; else if (m_use_avatar && m_organism->GetOrgInterface().GetAVFacing() == correct_facing) break; } return true; } bool cHardwareBCR::Inst_RotateUnoccupiedCell(cAvidaContext& ctx) { if (m_use_avatar && m_use_avatar != 2) return false; const int reg_used = FindModifiedRegister(rBX); int num_neighbors = m_organism->GetNeighborhoodSize(); if (m_use_avatar) num_neighbors = m_organism->GetOrgInterface().GetAVNumNeighbors(); for (int i = 0; i < num_neighbors; i++) { if ((!m_use_avatar && !m_organism->IsNeighborCellOccupied()) || (m_use_avatar == 2 && !m_organism->GetOrgInterface().FacedHasAV())) { setRegister(reg_used, 1, true); return true; } m_organism->Rotate(ctx, 1); // continue to rotate } setRegister(reg_used, 0, true); return true; } bool cHardwareBCR::Inst_RotateX(cAvidaContext& ctx) { int num_neighbors = m_organism->GetNeighborhoodSize(); if (m_use_avatar) num_neighbors = m_organism->GetOrgInterface().GetAVNumNeighbors(); int rot_dir = 1; // If this organism has no neighbors, ignore rotate. if (num_neighbors == 0) return false; const int reg_used = FindModifiedRegister(rBX); int rot_num = m_threads[m_cur_thread].reg[reg_used].value; // rotate the nop number of times in the appropriate direction rot_num < 0 ? rot_dir = -1 : rot_dir = 1; rot_num = abs(rot_num); if (rot_num > 7) rot_num = rot_num % 8; for (int i = 0; i < rot_num; i++) m_organism->Rotate(ctx, rot_dir); setRegister(reg_used, rot_num * rot_dir, true); return true; } // Will rotate organism to face a specified other org bool cHardwareBCR::Inst_RotateOrgID(cAvidaContext& ctx) { if (m_use_avatar && m_use_avatar != 2) return false; // Will rotate organism to face a specificied other org const int id_sought_reg = FindModifiedRegister(rBX); const int id_sought = m_threads[m_cur_thread].reg[id_sought_reg].value; const int worldx = m_world->GetPopulation().GetWorldX(); const int worldy = m_world->GetPopulation().GetWorldY(); int max_dist = 0; const int long_axis = (int) (max(worldx, worldy) * 0.5 + 0.5); m_world->GetConfig().LOOK_DIST.Get() != -1 ? max_dist = m_world->GetConfig().LOOK_DIST.Get() : max_dist = long_axis; bool have_org2use = false; // return false if invalid number or self if (id_sought < 0 || id_sought == m_organism->GetID()) return false; // if valid number, does the value represent a living organism? cOrganism* target_org = NULL; const Apto::Array<cOrganism*, Apto::Smart>& live_orgs = m_organism->GetOrgInterface().GetLiveOrgList(); for (int i = 0; i < live_orgs.GetSize(); i++) { cOrganism* org = live_orgs[i]; if (id_sought == org->GetID()) { target_org = org; have_org2use = true; break; } } if (!have_org2use) return false; else { int target_org_cell = target_org->GetOrgInterface().GetCellID(); int searching_org_cell = m_organism->GetOrgInterface().GetCellID(); if (m_use_avatar == 2) { target_org_cell = target_org->GetOrgInterface().GetAVCellID(); searching_org_cell = m_organism->GetOrgInterface().GetAVCellID(); if (target_org_cell == searching_org_cell) return true; // avatars in same cell } const int target_x = target_org_cell % worldx; const int target_y = target_org_cell / worldx; const int searching_x = searching_org_cell % worldx; const int searching_y = searching_org_cell / worldx; const int x_dist = target_x - searching_x; const int y_dist = target_y - searching_y; const int travel_dist = max(abs(x_dist), abs(y_dist)); if (travel_dist > max_dist) return false; int correct_facing = 0; if (y_dist < 0 && x_dist == 0) correct_facing = 0; // rotate N else if (y_dist < 0 && x_dist > 0) correct_facing = 1; // rotate NE else if (y_dist == 0 && x_dist > 0) correct_facing = 2; // rotate E else if (y_dist > 0 && x_dist > 0) correct_facing = 3; // rotate SE else if (y_dist > 0 && x_dist == 0) correct_facing = 4; // rotate S else if (y_dist > 0 && x_dist < 0) correct_facing = 5; // rotate SW else if (y_dist == 0 && x_dist < 0) correct_facing = 6; // rotate W else if (y_dist < 0 && x_dist < 0) correct_facing = 7; // rotate NW bool found_org = false; if (m_use_avatar == 2) { m_organism->GetOrgInterface().SetAVFacing(ctx, correct_facing); found_org = true; } else { int rotates = m_organism->GetNeighborhoodSize(); for (int i = 0; i < rotates; i++) { m_organism->Rotate(ctx, -1); if (!m_use_avatar && m_organism->GetOrgInterface().GetFacedDir() == correct_facing) { found_org = true; break; } } } // return some data as in look sensor if (found_org) { int dist_reg = FindModifiedNextRegister(id_sought_reg); int dir_reg = FindModifiedNextRegister(dist_reg); int fat_reg = FindModifiedNextRegister(dir_reg); int ft_reg = FindModifiedNextRegister(fat_reg); int group_reg = FindModifiedNextRegister(ft_reg); setRegister(dist_reg, -2, true); setRegister(dir_reg, m_sensor.ReturnRelativeFacing(target_org), true); setRegister(fat_reg, (int) target_org->GetPhenotype().GetCurBonus(), true); setRegister(ft_reg, target_org->GetForageTarget(), true); if (target_org->HasOpinion()) { setRegister(group_reg, target_org->GetOpinion().first, true); } if ((target_org->IsDisplaying() || m_world->GetConfig().USE_DISPLAY.Get()) && target_org->GetOrgDisplayData() != NULL) m_sensor.SetLastSeenDisplay(target_org->GetOrgDisplayData()); } return true; } } // Will rotate organism to face away from a specificied other org bool cHardwareBCR::Inst_RotateAwayOrgID(cAvidaContext& ctx) { if (m_use_avatar && m_use_avatar != 2) return false; // Will rotate organism to face a specificied other org const int id_sought_reg = FindModifiedRegister(rBX); const int id_sought = m_threads[m_cur_thread].reg[id_sought_reg].value; const int worldx = m_world->GetPopulation().GetWorldX(); const int worldy = m_world->GetPopulation().GetWorldY(); int max_dist = 0; const int long_axis = (int) (max(worldx, worldy) * 0.5 + 0.5); m_world->GetConfig().LOOK_DIST.Get() != -1 ? max_dist = m_world->GetConfig().LOOK_DIST.Get() : max_dist = long_axis; bool have_org2use = false; // return false if invalid number or self if (id_sought < 0 || id_sought == m_organism->GetID()) return false; // if valid number, does the value represent a living organism? cOrganism* target_org = NULL; const Apto::Array<cOrganism*, Apto::Smart>& live_orgs = m_organism->GetOrgInterface().GetLiveOrgList(); for (int i = 0; i < live_orgs.GetSize(); i++) { cOrganism* org = live_orgs[i]; if (id_sought == org->GetID()) { target_org = org; have_org2use = true; break; } } if (!have_org2use) return false; else { int target_org_cell = target_org->GetOrgInterface().GetCellID(); int searching_org_cell = m_organism->GetOrgInterface().GetCellID(); if (m_use_avatar == 2) { target_org_cell = target_org->GetOrgInterface().GetAVCellID(); searching_org_cell = m_organism->GetOrgInterface().GetAVCellID(); if (target_org_cell == searching_org_cell) return true; // avatars in same cell } const int target_x = target_org_cell % worldx; const int target_y = target_org_cell / worldx; const int searching_x = searching_org_cell % worldx; const int searching_y = searching_org_cell / worldx; const int x_dist = target_x - searching_x; const int y_dist = target_y - searching_y; const int travel_dist = max(abs(x_dist), abs(y_dist)); if (travel_dist > max_dist) return false; int correct_facing = 0; if (y_dist < 0 && x_dist == 0) correct_facing = 4; // rotate away from N else if (y_dist < 0 && x_dist > 0) correct_facing = 5; // rotate away from NE else if (y_dist == 0 && x_dist > 0) correct_facing = 6; // rotate away from E else if (y_dist > 0 && x_dist > 0) correct_facing = 7; // rotate away from SE else if (y_dist > 0 && x_dist == 0) correct_facing = 0; // rotate away from S else if (y_dist > 0 && x_dist < 0) correct_facing = 1; // rotate away from SW else if (y_dist == 0 && x_dist < 0) correct_facing = 2; // rotate away from W else if (y_dist < 0 && x_dist < 0) correct_facing = 3; // rotate away from NW bool found_org = false; if (m_use_avatar == 2) { m_organism->GetOrgInterface().SetAVFacing(ctx, correct_facing); found_org = true; } else { int rotates = m_organism->GetNeighborhoodSize(); for (int i = 0; i < rotates; i++) { m_organism->Rotate(ctx, -1); if (!m_use_avatar && m_organism->GetOrgInterface().GetFacedDir() == correct_facing) { found_org = true; break; } } } // return some data as in look sensor if (found_org) { int dist_reg = FindModifiedNextRegister(id_sought_reg); int dir_reg = FindModifiedNextRegister(dist_reg); int fat_reg = FindModifiedNextRegister(dir_reg); int ft_reg = FindModifiedNextRegister(fat_reg); int group_reg = FindModifiedNextRegister(ft_reg); setRegister(dist_reg, -2, true); setRegister(dir_reg, m_sensor.ReturnRelativeFacing(target_org), true); setRegister(fat_reg, (int) target_org->GetPhenotype().GetCurBonus(), true); setRegister(ft_reg, target_org->GetForageTarget(), true); if (target_org->HasOpinion()) { setRegister(group_reg, target_org->GetOpinion().first, true); } if ((target_org->IsDisplaying() || m_world->GetConfig().USE_DISPLAY.Get()) && target_org->GetOrgDisplayData() != NULL) m_sensor.SetLastSeenDisplay(target_org->GetOrgDisplayData()); } return true; } } bool cHardwareBCR::Inst_SenseResourceID(cAvidaContext& ctx) { Apto::Array<double> cell_res; if (!m_use_avatar) cell_res = m_organism->GetOrgInterface().GetResources(ctx); else if (m_use_avatar) cell_res = m_organism->GetOrgInterface().GetAVResources(ctx); int reg_to_set = FindModifiedRegister(rBX); double max_resource = 0.0; // if more than one resource is available, return the resource ID with the most available in this spot (note that, with global resources, the GLOBAL total will evaluated) for (int i = 0; i < cell_res.GetSize(); i++) { if (cell_res[i] > max_resource) { max_resource = cell_res[i]; setRegister(reg_to_set, i, true); } } return true; } bool cHardwareBCR::Inst_SenseNest(cAvidaContext& ctx) { Apto::Array<double> cell_res; if (!m_use_avatar) cell_res = m_organism->GetOrgInterface().GetResources(ctx); else if (m_use_avatar) cell_res = m_organism->GetOrgInterface().GetAVResources(ctx); const cResourceLib& resource_lib = m_world->GetEnvironment().GetResourceLib(); const int reg_used = FindModifiedRegister(rBX); int nest_id = m_threads[m_cur_thread].reg[reg_used].value; int nest_val = 0; // if invalid nop value, return the id of the first nest in the cell with val >= 1 if (nest_id < 0 || nest_id >= resource_lib.GetSize() || !resource_lib.GetResource(nest_id)->IsNest()) { for (int i = 0; i < cell_res.GetSize(); i++) { if (resource_lib.GetResource(i)->IsNest() && cell_res[i] >= 1) { nest_id = i; nest_val = (int) cell_res[i]; break; } } } else nest_val = (int) cell_res[nest_id]; setRegister(reg_used, nest_id, true); const int val_reg = FindModifiedNextRegister(reg_used); setRegister(val_reg, nest_val, true); return true; } bool cHardwareBCR::Inst_LookAhead(cAvidaContext& ctx) { int cell = m_organism->GetOrgInterface().GetCellID(); int facing = m_organism->GetOrgInterface().GetFacedDir(); if (m_use_avatar) { cell = m_organism->GetOrgInterface().GetAVCellID(); facing = m_organism->GetOrgInterface().GetAVFacing(); } return GoLook(ctx, facing, cell); } bool cHardwareBCR::Inst_LookAheadEX(cAvidaContext& ctx) { return DoLookAheadEX(ctx); } bool cHardwareBCR::Inst_LookAgainEX(cAvidaContext& ctx) { return DoLookAgainEX(ctx); } bool cHardwareBCR::Inst_LookAheadFTX(cAvidaContext& ctx) { return DoLookAheadEX(ctx, true); } bool cHardwareBCR::Inst_LookAgainFTX(cAvidaContext& ctx) { return DoLookAgainEX(ctx, true); } bool cHardwareBCR::DoLookAheadEX(cAvidaContext& ctx, bool use_ft) { int cell_id = m_organism->GetOrgInterface().GetCellID(); int facing = m_organism->GetOrgInterface().GetFacedDir(); if (m_use_avatar) { cell_id = m_organism->GetOrgInterface().GetAVCellID(); facing = m_organism->GetOrgInterface().GetAVFacing(); } // temp check on world geometry until code can handle other geometries if (m_world->GetConfig().WORLD_GEOMETRY.Get() != 1) { // Instruction sense-diff-ahead only written to work in bounded grids assert(false); return false; } if (!m_use_avatar && m_organism->GetNeighborhoodSize() == 0) return false; else if (m_use_avatar && m_organism->GetOrgInterface().GetAVNumNeighbors() == 0) return false; const int reg_session = FindUpstreamModifiedRegister(0, -1); const int reg_habitat = FindModifiedRegister(rBX); // ?rBX? const int reg_id_sought = FindModifiedNextRegister(reg_habitat); // ?rCX? const int reg_travel_distance = FindModifiedNextRegister(reg_id_sought); // ?rDX? const int reg_deviance = FindNextRegister(reg_travel_distance); // rDX + 1 = rEX const int reg_cv = FindNextRegister(reg_deviance); // rDX + 2 = rFX const int reg_search_distance = FindModifiedRegister(-1); // ?r?X? const int reg_search_type = FindModifiedRegister(-1); // ?r?X? const int reg_id_found = FindModifiedRegister(-1); // ?r?X? cOrgSensor::sLookInit look_init; look_init.habitat = m_threads[m_cur_thread].reg[reg_habitat].value; look_init.distance = (reg_search_distance == -1) ? std::numeric_limits<int>::max() : m_threads[m_cur_thread].reg[reg_search_distance].value; look_init.search_type = (reg_search_type == -1) ? 0 : m_threads[m_cur_thread].reg[reg_search_type].value; look_init.id_sought = m_threads[m_cur_thread].reg[reg_id_sought].value; cOrgSensor::sLookOut look_results; look_results.value = 0; look_results = m_sensor.SetLooking(ctx, look_init, facing, cell_id, use_ft); if (m_world->GetConfig().TRACK_LOOK_SETTINGS.Get()) { cString look_string = ""; look_string += cStringUtil::Stringf("%d", m_organism->GetForageTarget()); look_string += cStringUtil::Stringf(",%d", look_results.report_type); look_string += cStringUtil::Stringf(",%d", look_results.habitat); look_string += cStringUtil::Stringf(",%d", look_results.distance); look_string += cStringUtil::Stringf(",%d", look_results.search_type); look_string += cStringUtil::Stringf(",%d", look_results.id_sought); m_organism->GetOrgInterface().TryWriteLookData(look_string); } // Update Sessions m_threads[m_cur_thread].sensor_session.habitat = look_results.habitat; m_threads[m_cur_thread].sensor_session.distance = look_init.distance; m_threads[m_cur_thread].sensor_session.search_type = look_results.search_type; m_threads[m_cur_thread].sensor_session.id_sought = look_results.id_sought; if (reg_session != -1) { const int session_idx = Apto::Abs(m_threads[m_cur_thread].reg[reg_session].value % m_sensor_sessions.GetSize()); m_sensor_sessions[session_idx].habitat = look_results.habitat; m_sensor_sessions[session_idx].distance = look_init.distance; m_sensor_sessions[session_idx].search_type = look_results.search_type; m_sensor_sessions[session_idx].id_sought = look_results.id_sought; } if (look_results.report_type == 0) { setRegister(reg_habitat, look_results.habitat, true); setRegister(reg_id_sought, look_results.id_sought, true); setRegister(reg_travel_distance, -1, true); setRegister(reg_deviance, 0, true); setRegister(reg_cv, 0, true); if (reg_search_type != -1) setRegister(reg_search_type, look_results.search_type, true); if (reg_id_found != -1) setRegister(reg_id_found, -9, true); } else if (look_results.report_type == 1) { setRegister(reg_habitat, look_results.habitat, true); setRegister(reg_id_sought, look_results.id_sought, true); setRegister(reg_travel_distance, look_results.distance, true); setRegister(reg_deviance, look_results.deviance, true); setRegister(reg_cv, (look_results.count <= 1) ? look_results.value : look_results.count, true); if (reg_search_type != -1) setRegister(reg_search_type, look_results.search_type, true); if (reg_id_found != -1) setRegister(reg_id_found, (look_results.forage == -9) ? look_results.group : look_results.forage, true); } if (m_world->GetConfig().LOOK_DISABLE.Get() > 5) { int org_type = m_world->GetConfig().LOOK_DISABLE_TYPE.Get(); bool is_target_type = false; if (org_type == 0 && !m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 1 && m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 2) is_target_type = true; if (is_target_type) { int randsign = ctx.GetRandom().GetUInt(0,2) ? -1 : 1; int rand = ctx.GetRandom().GetInt(INT_MAX) * randsign; int target_reg = m_world->GetConfig().LOOK_DISABLE.Get(); if (target_reg == 6) setRegister(reg_habitat, rand, true); else if (target_reg == 7) setRegister(reg_travel_distance, rand, true); else if (target_reg == 8 && reg_search_type != -1) setRegister(reg_search_type, rand, true); else if (target_reg == 9) setRegister(reg_id_sought, rand, true); else if (target_reg == 10 || target_reg == 11) setRegister(reg_cv, rand, true); else if ((target_reg == 12 || target_reg == 13) && reg_id_found != -1) setRegister(reg_id_found, rand, true); } } if (m_world->GetConfig().TRACK_LOOK_OUTPUT.Get()) { cString look_string = ""; look_string += cStringUtil::Stringf("%d", m_organism->GetForageTarget()); look_string += cStringUtil::Stringf(",%d", look_results.report_type); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[reg_habitat].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[reg_id_sought].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[reg_travel_distance].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[reg_deviance].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[reg_cv].value); m_organism->GetOrgInterface().TryWriteLookEXOutput(look_string); } return true; } bool cHardwareBCR::DoLookAgainEX(cAvidaContext& ctx, bool use_ft) { int cell_id = m_organism->GetOrgInterface().GetCellID(); int facing = m_organism->GetOrgInterface().GetFacedDir(); if (m_use_avatar) { cell_id = m_organism->GetOrgInterface().GetAVCellID(); facing = m_organism->GetOrgInterface().GetAVFacing(); } // temp check on world geometry until code can handle other geometries if (m_world->GetConfig().WORLD_GEOMETRY.Get() != 1) { // Instruction sense-diff-ahead only written to work in bounded grids assert(false); return false; } if (!m_use_avatar && m_organism->GetNeighborhoodSize() == 0) return false; else if (m_use_avatar && m_organism->GetOrgInterface().GetAVNumNeighbors() == 0) return false; const int reg_session = FindUpstreamModifiedRegister(0, -1); const int reg_travel_distance = FindModifiedNextRegister(rDX); // ?rDX? const int reg_deviance = FindNextRegister(reg_travel_distance); // rDX + 1 = rEX const int reg_cv = FindNextRegister(reg_deviance); // rDX + 2 = rFX const int reg_id_found = FindModifiedRegister(-1); // ?r?X? cOrgSensor::sLookInit look_init = m_threads[m_cur_thread].sensor_session; if (reg_session != -1) { const int session_idx = Apto::Abs(m_threads[m_cur_thread].reg[reg_session].value % m_sensor_sessions.GetSize()); look_init = m_sensor_sessions[session_idx]; } cOrgSensor::sLookOut look_results; look_results.value = 0; look_results = m_sensor.SetLooking(ctx, look_init, facing, cell_id, use_ft); if (m_world->GetConfig().TRACK_LOOK_SETTINGS.Get()) { cString look_string = ""; look_string += cStringUtil::Stringf("%d", m_organism->GetForageTarget()); look_string += cStringUtil::Stringf(",%d", look_results.report_type); look_string += cStringUtil::Stringf(",%d", look_results.habitat); look_string += cStringUtil::Stringf(",%d", look_results.distance); look_string += cStringUtil::Stringf(",%d", look_results.search_type); look_string += cStringUtil::Stringf(",%d", look_results.id_sought); m_organism->GetOrgInterface().TryWriteLookData(look_string); } if (look_results.report_type == 0) { setRegister(reg_travel_distance, -1, true); setRegister(reg_deviance, 0, true); setRegister(reg_cv, 0, true); if (reg_id_found != -1) setRegister(reg_id_found, -9, true); } else if (look_results.report_type == 1) { setRegister(reg_travel_distance, look_results.distance, true); setRegister(reg_deviance, look_results.deviance, true); setRegister(reg_cv, (look_results.count <= 1) ? look_results.value : look_results.count, true); if (reg_id_found != -1) setRegister(reg_id_found, (look_results.forage == -9) ? look_results.group : look_results.forage, true); } if (m_world->GetConfig().LOOK_DISABLE.Get() > 5) { int org_type = m_world->GetConfig().LOOK_DISABLE_TYPE.Get(); bool is_target_type = false; if (org_type == 0 && !m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 1 && m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 2) is_target_type = true; if (is_target_type) { int randsign = ctx.GetRandom().GetUInt(0,2) ? -1 : 1; int rand = ctx.GetRandom().GetInt(INT_MAX) * randsign; int target_reg = m_world->GetConfig().LOOK_DISABLE.Get(); if (target_reg == 7) setRegister(reg_travel_distance, rand, true); else if (target_reg == 10 || target_reg == 11) setRegister(reg_cv, rand, true); else if ((target_reg == 12 || target_reg == 13) && reg_id_found != -1) setRegister(reg_id_found, rand, true); } } if (m_world->GetConfig().TRACK_LOOK_OUTPUT.Get()) { cString look_string = ""; look_string += cStringUtil::Stringf("%d", m_organism->GetForageTarget()); look_string += cStringUtil::Stringf(",%d", look_results.report_type); look_string += cStringUtil::Stringf(",%d", look_results.habitat); look_string += cStringUtil::Stringf(",%d", look_results.id_sought); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[reg_travel_distance].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[reg_deviance].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[reg_cv].value); m_organism->GetOrgInterface().TryWriteLookEXOutput(look_string); } return true; } // Will return relative org facing (rotations to intercept) rather than group info for sighted org bool cHardwareBCR::Inst_LookAheadIntercept(cAvidaContext& ctx) { m_sensor.SetReturnRelativeFacing(true); return Inst_LookAhead(ctx); } bool cHardwareBCR::Inst_LookAround(cAvidaContext& ctx) { // dir register is 5th mod (will be count reg) int hab_reg = FindModifiedRegister(rBX); int dist_reg = FindModifiedNextRegister(hab_reg); int st_reg = FindModifiedNextRegister(dist_reg); int id_reg = FindModifiedNextRegister(st_reg); int dir_reg = FindModifiedNextRegister(id_reg); int search_dir = abs(m_threads[m_cur_thread].reg[dir_reg].value) % 3; if (m_world->GetConfig().LOOK_DISABLE.Get() == 5) { int org_type = m_world->GetConfig().LOOK_DISABLE_TYPE.Get(); bool is_target_type = false; if (org_type == 0 && !m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 1 && m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 2) is_target_type = true; if (is_target_type) { int rand = ctx.GetRandom().GetInt(INT_MAX); search_dir = rand % 3; } } if (search_dir == 1) search_dir = -1; else if (search_dir == 2) search_dir = 1; int facing = m_organism->GetOrgInterface().GetFacedDir() + search_dir; if (m_use_avatar) facing = m_organism->GetOrgInterface().GetAVFacing() + search_dir; if (facing == -1) facing = 7; else if (facing == 9) facing = 1; else if (facing == 8) facing = 0; int cell = m_organism->GetOrgInterface().GetCellID(); if (m_use_avatar) cell = m_organism->GetOrgInterface().GetAVCellID(); return GoLook(ctx, facing, cell); } bool cHardwareBCR::Inst_LookAroundIntercept(cAvidaContext& ctx) { m_sensor.SetReturnRelativeFacing(true); return Inst_LookAround(ctx); } bool cHardwareBCR::Inst_LookFT(cAvidaContext& ctx) { // override any org inputs and just let this org see the food resource that matches it's forage target (not designed for predators) int cell = m_organism->GetOrgInterface().GetCellID(); int facing = m_organism->GetOrgInterface().GetFacedDir(); if (m_use_avatar) { facing = m_organism->GetOrgInterface().GetAVFacing(); cell = m_organism->GetOrgInterface().GetAVCellID(); } return GoLook(ctx, facing, cell, true); } bool cHardwareBCR::Inst_LookAroundFT(cAvidaContext& ctx) { // dir register is 5th mod (will be count reg) int hab_reg = FindModifiedRegister(rBX); int dist_reg = FindModifiedNextRegister(hab_reg); int st_reg = FindModifiedNextRegister(dist_reg); int id_reg = FindModifiedNextRegister(st_reg); int dir_reg = FindModifiedNextRegister(id_reg); int search_dir = abs(m_threads[m_cur_thread].reg[dir_reg].value) % 3; if (m_world->GetConfig().LOOK_DISABLE.Get() == 5) { int org_type = m_world->GetConfig().LOOK_DISABLE_TYPE.Get(); bool is_target_type = false; if (org_type == 0 && !m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 1 && m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 2) is_target_type = true; if (is_target_type) { int rand = ctx.GetRandom().GetInt(INT_MAX); search_dir = rand % 3; } } if (search_dir == 1) search_dir = -1; else if (search_dir == 2) search_dir = 1; int facing = m_organism->GetOrgInterface().GetFacedDir() + search_dir; if (m_use_avatar) facing = m_organism->GetOrgInterface().GetAVFacing() + search_dir; if (facing == -1) facing = 7; else if (facing == 9) facing = 1; else if (facing == 8) facing = 0; int cell = m_organism->GetOrgInterface().GetCellID(); if (m_use_avatar) cell = m_organism->GetOrgInterface().GetAVCellID(); return GoLook(ctx, facing, cell, true); } bool cHardwareBCR::GoLook(cAvidaContext& ctx, const int look_dir, const int cell_id, bool use_ft) { // temp check on world geometry until code can handle other geometries if (m_world->GetConfig().WORLD_GEOMETRY.Get() != 1) { // Instruction sense-diff-ahead only written to work in bounded grids return false; } if (NUM_REGISTERS < 8) m_world->GetDriver().Feedback().Error("Instruction look-ahead requires at least 8 registers"); if (!m_use_avatar && m_organism->GetNeighborhoodSize() == 0) return false; else if (m_use_avatar && m_organism->GetOrgInterface().GetAVNumNeighbors() == 0) return false; else if (m_organism->IsPredFT() && m_world->GetConfig().PRED_CONFUSION.Get() == 4) return false; // define our input (4) and output registers (8) sLookRegAssign reg_defs; reg_defs.habitat = FindModifiedRegister(rBX); reg_defs.distance = FindModifiedNextRegister(reg_defs.habitat); reg_defs.search_type = FindModifiedNextRegister(reg_defs.distance); reg_defs.id_sought = FindModifiedNextRegister(reg_defs.search_type); reg_defs.count = FindModifiedNextRegister(reg_defs.id_sought); reg_defs.value = FindModifiedNextRegister(reg_defs.count); reg_defs.group = FindModifiedNextRegister(reg_defs.value); reg_defs.ft = FindModifiedNextRegister(reg_defs.group); cOrgSensor::sLookOut look_results; look_results.report_type = 0; look_results.habitat = 0; look_results.distance = -1; look_results.search_type = 0; look_results.id_sought = -1; look_results.count = 0; look_results.value = 0; look_results.group = -9; look_results.forage = -9; look_results = InitLooking(ctx, reg_defs, look_dir, cell_id, use_ft); LookResults(ctx, reg_defs, look_results); return true; } cOrgSensor::sLookOut cHardwareBCR::InitLooking(cAvidaContext& ctx, sLookRegAssign& in_defs, int facing, int cell_id, bool use_ft) { const int habitat_reg = in_defs.habitat; const int distance_reg = in_defs.distance; const int search_reg = in_defs.search_type; const int id_reg = in_defs.id_sought; cOrgSensor::sLookInit reg_init; reg_init.habitat = m_threads[m_cur_thread].reg[habitat_reg].value; reg_init.distance = m_threads[m_cur_thread].reg[distance_reg].value; reg_init.search_type = m_threads[m_cur_thread].reg[search_reg].value; reg_init.id_sought = m_threads[m_cur_thread].reg[id_reg].value; return m_sensor.SetLooking(ctx, reg_init, facing, cell_id, use_ft); } void cHardwareBCR::LookResults(cAvidaContext& ctx, sLookRegAssign& regs, cOrgSensor::sLookOut& results) { if (m_world->GetConfig().TRACK_LOOK_SETTINGS.Get()) { cString look_string = ""; look_string += cStringUtil::Stringf("%d", m_organism->GetForageTarget()); look_string += cStringUtil::Stringf(",%d", results.report_type); look_string += cStringUtil::Stringf(",%d", results.habitat); look_string += cStringUtil::Stringf(",%d", results.distance); look_string += cStringUtil::Stringf(",%d", results.search_type); look_string += cStringUtil::Stringf(",%d", results.id_sought); m_organism->GetOrgInterface().TryWriteLookData(look_string); } // habitat_reg=0, distance_reg=1, search_type_reg=2, id_sought_reg=3, count_reg=4, value_reg=5, group_reg=6, forager_type_reg=7 // return defaults for failed to find if (results.report_type == 0) { setRegister(regs.habitat, results.habitat, true); setRegister(regs.distance, -1, true); setRegister(regs.search_type, results.search_type, true); setRegister(regs.id_sought, results.id_sought, true); setRegister(regs.count, 0, true); setRegister(regs.value, 0, true); setRegister(regs.group, -9, true); setRegister(regs.ft, -9, true); } // report results as sent else if (results.report_type == 1) { setRegister(regs.habitat, results.habitat, true); setRegister(regs.distance, results.distance, true); setRegister(regs.search_type, results.search_type, true); setRegister(regs.id_sought, results.id_sought, true); setRegister(regs.count, results.count, true); setRegister(regs.value, results.value, true); setRegister(regs.group, results.group, true); setRegister(regs.ft, results.forage, true); } if (m_world->GetConfig().LOOK_DISABLE.Get() > 5) { int org_type = m_world->GetConfig().LOOK_DISABLE_TYPE.Get(); bool is_target_type = false; if (org_type == 0 && !m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 1 && m_organism->IsPreyFT()) is_target_type = true; else if (org_type == 2) is_target_type = true; if (is_target_type) { int randsign = ctx.GetRandom().GetUInt(0,2) ? -1 : 1; int rand = ctx.GetRandom().GetInt(INT_MAX) * randsign; int target_reg = m_world->GetConfig().LOOK_DISABLE.Get(); if (target_reg == 6) setRegister(regs.habitat, rand, true); else if (target_reg == 7) setRegister(regs.distance, rand, true); else if (target_reg == 8) setRegister(regs.search_type, rand, true); else if (target_reg == 9) setRegister(regs.id_sought, rand, true); else if (target_reg == 10) setRegister(regs.count, rand, true); else if (target_reg == 11) setRegister(regs.value, rand, true); else if (target_reg == 12) setRegister(regs.group, rand, true); else if (target_reg == 13) setRegister(regs.ft, rand, true); } } if (m_world->GetConfig().TRACK_LOOK_OUTPUT.Get()) { cString look_string = ""; look_string += cStringUtil::Stringf("%d", m_organism->GetForageTarget()); look_string += cStringUtil::Stringf(",%d", results.report_type); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[regs.habitat].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[regs.distance].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[regs.search_type].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[regs.id_sought].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[regs.count].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[regs.value].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[regs.group].value); look_string += cStringUtil::Stringf(",%d", m_threads[m_cur_thread].reg[regs.ft].value); m_organism->GetOrgInterface().TryWriteLookOutput(look_string); } return; } bool cHardwareBCR::Inst_SenseFacedHabitat(cAvidaContext& ctx) { int reg_to_set = FindModifiedRegister(rBX); // get the resource library const cResourceLib& resource_lib = m_world->GetEnvironment().GetResourceLib(); // get the destination cell resource levels Apto::Array<double> cell_res; if (!m_use_avatar) cell_res = m_organism->GetOrgInterface().GetResources(ctx); else if (m_use_avatar) cell_res = m_organism->GetOrgInterface().GetAVResources(ctx); // check for any habitats ahead that affect movement, returning the most 'severe' habitat type // simulated predator ahead for (int i = 0; i < cell_res.GetSize(); i++) { if (resource_lib.GetResource(i)->GetHabitat() == 5 && cell_res[i] > 0) { setRegister(reg_to_set, 3, true); return true; } } // are there any barrier resources in the faced cell for (int i = 0; i < cell_res.GetSize(); i++) { if (resource_lib.GetResource(i)->GetHabitat() == 2 && cell_res[i] > 0) { setRegister(reg_to_set, 2, true); return true; } } // if no barriers, are there any hills in the faced cell for (int i = 0; i < cell_res.GetSize(); i++) { if (resource_lib.GetResource(i)->GetHabitat() == 1 && cell_res[i] > 0) { setRegister(reg_to_set, 1, true); return true; } } // if no barriers or hills, we return a 0 to indicate clear sailing setRegister(reg_to_set, 0, true); return true; } bool cHardwareBCR::Inst_SetForageTarget(cAvidaContext& ctx) { assert(m_organism != 0); int prop_target = getRegister(FindModifiedRegister(rBX)); //return false if org setting target to current one (avoid paying costs for not switching) const int old_target = m_organism->GetForageTarget(); if (old_target == prop_target) return false; // return false if predator trying to become prey and this has been disallowed if (old_target <= -2 && prop_target > -2 && (m_world->GetConfig().PRED_PREY_SWITCH.Get() == 0 || m_world->GetConfig().PRED_PREY_SWITCH.Get() == 2)) return false; // return false if trying to become predator and there are none in the experiment if (prop_target <= -2 && m_world->GetConfig().PRED_PREY_SWITCH.Get() < 0) return false; // return false if trying to become predator this has been disallowed via setforagetarget if (prop_target <= -2 && m_world->GetConfig().PRED_PREY_SWITCH.Get() == 2) return false; // a little mod help...can't set to -1, that's for juevniles only...so only exception to mod help is -2 if (!m_world->GetEnvironment().IsTargetID(prop_target) && prop_target != -2 && prop_target != -3) { int num_fts = 0; std::set<int> fts_avail = m_world->GetEnvironment().GetTargetIDs(); set <int>::iterator itr; for (itr = fts_avail.begin();itr!=fts_avail.end();itr++) if (*itr != -1 && *itr != -2 && *itr != -3) num_fts++; if (m_world->GetEnvironment().IsTargetID(-1) && num_fts == 0) prop_target = -1; else { // ft's may not be sequentially numbered int ft_num = abs(prop_target) % num_fts; itr = fts_avail.begin(); for (int i = 0; i < ft_num; i++) itr++; prop_target = *itr; } } // make sure we use a valid (resource) target // -2 target means setting to predator // if (!m_world->GetEnvironment().IsTargetID(prop_target) && (prop_target != -2)) return false; // switching between predator and prey means having to switch avatar list...don't run this for orgs with AVCell == -1 (avatars off or test cpu) if (m_use_avatar && (((prop_target == -2 || prop_target == -3) && old_target > -2) || (prop_target > -2 && (old_target == -2 || old_target == -3))) && (m_organism->GetOrgInterface().GetAVCellID() != -1)) { m_organism->GetOrgInterface().SwitchPredPrey(ctx); m_organism->SetForageTarget(ctx, prop_target); } else m_organism->SetForageTarget(ctx, prop_target); // Set the new target and return the value m_organism->RecordFTSet(); setRegister(FindModifiedRegister(rBX), prop_target, false); return true; } bool cHardwareBCR::Inst_SetForageTargetOnce(cAvidaContext& ctx) { assert(m_organism != 0); if (m_organism->HasSetFT()) return false; else return Inst_SetForageTarget(ctx); } bool cHardwareBCR::Inst_SetRandForageTargetOnce(cAvidaContext& ctx) { assert(m_organism != 0); int cap = 0; if (m_world->GetConfig().POPULATION_CAP.Get()) cap = m_world->GetConfig().POPULATION_CAP.Get(); else if (m_world->GetConfig().POP_CAP_ELDEST.Get()) cap = m_world->GetConfig().POP_CAP_ELDEST.Get(); if (cap && (m_organism->GetOrgInterface().GetLiveOrgList().GetSize() >= (((double)(cap)) * 0.5)) && ctx.GetRandom().P(0.5)) { if (m_organism->HasSetFT()) return false; else { int num_fts = 0; std::set<int> fts_avail = m_world->GetEnvironment().GetTargetIDs(); set <int>::iterator itr; for (itr = fts_avail.begin();itr!=fts_avail.end();itr++) if (*itr != -1 && *itr != -2 && *itr != -3) num_fts++; int prop_target = ctx.GetRandom().GetUInt(num_fts); if (m_world->GetEnvironment().IsTargetID(-1) && num_fts == 0) prop_target = -1; else { // ft's may not be sequentially numbered int ft_num = abs(prop_target) % num_fts; itr = fts_avail.begin(); for (int i = 0; i < ft_num; i++) itr++; prop_target = *itr; } // Set the new target and return the value m_organism->SetForageTarget(ctx, prop_target); m_organism->RecordFTSet(); setRegister(FindModifiedRegister(rBX), prop_target, false); return true; } } else return Inst_SetForageTargetOnce(ctx); } bool cHardwareBCR::Inst_GetForageTarget(cAvidaContext& ctx) { assert(m_organism != 0); const int target_reg = FindModifiedRegister(rBX); setRegister(target_reg, m_organism->GetForageTarget(), false); return true; } bool cHardwareBCR::Inst_CollectSpecific(cAvidaContext& ctx) { const int resource = m_world->GetConfig().COLLECT_SPECIFIC_RESOURCE.Get(); double res_before = m_organism->GetRBin(resource); bool success = DoActualCollect(ctx, resource, false); double res_after = m_organism->GetRBin(resource); int out_reg = FindModifiedRegister(rBX); setRegister(out_reg, (int)(res_after - res_before), true); setRegister(FindModifiedNextRegister(out_reg), (int)(res_after), true); return success; } bool cHardwareBCR::Inst_GetResStored(cAvidaContext& ctx) { int resource_id = abs(getRegister(FindModifiedRegister(rBX))); Apto::Array<double> bins = m_organism->GetRBins(); resource_id %= bins.GetSize(); int out_reg = FindModifiedRegister(rBX); setRegister(out_reg, (int)(bins[resource_id]), true); return true; } // Sets organism's opinion to the value in ?BX? bool cHardwareBCR::Inst_SetOpinion(cAvidaContext& ctx) { assert(m_organism != 0); m_organism->GetOrgInterface().SetOpinion(getRegister(FindModifiedRegister(rBX)), m_organism); return true; } /* Gets the organism's current opinion, placing the opinion in register ?BX? and the age of the opinion in register !?BX? */ bool cHardwareBCR::Inst_GetOpinion(cAvidaContext& ctx) { assert(m_organism != 0); if (m_organism->GetOrgInterface().HasOpinion(m_organism)) { const int opinion_reg = FindModifiedRegister(rBX); const int age_reg = FindNextRegister(opinion_reg); setRegister(opinion_reg, m_organism->GetOpinion().first, true); setRegister(age_reg, m_world->GetStats().GetUpdate() - m_organism->GetOpinion().second, true); } return true; } //! An organism joins a group by setting it opinion to the group id. bool cHardwareBCR::Inst_JoinGroup(cAvidaContext& ctx) { int opinion = m_world->GetConfig().DEFAULT_GROUP.Get(); // Check if the org is currently part of a group assert(m_organism != 0); int prop_group_id = getRegister(FindModifiedRegister(rBX)); // check if this is a valid group if (m_world->GetConfig().USE_FORM_GROUPS.Get() == 2 && !(m_world->GetEnvironment().IsGroupID(prop_group_id))) { return false; } // injected orgs might not have an opinion if (m_organism->GetOrgInterface().HasOpinion(m_organism)) { opinion = m_organism->GetOpinion().first; //return false if org setting opinion to current one (avoid paying costs for not switching) if (opinion == prop_group_id) return false; // A random chance for failure to join group based on config, if failed return true for resource cost. if (m_world->GetConfig().JOIN_GROUP_FAILURE.Get() > 0) { int percent_failure = m_world->GetConfig().JOIN_GROUP_FAILURE.Get(); double prob_failure = (double) percent_failure / 100.0; double rand = ctx.GetRandom().GetDouble(); if (rand <= prob_failure) return true; } // If tolerances are on the org must pass immigration chance if (m_world->GetConfig().TOLERANCE_WINDOW.Get() > 0) { m_organism->GetOrgInterface().AttemptImmigrateGroup(ctx, prop_group_id, m_organism); return true; } else { // otherwise, subtract org from current group m_organism->LeaveGroup(opinion); } } // Set the opinion m_organism->GetOrgInterface().SetOpinion(prop_group_id, m_organism); // Add org to group count if (m_organism->GetOrgInterface().HasOpinion(m_organism)) { opinion = m_organism->GetOpinion().first; m_organism->JoinGroup(opinion); } return true; } bool cHardwareBCR::Inst_GetGroupID(cAvidaContext&) { assert(m_organism != 0); if (m_organism->HasOpinion()) { const int group_reg = FindModifiedRegister(rBX); setRegister(group_reg, m_organism->GetOpinion().first, false); } return true; } bool cHardwareBCR::Inst_GetFacedOrgID(cAvidaContext& ctx) //Get ID of organism faced by this one, if there is an organism in front. { if (m_use_avatar && m_use_avatar != 2) return false; cOrganism* neighbor = NULL; if (!m_use_avatar && !m_organism->IsNeighborCellOccupied()) return false; else if (m_use_avatar == 2 && !m_organism->GetOrgInterface().FacedHasAV()) return false; if (!m_use_avatar) neighbor = m_organism->GetOrgInterface().GetNeighbor(); else if (m_use_avatar == 2) neighbor = m_organism->GetOrgInterface().GetRandFacedAV(ctx); if (neighbor->IsDead()) return false; const int out_reg = FindModifiedRegister(rBX); setRegister(out_reg, neighbor->GetID(), true); return true; } //Teach offspring learned targeting/foraging behavior bool cHardwareBCR::Inst_TeachOffspring(cAvidaContext&) { assert(m_organism != 0); m_organism->Teach(true); return true; } bool cHardwareBCR::Inst_LearnParent(cAvidaContext& ctx) { assert(m_organism != 0); bool halt = false; if (m_organism->HadParentTeacher()) { int old_target = m_organism->GetForageTarget(); int prop_target = -1; prop_target = m_organism->GetParentFT(); halt = (prop_target <= -2 && m_world->GetConfig().PRED_PREY_SWITCH.Get() < 0); if (!halt) { if (m_use_avatar && m_organism->GetOrgInterface().GetAVCellID() != -1 && (((prop_target == -2 || prop_target == -3) && old_target > -2) || (prop_target > -2 && (old_target == -2 || prop_target == -3)))) { m_organism->GetOrgInterface().SwitchPredPrey(ctx); m_organism->CopyParentFT(ctx); } else m_organism->CopyParentFT(ctx); } } return !halt; } bool cHardwareBCR::Inst_ModifySimpDisplay(cAvidaContext& ctx) { bool message_used = false; for (int i = 0; i < 4; i++) { if (m_inst_set->IsNop(getIP().NextInst())) { getIP().Advance(); int this_nop = m_inst_set->GetNopMod(getIP().GetInst()); switch (this_nop) { case 0: m_organism->SetSimpDisplay(0, GetRegister(rAX)); case 1: m_organism->SetSimpDisplay(1, GetRegister(rBX)); case 2: m_organism->SetSimpDisplay(2, GetRegister(rCX)); default: if (!message_used) m_organism->SetSimpDisplay(3, GetRegister(this_nop)); message_used = true; } } else break; } return true; } bool cHardwareBCR::Inst_ReadLastSimpDisplay(cAvidaContext& ctx) { if (!m_sensor.HasSeenDisplay()) return false; sOrgDisplay& last_seen = m_sensor.GetLastSeenDisplay(); bool message_read = false; for (int i = 0; i < 4; i++) { if (m_inst_set->IsNop(getIP().NextInst())) { getIP().Advance(); int this_nop = m_inst_set->GetNopMod(getIP().GetInst()); switch (this_nop) { case 0: setRegister(rAX, last_seen.distance, true); case 1: setRegister(rBX, last_seen.direction, true); case 2: setRegister(rCX, last_seen.value, true); default: if (!message_read) setRegister(this_nop, last_seen.message, true); message_read = true; } } else if (!m_inst_set->IsNop(getIP().NextInst()) && i == 0) { setRegister(rAX, last_seen.distance, true); setRegister(rBX, last_seen.direction, true); setRegister(rCX, last_seen.value, true); setRegister(rDX, last_seen.message, true); break; } else break; } return true; } bool cHardwareBCR::Inst_KillDisplay(cAvidaContext& ctx) { if (!m_organism->IsDisplaying()) return false; m_organism->KillDisplay(); return true; } //Attack organism faced by this one, if there is non-predator target in front, and steal it's merit, current bonus, and reactions. bool cHardwareBCR::Inst_AttackPrey(cAvidaContext& ctx) { if (!testAttack(ctx)) { return false; } cOrganism* target = getPreyTarget(ctx); if (!testPreyTarget(target)) { return false; } sAttackReg reg; setAttackReg(reg); if (!executeAttack(ctx, target, reg)) return false; return true; } bool cHardwareBCR::Inst_AttackFTPrey(cAvidaContext& ctx) { if (!testAttack(ctx)) { return false; } const int target_reg = FindModifiedRegister(rBX); int target_org_type = m_threads[m_cur_thread].reg[target_reg].value; cOrganism* target = NULL; if (!m_use_avatar) { target = m_organism->GetOrgInterface().GetNeighbor(); if (target_org_type != target->GetForageTarget()) { return false; } // attacking other carnivores is handled differently (e.g. using fights or tolerance) if (!target->IsPreyFT()) { return false; } } else if (m_use_avatar == 2) { const Apto::Array<cOrganism*>& av_neighbors = m_organism->GetOrgInterface().GetFacedPreyAVs(); bool target_match = false; int rand_index = ctx.GetRandom().GetUInt(0, av_neighbors.GetSize()); int j = 0; for (int i = 0; i < av_neighbors.GetSize(); i++) { if (rand_index + i < av_neighbors.GetSize()) { if (av_neighbors[rand_index + i]->GetForageTarget() == target_org_type) { target = av_neighbors[rand_index + i]; target_match = true; } break; } else { if (av_neighbors[j]->GetForageTarget() == target_org_type) { target = av_neighbors[j]; target_match = true; } break; j++; } } if (!target_match) { return false; } } if (!testPreyTarget(target)) { return false; } sAttackReg reg; setAttackReg(reg); if (!executeAttack(ctx, target, reg)) return false; return true; } bool cHardwareBCR::Inst_ScrambleReg(cAvidaContext& ctx) { for (int i = 0; i < 8; i++) setRegister(rAX + i, ctx.GetRandom().GetInt(), true); return true; } bool cHardwareBCR::DoActualCollect(cAvidaContext& ctx, int bin_used, bool unit) { // Set up res_change and max total Apto::Array<double> res_count; if (!m_use_avatar) res_count = m_organism->GetOrgInterface().GetResources(ctx); else if (m_use_avatar) res_count = m_organism->GetOrgInterface().GetAVResources(ctx); Apto::Array<double> res_change(res_count.GetSize()); res_change.SetAll(0.0); double total = m_organism->GetRBinsTotal(); double max = m_world->GetConfig().MAX_TOTAL_STORED.Get(); bool has_max = max > 0 ? true : false; double res_consumed = 0.0; // Collect a unit or some ABSORB_RESOURCE_FRACTION const cResourceLib& resource_lib = m_world->GetEnvironment().GetResourceLib(); if (unit) { double threshold = resource_lib.GetResource(bin_used)->GetThreshold(); if (res_count[bin_used] >= threshold) { res_consumed = threshold; } else { return false; } } else { res_consumed = res_count[bin_used] * m_world->GetConfig().ABSORB_RESOURCE_FRACTION.Get(); } if (has_max && res_consumed + total >= max) { res_consumed = max - total; res_change[bin_used] = -1 * res_consumed; } else res_change[bin_used] = -1 * res_consumed; if (res_consumed > 0) { m_organism->AddToRBin(bin_used, res_consumed); if (!m_use_avatar) m_organism->GetOrgInterface().UpdateResources(ctx, res_change); else if (m_use_avatar) m_organism->GetOrgInterface().UpdateAVResources(ctx, res_change); return true; } return false; } // PRED-PREY SUPPORT void cHardwareBCR::makePred(cAvidaContext& ctx) { if (m_organism->IsPreyFT()) { if (m_world->GetConfig().MAX_PRED.Get() && m_world->GetStats().GetNumPredCreatures() >= m_world->GetConfig().MAX_PRED.Get()) m_organism->GetOrgInterface().KillRandPred(ctx, m_organism); // switching between predator and prey means having to switch avatar list...don't run this for orgs with AVCell == -1 (avatars off or test cpu) if (m_use_avatar && m_organism->GetOrgInterface().GetAVCellID() != -1) { m_organism->GetOrgInterface().SwitchPredPrey(ctx); m_organism->SetPredFT(ctx); } else m_organism->SetPredFT(ctx); } } void cHardwareBCR::makeTopPred(cAvidaContext& ctx) { if (m_organism->IsPreyFT()) { if (m_world->GetConfig().MAX_PRED.Get() && m_world->GetStats().GetNumPredCreatures() >= m_world->GetConfig().MAX_PRED.Get()) m_organism->GetOrgInterface().KillRandPred(ctx, m_organism); // switching between predator and prey means having to switch avatar list...don't run this for orgs with AVCell == -1 (avatars off or test cpu) if (m_use_avatar && m_organism->GetOrgInterface().GetAVCellID() != -1) { m_organism->GetOrgInterface().SwitchPredPrey(ctx); m_organism->SetTopPredFT(ctx); } else m_organism->SetTopPredFT(ctx); } else if (m_organism->IsPredFT()) m_organism->SetTopPredFT(ctx); } void cHardwareBCR::setAttackReg(sAttackReg& reg) { reg.success_reg = FindModifiedRegister(rBX); reg.bonus_reg = FindModifiedNextRegister(reg.success_reg); reg.bin_reg = FindModifiedNextRegister(reg.bonus_reg); } bool cHardwareBCR::executeAttack(cAvidaContext& ctx, cOrganism* target, sAttackReg& reg, double odds) { if (!testAttackChance(ctx, target, reg, odds)) return false; double effic = m_world->GetConfig().PRED_EFFICIENCY.Get(); if (m_organism->IsTopPredFT()) effic *= effic; applyKilledPreyMerit(ctx, target, effic); applyKilledPreyReactions(target); // keep returns in same order as legacy code (important if reg assignments are shared) applyKilledPreyResBins(target, reg, effic); setRegister(reg.success_reg, 1, true); applyKilledPreyBonus(target, reg, effic); target->Die(ctx); // kill first -- could end up being killed by inject clone or MAX_PRED if parent was pred makePred(ctx); tryPreyClone(ctx); return true; } cOrganism* cHardwareBCR::getPreyTarget(cAvidaContext& ctx) { cOrganism* target = NULL; if (!m_use_avatar) target = m_organism->GetOrgInterface().GetNeighbor(); else if (m_use_avatar == 2) target = m_organism->GetOrgInterface().GetRandFacedPreyAV(); return target; } bool cHardwareBCR::testPreyTarget(cOrganism* target) { // attacking other carnivores is handled differently (e.g. using fights or tolerance) bool success = true; if (!target->IsPreyFT() || target->IsDead()) success = false; return success; } bool cHardwareBCR::testAttack(cAvidaContext& ctx) { if (m_use_avatar && m_use_avatar != 2) return false; if (m_world->GetConfig().PRED_PREY_SWITCH.Get() < 0) return false; if (!m_use_avatar && !m_organism->IsNeighborCellOccupied()) return false; else if (m_use_avatar == 2 && !m_organism->GetOrgInterface().FacedHasPreyAV()) return false; // prevent killing on refuges const cResourceLib& resource_lib = m_world->GetEnvironment().GetResourceLib(); for (int i = 0; i < resource_lib.GetSize(); i++) { if (resource_lib.GetResource(i)->GetRefuge()) { if (!m_use_avatar && m_organism->GetOrgInterface().GetFacedResourceVal(ctx, i) >= resource_lib.GetResource(i)->GetThreshold()) return false; else if (m_use_avatar == 2 && m_organism->GetOrgInterface().GetAVFacedResourceVal(ctx, i) >= resource_lib.GetResource(i)->GetThreshold()) return false; } } return true; } bool cHardwareBCR::testAttackChance(cAvidaContext& ctx, cOrganism* target, sAttackReg& reg, double odds) { bool success = true; if (odds == -1) odds = m_world->GetConfig().PRED_ODDS.Get(); if (ctx.GetRandom().GetDouble() >= odds || (m_world->GetConfig().MIN_PREY.Get() > 0 && m_world->GetStats().GetNumPreyCreatures() <= m_world->GetConfig().MIN_PREY.Get())) { injureOrg(ctx, target); setRegister(reg.success_reg, -1, true); setRegister(reg.bonus_reg, -1, true); if (m_world->GetConfig().USE_RESOURCE_BINS.Get()) setRegister(reg.bin_reg, -1, true); success = false; } return success; } void cHardwareBCR::applyKilledPreyMerit(cAvidaContext& ctx, cOrganism* target, double effic) { // add prey's merit to predator's--this will result in immediately applying merit increases; adjustments to bonus, give increase in next generation if (m_world->GetConfig().MERIT_INC_APPLY_IMMEDIATE.Get()) { const double target_merit = target->GetPhenotype().GetMerit().GetDouble(); double attacker_merit = m_organism->GetPhenotype().GetMerit().GetDouble(); attacker_merit += target_merit * effic; m_organism->UpdateMerit(ctx, attacker_merit); } } void cHardwareBCR::applyKilledPreyReactions(cOrganism* target) { // now add on the victims reaction counts to your own, this will allow you to pass any reaction tests... Apto::Array<int> target_reactions = target->GetPhenotype().GetLastReactionCount(); Apto::Array<int> org_reactions = m_organism->GetPhenotype().GetStolenReactionCount(); for (int i = 0; i < org_reactions.GetSize(); i++) { m_organism->GetPhenotype().SetStolenReactionCount(i, org_reactions[i] + target_reactions[i]); } } void cHardwareBCR::applyKilledPreyBonus(cOrganism* target, sAttackReg& reg, double effic) { // and add current merit bonus after adjusting for conversion efficiency const double target_bonus = target->GetPhenotype().GetCurBonus(); m_organism->GetPhenotype().SetCurBonus(m_organism->GetPhenotype().GetCurBonus() + (target_bonus * effic)); setRegister(reg.bonus_reg, (int) (target_bonus), true); } void cHardwareBCR::applyKilledPreyResBins(cOrganism* target, sAttackReg& reg, double effic) { // now add the victims internal resource bins to your own, if enabled, after correcting for conversion efficiency if (m_world->GetConfig().USE_RESOURCE_BINS.Get()) { Apto::Array<double> target_bins = target->GetRBins(); for (int i = 0; i < target_bins.GetSize(); i++) { m_organism->AddToRBin(i, target_bins[i] * effic); if (effic > 0) target->AddToRBin(i, -1 * (target_bins[i] * effic)); } const int spec_bin = (int) (m_organism->GetRBins()[m_world->GetConfig().COLLECT_SPECIFIC_RESOURCE.Get()]); setRegister(reg.bin_reg, spec_bin, true); } } void cHardwareBCR::tryPreyClone(cAvidaContext& ctx) { if (m_world->GetConfig().MIN_PREY.Get() < 0 && m_world->GetStats().GetNumPreyCreatures() <= abs(m_world->GetConfig().MIN_PREY.Get())) { // prey numbers can be crashing for other reasons and we wouldn't be using this switch if we didn't want an absolute min num prey // but can't dump a lot b/c could end up filling world with just clones (e.g. if attack happens when world is still being populated) int num_clones = abs(m_world->GetConfig().MIN_PREY.Get()) - m_world->GetStats().GetNumPreyCreatures(); for (int i = 0; i < min(2, num_clones); i++) m_organism->GetOrgInterface().InjectPreyClone(ctx, m_organism->SystematicsGroup("genotype")->ID()); } } void cHardwareBCR::injureOrg(cAvidaContext& ctx, cOrganism* target) { double injury = m_world->GetConfig().PRED_INJURY.Get(); if (injury == 0) return; if (m_world->GetConfig().MERIT_INC_APPLY_IMMEDIATE.Get()) { double target_merit = target->GetPhenotype().GetMerit().GetDouble(); target_merit -= target_merit * injury; target->UpdateMerit(ctx, target_merit); } Apto::Array<int> target_reactions = target->GetPhenotype().GetLastReactionCount(); for (int i = 0; i < target_reactions.GetSize(); i++) { target->GetPhenotype().SetReactionCount(i, target_reactions[i] - (int)((target_reactions[i] * injury))); } const double target_bonus = target->GetPhenotype().GetCurBonus(); target->GetPhenotype().SetCurBonus(target_bonus - (target_bonus * injury)); if (m_world->GetConfig().USE_RESOURCE_BINS.Get()) { Apto::Array<double> target_bins = target->GetRBins(); for (int i = 0; i < target_bins.GetSize(); i++) { target->AddToRBin(i, -1 * (target_bins[i] * injury)); } } }
39.144657
191
0.692466
FergusonAJ
47b049c9e4869ebbbd4de24229d857dc7f9d8ba3
712
cpp
C++
Cpp_primer_5th/code_part7/prog7_12.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part7/prog7_12.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part7/prog7_12.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; /*****?????*****/ struct Sales_data; istream &read(istream&, Sales_data&) /*****?????****/ struct Sales_data{ Sales_data() = default; Sales_data(const string &s): bookNo(s){} Sales_data(const string &s, unsigned n, double p): bookNo(s), units_sold(n), revenue(p*n){} Sales_data(istream &); string isbn() const{ return bookNo;} Sales_data& combin(const Sales_data&); double avg_price() const; string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; istream &read(istream &is , Sales_data &item){ double price = 0.0; is >> item.bookNo >> item.units_sold >> price; item.revenue = price * item.units_sold; return is; }
22.25
51
0.664326
Links789
47ba25b5b6bb5c35f5de6f1d7d57d2d57f51f8eb
939
cc
C++
test_rank.cc
kjwilder/ranker
ff0dd14e29443759e5047d093aa42c83ad9c5f37
[ "Unlicense" ]
null
null
null
test_rank.cc
kjwilder/ranker
ff0dd14e29443759e5047d093aa42c83ad9c5f37
[ "Unlicense" ]
null
null
null
test_rank.cc
kjwilder/ranker
ff0dd14e29443759e5047d093aa42c83ad9c5f37
[ "Unlicense" ]
null
null
null
#include <iostream> #include <cstdlib> #include <string> #include "./ranker.h" int main(int argc, char** argv) { uint num = 10, dump = 1; string method = "average"; // Can also be "min" or "max" or "default" if (argc > 1) num = (uint) atol(argv[1]); if (argc > 2) method = argv[2]; if (argc > 3) dump = (uint) atol(argv[3]); std::cerr << "Running: [" << argv[0] << " num=" << num << " method=" << method << " dump=" << dump << "]" << std::endl; vector<double> b(num); for (uint i = 0; i < num; ++i) b[i] = arc4random() % 8; vector<double> ranks; rank(b, ranks, method); if (dump) { for (uint i = 0; i < ranks.size(); ++i) { std::cout << b[i] << " " << ranks[i] << std::endl; } } std::cout << std::endl; rankhigh(b, ranks, method); if (dump) { for (uint i = 0; i < ranks.size(); ++i) { std::cout << b[i] << " " << ranks[i] << std::endl; } } return 0; }
24.076923
72
0.497338
kjwilder
47ba365ea94c1d5faa483f784bd17cc4b55b109f
7,470
cpp
C++
inference-engine/tests/functional/inference_engine/transformations/convert_nms_gather_path_to_unsigned_test.cpp
monroid/openvino
8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6
[ "Apache-2.0" ]
2,406
2020-04-22T15:47:54.000Z
2022-03-31T10:27:37.000Z
inference-engine/tests/functional/inference_engine/transformations/convert_nms_gather_path_to_unsigned_test.cpp
monroid/openvino
8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6
[ "Apache-2.0" ]
4,948
2020-04-22T15:12:39.000Z
2022-03-31T18:45:42.000Z
inference-engine/tests/functional/inference_engine/transformations/convert_nms_gather_path_to_unsigned_test.cpp
monroid/openvino
8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6
[ "Apache-2.0" ]
991
2020-04-23T18:21:09.000Z
2022-03-31T18:40:57.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include "common_test_utils/ngraph_test_utils.hpp" #include "ngraph/pass/visualize_tree.hpp" #include <ngraph/function.hpp> #include <ngraph/opsets/opset8.hpp> #include <ngraph/pass/manager.hpp> #include <transformations/common_optimizations/convert_nms_gather_path_to_unsigned.hpp> #include <transformations/init_node_info.hpp> using namespace testing; using namespace ngraph; using namespace std; TEST(TransformationTests, test_convert_to_unsigned_nms_gather_1) { // if Convert doesn't exist shared_ptr<Function> f(nullptr), f_ref(nullptr); { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); // usually input to gather data goes after reshape NMS scores auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, squeeze_node, opset8::Constant::create(element::i32, Shape{1}, {0})); f = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); pass::Manager manager; manager.register_pass<pass::InitNodeInfo>(); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); manager.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); } { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::u64); auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); f_ref = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); } auto res = compare_functions(f, f_ref); ASSERT_TRUE(res.first) << res.second; } TEST(TransformationTests, test_convert_to_unsigned_nms_gather_2) { // if Convert already exists shared_ptr<Function> f(nullptr), f_ref(nullptr); { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::i32); // usually input to gather data goes after reshape NMS scores auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); f = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); pass::Manager manager; manager.register_pass<pass::InitNodeInfo>(); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); manager.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); } { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::u32); auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); f_ref = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); } auto res = compare_functions(f, f_ref); ASSERT_TRUE(res.first) << res.second; } TEST(TransformationTests, test_convert_to_unsigned_nms_gather_3) { // if NMS output goes not into Gather indices no converts should be inserted auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto gather = make_shared<opset8::Gather>(nms->output(0), opset8::Constant::create(element::i32, Shape{1}, {2}), opset8::Constant::create(element::i32, Shape{1}, {0})); shared_ptr<Function> f = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); pass::Manager manager; manager.register_pass<pass::InitNodeInfo>(); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); manager.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); ASSERT_EQ(count_ops_of_type<opset1::Convert>(f), 0); }
53.741007
140
0.680321
monroid
47baa49a0ba1970330753567d5245aac574281a8
15,796
cpp
C++
test/unittest/unittest_nntrainer_modelfile.cpp
Gaminee/nntrainer
16c816d46d32dba8610f13b480c1ac18b4b0212f
[ "Apache-2.0" ]
null
null
null
test/unittest/unittest_nntrainer_modelfile.cpp
Gaminee/nntrainer
16c816d46d32dba8610f13b480c1ac18b4b0212f
[ "Apache-2.0" ]
null
null
null
test/unittest/unittest_nntrainer_modelfile.cpp
Gaminee/nntrainer
16c816d46d32dba8610f13b480c1ac18b4b0212f
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 /** * Copyright (C) 2020 Jihoon Lee <jhoon.it.lee@samsung.com> * * @file unittest_nntrainer_modelfile.cpp * @date 16 July 2020 * @brief NNTrainer datafile parmeterized tester. * @see https://github.com/nnstreamer/nntrainer * @author Jihoon Lee <jhoon.it.lee@samsung.com> * @bug No known bugs except for NYI items */ #include <gtest/gtest.h> #include <neuralnet.h> #include <nntrainer-api-common.h> #include <nntrainer_test_util.h> namespace initest { typedef enum { LOAD = 1 << 0, /**< should fail at load */ INIT = 1 << 1, /**< should fail at init */ } IniFailAt; }; class nntrainerIniTest : public ::testing::TestWithParam< std::tuple<const char *, const IniTestWrapper::Sections, int>> { public: static void save_ini(const char *filename, std::vector<IniSection> sections, std::ios_base::openmode mode = std::ios_base::out) { IniTestWrapper::save_ini(filename, sections, mode); } protected: virtual void SetUp() { name = std::string(std::get<0>(GetParam())); std::cout << "starting test case : " << name << std::endl << std::endl; auto sections = std::get<1>(GetParam()); ini = IniTestWrapper(name, sections); failAt = std::get<2>(GetParam()); ini.save_ini(); } virtual void TearDown() { ini.erase_ini(); } std::string getIniName() { return ini.getIniName(); } bool failAtLoad() { return failAt & initest::IniFailAt::LOAD; } bool failAtInit() { return failAt & initest::IniFailAt::INIT; } nntrainer::NeuralNetwork NN; private: int failAt; std::string name; IniTestWrapper ini; }; /** * @brief check given ini is failing/suceeding at load */ TEST_P(nntrainerIniTest, loadConfig) { std::cout << std::get<0>(GetParam()) << std::endl; int status = NN.loadFromConfig(getIniName()); if (failAtLoad()) { EXPECT_NE(status, ML_ERROR_NONE); } else { EXPECT_EQ(status, ML_ERROR_NONE); } } /** * @brief Negative test given ini is failing at loadingTwice */ TEST_P(nntrainerIniTest, loadConfigTwice_n) { std::cout << std::get<0>(GetParam()) << std::endl; NN.loadFromConfig(getIniName()); int status = NN.loadFromConfig(getIniName()); EXPECT_EQ(status, ML_ERROR_INVALID_PARAMETER); } /** * @brief check given ini is failing/succeeding at init */ TEST_P(nntrainerIniTest, init) { std::cout << std::get<0>(GetParam()) << std::endl; int status = NN.loadFromConfig(getIniName()); status = NN.init(); if (failAtInit()) { EXPECT_NE(status, ML_ERROR_NONE); } else { EXPECT_EQ(status, ML_ERROR_NONE); } } /** * @brief check given ini is failing/succeeding when init happens twice. * this should fail at all time. */ TEST_P(nntrainerIniTest, initTwice_n) { std::cout << std::get<0>(GetParam()) << std::endl; int status = NN.loadFromConfig(getIniName()); status = NN.init(); status = NN.init(); EXPECT_NE(status, ML_ERROR_NONE); } /** * @brief check given ini is failing/succeeding when init happens three times. * this should fail at all time. */ TEST_P(nntrainerIniTest, initThreetime_n) { std::cout << std::get<0>(GetParam()) << std::endl; int status = NN.loadFromConfig(getIniName()); status = NN.init(); status = NN.init(); status = NN.init(); EXPECT_NE(status, ML_ERROR_NONE); } /// @todo add run test could be added with iniTest flag to control skip static IniSection nw_base("model", "Type = NeuralNetwork | " "batch_size = 32 | " "epsilon = 1e-7 | " "loss = cross"); static IniSection adam("adam", "Optimizer = adam |" "Learning_rate = 0.00001 |" "Decay_rate = 0.96 |" "Decay_steps = 1000"); static IniSection nw_sgd = nw_base + "Optimizer = sgd |" "Learning_rate = 1"; static IniSection nw_adam = nw_base + adam; static IniSection nw_adam_n = nw_base + "Learning_rate = -1"; static IniSection dataset("DataSet", "BufferSize = 100 |" "TrainData = trainingSet.dat | " "TestData = testSet.dat |" "ValidData = valSet.dat |" "LabelData = label.dat"); static IniSection batch_normal("bn", "Type = batch_normalization |" "momentum = 1.2 |" "moving_mean_initializer = zeros |" "moving_variance_initializer = ones |" "gamma_initializer = zeros |" "beta_initializer = ones"); static IniSection flatten("flat", "Type = flatten"); static IniSection input("inputlayer", "Type = input |" "Input_Shape = 1:1:62720 |" "bias_initializer = zeros |" "Normalization = true |" "Activation = sigmoid"); static IniSection act_relu("activation_relu", "Type = activation | " "Activation = relu"); static IniSection out("fclayer", "Type = fully_connected |" "Unit = 10 |" "bias_initializer = zeros |" "Activation = softmax"); static IniSection conv2d("conv2d", "Type = conv2d |" "bias_initializer = zeros |" "Activation = sigmoid |" "filters = 6 |" "kernel_size = 5,5 |" "stride = 1,1 |" "padding = 0,0 |"); static IniSection input2d("inputlayer", "Type = input |" "Input_Shape = 3:100:100"); static IniSection backbone_random("block1", "backbone = random.ini"); static IniSection backbone_valid("block1", "backbone = base.ini"); static int SUCCESS = 0; static int LOADFAIL = initest::LOAD; static int INITFAIL = initest::INIT; static int ALLFAIL = LOADFAIL | INITFAIL; using I = IniSection; /** * @brief make ini test case from given parameter */ std::tuple<const char *, const IniTestWrapper::Sections, int> mkIniTc(const char *name, const IniTestWrapper::Sections vec, int flag) { return std::make_tuple(name, vec, flag); } /// @note each line contains 2 (positive or negative test) + 3 negative test. /// if, there are 6 positive tests and 9 negative tests /// which sums up to 6 * 2 = 12 positive tests and 9 * 2 + (6 + 9) * 3 = 63 /// negative tests // clang-format off INSTANTIATE_TEST_CASE_P( nntrainerIniAutoTests, nntrainerIniTest, ::testing::Values( /**< positive: basic valid scenarios (2 positive and 3 negative cases) */ mkIniTc("basic_p", {nw_adam, input, out}, SUCCESS), mkIniTc("basic2_p", {nw_sgd, input, out}, SUCCESS), mkIniTc("basic_act_p", {nw_sgd, input + "-Activation", act_relu, out }, SUCCESS), mkIniTc("basic_bn_p", {nw_sgd, input + "-Activation", batch_normal, act_relu, out }, SUCCESS), mkIniTc("basic_bn2_p", {nw_sgd, input + "-Activation", batch_normal + "Activation = relu", out }, SUCCESS), mkIniTc("basic_dataset_p", {nw_adam, dataset, input, out}, SUCCESS), mkIniTc("basic_dataset2_p", {nw_sgd, input, out, dataset}, SUCCESS), mkIniTc("basic_dataset3_p", {dataset, nw_sgd, input, out}, SUCCESS), mkIniTc("basic_conv2d_p", {nw_adam, conv2d + "input_shape = 1:1:62720"}, SUCCESS), mkIniTc("no_testSet_p", {nw_adam, dataset + "-TestData", input, out}, SUCCESS), mkIniTc("no_validSet_p", {nw_adam, dataset + "-ValidData", input, out}, SUCCESS), mkIniTc("no_bufferSize_p", {nw_adam, dataset + "-BufferSize", input, out}, SUCCESS), mkIniTc("buffer_size_smaller_than_batch_size_p", {nw_adam, dataset + "BufferSize=26", input, out}, SUCCESS), mkIniTc("buffer_size_smaller_than_batch_size2_p", {nw_adam, input, out, dataset + "BufferSize=26"}, SUCCESS), /**< half negative: init fail cases (1 positive and 4 negative cases) */ mkIniTc("unknown_loss_n", {nw_adam + "loss = unknown", input, out}, INITFAIL), mkIniTc("activation_very_first_n", {nw_sgd, act_relu, input, out}, INITFAIL), mkIniTc("bnlayer_very_first_n", {nw_sgd, batch_normal, input, out}, INITFAIL), mkIniTc("act_layer_after_act_n", {nw_sgd, input, act_relu, out}, INITFAIL), mkIniTc("act_layer_after_act_bn_n", {nw_sgd, input, act_relu, batch_normal, out }, INITFAIL), mkIniTc("last_act_layer_relu_n", {nw_sgd, input, out, act_relu }, INITFAIL), mkIniTc("last_act_layer_relu2_n", {nw_sgd, input, out + "-Activation", act_relu }, INITFAIL), /**< negative: basic invalid scenarios (5 negative cases) */ mkIniTc("no_model_sec_name_n", {I(nw_adam, "-", "")}, ALLFAIL), mkIniTc("no_model_sec_n", {input, out}, ALLFAIL), mkIniTc("empty_n", {}, ALLFAIL), mkIniTc("no_layers_n", {nw_adam}, ALLFAIL), mkIniTc("no_layers_2_n", {nw_adam, dataset}, ALLFAIL), /// #391 // mkIniTc("ini_has_empty_value_n", {nw_adam + "epsilon = _", input, out}, ALLFAIL), /**< negative: property(hyperparam) validation (5 negative cases) */ mkIniTc("wrong_opt_type_n", {nw_adam + "Optimizer = wrong_opt", input, out}, ALLFAIL), mkIniTc("adam_minus_lr_n", {nw_adam + "Learning_rate = -0.1", input, out}, ALLFAIL), mkIniTc("sgd_minus_lr_n", {nw_sgd + "Learning_rate = -0.1", input, out}, ALLFAIL), mkIniTc("no_loss_n", {nw_adam + "-loss", input, out}, INITFAIL), mkIniTc("unknown_layer_type_n", {nw_adam, input + "Type = asdf", out}, ALLFAIL), mkIniTc("unknown_layer_type2_n", {nw_adam, input, out + "Type = asdf", I(out, "outlayer", "")}, ALLFAIL), /**< negative: little bit of tweeks to check determinancy (5 negative cases) */ mkIniTc("wrong_nw_dataset_n", {nw_adam, input, out, dataset + "-LabelData"}, ALLFAIL), mkIniTc("wrong_nw_dataset2_n", {nw_adam, dataset + "-LabelData", input, out}, ALLFAIL), /**< negative: dataset is not complete (5 negative cases) */ mkIniTc("no_trainingSet_n", {nw_adam, dataset + "-TrainData", input, out}, ALLFAIL), mkIniTc("no_labelSet_n", {nw_adam, dataset + "-LabelData", input, out}, ALLFAIL), mkIniTc("backbone_filemissing_n", {nw_adam, dataset + "-LabelData", input, out}, ALLFAIL) /// #if gtest_version <= 1.7.0 )); /// #else gtest_version > 1.8.0 // ), [](const testing::TestParamInfo<nntrainerIniTest::ParamType>& info){ // return std::get<0>(info.param); // }); /// #end if */ // clang-format on /** * @brief Ini file unittest with backbone with wrong file */ TEST(nntrainerIniTest, backbone_n_01) { const char *ini_name = "backbone_n1.ini"; nntrainerIniTest::save_ini(ini_name, {nw_base, backbone_random}); nntrainer::NeuralNetwork NN; EXPECT_EQ(NN.loadFromConfig(ini_name), ML_ERROR_INVALID_PARAMETER); } /** * @brief Ini file unittest with backbone with empty backbone */ TEST(nntrainerIniTest, backbone_n_02) { const char *ini_name = "backbone_n2.ini"; nntrainerIniTest::save_ini("base.ini", {nw_base}); nntrainerIniTest::save_ini(ini_name, {nw_base, backbone_valid}); nntrainer::NeuralNetwork NN; EXPECT_EQ(NN.loadFromConfig(ini_name), ML_ERROR_INVALID_PARAMETER); } /** * @brief Ini file unittest with backbone with normal backbone */ TEST(nntrainerIniTest, backbone_p_03) { const char *ini_name = "backbone_p3.ini"; nntrainerIniTest::save_ini("base.ini", {nw_base, batch_normal}); nntrainerIniTest::save_ini(ini_name, {nw_base, backbone_valid}); nntrainer::NeuralNetwork NN; EXPECT_EQ(NN.loadFromConfig(ini_name), ML_ERROR_NONE); } /** * @brief Ini file unittest with backbone without model parameters */ TEST(nntrainerIniTest, backbone_p_04) { const char *ini_name = "backbone_p4.ini"; nntrainerIniTest::save_ini("base.ini", {flatten, conv2d}); nntrainerIniTest::save_ini(ini_name, {nw_base, backbone_valid}); nntrainer::NeuralNetwork NN; EXPECT_EQ(NN.loadFromConfig(ini_name), ML_ERROR_NONE); } /** * @brief Ini file unittest matching model with and without backbone */ TEST(nntrainerIniTest, backbone_p_05) { const char *bb_use_ini_name = "backbone_made.ini"; const char *direct_ini_name = "direct_made.ini"; /** Create a backbone.ini */ nntrainerIniTest::save_ini("base.ini", {nw_adam, conv2d}); /** Create a model of 4 conv layers using backbone */ std::string backbone_valid_orig_name = backbone_valid.getName(); nntrainerIniTest::save_ini(bb_use_ini_name, {nw_sgd, input2d, backbone_valid}); backbone_valid.rename("block2"); nntrainerIniTest::save_ini(bb_use_ini_name, {backbone_valid}, std::ios_base::app); backbone_valid.rename("block3"); nntrainerIniTest::save_ini(bb_use_ini_name, {backbone_valid}, std::ios_base::app); backbone_valid.rename("block4"); nntrainerIniTest::save_ini(bb_use_ini_name, {backbone_valid}, std::ios_base::app); backbone_valid.rename(backbone_valid_orig_name); nntrainer::NeuralNetwork NN_backbone; EXPECT_EQ(NN_backbone.loadFromConfig(bb_use_ini_name), ML_ERROR_NONE); EXPECT_EQ(NN_backbone.init(), ML_ERROR_NONE); /** * Model defined in backbone with adam with lr 0.0001 does not affect the * final model to be made using the backbone. */ EXPECT_EQ(NN_backbone.getLearningRate(), 1); /** Create the same model directly without using backbone */ std::string conv2d_orig_name = conv2d.getName(); nntrainerIniTest::save_ini(direct_ini_name, {nw_sgd, input2d}); conv2d.rename("block1conv2d"); nntrainerIniTest::save_ini(direct_ini_name, {conv2d}, std::ios_base::app); conv2d.rename("block2conv2d"); nntrainerIniTest::save_ini(direct_ini_name, {conv2d}, std::ios_base::app); conv2d.rename("block3conv2d"); nntrainerIniTest::save_ini(direct_ini_name, {conv2d}, std::ios_base::app); conv2d.rename("block4conv2d"); nntrainerIniTest::save_ini(direct_ini_name, {conv2d}, std::ios_base::app); conv2d.rename(conv2d_orig_name); nntrainer::NeuralNetwork NN_direct; EXPECT_EQ(NN_direct.loadFromConfig(direct_ini_name), ML_ERROR_NONE); EXPECT_EQ(NN_direct.init(), ML_ERROR_NONE); /** Summary of both the models must match precisely */ NN_backbone.printPreset(std::cout, ML_TRAIN_SUMMARY_MODEL); NN_direct.printPreset(std::cout, ML_TRAIN_SUMMARY_MODEL); EXPECT_EQ(NN_backbone.getInputDimension(), NN_direct.getInputDimension()); EXPECT_EQ(NN_backbone.getOutputDimension(), NN_direct.getOutputDimension()); auto flat_backbone = NN_backbone.getFlatGraph(); auto flat_direct = NN_direct.getFlatGraph(); EXPECT_EQ(flat_backbone.size(), flat_direct.size()); for (size_t idx = 0; idx < flat_backbone.size(); idx++) { EXPECT_EQ(flat_backbone[idx]->getType(), flat_direct[idx]->getType()); EXPECT_EQ(flat_backbone[idx]->getInputDimension(), flat_direct[idx]->getInputDimension()); EXPECT_EQ(flat_backbone[idx]->getOutputDimension(), flat_direct[idx]->getOutputDimension()); EXPECT_EQ(flat_backbone[idx]->getActivationType(), flat_direct[idx]->getActivationType()); EXPECT_EQ(flat_backbone[idx]->getName(), flat_direct[idx]->getName()); } } /** * @brief Main gtest */ int main(int argc, char **argv) { int result = -1; try { testing::InitGoogleTest(&argc, argv); } catch (...) { std::cerr << "Error duing IniGoogleTest" << std::endl; return 0; } try { result = RUN_ALL_TESTS(); } catch (...) { std::cerr << "Error duing RUN_ALL_TSETS()" << std::endl; } return result; }
37.34279
113
0.6451
Gaminee
47bae4bedba652c46011937b615aac6b912324ac
2,212
cpp
C++
Plugins~/Src/MeshSyncClientBlender/msblenContextState.cpp
Mu-L/MeshSyncDCCPlugins
dccf716d975435e4a897964a6f6789e046119740
[ "Apache-2.0" ]
18
2020-02-20T02:30:54.000Z
2020-04-13T01:39:12.000Z
Plugins~/Src/MeshSyncClientBlender/msblenContextState.cpp
Mu-L/MeshSyncDCCPlugins
dccf716d975435e4a897964a6f6789e046119740
[ "Apache-2.0" ]
6
2020-03-09T01:56:05.000Z
2020-03-20T21:55:30.000Z
Plugins~/Src/MeshSyncClientBlender/msblenContextState.cpp
Mu-L/MeshSyncDCCPlugins
dccf716d975435e4a897964a6f6789e046119740
[ "Apache-2.0" ]
4
2020-02-29T15:41:49.000Z
2020-04-02T06:22:24.000Z
#include "msblenContextState.h" #include <msblenUtils.h> using namespace msblenUtils; void msblenContextState::ObjectRecord::clearState() { touched = renamed = false; dst = nullptr; } void msblenContextState::eraseObjectRecords() { for (auto i = records.begin(); i != records.end(); /**/) { if (!i->second.touched) records.erase(i++); else ++i; } } void msblenContextState::eraseStaleObjects() { eraseObjectRecords(); manager.eraseStaleEntities(); } void msblenContextState::clear() { manager.clear(); } void msblenContextState::clearRecordsState() { for (std::map<const void*, msblenContextState::ObjectRecord>::value_type& kvp : records) kvp.second.clearState(); } msblenContextState::ObjectRecord& msblenContextState::touchRecord( msblenContextPathProvider& paths, const Object* obj, const std::string& base_path, bool children) { auto& rec = records[obj]; if (rec.touched && base_path.empty()) return rec; // already touched rec.touched = true; std::string local_path = paths.get_path(obj); if (local_path != rec.path) { rec.renamed = true; rec.path = local_path; } std::string path = base_path + local_path; manager.touch(path); // trace bones if (is_armature(obj)) { blender::blist_range<struct bPoseChannel> poses = blender::list_range((bPoseChannel*)obj->pose->chanbase.first); for (struct bPoseChannel* pose : poses) { records[pose->bone].touched = true; manager.touch(base_path + paths.get_path(obj, pose->bone)); } } // care children if (children) { each_child(obj, [&](Object* child) { touchRecord(paths, child, base_path, true); }); } // trace dupli group if (Collection* group = get_instance_collection(obj)) { const std::string group_path = path + '/' + (group->id.name + 2); manager.touch(group_path); auto gobjects = blender::list_range((CollectionObject*)group->gobject.first); for (auto go : gobjects) touchRecord(paths, go->ob, group_path, true); } return rec; }
26.333333
120
0.62613
Mu-L
47bb1acf4ff47f8f113f2614ea4efc6c29f40a96
720
cpp
C++
1100/10/1117b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
1100/10/1117b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
1100/10/1117b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <algorithm> #include <iostream> #include <vector> template <typename T> std::istream& operator >>(std::istream& input, std::vector<T>& v) { for (T& a : v) input >> a; return input; } void answer(unsigned long long h) { std::cout << h << '\n'; } void solve(std::vector<unsigned>& a, unsigned m, unsigned k) { std::sort(a.begin(), a.end(), std::greater<unsigned>()); const unsigned c = m / (k + 1); const unsigned r = m % (k + 1); answer(c * (1ull * a[0] * k + a[1]) + 1ull * r * a[0]); } int main() { size_t n; std::cin >> n; unsigned m, k; std::cin >> m >> k; std::vector<unsigned> a(n); std::cin >> a; solve(a, m, k); return 0; }
16
65
0.529167
actium
47bd74ead7bb1825623904024bbbe758333dc239
9,896
cpp
C++
HiroCamSDK/src/main/cpp/dependence/src/libmp4v2/src/mp4util.cpp
shirleyyuqi/UIFySim
15810480022003f5f84509229ef5acbd47e54172
[ "Apache-2.0" ]
1
2019-12-25T17:38:30.000Z
2019-12-25T17:38:30.000Z
HiroCamSDK/src/main/cpp/dependence/src/libmp4v2/src/mp4util.cpp
shirleyyuqi/UIFySim
15810480022003f5f84509229ef5acbd47e54172
[ "Apache-2.0" ]
1
2020-03-18T10:20:43.000Z
2020-03-18T10:20:43.000Z
mp4v2-2.0.0/src/mp4util.cpp
nichesuch/AirOrche
ab048fe01eb85633464ab676ff33e06c7fef1097
[ "MIT" ]
null
null
null
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * 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 is MPEG4IP. * * The Initial Developer of the Original Code is Cisco Systems Inc. * Portions created by Cisco Systems Inc. are * Copyright (C) Cisco Systems Inc. 2001-2005. All Rights Reserved. * * Contributor(s): * Dave Mackie dmackie@cisco.com * Bill May wmay@cisco.com */ #include "src/impl.h" namespace mp4v2 { namespace impl { /////////////////////////////////////////////////////////////////////////////// bool MP4NameFirstMatches(const char* s1, const char* s2) { if (s1 == NULL || *s1 == '\0' || s2 == NULL || *s2 == '\0') { return false; } if (*s2 == '*') { return true; } while (*s1 != '\0') { if (*s2 == '\0' || strchr("[.", *s2)) { break; } if (tolower(*s1) != tolower(*s2)) { return false; } s1++; s2++; } return true; } bool MP4NameFirstIndex(const char* s, uint32_t* pIndex) { if (s == NULL) { return false; } while (*s != '\0' && *s != '.') { if (*s == '[') { s++; ASSERT(pIndex); if (sscanf(s, "%u", pIndex) != 1) { return false; } return true; } s++; } return false; } char* MP4NameFirst(const char *s) { if (s == NULL) { return NULL; } const char* end = s; while (*end != '\0' && *end != '.') { end++; } char* first = (char*)MP4Calloc((end - s) + 1); if (first) { strncpy(first, s, end - s); } return first; } const char* MP4NameAfterFirst(const char *s) { if (s == NULL) { return NULL; } while (*s != '\0') { if (*s == '.') { s++; if (*s == '\0') { return NULL; } return s; } s++; } return NULL; } char* MP4ToBase16(const uint8_t* pData, uint32_t dataSize) { if (dataSize) { ASSERT(pData); } uint32_t size = 2 * dataSize + 1; char* s = (char*)MP4Calloc(size); uint32_t i, j; for (i = 0, j = 0; i < dataSize; i++) { size -= snprintf(&s[j], size, "%02x", pData[i]); j += 2; } return s; /* N.B. caller is responsible for free'ing s */ } char* MP4ToBase64(const uint8_t* pData, uint32_t dataSize) { if (pData == NULL || dataSize == 0) return NULL; static const char encoding[64] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' }; char* s = (char*)MP4Calloc((((dataSize + 2) * 4) / 3) + 1); const uint8_t* src = pData; if (pData == NULL) return NULL; char* dest = s; uint32_t numGroups = dataSize / 3; for (uint32_t i = 0; i < numGroups; i++) { *dest++ = encoding[src[0] >> 2]; *dest++ = encoding[((src[0] & 0x03) << 4) | (src[1] >> 4)]; *dest++ = encoding[((src[1] & 0x0F) << 2) | (src[2] >> 6)]; *dest++ = encoding[src[2] & 0x3F]; src += 3; } if (dataSize % 3 == 1) { *dest++ = encoding[src[0] >> 2]; *dest++ = encoding[((src[0] & 0x03) << 4)]; *dest++ = '='; *dest++ = '='; } else if (dataSize % 3 == 2) { *dest++ = encoding[src[0] >> 2]; *dest++ = encoding[((src[0] & 0x03) << 4) | (src[1] >> 4)]; *dest++ = encoding[((src[1] & 0x0F) << 2)]; *dest++ = '='; } *dest = '\0'; return s; /* N.B. caller is responsible for free'ing s */ } static bool convertBase64 (const char data, uint8_t *value) { static const uint8_t decodingarr64[128] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff, }; uint8_t index = (uint8_t)data; if ((index & 0x80) != 0) return false; if (decodingarr64[index] == 0xff) return false; *value = decodingarr64[index]; return true; } uint8_t *Base64ToBinary (const char *pData, uint32_t decodeSize, uint32_t *pDataSize) { uint8_t *ret; uint32_t size, ix, groups; if (pData == NULL || decodeSize == 0 || pDataSize == NULL) return NULL; if ((decodeSize % 4) != 0) { // must be multiples of 4 characters return NULL; } size = (decodeSize * 3) / 4; groups = decodeSize / 4; ret = (uint8_t *)MP4Calloc(size); if (ret == NULL) return NULL; for (ix = 0; ix < groups; ix++) { uint8_t value[4]; for (uint8_t jx = 0; jx < 4; jx++) { if (pData[jx] == '=') { if (ix != (groups - 1)) { free(ret); return NULL; } size--; value[jx] = 0; } else if (convertBase64(pData[jx], &value[jx]) == false) { free(ret); return NULL; } } ret[(ix * 3)] = value[0] << 2 | ((value[1] >> 4) & 0x3); ret[(ix * 3) + 1] = (value[1] << 4) | (value[2] >> 2 & 0xf); ret[(ix * 3) + 2] = ((value[2] & 0x3) << 6) | value[3]; pData += 4; } *pDataSize = size; return ret; } // log2 of value, rounded up static uint8_t ilog2(uint64_t value) { uint64_t powerOf2 = 1; for (uint8_t i = 0; i < 64; i++) { if (value <= powerOf2) { return i; } powerOf2 <<= 1; } return 64; } uint64_t MP4ConvertTime(uint64_t t, uint32_t oldTimeScale, uint32_t newTimeScale) { // avoid float point exception if (oldTimeScale == 0) { throw new Exception("division by zero", __FILE__, __LINE__, __FUNCTION__ ); } if (oldTimeScale == newTimeScale) return t; // check if we can safely use integer operations if (ilog2(t) + ilog2(newTimeScale) <= 64) { return (t * newTimeScale) / oldTimeScale; } // final resort is to use floating point double d = (double)newTimeScale; d *= double(t); d /= (double)oldTimeScale; d += 0.5; // round up. return (uint64_t)d; } const char* MP4NormalizeTrackType (const char* type) { if (!strcasecmp(type, "vide") || !strcasecmp(type, "video") || !strcasecmp(type, "mp4v") || !strcasecmp(type, "avc1") || !strcasecmp(type, "s263") // 3GPP H.263 || !strcasecmp(type, "encv")) { return MP4_VIDEO_TRACK_TYPE; } if (!strcasecmp(type, "soun") || !strcasecmp(type, "sound") || !strcasecmp(type, "audio") || !strcasecmp(type, "enca") || !strcasecmp(type, "samr") // 3GPP AMR || !strcasecmp(type, "sawb") // 3GPP AMR/WB || !strcasecmp(type, "mp4a")) { return MP4_AUDIO_TRACK_TYPE; } if (!strcasecmp(type, "sdsm") || !strcasecmp(type, "scene") || !strcasecmp(type, "bifs")) { return MP4_SCENE_TRACK_TYPE; } if (!strcasecmp(type, "odsm") || !strcasecmp(type, "od")) { return MP4_OD_TRACK_TYPE; } if (strcasecmp(type, "cntl") == 0) { return MP4_CNTL_TRACK_TYPE; } log.verbose1f("Attempt to normalize %s did not match",type); return type; } MP4Timestamp MP4GetAbsTimestamp() { /* MP4 epoch is midnight, January 1, 1904 * offset from midnight, January 1, 1970 is 2082844800 seconds * 208284480 is (((1970 - 1904) * 365) + 17) * 24 * 60 * 60 */ return time::getLocalTimeSeconds() + 2082844800; } /////////////////////////////////////////////////////////////////////////////// uint32_t STRTOINT32( const char* s ) { #if defined( MP4V2_INTSTRING_ALIGNMENT ) // it seems ARM integer instructions require 4-byte alignment so we // manually copy string-data into the integer before performing ops uint32_t tmp; memcpy( &tmp, s, sizeof(tmp) ); return MP4V2_NTOHL( tmp ); #else return MP4V2_NTOHL(*(uint32_t *)s); #endif } void INT32TOSTR( uint32_t i, char* s ) { #if defined( MP4V2_INTSTRING_ALIGNMENT ) // it seems ARM integer instructions require 4-byte alignment so we // manually copy string-data into the integer before performing ops uint32_t tmp = MP4V2_HTONL( i ); memcpy( s, &tmp, sizeof(tmp) ); #else *(uint32_t *)s = MP4V2_HTONL(i); #endif s[4] = 0; } /////////////////////////////////////////////////////////////////////////////// }} // namespace mp4v2::impl
28.033994
85
0.504446
shirleyyuqi
47c06b8d3ea9f4cfcee2a13f492820d16fceebdf
1,527
hpp
C++
include/boost/simd/constant/fourthrooteps.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/constant/fourthrooteps.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/constant/fourthrooteps.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! @file @copyright 2012-2015 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_CONSTANT_FOURTHROOTEPS_HPP_INCLUDED #define BOOST_SIMD_CONSTANT_FOURTHROOTEPS_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-constant Generate the 4th root of constant @ref Eps : \f$\sqrt[4]\epsilon\f$. @par Semantic: @code T r = Fourthrooteps<T>(); @endcode is similar to: @code if T is integral r = T(1) else if T is double r = pow(2.0, -13); else if T is float r = pow(2.0f, -5.75f); @endcode @return The Fourthrooteps constant for the proper type **/ template<typename T> T Fourthrooteps(); namespace functional { /*! @ingroup group-callable-constant Generate the constant fourthrooteps. @return The Fourthrooteps constant for the proper type **/ const boost::dispatch::functor<tag::fourthrooteps_> fourthrooteps = {}; } } } #endif #include <boost/simd/constant/definition/fourthrooteps.hpp> #include <boost/simd/arch/common/scalar/constant/constant_value.hpp> #include <boost/simd/arch/common/simd/constant/constant_value.hpp> #endif
25.032787
100
0.599214
yaeldarmon
47c0c074906c5921573aedfd4429293b5cdba56e
798
cpp
C++
acmicpc/4195.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
acmicpc/4195.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
acmicpc/4195.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <iostream> #include <map> using namespace std; #define MAX 200001 int root[MAX], num[MAX]; int find(int n) { if (n == root[n]) return n; root[n] = find(root[n]); return root[n]; } int uni(int a, int b) { int x = find(a); int y = find(b); if (x != y) { root[y] = x; num[x] += num[y]; num[y] = 1; } return num[x]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string a, b; int t, n; cin >> t; while (t--) { cin >> n; for (int i=1; i<=n*2; ++i) { root[i] = i; num[i] = 1; } map<string, int> dict; int label = 1; for (int i=0; i<n; ++i) { cin >> a >> b; if (dict.count(a) == 0) dict[a] = label++; if (dict.count(b) == 0) dict[b] = label++; cout << uni(dict[a], dict[b]) << '\n'; } } return 0; }
13.3
41
0.497494
juseongkr
47c175b7c4ab7e626ee2c7977a3473a902b69f5b
43,304
cxx
C++
src/Event.cxx
jsiado/CyMiniAna
8bffd7701bbb2efc1ffbce9d03dd278067bf9c20
[ "MIT" ]
null
null
null
src/Event.cxx
jsiado/CyMiniAna
8bffd7701bbb2efc1ffbce9d03dd278067bf9c20
[ "MIT" ]
17
2018-01-15T01:42:56.000Z
2018-08-14T21:08:45.000Z
src/Event.cxx
jsiado/CyMiniAna
8bffd7701bbb2efc1ffbce9d03dd278067bf9c20
[ "MIT" ]
3
2018-01-30T19:08:30.000Z
2019-12-09T11:59:45.000Z
/* Created: -- Last Updated: 13 December 2017 Dan Marley daniel.edison.marley@cernSPAMNOT.ch University of Michigan, Ann Arbor, MI 48109 ----- Event class Contains all the objects (& structs) with event information Assumes a flat ntuple data structure */ #include "Analysis/CyMiniAna/interface/Event.h" // constructor Event::Event( TTreeReader &myReader, configuration &cmaConfig ) : m_config(&cmaConfig), m_ttree(myReader), m_treeName("SetMe"), m_fileName("SetMe"), m_DNN(0.0){ m_treeName = m_ttree.GetTree()->GetName(); // for systematics m_fileName = m_config->filename(); // for accessing file metadata // Set options for the class m_isMC = m_config->isMC(); // simulated or real sample m_useTruth = m_config->useTruth(); // access and use truth information m_grid = m_config->isGridFile(); // file directly from original analysis team m_useJets = m_config->useJets(); // use AK4 jets in analysis m_useLargeRJets= m_config->useLargeRJets(); // use AK8 jets in analysis m_useLeptons = m_config->useLeptons(); // use leptons in analysis m_useNeutrinos = m_config->useNeutrinos(); // use neutrinos in analysis m_useWprime = m_config->useWprime(); // use reconstructed Wprime in analysis m_neutrinoReco = m_config->neutrinoReco(); // reconstruct neutrino m_wprimeReco = m_config->wprimeReco(); // reconstruct Wprime m_DNNinference = m_config->DNNinference(); // use DNN to predict values m_DNNtraining = m_config->DNNtraining(); // load DNN features (save/use later) m_getDNN = (m_DNNinference || m_DNNtraining); m_useDNN = m_config->useDNN(); // use DNN in analysis // b-tagging working points m_CSVv2L = m_config->CSVv2L(); m_CSVv2M = m_config->CSVv2M(); m_CSVv2T = m_config->CSVv2T(); //** Access branches from Tree **// m_eventNumber = new TTreeReaderValue<unsigned long long>(m_ttree,"eventNumber"); m_runNumber = new TTreeReaderValue<unsigned int>(m_ttree,"runNumber"); m_lumiblock = new TTreeReaderValue<unsigned int>(m_ttree,"lumiblock"); m_npv = new TTreeReaderValue<unsigned int>(m_ttree,"npv"); m_rho = new TTreeReaderValue<float>(m_ttree,"rho"); m_true_pileup = new TTreeReaderValue<unsigned int>(m_ttree,"true_pileup"); /** Triggers **/ m_HLT_Ele45_CaloIdVT_GsfTrkIdT_PFJet200_PFJet50 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_Ele45_CaloIdVT_GsfTrkIdT_PFJet200_PFJet50"); m_HLT_Ele50_CaloIdVT_GsfTrkIdT_PFJet165 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_Ele50_CaloIdVT_GsfTrkIdT_PFJet165"); m_HLT_Ele115_CaloIdVT_GsfTrkIdT = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_Ele115_CaloIdVT_GsfTrkIdT"); m_HLT_Mu40_Eta2P1_PFJet200_PFJet50 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_Mu40_Eta2P1_PFJet200_PFJet50"); m_HLT_Mu50 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_Mu50"); m_HLT_TkMu50 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_TkMu50"); m_HLT_PFHT800 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_PFHT800"); m_HLT_PFHT900 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_PFHT900"); m_HLT_AK8PFJet450 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_AK8PFJet450"); m_HLT_PFHT700TrimMass50 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_PFHT700TrimMass50"); m_HLT_PFJet360TrimMass30 = new TTreeReaderValue<unsigned int>(m_ttree,"HLT_PFJet360TrimMass30"); //m_HLT_Ele45_WPLoose_Gsf = new TTreeReaderValue<int>(m_ttree,"HLT_Ele45_WPLoose_Gsf"); //m_HLT_TkMu50 = new TTreeReaderValue<int>(m_ttree,"HLT_TkMu50"); /** Filters **/ m_Flag_goodVertices = new TTreeReaderValue<unsigned int>(m_ttree,"Flag_goodVertices"); m_Flag_eeBadScFilter = new TTreeReaderValue<unsigned int>(m_ttree,"Flag_eeBadScFilter"); m_Flag_HBHENoiseFilter = new TTreeReaderValue<unsigned int>(m_ttree,"Flag_HBHENoiseFilter"); m_Flag_HBHENoiseIsoFilter = new TTreeReaderValue<unsigned int>(m_ttree,"Flag_HBHENoiseIsoFilter"); m_Flag_globalTightHalo2016Filter = new TTreeReaderValue<unsigned int>(m_ttree,"Flag_globalTightHalo2016Filter"); m_Flag_EcalDeadCellTriggerPrimitiveFilter = new TTreeReaderValue<unsigned int>(m_ttree,"Flag_EcalDeadCellTriggerPrimitiveFilter"); /** JETS **/ if (m_useJets){ // small-R jet information m_jet_pt = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK4pt"); m_jet_eta = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK4eta"); m_jet_phi = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK4phi"); m_jet_m = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK4mass"); m_jet_bdisc = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK4bDisc"); m_jet_deepCSV = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK4deepCSV"); m_jet_area = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK4area"); m_jet_uncorrPt = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK4uncorrPt"); m_jet_uncorrE = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK4uncorrE"); } if (m_useLargeRJets){ // large-R Jet information m_ljet_pt = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8pt"); m_ljet_eta = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8eta"); m_ljet_phi = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8phi"); m_ljet_m = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8mass"); m_ljet_SDmass = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8SDmass"); m_ljet_tau1 = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8tau1"); m_ljet_tau2 = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8tau2"); m_ljet_tau3 = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8tau3"); m_ljet_area = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8area"); m_ljet_charge = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8charge"); m_ljet_subjet0_charge = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet0charge"); m_ljet_subjet0_bdisc = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet0bDisc"); m_ljet_subjet0_deepCSV= new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet0deepCSV"); m_ljet_subjet0_pt = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet0pt"); m_ljet_subjet0_mass = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet0mass"); if (m_config->isGridFile()){ m_ljet_subjet0_tau1 = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet0tau1"); m_ljet_subjet0_tau2 = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet0tau2"); m_ljet_subjet0_tau3 = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet0tau3"); m_ljet_subjet1_tau1 = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet1tau1"); m_ljet_subjet1_tau2 = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet1tau2"); m_ljet_subjet1_tau3 = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet1tau3"); } m_ljet_subjet1_charge = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet1charge"); m_ljet_subjet1_bdisc = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet1bDisc"); m_ljet_subjet1_deepCSV= new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet1deepCSV"); m_ljet_subjet1_pt = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet1pt"); m_ljet_subjet1_mass = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8subjet1mass"); m_ljet_BEST_class = new TTreeReaderValue<std::vector<int>>(m_ttree,"AK8BEST_class"); m_ljet_BEST_t = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8BEST_t"); m_ljet_BEST_w = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8BEST_w"); m_ljet_BEST_z = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8BEST_z"); m_ljet_BEST_h = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8BEST_h"); m_ljet_BEST_j = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8BEST_j"); m_ljet_uncorrPt = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8uncorrPt"); m_ljet_uncorrE = new TTreeReaderValue<std::vector<float>>(m_ttree,"AK8uncorrE"); } /** LEPTONS **/ if (m_useLeptons){ m_el_pt = new TTreeReaderValue<std::vector<float>>(m_ttree,"ELpt"); m_el_eta = new TTreeReaderValue<std::vector<float>>(m_ttree,"ELeta"); m_el_phi = new TTreeReaderValue<std::vector<float>>(m_ttree,"ELphi"); m_el_e = new TTreeReaderValue<std::vector<float>>(m_ttree,"ELenergy"); m_el_charge = new TTreeReaderValue<std::vector<float>>(m_ttree,"ELcharge"); //m_el_iso = new TTreeReaderValue<std::vector<float>>(m_ttree,"ELiso"); m_el_id_loose = new TTreeReaderValue<std::vector<unsigned int>>(m_ttree,"ELlooseID"); m_el_id_medium = new TTreeReaderValue<std::vector<unsigned int>>(m_ttree,"ELmediumID"); m_el_id_tight = new TTreeReaderValue<std::vector<unsigned int>>(m_ttree,"ELtightID"); m_el_id_loose_noIso = new TTreeReaderValue<std::vector<unsigned int>>(m_ttree,"ELlooseIDnoIso"); m_el_id_medium_noIso = new TTreeReaderValue<std::vector<unsigned int>>(m_ttree,"ELmediumIDnoIso"); m_el_id_tight_noIso = new TTreeReaderValue<std::vector<unsigned int>>(m_ttree,"ELtightIDnoIso"); m_mu_pt = new TTreeReaderValue<std::vector<float>>(m_ttree,"MUpt"); m_mu_eta = new TTreeReaderValue<std::vector<float>>(m_ttree,"MUeta"); m_mu_phi = new TTreeReaderValue<std::vector<float>>(m_ttree,"MUphi"); m_mu_e = new TTreeReaderValue<std::vector<float>>(m_ttree,"MUenergy"); m_mu_charge = new TTreeReaderValue<std::vector<float>>(m_ttree,"MUcharge"); m_mu_iso = new TTreeReaderValue<std::vector<float>>(m_ttree,"MUcorrIso"); m_mu_id_loose = new TTreeReaderValue<std::vector<unsigned int>>(m_ttree,"MUlooseID"); m_mu_id_medium = new TTreeReaderValue<std::vector<unsigned int>>(m_ttree,"MUmediumID"); m_mu_id_tight = new TTreeReaderValue<std::vector<unsigned int>>(m_ttree,"MUtightID"); } if (!m_neutrinoReco && m_useNeutrinos){ // Neutrinos aren't stored in the baseline ntuples, requires 'kinematicReco' to create m_nu_pt = new TTreeReaderValue<std::vector<float>>(m_ttree, "nu_pt"); m_nu_eta = new TTreeReaderValue<std::vector<float>>(m_ttree, "nu_eta"); m_nu_phi = new TTreeReaderValue<std::vector<float>>(m_ttree, "nu_phi"); } m_met_met = new TTreeReaderValue<float>(m_ttree,"METpt"); m_met_phi = new TTreeReaderValue<float>(m_ttree,"METphi"); m_HTAK8 = new TTreeReaderValue<float>(m_ttree,"HTak8"); m_HTAK4 = new TTreeReaderValue<float>(m_ttree,"HTak4"); // set some event weights and access necessary branches m_xsection = 1.0; m_kfactor = 1.0; m_sumOfWeights = 1.0; m_LUMI = m_config->LUMI(); Sample ss = m_config->sample(); // MC information if (m_isMC){ //m_weight_mc = 1;//new TTreeReaderValue<float>(m_ttree,"evt_Gen_Weight"); m_xsection = ss.XSection; m_kfactor = ss.KFactor; // most likely =1 m_sumOfWeights = ss.sumOfWeights; m_mc_pt = new TTreeReaderValue<std::vector<float>>(m_ttree,"GENpt"); m_mc_eta = new TTreeReaderValue<std::vector<float>>(m_ttree,"GENeta"); m_mc_phi = new TTreeReaderValue<std::vector<float>>(m_ttree,"GENphi"); m_mc_e = new TTreeReaderValue<std::vector<float>>(m_ttree,"GENenergy"); m_mc_pdgId = new TTreeReaderValue<std::vector<int>>(m_ttree,"GENid"); m_mc_status = new TTreeReaderValue<std::vector<int>>(m_ttree,"GENstatus"); m_mc_parent_idx = new TTreeReaderValue<std::vector<int>>(m_ttree,"GENparent_idx"); m_mc_child0_idx = new TTreeReaderValue<std::vector<int>>(m_ttree,"GENchild0_idx"); m_mc_child1_idx = new TTreeReaderValue<std::vector<int>>(m_ttree,"GENchild1_idx"); m_mc_isHadTop = new TTreeReaderValue<std::vector<int>>(m_ttree,"GENisHadTop"); /* m_mc_ht = new TTreeReaderValue<float>(m_ttree,"evt_Gen_Ht"); m_truth_jet_pt = new TTreeReaderValue<float>(m_ttree,"jetAK4CHS_GenJetPt"); m_truth_jet_eta = new TTreeReaderValue<std::vector<float>>(m_ttree,"jetAK4CHS_GenJetEta"); m_truth_jet_phi = new TTreeReaderValue<std::vector<float>>(m_ttree,"jetAK4CHS_GenJetPhi"); m_truth_jet_e = new TTreeReaderValue<std::vector<float>>(m_ttree,"jetAK4CHS_GenJetCharge"); m_truth_ljet_pt = new TTreeReaderValue<std::vector<float>>(m_ttree,"jetAK8CHS_GenJetPt"); m_truth_ljet_eta = new TTreeReaderValue<std::vector<float>>(m_ttree,"jetAK8CHS_GenJetEta"); m_truth_ljet_phi = new TTreeReaderValue<std::vector<float>>(m_ttree,"jetAK8CHS_GenJetPhi"); m_truth_ljet_e = new TTreeReaderValue<std::vector<float>>(m_ttree,"jetAK8CHS_GenJetE"); m_truth_ljet_charge = new TTreeReaderValue<std::vector<float>>(m_ttree,"jetAK8CHS_GenJetCharge"); m_truth_ljet_subjet_charge = new TTreeReaderValue<std::vector<float>>(m_ttree,"subjetAK8CHS_GenJetCharge"); */ } // end isMC // Truth matching tool m_truthMatchingTool = new truthMatching(cmaConfig); m_truthMatchingTool->initialize(); // DNN material m_deepLearningTool = new DeepLearning(cmaConfig); if (!m_getDNN && m_useDNN) m_dnn_score = new TTreeReaderValue<float>(m_ttree,"ljet_CWoLa"); // Kinematic reconstruction algorithms m_neutrinoRecoTool = new NeutrinoReco(cmaConfig); m_wprimeTool = new WprimeReco(cmaConfig); } // end constructor Event::~Event() {} void Event::initialize_eventWeights(){ /* Create vectors of the systematics that are weights for the nominal events Must be called from the constructor for the access to TTreeReaderValues to work! */ std::map<std::string,unsigned int> mapWeightSystematics = m_config->mapOfWeightVectorSystematics(); m_listOfWeightSystematics = m_config->listOfWeightSystematics(); m_weightSystematicsFloats.clear(); m_weightSystematicsVectorFloats.clear(); // systematics from the nominal tree that are floats for (const auto& nom_syst : m_listOfWeightSystematics){ if (!m_config->useLeptons() && nom_syst.find("leptonSF")!=std::string::npos) continue; m_weightSystematicsFloats[nom_syst] = new TTreeReaderValue<float>(m_ttree,nom_syst.c_str()); } // systematics from the nominal tree that are vectors for (const auto& syst : mapWeightSystematics) m_weightSystematicsVectorFloats[syst.first] = new TTreeReaderValue<std::vector<float>>(m_ttree,syst.first.c_str()); return; } void Event::updateEntry(Long64_t entry){ /* Update the entry -> update all TTree variables */ cma::DEBUG("EVENT : Update Entry "+std::to_string(entry) ); m_entry = entry; // make sure the entry exists if(isValidRecoEntry()) m_ttree.SetEntry(m_entry); else cma::ERROR("EVENT : Invalid Reco entry "+std::to_string(m_entry)+"!"); return; } void Event::clear(){ /* Clear many of the vectors/maps for each event -- SAFETY PRECAUTION */ m_truth_ljets.clear(); m_truth_jets.clear(); m_truth_leptons.clear(); m_truth_neutrinos.clear(); m_jets.clear(); m_ljets.clear(); m_leptons.clear(); m_neutrinos.clear(); m_btag_jets.clear(); m_btag_jets_default.clear(); m_weight_btag_default = 1.0; m_nominal_weight = 1.0; m_HT = 0; m_ST = 0; return; } void Event::execute(Long64_t entry){ /* Get the values from the event */ cma::DEBUG("EVENT : Execute event " ); // Load data from root tree for this event updateEntry(entry); // Reset many event-level values clear(); // Get the event weights (for cutflow & histograms) initialize_weights(); cma::DEBUG("EVENT : Setup weights "); // Filters initialize_filters(); // Triggers initialize_triggers(); // Truth Information if (m_useTruth){ initialize_truth(); cma::DEBUG("EVENT : Setup truth information "); } // Jets if (m_useJets){ initialize_jets(); cma::DEBUG("EVENT : Setup small-R jets "); } // Large-R Jets if (m_useLargeRJets){ initialize_ljets(); cma::DEBUG("EVENT : Setup large-R jets "); } // Leptons if (m_useLeptons){ initialize_leptons(); cma::DEBUG("EVENT : Setup leptons "); } // Get some kinematic variables (MET, HT, ST) initialize_kinematics(); cma::DEBUG("EVENT : Setup kinematic variables "); // Neutrinos if (m_useNeutrinos){ // relies on kinematic reconstruction, unless the information is saved in root file initialize_neutrinos(); cma::DEBUG("EVENT : Setup neutrinos "); } // Kinematic reconstruction (if they values aren't in the root file) if (m_useWprime){ wprimeReconstruction(); } if (m_useNeutrinos){ deepLearningPrediction(); // store features in map (easily access later) cma::DEBUG("EVENT : Deep learning "); } cma::DEBUG("EVENT : Setup Event "); return; } void Event::initialize_filters(){ /* Setup the filters */ m_filters.clear(); m_filters["goodVertices"] = **m_Flag_goodVertices; m_filters["eeBadScFilter"] = **m_Flag_eeBadScFilter; m_filters["HBHENoiseFilter"] = **m_Flag_HBHENoiseFilter; m_filters["HBHENoiseIsoFilter"] = **m_Flag_HBHENoiseIsoFilter; m_filters["globalTightHalo2016Filter"] = **m_Flag_globalTightHalo2016Filter; m_filters["EcalDeadCellTriggerPrimitiveFilter"] = **m_Flag_EcalDeadCellTriggerPrimitiveFilter; return; } void Event::initialize_triggers(){ /* Setup triggers */ m_triggers.clear(); m_triggers["HLT_Ele45_CaloIdVT_GsfTrkIdT_PFJet200_PFJet50"] = **m_HLT_Ele45_CaloIdVT_GsfTrkIdT_PFJet200_PFJet50; m_triggers["HLT_Ele50_CaloIdVT_GsfTrkIdT_PFJet165"] = **m_HLT_Ele50_CaloIdVT_GsfTrkIdT_PFJet165; m_triggers["HLT_Ele115_CaloIdVT_GsfTrkIdT"] = **m_HLT_Ele115_CaloIdVT_GsfTrkIdT; m_triggers["HLT_Mu40_Eta2P1_PFJet200_PFJet50"] = **m_HLT_Mu40_Eta2P1_PFJet200_PFJet50; m_triggers["HLT_Mu50"] = **m_HLT_Mu50; m_triggers["HLT_TkMu50"] = **m_HLT_TkMu50; m_triggers["HLT_PFHT800"] = **m_HLT_PFHT800; m_triggers["HLT_PFHT900"] = **m_HLT_PFHT900; m_triggers["HLT_AK8PFJet450"] = **m_HLT_AK8PFJet450; m_triggers["HLT_PFHT700TrimMass50"] = **m_HLT_PFHT700TrimMass50; m_triggers["HLT_PFJet360TrimMass30"] = **m_HLT_PFJet360TrimMass30; return; } void Event::initialize_truth(){ /* Setup truth information (MC and physics objects) */ m_truth_partons.clear(); unsigned int nPartons( (*m_mc_pt)->size() ); cma::DEBUG("EVENT : N Partons = "+std::to_string(nPartons)); // loop over truth partons unsigned int p_idx(0); for (unsigned int i=0; i<nPartons; i++){ Parton parton; parton.p4.SetPtEtaPhiE((*m_mc_pt)->at(i),(*m_mc_eta)->at(i),(*m_mc_phi)->at(i),(*m_mc_e)->at(i)); int status = (*m_mc_status)->at(i); int pdgId = (*m_mc_pdgId)->at(i); unsigned int abs_pdgId = std::abs(pdgId); parton.pdgId = pdgId; parton.status = status; // simple booleans for type parton.isWprime = ( abs_pdgId==9900213 ); parton.isVLQ = ( abs_pdgId==8000001 || abs_pdgId==7000001 ); parton.isTop = ( abs_pdgId==6 ); parton.isW = ( abs_pdgId==24 ); parton.isZ = ( abs_pdgId==23 ); parton.isHiggs = ( abs_pdgId==25 ); parton.isLepton = ( abs_pdgId>=11 && abs_pdgId<=16 ); parton.isQuark = ( abs_pdgId<7 ); if (parton.isLepton){ parton.isTau = ( abs_pdgId==15 ); parton.isMuon = ( abs_pdgId==13 ); parton.isElectron = ( abs_pdgId==11 ); parton.isNeutrino = ( abs_pdgId==12 || abs_pdgId==14 || abs_pdgId==16 ); } else if (parton.isQuark){ parton.isLight = ( abs_pdgId<5 ); parton.isBottom = ( abs_pdgId==5 ); } parton.index = p_idx; // index in vector of truth_partons parton.parent_idx = (*m_mc_parent_idx)->at(i); parton.child0_idx = (*m_mc_child0_idx)->at(i); parton.child1_idx = (*m_mc_child1_idx)->at(i); m_truth_partons.push_back( parton ); p_idx++; } m_truthMatchingTool->setTruthPartons(m_truth_partons); m_truthMatchingTool->buildWprimeSystem(); m_truth_wprime = m_truthMatchingTool->wprime(); // build the truth wprime decay chain return; } void Event::initialize_jets(){ /* Setup struct of jets (small-r) and relevant information * b-tagging: https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation80XReReco CSVv2L -0.5884 CSVv2M 0.4432 CSVv2T 0.9432 */ unsigned int nJets = (*m_jet_pt)->size(); m_jets.clear(); m_jets_iso.clear(); // jet collection for lepton 2D isolation for (const auto& btagWP : m_config->btagWkpts() ){ m_btag_jets[btagWP].clear(); } unsigned int idx(0); unsigned int idx_iso(0); for (unsigned int i=0; i<nJets; i++){ Jet jet; jet.p4.SetPtEtaPhiM( (*m_jet_pt)->at(i),(*m_jet_eta)->at(i),(*m_jet_phi)->at(i),(*m_jet_m)->at(i)); bool isGood(jet.p4.Pt()>50 && std::abs(jet.p4.Eta())<2.4); bool isGoodIso( jet.p4.Pt()>15 && std::abs(jet.p4.Eta())<2.4); if (!isGood && !isGoodIso) continue; jet.bdisc = (*m_jet_bdisc)->at(i); jet.deepCSV = (*m_jet_deepCSV)->at(i); jet.area = (*m_jet_area)->at(i); jet.uncorrE = (*m_jet_uncorrE)->at(i); jet.uncorrPt = (*m_jet_uncorrPt)->at(i); jet.index = idx; jet.isGood = isGood; if (isGood){ m_jets.push_back(jet); getBtaggedJets(jet); // only care about b-tagging for 'real' AK4 idx++; } if (isGoodIso){ m_jets_iso.push_back(jet); // used for 2D isolation idx_iso++; } } m_btag_jets_default = m_btag_jets.at(m_config->jet_btagWkpt()); return; } void Event::initialize_ljets(){ /* Setup struct of large-R jets and relevant information 0 :: Top (lepton Q < 0) 1 :: Anti-top (lepton Q > 0) */ unsigned int nLjets = (*m_ljet_pt)->size(); m_ljets.clear(); unsigned int idx(0); for (unsigned int i=0; i<nLjets; i++){ Ljet ljet; ljet.p4.SetPtEtaPhiM( (*m_ljet_pt)->at(i),(*m_ljet_eta)->at(i),(*m_ljet_phi)->at(i),(*m_ljet_m)->at(i)); ljet.softDropMass = (*m_ljet_SDmass)->at(i); ljet.tau1 = (*m_ljet_tau1)->at(i); ljet.tau2 = (*m_ljet_tau2)->at(i); ljet.tau3 = (*m_ljet_tau3)->at(i); ljet.tau21 = ljet.tau2 / ljet.tau1; ljet.tau32 = ljet.tau3 / ljet.tau2; //bool toptag = (ljet.softDropMass>105. && ljet.softDropMass<210 && ljet.tau32<0.65); // check if the AK8 is 'good' bool isGood(ljet.p4.Pt()>400. && fabs(ljet.p4.Eta())<2.4); // && toptag); if (!isGood) continue; ljet.charge = (*m_ljet_charge)->at(i); ljet.BEST_t = (*m_ljet_BEST_t)->at(i); ljet.BEST_w = (*m_ljet_BEST_w)->at(i); ljet.BEST_z = (*m_ljet_BEST_z)->at(i); ljet.BEST_h = (*m_ljet_BEST_h)->at(i); ljet.BEST_j = (*m_ljet_BEST_j)->at(i); ljet.BEST_class = (*m_ljet_BEST_class)->at(i); ljet.subjet0_bdisc = (*m_ljet_subjet0_bdisc)->at(i); ljet.subjet0_charge = (*m_ljet_subjet0_charge)->at(i); ljet.subjet0_mass = (*m_ljet_subjet0_mass)->at(i); ljet.subjet0_pt = (*m_ljet_subjet0_pt)->at(i); ljet.subjet1_bdisc = (*m_ljet_subjet1_bdisc)->at(i); ljet.subjet1_charge = (*m_ljet_subjet1_charge)->at(i); ljet.subjet1_mass = (*m_ljet_subjet1_mass)->at(i); ljet.subjet1_pt = (*m_ljet_subjet1_pt)->at(i); float subjet0_tau1(-999.); float subjet0_tau2(-999.); float subjet0_tau3(-999.); float subjet1_tau1(-999.); float subjet1_tau2(-999.); float subjet1_tau3(-999.); if (m_config->isGridFile()){ // older files will not have this option subjet0_tau1 = (*m_ljet_subjet0_tau1)->at(i); subjet0_tau2 = (*m_ljet_subjet0_tau2)->at(i); subjet0_tau3 = (*m_ljet_subjet0_tau3)->at(i); subjet1_tau1 = (*m_ljet_subjet1_tau1)->at(i); subjet1_tau2 = (*m_ljet_subjet1_tau2)->at(i); subjet1_tau3 = (*m_ljet_subjet1_tau3)->at(i); } ljet.subjet0_tau1 = subjet0_tau1; //(*m_ljet_subjet0_tau1)->at(i); ljet.subjet0_tau2 = subjet0_tau2; //(*m_ljet_subjet0_tau2)->at(i); ljet.subjet0_tau3 = subjet0_tau3; //(*m_ljet_subjet0_tau3)->at(i); ljet.subjet1_tau1 = subjet1_tau1; //(*m_ljet_subjet1_tau1)->at(i); ljet.subjet1_tau2 = subjet1_tau2; //(*m_ljet_subjet1_tau2)->at(i); ljet.subjet1_tau3 = subjet1_tau3; //(*m_ljet_subjet1_tau3)->at(i); ljet.target = -1; // not used in this analysis ljet.isGood = isGood; ljet.index = idx; ljet.area = (*m_ljet_area)->at(i); ljet.uncorrE = (*m_ljet_uncorrE)->at(i); ljet.uncorrPt = (*m_ljet_uncorrPt)->at(i); // Truth-matching to jet ljet.truth_partons.clear(); if (m_useTruth){ // && m_config->isTtbar()) { cma::DEBUG("EVENT : Truth match AK8"); // match subjets (and then the AK8 jet) to truth tops m_truthMatchingTool->matchJetToTruthTop(ljet); // match to partons cma::DEBUG("EVENT : ++ Ljet had top = "+std::to_string(ljet.isHadTop)+" for truth top "+std::to_string(ljet.matchId)); } // end truth matching ljet to partons m_ljets.push_back(ljet); idx++; } return; } void Event::initialize_leptons(){ /* Setup struct of lepton and relevant information */ m_leptons.clear(); m_electrons.clear(); m_muons.clear(); // Muons unsigned int nMuons = (*m_mu_pt)->size(); for (unsigned int i=0; i<nMuons; i++){ Lepton mu; mu.p4.SetPtEtaPhiE( (*m_mu_pt)->at(i),(*m_mu_eta)->at(i),(*m_mu_phi)->at(i),(*m_mu_e)->at(i)); bool isMedium = (*m_mu_id_medium)->at(i); bool isTight = (*m_mu_id_tight)->at(i); bool iso = customIsolation(mu); // 2D isolation cut between leptons & AK4 (need AK4 initialized first!) bool isGood(mu.p4.Pt()>60 && std::abs(mu.p4.Eta())<2.4 && isMedium && iso); if (!isGood) continue; mu.charge = (*m_mu_charge)->at(i); mu.loose = (*m_mu_id_loose)->at(i); mu.medium = isMedium; mu.tight = isTight; mu.iso = (*m_mu_iso)->at(i); mu.isGood = isGood; mu.isMuon = true; mu.isElectron = false; m_leptons.push_back(mu); } // Electrons unsigned int nElectrons = (*m_el_pt)->size(); for (unsigned int i=0; i<nElectrons; i++){ Lepton el; el.p4.SetPtEtaPhiE( (*m_el_pt)->at(i),(*m_el_eta)->at(i),(*m_el_phi)->at(i),(*m_el_e)->at(i)); bool isTightNoIso = (*m_el_id_tight_noIso)->at(i); bool iso = customIsolation(el); // 2D isolation cut between leptons & AK4 (need AK4 initialized first!) bool isGood(el.p4.Pt()>60 && std::abs(el.p4.Eta())<2.4 && isTightNoIso && iso); if (!isGood) continue; el.charge = (*m_el_charge)->at(i); el.loose = (*m_el_id_loose)->at(i); el.medium = (*m_el_id_medium)->at(i); el.tight = (*m_el_id_tight)->at(i); el.loose_noIso = (*m_el_id_loose_noIso)->at(i); el.medium_noIso = (*m_el_id_medium_noIso)->at(i); el.tight_noIso = isTightNoIso; el.isGood = isGood; el.isMuon = false; el.isElectron = true; m_leptons.push_back(el); } return; } void Event::initialize_neutrinos(){ /* Build the neutrinos */ m_neutrinos.clear(); Neutrino nu1; nu1.p4.SetPtEtaPhiM( m_met.p4.Pt(), 0, m_met.p4.Phi(), 0); // "dummy" value pz=0 int nlep = m_leptons.size(); if (nlep<1){ // not enough leptons to do reconstruction, so just create dummy value m_neutrinos.push_back(nu1); return; } m_neutrinoRecoTool->setObjects(m_leptons.at(0),m_met); if (m_neutrinoReco){ // reconstruct neutrinos! float pz = m_neutrinoRecoTool->execute(true); // standard reco; tool assumes 1-lepton final state float nuE = sqrt( pow(m_met.p4.Px(),2) + pow(m_met.p4.Py(),2) + pow(pz,2)); nu1.p4.SetPxPyPzE( m_met.p4.Px(), m_met.p4.Py(), pz, nuE ); nu1.isImaginary = m_neutrinoRecoTool->isImaginary(); float pz_samp = m_neutrinoRecoTool->execute(false); nu1.pz_sampling = pz_samp; nu1.pz_samplings = m_neutrinoRecoTool->pzSolutions(); m_neutrinos.push_back(nu1); } else{ // Assign neutrinos from root file m_neutrinos.push_back(nu1); // dummy value for now } return; } void Event::initialize_weights(){ /* Event weights */ m_nominal_weight = 1.0; m_weight_btag.clear(); if (m_isMC){ m_nominal_weight = 1.0; //(**m_weight_pileup) * (**m_weight_mc); m_nominal_weight *= (m_xsection) * (m_kfactor) * m_LUMI / (m_sumOfWeights); /* // event weights m_weight_btag["70"] = (**m_weight_btag_70); m_weight_btag["77"] = (**m_weight_btag_77); m_weight_btag_default = m_weight_btag[m_config->jet_btagWkpt()]; m_nominal_weight *= m_weight_btag_default; */ } return; } void Event::initialize_kinematics(){ /* Kinematic variables (HT, ST, MET) */ m_HT_ak4 = **m_HTAK4; m_HT_ak8 = **m_HTAK8; m_HT = 0.0; m_ST = 0.0; // Get hadronic transverse energy if (m_useJets){ // include small-R jet pT for (auto &small_jet : m_jets ){ m_HT += small_jet.p4.Pt(); } } else{ // include large-R jet pT for (auto &large_jet : m_ljets){ m_HT += large_jet.p4.Pt(); } } // set MET m_met.p4.SetPtEtaPhiM(**m_met_met,0.,**m_met_phi,0.); // Get MET and lepton transverse energy m_ST += m_HT; m_ST += m_met.p4.Pt(); if (m_useLeptons){ for (const auto& lep : m_leptons) m_ST += lep.p4.Pt(); } // transverse mass of the W (only relevant for 1-lepton) float mtw(0.0); if (m_leptons.size()>0){ Lepton lep = m_leptons.at(0); float dphi = m_met.p4.Phi() - lep.p4.Phi(); mtw = sqrt( 2 * lep.p4.Pt() * m_met.p4.Pt() * (1-cos(dphi)) ); } m_met.mtw = mtw; return; } bool Event::customIsolation( Lepton& lep ){ /* 2D isolation cut for leptons - Check that the lepton and nearest AK4 jet satisfies DeltaR() < 0.4 || pTrel>30 */ bool pass(false); //int min_index(-1); // index of AK4 closest to lep float drmin(100.0); // min distance between lep and AK4s float ptrel(0.0); // pTrel between lepton and AK4s if (m_jets_iso.size()<1) return false; // no AK4 -- event will fail anyway for (const auto& jet : m_jets_iso){ float dr = lep.p4.DeltaR( jet.p4 ); if (dr < drmin) { drmin = dr; ptrel = cma::ptrel( lep.p4,jet.p4 ); //min_index = jet.index; } } lep.drmin = drmin; lep.ptrel = ptrel; if (drmin > 0.4 || ptrel > 30) pass = true; return pass; } void Event::wprimeReconstruction(){ /* Access Wprime reconstruction tool */ m_wprime = {}; m_wprime_smp = {}; if (m_wprimeReco){ if (m_leptons.size()>0 && m_jets.size()>1){ Neutrino nu = m_neutrinos.at(0); m_wprimeTool->setLepton( m_leptons.at(0) ); m_wprimeTool->setNeutrino( nu ); m_wprimeTool->setJets( m_jets ); m_wprimeTool->setBtagJets( m_btag_jets_default ); m_wprime = m_wprimeTool->execute(); Neutrino nu_smp; float nuE = sqrt( pow(nu.p4.Px(),2) + pow(nu.p4.Py(),2) + pow(nu.pz_sampling,2)); nu_smp.p4.SetPxPyPzE( nu.p4.Px(), nu.p4.Py(), nu.pz_sampling, nuE ); m_wprimeTool->setNeutrino( nu_smp ); m_wprime_smp = m_wprimeTool->execute(); } } else{ } return; } void Event::getBtaggedJets( Jet& jet ){ /* Determine the b-tagging */ jet.isbtagged["L"] = false; jet.isbtagged["M"] = false; jet.isbtagged["T"] = false; if (jet.bdisc > m_CSVv2L){ jet.isbtagged["L"] = true; m_btag_jets["L"].push_back(jet.index); // 0 = index of this jet if (jet.bdisc > m_CSVv2M){ jet.isbtagged["M"] = true; m_btag_jets["M"].push_back(jet.index); if (jet.bdisc > m_CSVv2T){ jet.isbtagged["T"] = true; m_btag_jets["T"].push_back(jet.index); } } } return; } double Event::getSystEventWeight( const std::string &syst, const int weightIndex ){ /* Calculate the event weight given some systematic -- only call for nominal events and systematic weights -- for non-nominal tree systematics, use the nominal event weight @param syst Name of systematic (nominal or some weight systematic) @param weightIndex Index of btagging SF; default to -1 */ double syst_event_weight(1.0); if (syst.compare("nominal")==0){ // nominal event weight syst_event_weight = m_nominal_weight; } else if (syst.find("pileup")!=std::string::npos){ // pileup event weight syst_event_weight = (**m_weight_mc); syst_event_weight *= m_weight_btag_default; syst_event_weight *= (m_xsection) * (m_kfactor) * (m_LUMI); syst_event_weight /= (m_sumOfWeights); syst_event_weight *= **m_weightSystematicsFloats.at(syst); } else if (syst.find("leptonSF")!=std::string::npos){ // leptonSF event weight syst_event_weight = (**m_weight_pileup) * (**m_weight_mc); syst_event_weight *= m_weight_btag_default; syst_event_weight *= (m_xsection) * (m_kfactor) * (m_LUMI); syst_event_weight /= (m_sumOfWeights); syst_event_weight *= **m_weightSystematicsFloats.at(syst); } else if (syst.find("bTagSF")!=std::string::npos){ // bTagSF event weight -- check indices for eigenvector systematics syst_event_weight = (**m_weight_pileup) * (**m_weight_mc); syst_event_weight *= (m_xsection) * (m_kfactor) * (m_LUMI); syst_event_weight /= (m_sumOfWeights); } else{ // safety to catch something weird -- just return 1.0 cma::WARNING("EVENT : Passed systematic variation, "+syst+", to Event::getSystEventWeight() "); cma::WARNING("EVENT : that is inconsistent with the CyMiniAna options of "); cma::WARNING("EVENT : nominal, jvt, pileup, leptonSF, and bTagSF. "); cma::WARNING("EVENT : Returning a weight of 1.0. "); syst_event_weight = 1.0; } return syst_event_weight; } /*** RETURN PHYSICS INFORMATION ***/ std::vector<int> Event::btag_jets(const std::string &wkpt) const{ /* Small-R Jet b-tagging */ std::string tmp_wkpt(wkpt); if(m_btag_jets.find(wkpt) == m_btag_jets.end()){ cma::WARNING("EVENT : B-tagging working point "+wkpt+" does not exist."); cma::WARNING("EVENT : Return vector of b-tagged jets for default working point "+m_config->jet_btagWkpt()); tmp_wkpt = m_config->jet_btagWkpt(); } return m_btag_jets.at(tmp_wkpt); } void Event::deepLearningPrediction(){ /* Deep learning for neutrino eta -- VIPER -- Call this after neutrinos are reconstructed */ m_deepLearningTool->clear(); if (m_DNNinference){ cma::DEBUG("EVENT : Calculate DNN "); if (m_neutrinos.size()<1 || m_leptons.size()<1) // nothing to do return; m_deepLearningTool->clear(); m_deepLearningTool->setNeutrino( m_neutrinos.at(0) ); m_deepLearningTool->setMET( m_met ); m_deepLearningTool->setLepton( m_leptons.at(0) ); m_deepLearningTool->setJets( m_jets ); m_deepLearningTool->inference(); //m_leptons.at(0),m_met,m_jets m_neutrinos.at(0).viper = m_deepLearningTool->prediction(); } else if (m_DNNtraining){ // train on events with 1 truth-level neutrino from W boson // basic kinematic cuts on lepton, MET, jets cma::DEBUG("EVENT : DNN Training "); if (m_leptons.size()==1 && m_useTruth){ cma::DEBUG("EVENT : Begin loop over truth partons "); Parton true_nu; int n_wdecays2leptons(0); for (const auto& p : m_truth_partons){ if (p.isW && p.child0_idx>=0 && p.child1_idx>=0) { Parton child0 = m_truth_partons.at( p.child0_idx ); Parton child1 = m_truth_partons.at( p.child1_idx ); if (child0.isNeutrino) { n_wdecays2leptons++; true_nu = child0; } else if (child1.isNeutrino) { n_wdecays2leptons++; true_nu = child1; } } } // only want to train on single lepton events (reco & truth-level) if (n_wdecays2leptons==1){ m_deepLearningTool->setNeutrino( m_neutrinos.at(0) ); m_deepLearningTool->setTrueNeutrino( true_nu ); m_deepLearningTool->setMET( m_met ); m_deepLearningTool->setLepton( m_leptons.at(0) ); m_deepLearningTool->setJets( m_jets ); m_deepLearningTool->training(); } // end training if truth-level neutrino found } // end if at least 1 lepton and useTruth } // end if training DNN return; } std::map<std::string,double> Event::deepLearningFeatures(){ /* Return the DNN features to the outside world -- call after deepLearningPrediction() */ return m_deepLearningTool->features(); } /*** RETURN WEIGHTS ***/ float Event::weight_mc(){ return 1.0; //**m_weight_mc; } float Event::weight_pileup(){ return 1.0; //**m_weight_pileup; } float Event::weight_btag(const std::string &wkpt){ std::string tmp_wkpt(wkpt); if(m_weight_btag.find(wkpt) == m_weight_btag.end()){ cma::WARNING("EVENT : B-tagging working point "+wkpt+" does not exist"); cma::WARNING("EVENT : Return calo-jet b-tag SF for default working point "+m_config->jet_btagWkpt()); tmp_wkpt = m_config->jet_btagWkpt(); } return m_weight_btag[tmp_wkpt]; } // Get weight systematics std::map<std::string,float> Event::weightSystematicsFloats(){ /* systematics floats */ std::map<std::string,float> tmp_weightSystematicsFloats; for (const auto& wsf : m_weightSystematicsFloats) tmp_weightSystematicsFloats[wsf.first] = **wsf.second; return tmp_weightSystematicsFloats; } std::map<std::string,std::vector<float> > Event::weightSystematicsVectorFloats(){ /* weight systematics stored as vectors */ std::map<std::string,std::vector<float> > tmp_weightSystematicsVectorFloats; return tmp_weightSystematicsVectorFloats; } /*** RETURN EVENT INFORMATION ***/ void Event::truth(){ /* Do something with truth information (possibly change type and return information?) */ return; } /*** DELETE VARIABLES ***/ void Event::finalize(){ // delete variables cma::DEBUG("EVENT : Finalize() "); delete m_eventNumber; delete m_runNumber; delete m_lumiblock; if (m_useJets){ delete m_jet_pt; delete m_jet_eta; delete m_jet_phi; delete m_jet_m; delete m_jet_bdisc; delete m_jet_deepCSV; delete m_jet_area; delete m_jet_uncorrPt; delete m_jet_uncorrE; } if (m_useLargeRJets){ delete m_ljet_pt; delete m_ljet_eta; delete m_ljet_phi; delete m_ljet_m; delete m_ljet_tau1; delete m_ljet_tau2; delete m_ljet_tau3; delete m_ljet_charge; delete m_ljet_SDmass; delete m_ljet_subjet0_charge; delete m_ljet_subjet0_bdisc; delete m_ljet_subjet0_deepCSV; delete m_ljet_subjet0_pt; delete m_ljet_subjet0_mass; delete m_ljet_subjet1_charge; delete m_ljet_subjet1_bdisc; delete m_ljet_subjet1_deepCSV; delete m_ljet_subjet1_pt; delete m_ljet_subjet1_mass; delete m_ljet_area; delete m_ljet_uncorrPt; delete m_ljet_uncorrE; } if (m_useLeptons){ delete m_el_pt; delete m_el_eta; delete m_el_phi; delete m_el_e; delete m_el_charge; //delete m_el_iso; delete m_el_id_loose; delete m_el_id_medium; delete m_el_id_tight; delete m_el_id_loose_noIso; delete m_el_id_medium_noIso; delete m_el_id_tight_noIso; delete m_mu_pt; delete m_mu_eta; delete m_mu_phi; delete m_mu_e; delete m_mu_charge; delete m_mu_iso; delete m_mu_id_loose; delete m_mu_id_medium; delete m_mu_id_tight; } delete m_met_met; delete m_met_phi; delete m_HTAK8; delete m_HTAK4; delete m_HLT_Ele45_CaloIdVT_GsfTrkIdT_PFJet200_PFJet50; delete m_HLT_Ele50_CaloIdVT_GsfTrkIdT_PFJet165; delete m_HLT_Ele115_CaloIdVT_GsfTrkIdT; delete m_HLT_Mu40_Eta2P1_PFJet200_PFJet50; delete m_HLT_Mu50; delete m_HLT_PFHT800; delete m_HLT_PFHT900; delete m_HLT_AK8PFJet450; delete m_HLT_PFHT700TrimMass50; delete m_HLT_PFJet360TrimMass30; delete m_Flag_goodVertices; delete m_Flag_eeBadScFilter; delete m_Flag_HBHENoiseFilter; delete m_Flag_HBHENoiseIsoFilter; delete m_Flag_globalTightHalo2016Filter; delete m_Flag_EcalDeadCellTriggerPrimitiveFilter; if (m_isMC){ delete m_mc_pt; delete m_mc_eta; delete m_mc_phi; delete m_mc_e; delete m_mc_pdgId; delete m_mc_status; delete m_mc_isHadTop; /* delete m_weight_mc; delete m_weight_pileup; delete m_weight_pileup_UP; delete m_weight_pileup_DOWN; delete m_mc_ht; delete m_truth_jet_pt; delete m_truth_jet_eta; delete m_truth_jet_phi; delete m_truth_jet_e; delete m_truth_ljet_pt; delete m_truth_ljet_eta; delete m_truth_ljet_phi; delete m_truth_ljet_m; delete m_truth_ljet_charge; delete m_truth_ljet_subjet0_charge; delete m_truth_ljet_subjet0_bdisc; delete m_truth_ljet_subjet1_charge; delete m_truth_ljet_subjet1_bdisc; */ } // end isMC return; } // THE END
36.917306
146
0.643705
jsiado
47c25a172a351618765dc20a09321167ea17f565
9,246
cpp
C++
dlb_st2110/0.9/dlb_st2110/src/dlb_st2110_hardware.cpp
DolbyLaboratories/pmd_tool
4c6d27df5f531d488a627f96f489cf213cbf121a
[ "BSD-3-Clause" ]
11
2020-04-05T19:58:40.000Z
2022-02-04T19:18:12.000Z
dlb_st2110/0.9/dlb_st2110/src/dlb_st2110_hardware.cpp
DolbyLaboratories/pmd_tool
4c6d27df5f531d488a627f96f489cf213cbf121a
[ "BSD-3-Clause" ]
1
2020-02-25T22:08:30.000Z
2020-02-25T22:08:30.000Z
dlb_st2110/0.9/dlb_st2110/src/dlb_st2110_hardware.cpp
DolbyLaboratories/pmd_tool
4c6d27df5f531d488a627f96f489cf213cbf121a
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************ * dlb_st2110 * Copyright (c) 2021, Dolby Laboratories Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ #include <rivermax_api.h> #include "dlb_st2110_hardware.h" #include "dlb_st2110_logging.h" #define RMAX_CPUELT(_cpu) ((_cpu) / RMAX_NCPUBITS) #define RMAX_CPUMASK(_cpu) ((rmax_cpu_mask_t) 1 << ((_cpu) % RMAX_NCPUBITS)) #define RMAX_CPU_SET(_cpu, _cpusetp) \ do { \ size_t _cpu2 = (_cpu); \ if (_cpu2 < (8 * sizeof (rmax_cpu_set_t))) { \ (((rmax_cpu_mask_t *)((_cpusetp)->rmax_bits))[RMAX_CPUELT(_cpu2)] |= \ RMAX_CPUMASK(_cpu2)); \ } \ } while (0) static std::string exec(std::string cmd) { std::array<char, 128> buffer; std::string result; std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose); if (!pipe) { throw std::runtime_error("popen() failed!"); } while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { result += buffer.data(); } return result; } std::string PmcGet(const char *variable, const char *key) { char key_with_ws[256]; strncpy(key_with_ws,"\t", 256); strncat(key_with_ws, key, 256); strncat(key_with_ws, " ", 256); std::string cfgText = exec(std::string("sudo pmc -u -b 0 'GET ") + variable + std::string("'")); if (cfgText.length() == 0) { throw std::runtime_error("PmcGet Failed"); } std::string::size_type start = cfgText.rfind(key_with_ws) + strlen(key_with_ws); std::string::size_type end = cfgText.find("\n",start); std::string result = cfgText.substr(start,end-start); // remove all white space result.erase(remove_if(result.begin(),result.end(), isspace), result.end()); return(result); } ST2110Hardware::ST2110Hardware(std::string localInterface, unsigned int fs) { std::string tmpStr; int fd; struct ifreq ifr; struct timespec time; fd = socket(AF_INET, SOCK_DGRAM, 0); ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name, localInterface.c_str(), IFNAMSIZ-1); ioctl(fd, SIOCGIFADDR, &ifr); close(fd); if ((((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr).s_addr == 0) { throw std::runtime_error("Invalid Interface Name - Check interface is connected"); } srcIpStr = inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr); /* display result */ CLOG(INFO, HARDWARE_LOG) << "Local IP Address Selected: " << srcIpStr; interface = localInterface; CLOG(INFO, HARDWARE_LOG) << "Interface Selected: " << interface; tmpStr = PmcGet("DOMAIN", "domainNumber"); domain = std::stoi(tmpStr, NULL, 10); CLOG(INFO, HARDWARE_LOG) << "Using PTP Domain: " << domain; tmpStr = PmcGet("TIME_STATUS_NP", "gmPresent"); if (!tmpStr.compare("true")) { synched = true; CLOG(INFO, HARDWARE_LOG) << "PTP Grandmaster is present"; } else { synched = false; CLOG(INFO, HARDWARE_LOG) << "PTP Grandmaster is not present"; } gmIdentity = PmcGet("TIME_STATUS_NP", "gmIdentity"); // remove punctuation gmIdentity.erase(remove_if(gmIdentity.begin(), gmIdentity.end(), ispunct), gmIdentity.end()); // Insert hyphens and if (gmIdentity.size() != 16) { throw std::runtime_error("Grandmaster identity badly configured"); } gmIdentity.insert(2,"-"); gmIdentity.insert(5,"-"); gmIdentity.insert(8,"-"); gmIdentity.insert(11,"-"); gmIdentity.insert(14,"-"); gmIdentity.insert(17,"-"); gmIdentity.insert(20,"-"); CLOG(INFO, HARDWARE_LOG) << "Grandmaster Identity: " << gmIdentity; samplingFrequency = fs; CLOG(INFO, HARDWARE_LOG) << "Sampling Frequency: " << samplingFrequency; // Initialize Rivermax RiverMaxInit(); // Seed random number generator used for ssrc etc. clock_gettime(CLOCK_MONOTONIC, &time); srand((unsigned int)time.tv_nsec & 0xffffffff); CLOG(INFO, HARDWARE_LOG) << "RiverMax Initialized, Random Number Generator Seeded, Hardware Initialization complete"; } ST2110Hardware::~ST2110Hardware(void) { rmax_status_t rmaxStatus; struct timespec sleepTime; unsigned int timeOut = 100; // sleep time is 10ms sleepTime.tv_sec = 0; sleepTime.tv_nsec = 10000000; rmaxStatus = rmax_cleanup(); // Wait for a certain length of time for system to not be busy // If stuck then timeout with error while((rmaxStatus == RMAX_ERR_BUSY) && timeOut > 0) { clock_nanosleep(CLOCK_MONOTONIC, 0, &sleepTime, NULL); rmaxStatus = rmax_cleanup(); timeOut--; } if (timeOut == 0) { CLOG(WARNING, HARDWARE_LOG) << "rmax_cleanup timed out"; } else { CLOG(INFO, HARDWARE_LOG) << "rmax_cleanup complete"; } RmaxError("rmax_cleanup", rmaxStatus); } void ST2110Hardware::RiverMaxInit(void) { // Initialize Rivermax rmax_init_config init_config; int internal_thread_core = 1; memset(&init_config, 0, sizeof(init_config)); if (internal_thread_core > 0) { RMAX_CPU_SET(internal_thread_core, &init_config.cpu_mask); init_config.flags |= RIVERMAX_CPU_MASK; } else { std::cout << "Warning - no CPU affinity set!!!\n"; } rmax_status_t status = rmax_init(&init_config); RmaxError("rmax_init", status); } rmax_status_t rmaxErrorCodes[NUM_RMAX_ERR_CODES] = { RMAX_ERR_NO_HW_RESOURCES, RMAX_ERR_NO_FREE_CHUNK, RMAX_ERR_NO_CHUNK_TO_SEND, RMAX_ERR_HW_SEND_QUEUE_FULL, RMAX_ERR_NO_MEMORY, RMAX_ERR_NOT_INITIALAZED, RMAX_ERR_NOT_IMPLEMENTED, RMAX_ERR_NO_DEVICE, RMAX_ERR_BUSY, RMAX_ERR_CANCELLED, RMAX_ERR_HW_COMPLETION_ISSUE, RMAX_ERR_LICENSE_ISSUE, RMAX_ERR_UNKNOWN_ISSUE, RMAX_ERR_NO_ATTACH, RMAX_ERR_STEERING_ISSUE, RMAX_ERR_METHOD_NOT_SUPPORTED_BY_STREAM, RMAX_ERR_CHECKSUM_ISSUE, RMAX_ERR_DESTINATION_UNREACHABLE, RMAX_ERR_MEMORY_REGISTRATION, RMAX_ERR_NO_DEPENDENCY, RMAX_ERR_EXCEEDS_LIMIT, RMAX_ERR_UNSUPPORTED, RMAX_INVALID_PARAMETER_MIX }; const char rmaxErrorMessages[NUM_RMAX_ERR_CODES][RMAX_ERR_MSG_LEN] = { "NO HW RESOURCES", "NO FREE CHUNK", "NO CHUNK TO SEND", "HW SEND QUEUE FULL", "NO MEMORY", "NOT INITIALAZED", "NOT IMPLEMENTED", "NO DEVICE", "BUSY", "CANCELLED", "HW COMPLETION ISSUE", "LICENSE ISSUE", "UNKNOWN ISSUE", "NO ATTACH", "STEERING ISSUE", "METHOD NOT SUPPORTED BY STREAM", "CHECKSUM ISSUE", "DESTINATION UNREACHABLE", "MEMORY REGISTRATION", "NO DEPENDENCY", "EXCEEDS LIMIT", "UNSUPPORTED", "RMAX INVALID PARAMETER MIX" }; void ST2110Hardware::RmaxError(const char *msg, rmax_status_t error) { const unsigned int maxErrorMsgSize = 256; char errorMsg[maxErrorMsgSize]; unsigned int i; if ((error == RMAX_OK) || (error == RMAX_SIGNAL)) { return; } snprintf(errorMsg, maxErrorMsgSize, "Uknown Error Message #%u", error); if ((error >= RMAX_ERR_INVALID_PARAM_1) && (error <= RMAX_ERR_INVALID_PARAM_10)) { snprintf(errorMsg, maxErrorMsgSize, "Error: %s, Invalid Parameter %u\n", msg, error - RMAX_ERR_INVALID_PARAM_1 + 1); } else { for (i = 0 ; i < NUM_RMAX_ERR_CODES ; i++) { if (error == rmaxErrorCodes[i]) { snprintf(errorMsg, maxErrorMsgSize, "Error: %s, %s\n", msg, rmaxErrorMessages[i]); } } } throw(std::runtime_error(errorMsg)); }
32.442105
124
0.652498
DolbyLaboratories
47c30f2e4a346afa32e383094f6e32de924e1f01
5,742
cpp
C++
src/Buffer.cpp
twh2898/glpp
b413293b525d885fefd20fedb51988edf1999b70
[ "MIT" ]
null
null
null
src/Buffer.cpp
twh2898/glpp
b413293b525d885fefd20fedb51988edf1999b70
[ "MIT" ]
null
null
null
src/Buffer.cpp
twh2898/glpp
b413293b525d885fefd20fedb51988edf1999b70
[ "MIT" ]
null
null
null
#include "glpp/Buffer.hpp" namespace glpp { void Attribute::enable() const { glVertexAttribPointer(index, size, type, normalized, stride, pointer); glVertexAttribDivisor(index, divisor); glEnableVertexAttribArray(index); } void Attribute::disable() const { glDisableVertexAttribArray(index); } } namespace glpp { Buffer::Buffer(Target target) : target(target) { glGenBuffers(1, &buffer); } Buffer::Buffer(Buffer && other) : target(other.target), buffer(other.buffer) { other.buffer = 0; } Buffer & Buffer::operator=(Buffer && other) { target = other.target; buffer = other.buffer; other.buffer = 0; return *this; } Buffer::~Buffer() { if (buffer) glDeleteBuffers(1, &buffer); } Buffer::Target Buffer::getTarget() const { return target; } GLuint Buffer::getBufferId() const { return buffer; } void Buffer::bind() const { glBindBuffer(target, buffer); } void Buffer::unbind() const { glBindBuffer(target, 0); } void Buffer::bufferData(GLsizeiptr size, const void * data, Usage usage) { bind(); glBufferData(target, size, data, usage); } void Buffer::bufferSubData(GLintptr offset, GLsizeiptr size, const void * data) { bind(); glBufferSubData(target, offset, size, data); } } namespace glpp { AttributedBuffer::AttributedBuffer(const std::vector<Attribute> & attrib, Buffer && buffer) : attrib(attrib), buffer(std::move(buffer)) {} AttributedBuffer::AttributedBuffer(AttributedBuffer && other) : attrib(std::move(other.attrib)), buffer(std::move(other.buffer)) {} AttributedBuffer & AttributedBuffer::operator=(AttributedBuffer && other) { attrib = std::move(other.attrib); buffer = std::move(other.buffer); return *this; } void AttributedBuffer::bufferData(GLsizeiptr size, const void * data, Usage usage) { buffer.bufferData(size, data, usage); for (auto & a : attrib) { a.enable(); } } } namespace glpp { BufferArray::BufferArray() : elementBuffer(nullptr) { glGenVertexArrays(1, &array); } BufferArray::BufferArray(const std::vector<std::vector<Attribute>> & attributes) : BufferArray() { for (auto & attr : attributes) { Buffer buffer(Buffer::Array); buffers.emplace_back(attr, std::move(buffer)); } } BufferArray::BufferArray(std::vector<Buffer> && buffers) : BufferArray() { buffers = std::move(buffers); } BufferArray::BufferArray(BufferArray && other) : array(other.array), buffers(std::move(other.buffers)), elementBuffer(std::move(other.elementBuffer)) { other.array = 0; } BufferArray & BufferArray::operator=(BufferArray && other) { array = other.array; other.array = 0; buffers = std::move(other.buffers); elementBuffer = std::move(other.elementBuffer); return *this; } BufferArray::~BufferArray() { if (array) glDeleteVertexArrays(1, &array); } GLuint BufferArray::getArrayId() const { return array; } std::size_t BufferArray::size() const { return buffers.size(); } const std::vector<AttributedBuffer> & BufferArray::getBuffers() const { return buffers; } std::vector<AttributedBuffer> & BufferArray::getBuffers() { return buffers; } void BufferArray::bind() const { glBindVertexArray(array); } void BufferArray::unbind() const { glBindVertexArray(0); } void BufferArray::bufferData(size_t index, GLsizeiptr size, const void * data, Usage usage) { buffers[index].bufferData(size, data, usage); } void BufferArray::bufferSubData(size_t index, GLintptr offset, GLsizeiptr size, const void * data) { buffers[index].bufferSubData(offset, size, data); } void BufferArray::bufferElements(GLsizeiptr size, const void * data, Usage usage) { if (!elementBuffer) elementBuffer = std::make_unique<Buffer>(Buffer::Index); elementBuffer->bufferData(size, data, usage); } void BufferArray::drawArrays(Mode mode, GLint first, GLsizei count) const { bind(); glDrawArrays(mode, first, count); } void BufferArray::drawArraysInstanced(Mode mode, GLint first, GLsizei count, GLsizei primcount) const { bind(); glDrawArraysInstanced(mode, first, count, primcount); } void BufferArray::drawElements(Mode mode, GLsizei count, GLenum type, const void * indices) const { bind(); glDrawElements(mode, count, type, indices); } void BufferArray::drawElementsInstanced(Mode mode, GLsizei count, GLenum type, const void * indices, GLsizei primcount) const { bind(); glDrawElementsInstanced(mode, count, type, indices, primcount); } }
29.147208
88
0.547893
twh2898
47c3f83ad828e82b70371511ad1432f7cbc01dcc
229
hpp
C++
apps/smart_switch/messaging_config.hpp
ecrampton1/MspPeripheralmm
ae1f64cc785b9a3b994074e851e68c170aef613f
[ "MIT" ]
null
null
null
apps/smart_switch/messaging_config.hpp
ecrampton1/MspPeripheralmm
ae1f64cc785b9a3b994074e851e68c170aef613f
[ "MIT" ]
1
2021-03-07T14:18:31.000Z
2021-03-07T14:18:31.000Z
apps/smart_switch/messaging_config.hpp
ecrampton1/MspPeripheralmm
ae1f64cc785b9a3b994074e851e68c170aef613f
[ "MIT" ]
null
null
null
#ifndef MESSAGING_CONFIG_HPP_ #define MESSAGING_CONFIG_HPP_ static constexpr uint8_t NODEID = 12; #define FOR_ALL_INCOMING_MESSAGES(ACTION) \ ACTION( SwitchQuery ) \ ACTION( SwitchRequest ) #endif //MESSAGING_CONFIG_HPP_
16.357143
43
0.799127
ecrampton1
47c4f41adfef2f62a4ded2a00efa0df1d6622b27
4,605
cpp
C++
tests/testRoundOverflow.cpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
1
2019-05-10T02:50:50.000Z
2019-05-10T02:50:50.000Z
tests/testRoundOverflow.cpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
2
2020-10-28T03:44:51.000Z
2021-01-18T19:49:33.000Z
tests/testRoundOverflow.cpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
2
2018-08-31T14:02:47.000Z
2020-04-17T16:01:54.000Z
//--------------------------------------------------------------------------- // // Example of redistribution with Boost serialization and 2 Redistributions // (1 producer and 2 consumers) // // Matthieu Dreher // Argonne National Laboratory // 9700 S. Cass Ave. // Argonne, IL 60439 // mdreher@anl.gov // //-------------------------------------------------------------------------- #include <bredala/data_model/simplefield.hpp> #include <bredala/data_model/vectorfield.hpp> #include <bredala/data_model/arrayfield.hpp> #include <bredala/data_model/pconstructtype.h> #include <bredala/data_model/boost_macros.h> #include <bredala/transport/mpi/redist_round_mpi.h> #include "tools.hpp" using namespace decaf; using namespace std; void runTestParallel2RedistOverlap(int startSource, int nbSource, int startReceptors1, int nbReceptors1, unsigned long long nbParticle) { int size_world, rank; MPI_Comm_size(MPI_COMM_WORLD, &size_world); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (!isBetween(rank, startSource, nbSource) && !isBetween(rank, startReceptors1, nbReceptors1)) return; RedistRoundMPI *component1 = nullptr; unsigned int* buffer = nullptr; std::cout<<"Current rank : "<<rank<<std::endl; if (isBetween(rank, startSource, nbSource) || isBetween(rank, startReceptors1, nbReceptors1)) { std::cout <<"consutrcution for the first component ."<<std::endl; component1 = new RedistRoundMPI(startSource, nbSource, startReceptors1, nbReceptors1, MPI_COMM_WORLD, DECAF_REDIST_COLLECTIVE); } fprintf(stderr, "-------------------------------------\n" "Test with Redistribution component with overlapping...\n" "-------------------------------------\n"); if (isBetween(rank, startSource, nbSource)) { fprintf(stderr, "Running Redistribution test between %d producers and %d consumers\n", nbSource, nbReceptors1); // Initialisation of the positions buffer = new unsigned int[nbParticle]; // Creation of the first data model ArrayFieldu array1(buffer, nbParticle, 1, false); pConstructData container1; container1->appendData(std::string("pos"), array1, DECAF_POS, DECAF_PRIVATE, DECAF_SPLIT_DEFAULT, DECAF_MERGE_APPEND_VALUES); component1->process(container1, decaf::DECAF_REDIST_SOURCE); } // receiving at the first destination if (isBetween(rank, startReceptors1, nbReceptors1)) { fprintf(stderr, "Receiving at Receptor1...\n"); pConstructData result; component1->process(result, decaf::DECAF_REDIST_DEST); component1->flush(); // We still need to flush if not doing a get/put fprintf(stderr, "===========================\n" "Final Merged map has %u items (Expect %llu)\n" "Final Merged map has %zu fields (Expect 1)\n", result->getNbItems(), (nbParticle * nbSource) / nbReceptors1, result->getMap()->size()); result->printKeys(); //printMap(*result); fprintf(stderr, "===========================\n" "Simple test between %d producers and %d consumers completed\n", nbSource, nbReceptors1); } if (isBetween(rank, startSource, nbSource)) { component1->flush(); } if (component1) delete component1; if (buffer) delete [] buffer; fprintf(stderr, "-------------------------------------\n" "Test with Redistribution component with overlapping completed\n" "-------------------------------------\n"); } int main(int argc, char** argv) { MPI_Init(NULL, NULL); char processorName[MPI_MAX_PROCESSOR_NAME]; int size_world, rank, nameLen; MPI_Comm_size(MPI_COMM_WORLD, &size_world); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Get_processor_name(processorName,&nameLen); srand(time(NULL) + rank * size_world + nameLen); unsigned long long items; items = strtoull(argv[1], NULL, 10); fprintf(stderr, "Number of items loaded: %llu\n", items); runTestParallel2RedistOverlap(0, 5, 5, 2, items); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); return 0; }
32.659574
94
0.562215
tpeterka
47c66700d43402dc38bfb61fad5360d931f13a8e
2,047
cc
C++
cpp/common/logging_test.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
37
2017-06-09T13:55:23.000Z
2022-01-28T12:51:17.000Z
cpp/common/logging_test.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
null
null
null
cpp/common/logging_test.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
5
2017-06-09T13:55:26.000Z
2021-11-11T03:51:56.000Z
//***************************************************************** // Copyright 2015 MIT Lincoln Laboratory // Project: SPAR // Authors: OMD // Description: Unit tests for the logging stuff. // // Modifications: // Date Name Modification // ---- ---- ------------ // 16 May 2012 omd Original Version //***************************************************************** #define BOOST_TEST_MODULE LoggingTest #include "logging.h" #include <sstream> #include "test-init.h" using std::stringstream; // Tests that basic logging, where all logs end up in the same same log file, // work as expected. BOOST_AUTO_TEST_CASE(SingleFileLogPolicyWorks) { stringstream output; Log::SetOutputStream(&output); LOG(DEBUG) << "Message 1"; LOG(INFO) << "Message 2"; LOG(WARNING) << "Message 3"; LOG(ERROR) << "Message 4"; Log::SetApplicationLogLevel(WARNING); LOG(DEBUG) << "Should not be logged"; LOG(INFO) << "Should not be logged either"; LOG(WARNING) << "Message 5"; LOG(ERROR) << "Message 6"; // Now change the log level via preprocessor. That should cause all log // messages below ERROR to not even be compiled in! #undef MIN_LOG_LEVEL #define MIN_LOG_LEVEL 3 LOG(DEBUG) << "Not Logged"; LOG(INFO) << "Not Logged"; LOG(WARNING) << "Not Logged"; LOG(ERROR) << "Message 7"; std::string output_str = output.str(); BOOST_CHECK(output_str.find("Message 1\n") != std::string::npos); BOOST_CHECK(output_str.find("Message 2\n") != std::string::npos); BOOST_CHECK(output_str.find("Message 3\n") != std::string::npos); BOOST_CHECK(output_str.find("Message 4\n") != std::string::npos); BOOST_CHECK(output_str.find("Message 5\n") != std::string::npos); BOOST_CHECK(output_str.find("Message 6\n") != std::string::npos); BOOST_CHECK(output_str.find("Message 7\n") != std::string::npos); BOOST_CHECK(output_str.find("Should not") == std::string::npos); BOOST_CHECK(output_str.find("Not Logged") == std::string::npos); }
31.984375
77
0.609184
nathanawmk
47c6c005554922431087bdabdb6764600c4d0542
3,270
cpp
C++
src/BabylonImGui/src/inspector/inspector.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
277
2017-05-18T08:27:10.000Z
2022-03-26T01:31:37.000Z
src/BabylonImGui/src/inspector/inspector.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
77
2017-09-03T15:35:02.000Z
2022-03-28T18:47:20.000Z
src/BabylonImGui/src/inspector/inspector.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
37
2017-03-30T03:36:24.000Z
2022-01-28T08:28:36.000Z
#include <babylon/inspector/inspector.h> #include <iomanip> #include <sstream> // glad #include <glad/glad.h> #define GLFW_INCLUDE_NONE // GLFW #include <GLFW/glfw3.h> #ifdef _WIN32 #undef APIENTRY #define GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WGL #include <GLFW/glfw3native.h> #endif // ImGui #include <imgui.h> // ImGui GL2 #include <imgui_impl_glfw.h> #include <imgui_impl_opengl3.h> // ImGUI bindings and utils #include <imgui_utils/icons_font_awesome_5.h> #include <imgui_utils/imgui_utils.h> // BabylonCpp #include <babylon/misc/string_tools.h> // Inspector #include <babylon/inspector/actions/action_store.h> #include <babylon/inspector/components/actiontabs/action_tabs_component.h> #include <babylon/inspector/components/global_state.h> #include <babylon/inspector/components/sceneexplorer/scene_explorer_component.h> #ifdef _WIN32 // See warning about windows mixing dll and stl in this file! #include <babylon/core/logging/log_levels_statics.cpp.h> #endif namespace BABYLON { static ImFont* _fontRegular = nullptr; static ImFont* _fontSolid = nullptr; std::function<void(const std::string&)> Inspector::OnSampleChanged; Inspector::Inspector(GLFWwindow* glfwWindow, Scene* scene) // KK remove glfwWindow : _glfwWindow{glfwWindow} , _scene{scene} , _actionStore{std::make_unique<ActionStore>()} , _globalState{GlobalState::New()} , _sceneExplorerHost{nullptr} , _actionTabsHost{nullptr} { // Create action tabs IActionTabsComponentProps actionTabsComponentProps; actionTabsComponentProps.scene = scene; actionTabsComponentProps.globalState = _globalState; _actionTabsHost = std::make_unique<ActionTabsComponent>(actionTabsComponentProps); } Inspector::~Inspector() = default; Scene* Inspector::scene() const { return _scene; } void Inspector::setScene(Scene* scene) { _scene = scene; // Create Scene explorer ISceneExplorerComponentProps sceneExplorerComponentProps; sceneExplorerComponentProps.scene = scene; sceneExplorerComponentProps.globalState = _globalState; _sceneExplorerHost = std::make_unique<SceneExplorerComponent>(sceneExplorerComponentProps); // Create action tabs _actionTabsHost->setScene(scene); } void Inspector::render() { _renderInspector(); } void Inspector::_showFps() { char stats[1000]; sprintf(stats, "FPS: %.1lf", ImGui::GetIO().Framerate); // auto statsSize = ImGui::CalcTextSize(stats); // ImGui::SameLine(ImGui::GetContentRegionMax().x - statsSize.x); ImGui::Text("%s", stats); } void Inspector::_fileMenu() { } void Inspector::_addActions() { _actionStore->addAction("exit", ICON_FA_POWER_OFF, "Exit", "Alt+F4", []() {}); } void Inspector::_doMenuItem(InspectorAction& a, bool enabled) { if (ImGui::MenuItem(a.iconWithLabel.c_str(), a.shortcut, a.isSelected(), enabled)) { a.invoke(); } } void Inspector::_pushFonts() { ImGui::PushFont(_fontRegular); ImGui::PushFont(_fontSolid); } void Inspector::_popFonts() { ImGui::PopFont(); ImGui::PopFont(); } void Inspector::_renderInspector() { // Render the scene explorer if (_sceneExplorerHost) _sceneExplorerHost->render(); // Render the action tabs if (_actionTabsHost) _actionTabsHost->render(); } } // end of namespace BABYLON
23.191489
93
0.745872
sacceus
47c7d15a0ef1098622a38870faeb081adc0ac63e
6,780
cc
C++
federated/session_manager_proxy_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
federated/session_manager_proxy_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
federated/session_manager_proxy_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "federated/session_manager_proxy.h" #include <memory> #include <stdlib.h> #include <string> #include <time.h> #include <utility> #include <vector> #include <base/callback.h> #include <base/check.h> #include <base/memory/ptr_util.h> #include <base/memory/ref_counted.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <session_manager/dbus-proxy-mocks.h> #include "federated/utils.h" namespace federated { namespace { using ::testing::_; using ::testing::Invoke; using ::testing::Mock; using ::testing::SaveArg; using ::testing::StrictMock; using ::testing::Test; class MockSessionManagerObserver : public SessionManagerObserverInterface { public: ~MockSessionManagerObserver() = default; MOCK_METHOD(void, OnSessionStarted, (), (override)); MOCK_METHOD(void, OnSessionStopped, (), (override)); }; } // namespace class SessionManagerProxyTest : public Test { public: SessionManagerProxyTest() : mock_session_manager_interface_proxy_( new StrictMock<org::chromium::SessionManagerInterfaceProxyMock>()) { } SessionManagerProxyTest(const SessionManagerProxyTest&) = delete; SessionManagerProxyTest& operator=(const SessionManagerProxyTest&) = delete; void SetUp() override { EXPECT_CALL(*mock_session_manager_interface_proxy_, DoRegisterSessionStateChangedSignalHandler(_, _)) .WillOnce(SaveArg<0>(&session_state_changed_callback_)); session_manager_proxy_ = std::make_unique<SessionManagerProxy>( base::WrapUnique<org::chromium::SessionManagerInterfaceProxyInterface>( mock_session_manager_interface_proxy_)); } void TearDown() override { session_manager_proxy_.reset(); Mock::VerifyAndClearExpectations(mock_session_manager_interface_proxy_); } // Mocks the session state change signals void InvokeSessionStateChange(const std::string& session_state) { session_state_changed_callback_.Run(session_state); } SessionManagerProxy* session_manager_proxy() const { CHECK_NE(session_manager_proxy_, nullptr); return session_manager_proxy_.get(); } // Sets the primary session and the EXPECT_CALL of RetrievePrimarySession. void SetPrimarySession(const std::string& username, const std::string& sanitized_username) { primary_session_ = {username, sanitized_username}; EXPECT_CALL(*mock_session_manager_interface_proxy_, RetrievePrimarySession(_, _, _, _)) .Times(1) .WillOnce( Invoke(this, &SessionManagerProxyTest::RetrievePrimarySessionImpl)); } // Sets the session state and the EXPECT_CALL of RetrieveSessionState. void SetSessionState(const std::string& state) { session_state_ = state; EXPECT_CALL(*mock_session_manager_interface_proxy_, RetrieveSessionState(_, _, _)) .Times(1) .WillOnce( Invoke(this, &SessionManagerProxyTest::RetrieveSessionStateImpl)); } private: // Invoked when SessionManagerInterfaceProxyMock::RetrievePrimarySession() is // called. bool RetrievePrimarySessionImpl(std::string* const username, std::string* const sanitized_username, brillo::ErrorPtr* /* error */, int /* timeout_ms */) const { *username = primary_session_.first; // Set in SetPrimarySession(). *sanitized_username = primary_session_.second; return true; } // Invoked when SessionManagerInterfaceProxyMock::RetrieveSessionState() is // called. bool RetrieveSessionStateImpl(std::string* const state, brillo::ErrorPtr* /* error */, int /* timeout_ms */) const { *state = session_state_; // Set in SetSessionState(). return true; } // Primary session consists of username and sanitized_username. std::pair<std::string, std::string> primary_session_; std::string session_state_; org::chromium::SessionManagerInterfaceProxyMock* const mock_session_manager_interface_proxy_; std::unique_ptr<SessionManagerProxy> session_manager_proxy_; base::RepeatingCallback<void(const std::string& state)> session_state_changed_callback_; }; // Tests that GetSanitizedUsername can get the user_hash of current primary // session. TEST_F(SessionManagerProxyTest, GetSanitizedUsername) { SetPrimarySession("user1", "hash1"); EXPECT_EQ(session_manager_proxy()->GetSanitizedUsername(), "hash1"); SetPrimarySession("user2", "hash2"); EXPECT_EQ(session_manager_proxy()->GetSanitizedUsername(), "hash2"); } // Tests that RetrieveSessionState works. RetrieveSessionState can get whatever // session state, although only kSessionStartedState and kSessionStoppedState // are concerned. TEST_F(SessionManagerProxyTest, RetrieveSessionState) { SetSessionState(kSessionStartedState); EXPECT_EQ(session_manager_proxy()->RetrieveSessionState(), kSessionStartedState); SetSessionState(kSessionStoppedState); EXPECT_EQ(session_manager_proxy()->RetrieveSessionState(), kSessionStoppedState); SetSessionState("unknown_state"); EXPECT_EQ(session_manager_proxy()->RetrieveSessionState(), "unknown_state"); } // Tests that session_manager_proxy can invoke observers when session state // changes. TEST_F(SessionManagerProxyTest, OnSessionStateChanged) { StrictMock<MockSessionManagerObserver> mock_observer; session_manager_proxy()->AddObserver(&mock_observer); // Generates a random state array, records the counts of started and stopped // state. std::vector<std::string> state_vector; int started_state_count = 0; int stopped_state_count = 0; const std::vector<std::string> available_states = { kSessionStartedState, kSessionStoppedState, "unknown_state"}; static unsigned int seed = time(NULL) + 1234; for (size_t i = 0; i < 100; i++) { const int index = rand_r(&seed) % 3; if (index == 0) started_state_count++; else if (index == 1) stopped_state_count++; state_vector.push_back(available_states[index]); } // Each time OnSessionStateChanged with state = kSessionStartedState, // observer's OnSessionStarted is invoked. EXPECT_CALL(mock_observer, OnSessionStarted()).Times(started_state_count); // Each time OnSessionStateChanged with state = kSessionStoppedState, // observer's OnSessionStopped is invoked. EXPECT_CALL(mock_observer, OnSessionStopped()).Times(stopped_state_count); for (const auto& state : state_vector) { InvokeSessionStateChange(state); } } } // namespace federated
33.731343
80
0.725664
Toromino
47cf64f750b91e4cf5b82e79ad54c4b1f14cd3ac
3,947
cc
C++
pkg/src/bibliography/reference.cc
saaymeen/bib-parser
e1a5a2db7fa5dfef9b09c032beeeca6129043419
[ "Unlicense" ]
1
2020-06-12T10:33:56.000Z
2020-06-12T10:33:56.000Z
pkg/src/bibliography/reference.cc
saaymeen/bib-parser
e1a5a2db7fa5dfef9b09c032beeeca6129043419
[ "Unlicense" ]
null
null
null
pkg/src/bibliography/reference.cc
saaymeen/bib-parser
e1a5a2db7fa5dfef9b09c032beeeca6129043419
[ "Unlicense" ]
2
2020-06-12T10:31:41.000Z
2020-06-12T13:19:08.000Z
#include <string> #include <unordered_map> #include <vector> #include "bib-parser/bibliography/reference.h" using std::string; using std::unordered_map; using std::vector; using TUCSE::EntryType; using TUCSE::FieldType; using TUCSE::Reference; Reference::Reference(string const &citationKey, EntryType const entryType) : citationKey{citationKey}, entryType{entryType}, fields{} {}; EntryType Reference::getEntryType() const noexcept { return entryType; } void Reference::addField(FieldType const fieldType, string const &value) noexcept { fields.insert({fieldType, value}); } string Reference::getCitationKey() const noexcept { return citationKey; } unordered_map<FieldType, string> Reference::getFields() const noexcept { return fields; } std::string Reference::getFieldValue(FieldType const fieldType) const { return fields.at(fieldType); } bool Reference::isValid() const noexcept { bool valid{false}; vector<FieldType> requiredFieldTypes; switch (entryType) { case EntryType::Article: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Journal); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Book: requiredFieldTypes.push_back(FieldType::Title); break; case EntryType::Booklet: requiredFieldTypes.push_back(FieldType::Title); break; case EntryType::Conference: case EntryType::InProceedings: // Same as conference requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Booktitle); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::InBook: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Editor); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Chapter); requiredFieldTypes.push_back(FieldType::Pages); requiredFieldTypes.push_back(FieldType::Publisher); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::InCollection: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Booktitle); requiredFieldTypes.push_back(FieldType::Publisher); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Manual: requiredFieldTypes.push_back(FieldType::Title); break; case EntryType::MastersThesis: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::School); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Miscellaneous: valid = true; // Misc does not require any specific fields break; case EntryType::PHDThesis: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::School); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Proceedings: requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::TechReport: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Institution); requiredFieldTypes.push_back(FieldType::Year); break; case EntryType::Unpublished: requiredFieldTypes.push_back(FieldType::Author); requiredFieldTypes.push_back(FieldType::Title); requiredFieldTypes.push_back(FieldType::Note); break; default: valid = false; break; } if (requiredFieldTypes.empty() == false) { bool containsAll{true}; for (auto const &requiredFieldType : requiredFieldTypes) { if (fields.count(requiredFieldType) == 0) { containsAll = false; } } if (containsAll) { valid = true; } } return valid; }
25.62987
81
0.776032
saaymeen
47d20a53ccc40177b08696933123dd87db5c76d9
51,908
cc
C++
mysql-server/router/tests/component/test_routing_connection.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/router/tests/component/test_routing_connection.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/router/tests/component/test_routing_connection.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2018, 2020, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <fstream> #include <stdexcept> #include <thread> #include <gmock/gmock.h> #include <gtest/gtest.h> #ifdef RAPIDJSON_NO_SIZETYPEDEFINE // if we build within the server, it will set RAPIDJSON_NO_SIZETYPEDEFINE // globally and require to include my_rapidjson_size_t.h #include "my_rapidjson_size_t.h" #endif #include <rapidjson/document.h> #include "dim.h" #include "mock_server_rest_client.h" #include "mock_server_testutils.h" #include "mysql_session.h" #include "mysqlrouter/cluster_metadata.h" #include "mysqlrouter/rest_client.h" #include "random_generator.h" #include "rest_metadata_client.h" #include "router_component_test.h" #include "router_component_testutils.h" #include "tcp_port_pool.h" #define ASSERT_NO_ERROR(expr) \ ASSERT_THAT(expr, ::testing::Eq(std::error_code{})) using mysqlrouter::ClusterType; using mysqlrouter::MySQLSession; using namespace std::chrono_literals; static constexpr const char kMockServerConnectionsUri[] = "/api/v1/mock_server/connections/"; static const std::string kRestApiUsername("someuser"); static const std::string kRestApiPassword("somepass"); class ConfigGenerator { std::map<std::string, std::string> defaults_; std::string config_dir_; std::string metadata_cache_section_; std::string routing_primary_section_; std::string routing_secondary_section_; std::string monitoring_section_; std::vector<uint16_t> metadata_server_ports_; uint16_t router_rw_port_; uint16_t router_ro_port_; uint16_t monitoring_port_; std::string disconnect_on_metadata_unavailable_ = "&disconnect_on_metadata_unavailable=no"; std::string disconnect_on_promoted_to_primary_ = "&disconnect_on_promoted_to_primary=no"; std::chrono::milliseconds metadata_refresh_ttl_; public: ConfigGenerator(const std::map<std::string, std::string> &defaults, const std::string &config_dir, const std::vector<uint16_t> metadata_server_ports, uint16_t router_rw_port, uint16_t router_ro_port, uint16_t monitoring_port, std::chrono::milliseconds metadata_refresh_ttl) : defaults_(defaults), config_dir_(config_dir), metadata_server_ports_(metadata_server_ports), router_rw_port_(router_rw_port), router_ro_port_(router_ro_port), monitoring_port_{monitoring_port}, metadata_refresh_ttl_{metadata_refresh_ttl} {} void disconnect_on_metadata_unavailable(const std::string &value) { disconnect_on_metadata_unavailable_ = value; } void disconnect_on_promoted_to_primary(const std::string &value) { disconnect_on_promoted_to_primary_ = value; } // void metadata_refresh_ttl(unsigned ttl) { metadata_refresh_ttl_ = ttl; } void add_metadata_cache_section( std::chrono::milliseconds ttl, ClusterType cluster_type = ClusterType::GR_V2) { // NOT: Those tests are using bootstrap_server_addresses in the static // configuration which is now moved to the dynamic state file. This way we // are testing the backward compatibility of the old // bootstrap_server_addresses still working. If this is ever changed to // use // dynamic state file, a new test should be added to test that // bootstrap_server_addresses is still handled properly. const std::string cluster_type_str = (cluster_type == ClusterType::RS_V2) ? "ar" : "gr"; metadata_cache_section_ = "[logger]\n" "level = DEBUG\n\n" "[metadata_cache:test]\n" "cluster_type=" + cluster_type_str + "\n" "router_id=1\n" "bootstrap_server_addresses="; size_t i = 0; for (uint16_t port : metadata_server_ports_) { metadata_cache_section_ += "mysql://127.0.0.1:" + std::to_string(port); if (i < metadata_server_ports_.size() - 1) metadata_cache_section_ += ","; } metadata_cache_section_ += "\n" "user=mysql_router1_user\n" "metadata_cluster=test\n" "connect_timeout=1\n" "ttl=" + std::to_string(ttl.count() / 1000.0) + "\n\n"; } std::string get_metadata_cache_routing_section(uint16_t router_port, const std::string &role, const std::string &strategy, bool is_rw = false) { std::string result; if (is_rw) { result = "[routing:test_default_rw]\n" "bind_port=" + std::to_string(router_port) + "\n" + "destinations=metadata-cache://test/default?role=" + role + disconnect_on_metadata_unavailable_ + "\n" + "protocol=classic\n"; } else { result = "[routing:test_default_ro]\n" "bind_port=" + std::to_string(router_port) + "\n" + "destinations=metadata-cache://test/default?role=" + role + disconnect_on_metadata_unavailable_ + disconnect_on_promoted_to_primary_ + "\n" + "protocol=classic\n"; } if (!strategy.empty()) result += std::string("routing_strategy=" + strategy + "\n"); return result; } void add_routing_primary_section() { routing_primary_section_ = get_metadata_cache_routing_section( router_rw_port_, "PRIMARY", "round-robin", true); } void add_routing_secondary_section() { routing_secondary_section_ = get_metadata_cache_routing_section( router_ro_port_, "SECONDARY", "round-robin", false); } void add_routing_primary_and_secondary_section() { routing_secondary_section_ = get_metadata_cache_routing_section( router_ro_port_, "PRIMARY_AND_SECONDARY", "round-robin", false); } void add_monitoring_section(const std::string &config_dir) { std::string passwd_filename = mysql_harness::Path(config_dir).join("users").str(); monitoring_section_ = "[rest_api]\n" "[rest_metadata_cache]\n" "require_realm=somerealm\n" "[http_auth_realm:somerealm]\n" "backend=somebackend\n" "method=basic\n" "name=somename\n" "[http_auth_backend:somebackend]\n" "backend=file\n" "filename=" + passwd_filename + "\n" "[http_server]\n" "port=" + std::to_string(monitoring_port_) + "\n"; } std::string make_DEFAULT_section( const std::map<std::string, std::string> *params) { auto l = [params](const char *key) -> std::string { return (params->count(key)) ? std::string(key) + " = " + params->at(key) + "\n" : ""; }; return std::string("[DEFAULT]\n") + l("logging_folder") + l("plugin_folder") + l("runtime_folder") + l("config_folder") + l("data_folder") + l("keyring_path") + l("master_key_path") + l("master_key_reader") + l("master_key_writer") + "\n"; } std::string create_config_file( const std::map<std::string, std::string> *params, const std::string &directory) { Path file_path = Path(directory).join("mysqlrouter.conf"); std::ofstream ofs_config(file_path.str()); if (!ofs_config.good()) { throw(std::runtime_error("Could not create config file " + file_path.str())); } ofs_config << make_DEFAULT_section(params); ofs_config << metadata_cache_section_ << routing_primary_section_ << routing_secondary_section_ << monitoring_section_ << std::endl; ofs_config.close(); return file_path.str(); } std::string build_config_file(const std::string &temp_test_dir, ClusterType cluster_type, bool is_primary_and_secondary = false) { add_metadata_cache_section(metadata_refresh_ttl_, cluster_type); add_routing_primary_section(); add_monitoring_section(temp_test_dir); if (is_primary_and_secondary) { add_routing_primary_and_secondary_section(); } else { add_routing_secondary_section(); } init_keyring(defaults_, temp_test_dir); return create_config_file(&defaults_, config_dir_); } }; class RouterRoutingConnectionCommonTest : public RouterComponentTest { public: void SetUp() override { RouterComponentTest::SetUp(); mysql_harness::DIM &dim = mysql_harness::DIM::instance(); // RandomGenerator dim.set_RandomGenerator( []() { static mysql_harness::RandomGenerator rg; return &rg; }, [](mysql_harness::RandomGeneratorInterface *) {}); #if 1 { auto &cmd = launch_command( ProcessManager::get_origin().join("mysqlrouter_passwd").str(), {"set", mysql_harness::Path(temp_test_dir_.name()).join("users").str(), kRestApiUsername}, EXIT_SUCCESS, true); cmd.register_response("Please enter password", kRestApiPassword + "\n"); EXPECT_EQ(cmd.wait_for_exit(), 0); } #endif cluster_nodes_ports_ = { port_pool_.get_next_available(), // first is PRIMARY port_pool_.get_next_available(), port_pool_.get_next_available(), port_pool_.get_next_available(), port_pool_.get_next_available()}; cluster_nodes_http_ports_ = { port_pool_.get_next_available(), port_pool_.get_next_available(), port_pool_.get_next_available(), port_pool_.get_next_available(), port_pool_.get_next_available()}; router_rw_port_ = port_pool_.get_next_available(); router_ro_port_ = port_pool_.get_next_available(); monitoring_port_ = port_pool_.get_next_available(); config_generator_.reset(new ConfigGenerator( get_DEFAULT_defaults(), temp_conf_dir_.name(), {cluster_nodes_ports_[0]}, router_rw_port_, router_ro_port_, monitoring_port_, metadata_refresh_ttl_)); mock_http_hostname_ = "127.0.0.1"; mock_http_uri_ = kMockServerGlobalsRestUri; } auto &launch_router(uint16_t /* router_port */, const std::string &config_file, std::chrono::milliseconds wait_for_ready = 5s) { return ProcessManager::launch_router({"-c", config_file}, EXIT_SUCCESS, true, false, wait_for_ready); } auto &launch_server(uint16_t cluster_port, const std::string &json_file, uint16_t http_port, size_t number_of_servers = 5) { auto &cluster_node = ProcessManager::launch_mysql_server_mock( get_data_dir().join(json_file).str(), cluster_port, EXIT_SUCCESS, false, http_port); std::vector<uint16_t> nodes_ports; nodes_ports.resize(number_of_servers); std::copy_n(cluster_nodes_ports_.begin(), number_of_servers, nodes_ports.begin()); EXPECT_TRUE(MockServerRestClient(http_port).wait_for_rest_endpoint_ready()); set_mock_metadata(http_port, "", nodes_ports); return cluster_node; } void setup_cluster(const std::string &js_for_primary, unsigned number_of_servers, uint16_t /*my_port*/ = 0) { // launch cluster nodes for (unsigned port = 0; port < number_of_servers; ++port) { const std::string js_file = port == 0 ? js_for_primary : "rest_server_mock_with_gr.js"; cluster_nodes_.push_back( &launch_server(cluster_nodes_ports_[port], js_file, cluster_nodes_http_ports_[port], number_of_servers)); ASSERT_NO_FATAL_FAILURE( check_port_ready(*cluster_nodes_[port], cluster_nodes_ports_[port])); } } struct server_globals { bool primary_removed{false}; bool primary_failover{false}; bool secondary_failover{false}; bool secondary_removed{false}; bool cluster_partition{false}; bool MD_failed{false}; bool GR_primary_failed{false}; bool GR_health_failed{false}; server_globals &set_primary_removed() { primary_removed = true; return *this; } server_globals &set_primary_failover() { primary_failover = true; return *this; } server_globals &set_secondary_failover() { secondary_failover = true; return *this; } server_globals &set_secondary_removed() { secondary_removed = true; return *this; } server_globals &set_cluster_partition() { cluster_partition = true; return *this; } server_globals &set_MD_failed() { MD_failed = true; return *this; } server_globals &set_GR_primary_failed() { GR_primary_failed = true; return *this; } server_globals &set_GR_health_failed() { GR_health_failed = true; return *this; } }; void set_additional_globals(uint16_t http_port, const server_globals &globals) { auto json_doc = mock_GR_metadata_as_json("", cluster_nodes_ports_); JsonAllocator allocator; json_doc.AddMember("primary_removed", globals.primary_removed, allocator); json_doc.AddMember("primary_failover", globals.primary_failover, allocator); json_doc.AddMember("secondary_failover", globals.secondary_failover, allocator); json_doc.AddMember("secondary_removed", globals.secondary_removed, allocator); json_doc.AddMember("cluster_partition", globals.cluster_partition, allocator); json_doc.AddMember("MD_failed", globals.MD_failed, allocator); json_doc.AddMember("GR_primary_failed", globals.GR_primary_failed, allocator); json_doc.AddMember("GR_health_failed", globals.GR_health_failed, allocator); const auto json_str = json_to_string(json_doc); EXPECT_NO_THROW(MockServerRestClient(http_port).set_globals(json_str)); } TcpPortPool port_pool_; std::chrono::milliseconds metadata_refresh_ttl_{100}; std::chrono::milliseconds wait_for_cache_ready_timeout{ metadata_refresh_ttl_ + std::chrono::milliseconds(5000)}; std::chrono::milliseconds wait_for_cache_update_timeout{ metadata_refresh_ttl_ * 20}; std::unique_ptr<ConfigGenerator> config_generator_; TempDirectory temp_test_dir_; TempDirectory temp_conf_dir_; std::vector<uint16_t> cluster_nodes_ports_; std::vector<uint16_t> cluster_nodes_http_ports_; std::vector<ProcessWrapper *> cluster_nodes_; uint16_t router_rw_port_; uint16_t router_ro_port_; uint16_t monitoring_port_; // http properties std::string mock_http_hostname_; std::string mock_http_uri_; }; class RouterRoutingConnectionTest : public RouterRoutingConnectionCommonTest {}; static std::vector<std::string> vec_from_lines(const std::string &s) { std::vector<std::string> lines; std::istringstream lines_stream{s}; for (std::string line; std::getline(lines_stream, line);) { lines.push_back(line); } return lines; } /** * @test * Verify connections through router fail if metadata's schema-version is * too old. */ TEST_F(RouterRoutingConnectionTest, OldSchemaVersion) { // preparation // SCOPED_TRACE("// [prep] creating router config"); TempDirectory tmp_dir; config_generator_.reset(new ConfigGenerator( get_DEFAULT_defaults(), tmp_dir.name(), {cluster_nodes_ports_[0]}, router_rw_port_, router_ro_port_, monitoring_port_, metadata_refresh_ttl_)); SCOPED_TRACE("// [prep] launch the primary node on port " + std::to_string(cluster_nodes_ports_.at(0)) + " working also as metadata server"); cluster_nodes_.push_back(&launch_server(cluster_nodes_ports_.at(0), "metadata_old_schema.js", cluster_nodes_http_ports_[0])); SCOPED_TRACE("// [prep] launching router"); auto &router = launch_router(router_rw_port_, config_generator_->build_config_file( temp_test_dir_.name(), ClusterType::GR_V2), -1s); ASSERT_NO_FATAL_FAILURE(check_port_ready(router, router_rw_port_)); SCOPED_TRACE("// [prep] waiting " + std::to_string(wait_for_cache_ready_timeout.count()) + "ms until metadata is initialized (and failed)"); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_fetched( wait_for_cache_ready_timeout, metadata_status, [](const RestMetadataClient::MetadataStatus &cur) { return cur.refresh_failed > 0; })); // testing // SCOPED_TRACE("// [test] expect connecting clients to fail"); MySQLSession client; ASSERT_THROW(client.connect("127.0.0.1", router_rw_port_, "username", "password", "", ""), MySQLSession::Error); SCOPED_TRACE("// [test] expect router log to contain error message"); // posix RE has [0-9], but no \\d // simple RE has \\d, but no [0-9] constexpr const char log_msg_re[]{ #ifdef GTEST_USES_POSIX_RE "Unsupported metadata schema on .*\\. Expected Metadata Schema version " "compatible to [0-9]\\.[0-9]\\.[0-9], [0-9]\\.[0-9]\\.[0-9], got " "0\\.0\\.1" #else "Unsupported metadata schema on .*\\. Expected Metadata Schema version " "compatible to \\d\\.\\d\\.\\d, \\d\\.\\d\\.\\d, got 0\\.0\\.1" #endif }; ASSERT_THAT(vec_from_lines(router.get_full_logfile()), ::testing::Contains(::testing::ContainsRegex(log_msg_re))); } /** * @test * Verify that router doesn't start when * disconnect_on_promoted_to_primary has invalid value. */ TEST_F(RouterRoutingConnectionTest, IsRouterFailToStartWhen_disconnect_on_promoted_to_primary_invalid) { config_generator_->disconnect_on_promoted_to_primary( "&disconnect_on_promoted_to_primary=bogus"); auto &router = ProcessManager::launch_router( {"-c", config_generator_->build_config_file(temp_test_dir_.name(), ClusterType::GR_V2)}, EXIT_FAILURE, true, false, -1s); check_port_not_ready(router, router_ro_port_); } /** * @test * Verify that router doesn't start when * disconnect_on_metadata_unavailable has invalid value. */ TEST_F(RouterRoutingConnectionTest, IsRouterFailToStartWhen_disconnect_on_metadata_unavailable_invalid) { config_generator_->disconnect_on_metadata_unavailable( "&disconnect_on_metadata_unavailable=bogus"); auto &router = ProcessManager::launch_router( {"-c", config_generator_->build_config_file(temp_test_dir_.name(), ClusterType::GR_V2)}, EXIT_FAILURE, true, false, -1s); check_port_not_ready(router, router_ro_port_); } struct TracefileTestParam { std::string tracefile; ClusterType cluster_type; std::string param{}; TracefileTestParam(const std::string tracefile_, const ClusterType cluster_type_, const std::string param_ = "") : tracefile(tracefile_), cluster_type(cluster_type_), param(param_) {} }; class IsConnectionsClosedWhenPrimaryRemovedFromClusterTest : public RouterRoutingConnectionTest, public ::testing::WithParamInterface<TracefileTestParam> {}; /** * @test * Verify that all connections to Primary are closed when Primary is * removed from Cluster */ TEST_P(IsConnectionsClosedWhenPrimaryRemovedFromClusterTest, IsConnectionsClosedWhenPrimaryRemovedFromCluster) { TempDirectory tmp_dir("conf"); const std::string tracefile = GetParam().tracefile; config_generator_.reset(new ConfigGenerator( get_DEFAULT_defaults(), tmp_dir.name(), {cluster_nodes_ports_[0], cluster_nodes_ports_[1]}, router_rw_port_, router_ro_port_, monitoring_port_, metadata_refresh_ttl_)); SCOPED_TRACE("// launch the primary node on port " + std::to_string(cluster_nodes_ports_.at(0)) + " working also as metadata server"); cluster_nodes_.push_back(&launch_server(cluster_nodes_ports_[0], tracefile, cluster_nodes_http_ports_[0], 4)); SCOPED_TRACE("// launch the secondary node on port " + std::to_string(cluster_nodes_ports_.at(1)) + " working also as metadata server"); cluster_nodes_.push_back(&launch_server(cluster_nodes_ports_[1], tracefile, cluster_nodes_http_ports_[1], 4)); SCOPED_TRACE("// launch the rest of secondary cluster nodes"); for (unsigned port = 2; port < 4; ++port) { cluster_nodes_.push_back( &launch_server(cluster_nodes_ports_[port], tracefile, cluster_nodes_http_ports_[port], 4)); } SCOPED_TRACE("// launching router"); auto &router = launch_router( router_rw_port_, config_generator_->build_config_file( temp_test_dir_.name(), GetParam().cluster_type)); ASSERT_NO_FATAL_FAILURE(check_port_ready(router, router_rw_port_)); SCOPED_TRACE("// waiting " + std::to_string(wait_for_cache_ready_timeout.count()) + "ms until metadata is initialized"); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); SCOPED_TRACE("// connecting clients"); std::vector<std::pair<MySQLSession, uint16_t>> clients(2); for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_FATAL_FAILURE(client.connect("127.0.0.1", router_rw_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; client_and_port.second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } set_additional_globals(cluster_nodes_http_ports_[0], server_globals().set_primary_removed()); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_updated( wait_for_cache_update_timeout, metadata_status)); // verify that connections to PRIMARY are broken for (auto &client_and_port : clients) { auto &client = client_and_port.first; EXPECT_TRUE(wait_connection_dropped(client)); } } INSTANTIATE_TEST_SUITE_P( IsConnectionsClosedWhenPrimaryRemovedFromCluster, IsConnectionsClosedWhenPrimaryRemovedFromClusterTest, ::testing::Values( TracefileTestParam( "metadata_3_secondaries_server_removed_from_cluster_v2_gr.js", ClusterType::GR_V2), TracefileTestParam( "metadata_3_secondaries_server_removed_from_cluster.js", ClusterType::GR_V1))); class IsConnectionsClosedWhenSecondaryRemovedFromClusterTest : public RouterRoutingConnectionTest, public ::testing::WithParamInterface<TracefileTestParam> {}; /** * @test * Verify that all connections to Secondary are closed when Secondary is * removed from Cluster. * */ TEST_P(IsConnectionsClosedWhenSecondaryRemovedFromClusterTest, IsConnectionsClosedWhenSecondaryRemovedFromCluster) { const std::string tracefile = GetParam().tracefile; ASSERT_NO_FATAL_FAILURE(setup_cluster(tracefile, 4)); launch_router(router_rw_port_, config_generator_->build_config_file(temp_test_dir_.name(), GetParam().cluster_type)); SCOPED_TRACE("// connect clients"); std::vector<std::pair<MySQLSession, uint16_t>> clients(6); for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_FATAL_FAILURE(client.connect("127.0.0.1", router_ro_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; client_and_port.second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } SCOPED_TRACE("// removed secondary from mock-server on port " + std::to_string(cluster_nodes_http_ports_[0])); set_additional_globals(cluster_nodes_http_ports_[0], server_globals().set_secondary_removed()); // wait for metadata refresh RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); RestMetadataClient::MetadataStatus metadata_status; ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_updated( wait_for_cache_update_timeout, metadata_status)); SCOPED_TRACE("// verify that connections to SECONDARY_1 are broken"); for (auto &client_and_port : clients) { auto &client = client_and_port.first; uint16_t port = client_and_port.second; if (port == cluster_nodes_ports_[1]) { SCOPED_TRACE("// connections to aborted server fails"); EXPECT_TRUE(wait_connection_dropped(client)); } else { SCOPED_TRACE("// connection to server on port " + std::to_string(port) + " still succeeds"); try { std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; } catch (const std::exception &e) { FAIL() << e.what(); } } } } INSTANTIATE_TEST_SUITE_P( IsConnectionsClosedWhenSecondaryRemovedFromCluster, IsConnectionsClosedWhenSecondaryRemovedFromClusterTest, ::testing::Values( TracefileTestParam( "metadata_3_secondaries_server_removed_from_cluster_v2_gr.js", ClusterType::GR_V2), TracefileTestParam( "metadata_3_secondaries_server_removed_from_cluster.js", ClusterType::GR_V1))); class IsRWConnectionsClosedWhenPrimaryFailoverTest : public RouterRoutingConnectionTest, public ::testing::WithParamInterface<TracefileTestParam> {}; /** * @test * Verify that when Primary is demoted, then all RW connections * to that server are closed. */ TEST_P(IsRWConnectionsClosedWhenPrimaryFailoverTest, IsRWConnectionsClosedWhenPrimaryFailover) { const std::string tracefile = GetParam().tracefile; ASSERT_NO_FATAL_FAILURE(setup_cluster(tracefile, 4)); launch_router(router_ro_port_, config_generator_->build_config_file(temp_test_dir_.name(), GetParam().cluster_type)); // connect clients std::vector<std::pair<MySQLSession, uint16_t>> clients(2); for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_THROW(client.connect("127.0.0.1", router_rw_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; client_and_port.second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } set_additional_globals(cluster_nodes_http_ports_[0], server_globals().set_primary_failover()); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_updated( wait_for_cache_update_timeout, metadata_status)); // verify if RW connections to PRIMARY are closed for (auto &client_and_port : clients) { auto &client = client_and_port.first; EXPECT_TRUE(wait_connection_dropped(client)); } } INSTANTIATE_TEST_SUITE_P( IsRWConnectionsClosedWhenPrimaryFailover, IsRWConnectionsClosedWhenPrimaryFailoverTest, ::testing::Values( TracefileTestParam("metadata_3_secondaries_primary_failover_v2_gr.js", ClusterType::GR_V2), TracefileTestParam("metadata_3_secondaries_primary_failover.js", ClusterType::GR_V1))); class IsROConnectionsKeptWhenPrimaryFailoverTest : public RouterRoutingConnectionTest, public ::testing::WithParamInterface<TracefileTestParam> {}; /** * @test * Verify that when Primary is demoted, then RO connections * to that server are kept. */ TEST_P(IsROConnectionsKeptWhenPrimaryFailoverTest, IsROConnectionsKeptWhenPrimaryFailover) { const std::string tracefile = GetParam().tracefile; ASSERT_NO_FATAL_FAILURE(setup_cluster(tracefile, 4)); config_generator_->disconnect_on_promoted_to_primary(""); launch_router(router_ro_port_, config_generator_->build_config_file( temp_test_dir_.name(), GetParam().cluster_type, true)); // connect clients std::vector<std::pair<MySQLSession, uint16_t>> clients(4); for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_THROW(client.connect("127.0.0.1", router_ro_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; client_and_port.second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } set_additional_globals(cluster_nodes_http_ports_[0], server_globals().set_primary_failover()); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_updated( wait_for_cache_update_timeout, metadata_status)); // verify that RO connections to PRIMARY are kept for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_THROW(std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}); } } INSTANTIATE_TEST_SUITE_P( IsROConnectionsKeptWhenPrimaryFailover, IsROConnectionsKeptWhenPrimaryFailoverTest, ::testing::Values( TracefileTestParam("metadata_3_secondaries_primary_failover_v2_gr.js", ClusterType::GR_V2), TracefileTestParam("metadata_3_secondaries_primary_failover.js", ClusterType::GR_V1))); class RouterRoutingConnectionPromotedTest : public RouterRoutingConnectionCommonTest, public testing::WithParamInterface<TracefileTestParam> {}; /** * @test * Verify that when server is promoted from Secondary to Primary and * disconnect_on_promoted_to_primary is set to 'no' (default value) then * connections to that server are not closed. */ TEST_P(RouterRoutingConnectionPromotedTest, IsConnectionsToSecondaryKeptWhenPromotedToPrimary) { const std::string tracefile = GetParam().tracefile; const std::string param = GetParam().param; ASSERT_NO_FATAL_FAILURE(setup_cluster(tracefile, 4)); config_generator_->disconnect_on_promoted_to_primary(param); launch_router(router_ro_port_, config_generator_->build_config_file(temp_test_dir_.name(), GetParam().cluster_type)); // connect clients std::vector<std::pair<MySQLSession, uint16_t>> clients(6); for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_THROW(client.connect("127.0.0.1", router_ro_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; client_and_port.second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } server_globals globals; globals.primary_failover = true; set_additional_globals(cluster_nodes_http_ports_[0], globals); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_updated( wait_for_cache_update_timeout, metadata_status)); // verify that connections to SECONDARY_1 are kept (all RO connections // should NOT be closed) for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_THROW(std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}); } } INSTANTIATE_TEST_SUITE_P( RouterRoutingIsConnectionNotClosedWhenPromoted, RouterRoutingConnectionPromotedTest, ::testing::Values( TracefileTestParam("metadata_3_secondaries_primary_failover_v2_gr.js", ClusterType::GR_V2, "&disconnect_on_promoted_to_primary=no"), TracefileTestParam("metadata_3_secondaries_primary_failover.js", ClusterType::GR_V1, "&disconnect_on_promoted_to_primary=no"), TracefileTestParam("metadata_3_secondaries_primary_failover_v2_gr.js", ClusterType::GR_V2, ""), TracefileTestParam("metadata_3_secondaries_primary_failover.js", ClusterType::GR_V1, ""))); class IsConnectionToSecondaryClosedWhenPromotedToPrimaryTest : public RouterRoutingConnectionTest, public ::testing::WithParamInterface<TracefileTestParam> {}; /** * @test * Verify that when server is promoted from Secondary to Primary and * disconnect_on_promoted_to_primary is set to 'yes' then connections * to that server are closed. */ TEST_P(IsConnectionToSecondaryClosedWhenPromotedToPrimaryTest, IsConnectionToSecondaryClosedWhenPromotedToPrimary) { const std::string tracefile = GetParam().tracefile; ASSERT_NO_FATAL_FAILURE(setup_cluster(tracefile, 4)); config_generator_->disconnect_on_promoted_to_primary( "&disconnect_on_promoted_to_primary=yes"); launch_router(router_ro_port_, config_generator_->build_config_file(temp_test_dir_.name(), GetParam().cluster_type)); // connect clients std::vector<std::pair<MySQLSession, uint16_t>> clients(6); for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_THROW(client.connect("127.0.0.1", router_ro_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; client_and_port.second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } set_additional_globals(cluster_nodes_http_ports_[0], server_globals().set_primary_failover()); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_updated( wait_for_cache_update_timeout, metadata_status)); // verify that connections to SECONDARY_1 are closed for (auto &client_and_port : clients) { auto &client = client_and_port.first; uint16_t port = client_and_port.second; if (port == cluster_nodes_ports_[1]) EXPECT_TRUE(wait_connection_dropped(client)); else ASSERT_NO_THROW(std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}); } } INSTANTIATE_TEST_SUITE_P( IsConnectionToSecondaryClosedWhenPromotedToPrimary, IsConnectionToSecondaryClosedWhenPromotedToPrimaryTest, ::testing::Values( TracefileTestParam("metadata_3_secondaries_primary_failover_v2_gr.js", ClusterType::GR_V2), TracefileTestParam("metadata_3_secondaries_primary_failover.js", ClusterType::GR_V1))); class IsConnectionToMinorityClosedWhenClusterPartitionTest : public RouterRoutingConnectionTest, public ::testing::WithParamInterface<TracefileTestParam> {}; /** * @test * Verify that when GR is partitioned, then connections to servers that * are not in majority are closed. */ TEST_P(IsConnectionToMinorityClosedWhenClusterPartitionTest, IsConnectionToMinorityClosedWhenClusterPartition) { const std::string tracefile = GetParam().tracefile; /* * create cluster with 5 servers */ ASSERT_NO_FATAL_FAILURE(setup_cluster(tracefile, 5)); launch_router(router_ro_port_, config_generator_->build_config_file(temp_test_dir_.name(), GetParam().cluster_type)); // connect clients std::vector<std::pair<MySQLSession, uint16_t>> clients(10); // connect clients to Primary for (size_t i = 0; i < 2; ++i) { auto &client = clients[i].first; ASSERT_NO_FATAL_FAILURE(client.connect("127.0.0.1", router_rw_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; clients[i].second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } // connect clients to Secondaries for (size_t i = 2; i < 10; ++i) { auto &client = clients[i].first; ASSERT_NO_THROW(client.connect("127.0.0.1", router_ro_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; clients[i].second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } /* * Partition the cluster: * - 2 servers are ONLINE: Primary and Secondary_1 * - 3 servers are OFFLINE: Secondary_2, Secondary_3, Secondary_4 * * Connetions to OFFLINE servers should be closed. * Since only 2 servers are ONLINE (minority) connections to them should be * closed as well. */ set_additional_globals(cluster_nodes_http_ports_[0], server_globals().set_cluster_partition()); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_changed( wait_for_cache_update_timeout, metadata_status)); /* * Connections to servers that are offline should be closed * Connections to servers in minority should be closed as well */ for (auto &client_and_port : clients) { auto &client = client_and_port.first; EXPECT_TRUE(wait_connection_dropped(client)); } } INSTANTIATE_TEST_SUITE_P( IsConnectionToMinorityClosedWhenClusterPartition, IsConnectionToMinorityClosedWhenClusterPartitionTest, ::testing::Values( TracefileTestParam("metadata_4_secondaries_partitioning_v2_gr.js", ClusterType::GR_V2), TracefileTestParam("metadata_4_secondaries_partitioning.js", ClusterType::GR_V1))); class IsConnectionClosedWhenClusterOverloadedTest : public RouterRoutingConnectionCommonTest, public testing::WithParamInterface<TracefileTestParam> {}; /** * @test * Verity that when GR is overloaded and * disconnect_on_metadata_unavailable is set to 'yes' then all connection to * GR are closed */ TEST_P(IsConnectionClosedWhenClusterOverloadedTest, IsConnectionClosedWhenClusterOverloaded) { const std::string tracefile = GetParam().tracefile; ASSERT_NO_FATAL_FAILURE(setup_cluster(tracefile, 4)); config_generator_->disconnect_on_metadata_unavailable( "&disconnect_on_metadata_unavailable=yes"); launch_router(router_ro_port_, config_generator_->build_config_file(temp_test_dir_.name(), GetParam().cluster_type)); // connect clients std::vector<std::pair<MySQLSession, uint16_t>> clients(6); for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_FATAL_FAILURE(client.connect("127.0.0.1", router_ro_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; client_and_port.second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } /* * There is only 1 metadata server, so then primary * goes away, metadata is unavailable. */ MockServerRestClient(cluster_nodes_http_ports_[0]) .send_delete(kMockServerConnectionsUri); cluster_nodes_[0]->kill(); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_changed( wait_for_cache_update_timeout, metadata_status)); // verify that all connections are closed for (auto &client_and_port : clients) { auto &client = client_and_port.first; EXPECT_TRUE(wait_connection_dropped(client)); } } INSTANTIATE_TEST_SUITE_P( IsConnectionClosedWhenClusterOverloaded, IsConnectionClosedWhenClusterOverloadedTest, ::testing::Values(TracefileTestParam("metadata_3_secondaries_pass_v2_gr.js", ClusterType::GR_V2), TracefileTestParam("metadata_3_secondaries_pass.js", ClusterType::GR_V1))); class RouterRoutingConnectionMDUnavailableTest : public RouterRoutingConnectionCommonTest, public testing::WithParamInterface<TracefileTestParam> {}; /** * @test * Verify that when GR is overloaded and * disconnect_on_metadata_unavailable is set to 'no' (default value) then * connections to GR are NOT closed. */ TEST_P(RouterRoutingConnectionMDUnavailableTest, IsConnectionKeptWhenClusterOverloaded) { const std::string tracefile = GetParam().tracefile; const std::string param = GetParam().param; ASSERT_NO_FATAL_FAILURE(setup_cluster(tracefile, 4)); config_generator_->disconnect_on_promoted_to_primary(param); launch_router(router_ro_port_, config_generator_->build_config_file(temp_test_dir_.name(), GetParam().cluster_type)); // connect clients std::vector<std::pair<MySQLSession, uint16_t>> clients(6); for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_THROW(client.connect("127.0.0.1", router_ro_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; client_and_port.second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } /* * There is only 1 metadata server, so then primary * goes away, metadata is unavailable. */ MockServerRestClient(cluster_nodes_http_ports_[0]) .send_delete(kMockServerConnectionsUri); cluster_nodes_[0]->kill(); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_changed( wait_for_cache_update_timeout, metadata_status)); // verify if all connections are NOT closed for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_THROW(std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}); } } INSTANTIATE_TEST_SUITE_P( RouterRoutingIsConnectionNotClosedWhenMDUnavailable, RouterRoutingConnectionMDUnavailableTest, ::testing::Values( TracefileTestParam("metadata_3_secondaries_pass_v2_gr.js", ClusterType::GR_V2, "&disconnect_on_metadata_unavailable=no"), TracefileTestParam("metadata_3_secondaries_pass.js", ClusterType::GR_V1, "&disconnect_on_metadata_unavailable=no"), TracefileTestParam("metadata_3_secondaries_pass_v2_gr.js", ClusterType::GR_V2, ""), TracefileTestParam("metadata_3_secondaries_pass.js", ClusterType::GR_V1, ""))); using server_globals = RouterRoutingConnectionCommonTest::server_globals; struct MDRefreshTestParam { ClusterType cluster_type; std::string tracefile1; std::string tracefile2; server_globals globals; MDRefreshTestParam(ClusterType cluster_type_, std::string tracefile1_, std::string tracefile2_, server_globals globals_) : cluster_type(cluster_type_), tracefile1(tracefile1_), tracefile2(tracefile2_), globals(globals_) {} }; class RouterRoutingConnectionMDRefreshTest : public RouterRoutingConnectionCommonTest, public testing::WithParamInterface<MDRefreshTestParam> {}; /** * @test * Verify if connections are not closed when fetching metadata from * current metadata server fails, but fetching from subsequent metadata server * passes. * * 1. Start cluster with 1 Primary and 4 Secondary * 2. Establish 2 RW connections and 8 RO connections * 3. Fetching MD from Primary fails * 4. Fetching MD from Secondary passes * 5. Check if connections are still open. */ TEST_P(RouterRoutingConnectionMDRefreshTest, IsConnectionNotClosedWhenRrefreshFailedForParticularMDServer) { /* * Primary and first secondary are metadata-cache servers */ TempDirectory temp_dir("conf"); config_generator_.reset(new ConfigGenerator( get_DEFAULT_defaults(), temp_dir.name(), {cluster_nodes_ports_[0], cluster_nodes_ports_[1]}, router_rw_port_, router_ro_port_, monitoring_port_, metadata_refresh_ttl_)); // launch the primary node working also as metadata server cluster_nodes_.push_back(&launch_server(cluster_nodes_ports_[0], GetParam().tracefile1, cluster_nodes_http_ports_[0], 4)); // launch the secondary node working also as metadata server cluster_nodes_.push_back(&launch_server(cluster_nodes_ports_[1], GetParam().tracefile2, cluster_nodes_http_ports_[1], 4)); // launch the rest of secondary cluster nodes for (unsigned port = 2; port < 4; ++port) { cluster_nodes_.push_back(&launch_server( cluster_nodes_ports_[port], "rest_server_mock_with_gr.js", cluster_nodes_http_ports_[port], 4)); } config_generator_->disconnect_on_metadata_unavailable( "&disconnect_on_metadata_unavailable=yes"); launch_router(router_ro_port_, config_generator_->build_config_file(temp_test_dir_.name(), GetParam().cluster_type)); // connect clients std::vector<std::pair<MySQLSession, uint16_t>> clients(10); for (size_t i = 0; i < 2; ++i) { auto &client = clients[i].first; ASSERT_NO_THROW(client.connect("127.0.0.1", router_rw_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; clients[i].second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } for (size_t i = 2; i < 10; ++i) { auto &client = clients[i].first; ASSERT_NO_THROW(client.connect("127.0.0.1", router_ro_port_, "username", "password", "", "")); std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}; clients[i].second = static_cast<uint16_t>(std::stoul(std::string((*result)[0]))); } ASSERT_TRUE(MockServerRestClient(cluster_nodes_http_ports_[0]) .wait_for_rest_endpoint_ready()); set_additional_globals(cluster_nodes_http_ports_[0], GetParam().globals); RestMetadataClient::MetadataStatus metadata_status; RestMetadataClient rest_metadata_client(mock_http_hostname_, monitoring_port_, kRestApiUsername, kRestApiPassword); ASSERT_NO_ERROR(rest_metadata_client.wait_for_cache_updated( wait_for_cache_update_timeout, metadata_status)); // verify if all connections are NOT closed for (auto &client_and_port : clients) { auto &client = client_and_port.first; ASSERT_NO_THROW(std::unique_ptr<MySQLSession::ResultRow> result{ client.query_one("select @@port")}); } } MDRefreshTestParam steps[] = { MDRefreshTestParam(ClusterType::GR_V2, "metadata_3_secondaries_failed_to_update_v2_gr.js", "metadata_3_secondaries_pass_v2_gr.js", server_globals().set_MD_failed()), MDRefreshTestParam( ClusterType::GR_V1, "metadata_3_secondaries_failed_to_update.js", "metadata_3_secondaries_pass.js", server_globals().set_MD_failed()), MDRefreshTestParam(ClusterType::GR_V2, "metadata_3_secondaries_failed_to_update_v2_gr.js", "metadata_3_secondaries_pass_v2_gr.js", server_globals().set_GR_primary_failed()), MDRefreshTestParam(ClusterType::GR_V1, "metadata_3_secondaries_failed_to_update.js", "metadata_3_secondaries_pass.js", server_globals().set_GR_primary_failed()), MDRefreshTestParam(ClusterType::GR_V2, "metadata_3_secondaries_failed_to_update_v2_gr.js", "metadata_3_secondaries_pass_v2_gr.js", server_globals().set_GR_health_failed()), MDRefreshTestParam(ClusterType::GR_V1, "metadata_3_secondaries_failed_to_update.js", "metadata_3_secondaries_pass.js", server_globals().set_GR_health_failed())}; INSTANTIATE_TEST_SUITE_P(RouterRoutingIsConnectionNotDisabledWhenMDRefresh, RouterRoutingConnectionMDRefreshTest, testing::ValuesIn(steps)); int main(int argc, char *argv[]) { init_windows_sockets(); ProcessManager::set_origin(Path(argv[0]).dirname()); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
38.853293
80
0.678585
silenc3502
47d7d065dbf3721fde1de556c174656dad925aeb
391
cpp
C++
quadoutlet/retriggerablemonostable.cpp
980f/dro
571452d480ea6f428c16a016e629dc3722a7fc7d
[ "MIT" ]
null
null
null
quadoutlet/retriggerablemonostable.cpp
980f/dro
571452d480ea6f428c16a016e629dc3722a7fc7d
[ "MIT" ]
null
null
null
quadoutlet/retriggerablemonostable.cpp
980f/dro
571452d480ea6f428c16a016e629dc3722a7fc7d
[ "MIT" ]
null
null
null
#include "retriggerablemonostable.h" RetriggerableMonostable::RetriggerableMonostable(const BoolishRef &output, Ticks ticks) : Q(output),period(ticks){ } void RetriggerableMonostable::trigger(){ Q = 1; restart(period); } void RetriggerableMonostable::stop(){ Q = 0; freeze(); systicksRemaining = 0;//preclude restarting. } void RetriggerableMonostable::onDone(){ Q = 0; }
17.772727
89
0.7289
980f
c51780512e28374845c1afe517668cfdbb12b6e0
3,565
cpp
C++
src/runtime/Consistency.cpp
swiftcurrent2018/iris
7ae5567c8235137e4c10d6bb079f1a13a1c6342d
[ "BSD-3-Clause" ]
null
null
null
src/runtime/Consistency.cpp
swiftcurrent2018/iris
7ae5567c8235137e4c10d6bb079f1a13a1c6342d
[ "BSD-3-Clause" ]
null
null
null
src/runtime/Consistency.cpp
swiftcurrent2018/iris
7ae5567c8235137e4c10d6bb079f1a13a1c6342d
[ "BSD-3-Clause" ]
null
null
null
#include "Consistency.h" #include "Debug.h" #include "Device.h" #include "Command.h" #include "Kernel.h" #include "Mem.h" #include "Scheduler.h" #include "Task.h" namespace brisbane { namespace rt { Consistency::Consistency(Scheduler* scheduler) { scheduler_ = scheduler; } Consistency::~Consistency() { } void Consistency::Resolve(Task* task) { for (int i = 0; i < task->ncmds(); i++) { Command* cmd = task->cmd(i); if (cmd->type() != BRISBANE_CMD_KERNEL) continue; //TODO: handle others cmds Resolve(task, cmd); } } void Consistency::Resolve(Task* task, Command* cmd) { // if (task->parent()) return; Device* dev = task->dev(); Kernel* kernel = cmd->kernel(); brisbane_poly_mem* polymems = cmd->polymems(); int npolymems = cmd->npolymems(); std::map<int, KernelArg*>* args = kernel->args(); int mem_idx = 0; for (std::map<int, KernelArg*>::iterator I = args->begin(), E = args->end(); I != E; ++I) { KernelArg* arg = I->second; Mem* mem = I->second->mem; if (!mem) continue; if (npolymems) ResolveWithPolymem(task, cmd, mem, arg, polymems + mem_idx); else ResolveWithoutPolymem(task, cmd, mem, arg); mem_idx++; } } void Consistency::ResolveWithPolymem(Task* task, Command* cmd, Mem* mem, KernelArg* arg, brisbane_poly_mem* polymem) { Device* dev = task->dev(); Kernel* kernel = cmd->kernel(); size_t off = 0UL; size_t size = 0UL; if (arg->mode == brisbane_r) { off = polymem->typesz * polymem->r0; size = polymem->typesz * (polymem->r1 - polymem->r0 + 1); } else if (arg->mode == brisbane_w) { off = polymem->typesz * polymem->w0; size = polymem->typesz * (polymem->w1 - polymem->w0 + 1); } else if (arg->mode == brisbane_rw) { off = polymem->r0 < polymem->w0 ? polymem->r0 : polymem->w0; size = polymem->typesz * (polymem->r1 > polymem->w1 ? polymem->r1 - off + 1 : polymem->w1 - off + 1); off *= polymem->typesz; } else _error("not supprt mode[0x%x]", arg->mode); Device* owner = mem->Owner(off, size); if (!owner || mem->IsOwner(off, size, dev)) return; Task* task_d2h = new Task(scheduler_->platform()); task_d2h->set_system(); Command* d2h = Command::CreateD2H(task, mem, off, size, (char*) mem->host_inter() + off); task_d2h->AddCommand(d2h); scheduler_->SubmitTaskDirect(task_d2h, owner); task_d2h->Wait(); Command* h2d = arg->mode == brisbane_r ? Command::CreateH2DNP(task, mem, off, size, (char*) mem->host_inter() + off) : Command::CreateH2D(task, mem, off, size, (char*) mem->host_inter() + off); dev->ExecuteH2D(h2d); _trace("kernel[%s] memcpy[%lu] [%s] -> [%s]", kernel->name(), mem->uid(), owner->name(), dev->name()); task_d2h->Release(); Command::Release(h2d); } void Consistency::ResolveWithoutPolymem(Task* task, Command* cmd, Mem* mem, KernelArg* arg) { Device* dev = task->dev(); Kernel* kernel = cmd->kernel(); Device* owner = mem->Owner(); if (!owner || mem->IsOwner(0, mem->size(), dev)) return; Task* task_d2h = new Task(scheduler_->platform()); task_d2h->set_system(); Command* d2h = Command::CreateD2H(task_d2h, mem, 0, mem->size(), mem->host_inter()); task_d2h->AddCommand(d2h); scheduler_->SubmitTaskDirect(task_d2h, owner); task_d2h->Wait(); Command* h2d = Command::CreateH2D(task, mem, 0, mem->size(), mem->host_inter()); dev->ExecuteH2D(h2d); _trace("kernel[%s] memcpy[%lu] [%s] -> [%s]", kernel->name(), mem->uid(), owner->name(), dev->name()); task_d2h->Release(); Command::Release(h2d); } } /* namespace rt */ } /* namespace brisbane */
31.548673
118
0.634222
swiftcurrent2018
c51a1573724e40f8ea13aecbcc47a8ed7cec6052
737
cpp
C++
AIC/AIC'20 - Level 2 Training Contests/Contest #10/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AIC/AIC'20 - Level 2 Training Contests/Contest #10/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AIC/AIC'20 - Level 2 Training Contests/Contest #10/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
//https://vjudge.net/contest/436257#problem/B #include <bits/stdc++.h> using namespace std; bool solve(string A, string B) { if (A == B) { return true; } string X = A, Y = B; sort(X.begin(), X.end()); sort(Y.begin(), Y.end()); if ((A.size() & 1) || (X != Y)) { return false; } string A1 = A.substr(0, A.size() / 2), A2 = A.substr(A.size() / 2, A.size() / 2); string B1 = B.substr(0, B.size() / 2), B2 = B.substr(B.size() / 2, B.size() / 2); return ((solve(A1, B1) && solve(A2, B2)) || (solve(A1, B2) && solve(A2, B1))); } int main () { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); string A, B; cin >> A >> B; cout << (solve(A, B) ? "YES" : "NO"); }
27.296296
85
0.497965
MaGnsio
c51a70404b06ddc50ef0b305ed28bc0d083e84be
1,708
cpp
C++
ESP01_NowSender/src/esp_now_ext/esp_now_ext.cpp
Pliskin707/ESPNOW_SmartHome
6d09049fd39a4995e0cb4fb647aa9c260253f7aa
[ "MIT" ]
null
null
null
ESP01_NowSender/src/esp_now_ext/esp_now_ext.cpp
Pliskin707/ESPNOW_SmartHome
6d09049fd39a4995e0cb4fb647aa9c260253f7aa
[ "MIT" ]
2
2021-12-23T14:48:25.000Z
2021-12-23T23:49:06.000Z
ESP01_NowSender/src/esp_now_ext/esp_now_ext.cpp
Pliskin707/ESPNOW_SmartHome
6d09049fd39a4995e0cb4fb647aa9c260253f7aa
[ "MIT" ]
null
null
null
#include "esp_now_ext.hpp" EspNowExtClass EspNowExt; static uint8_t _txRetries = 0; static struct { uint8_t txRetriesRemaining; uint8_t len; mac dest; const uint8_t * data; } _txPackage = {0, 0, {0}, nullptr}; bool EspNowExtClass::begin (const uint8_t txRetries) { if (esp_now_init() == 0) { _txRetries = txRetries; esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER); // priority is given to the station interface (not the SoftAP) esp_now_register_send_cb(&this->_txCallback); return true; } return false; } int EspNowExtClass::addPeer (const uint8_t mac[6]) { return esp_now_add_peer((uint8_t *) mac, ESP_NOW_ROLE_IDLE, 11, nullptr, 0); // from the documentation: "The peer's Role does not affect any function, but only stores the Role information for the application layer." } int EspNowExtClass::send (const mac destination, const void * data, const uint8_t len) { _txPackage.txRetriesRemaining = _txRetries; _txPackage.len = len; memcpy(_txPackage.dest, destination, sizeof(mac)); _txPackage.data = (const uint8_t *) data; return esp_now_send((uint8_t *) _txPackage.dest, (uint8_t *) _txPackage.data, _txPackage.len); } int EspNowExtClass::send (const void * data, const uint8_t len) { return this->send(nullptr, data, len); } void EspNowExtClass::_txCallback (uint8_t * mac_addr, uint8_t status) { if ((status != 0) && _txPackage.txRetriesRemaining) EspNowExt._retrySend(); } void EspNowExtClass::_retrySend (void) { if (_txPackage.txRetriesRemaining) _txPackage.txRetriesRemaining--; esp_now_send((uint8_t *) _txPackage.dest, (uint8_t *) _txPackage.data, _txPackage.len); }
29.448276
221
0.70726
Pliskin707
c51a83a62be319f139825ca299feea89f5fbee2d
91,003
cpp
C++
src/plugins/DreamColor/DreamColorCalib.cpp
SchademanK/Ookala
9a5112e1d3067d589c150fb9c787ae36801a67dc
[ "MIT" ]
null
null
null
src/plugins/DreamColor/DreamColorCalib.cpp
SchademanK/Ookala
9a5112e1d3067d589c150fb9c787ae36801a67dc
[ "MIT" ]
null
null
null
src/plugins/DreamColor/DreamColorCalib.cpp
SchademanK/Ookala
9a5112e1d3067d589c150fb9c787ae36801a67dc
[ "MIT" ]
null
null
null
// -------------------------------------------------------------------------- // $Id: DreamColorCalib.cpp 135 2008-12-19 00:49:58Z omcf $ // -------------------------------------------------------------------------- // Copyright (c) 2008 Hewlett-Packard Development Company, L.P. // // 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 <math.h> #include <vector> #include <algorithm> #ifdef _WIN32 #include <time.h> #endif #include "Dict.h" #include "DictHash.h" #include "PluginRegistry.h" #include "PluginChain.h" #include "DataSavior.h" #include "Sensor.h" #include "Ddc.h" #include "Color.h" #include "Interpolate.h" #include "plugins/DreamColor/DreamColorSpaceInfo.h" #include "plugins/DreamColor/DreamColorCtrl.h" #include "plugins/WsLut/WsLut.h" #include "DreamColorCalib.h" namespace Ookala { struct DataPoint { Yxy measuredYxy; Rgb linearRgb; uint32_t backlightReg[4]; }; }; // ===================================== // // DreamColorCalib // // ------------------------------------- Ookala::DreamColorCalib::DreamColorCalib(): Plugin() { setName("DreamColorCalib"); mNumGraySamples = 16; } // ------------------------------------- Ookala::DreamColorCalib::DreamColorCalib(const DreamColorCalib &src): Plugin(src) { mNumGraySamples = src.mNumGraySamples; } // ------------------------------------- // // virtual Ookala::DreamColorCalib::~DreamColorCalib() { } // ---------------------------- // Ookala::DreamColorCalib & Ookala::DreamColorCalib::operator=(const DreamColorCalib &src) { if (this != &src) { Plugin::operator=(src); mNumGraySamples = src.mNumGraySamples; } return *this; } // ------------------------------------- // // virtual bool Ookala::DreamColorCalib::checkCalibRecord(CalibRecordDictItem *calibRec) { DreamColorCalibRecord *myCalibRec; if (calibRec->getCalibrationPluginName() != std::string("DreamColorCalib")) { return false; } myCalibRec = dynamic_cast<DreamColorCalibRecord *>(calibRec); if (!myCalibRec) { return false; } // Check the preset and the brightness register on the // display. // // XXX: We should really be scanning by EDID here, but // we're not serializing that yet, so just pick a display // for now. if (!mRegistry) { setErrorString("No Registry in DreamColorCalib."); return false; } std::vector<Plugin *> plugins = mRegistry->queryByName("DreamColorCtrl"); if (plugins.empty()) { setErrorString("No DreamColorCtrl plugin found."); return false; } DreamColorCtrl *disp = dynamic_cast<DreamColorCtrl *>(plugins[0]); if (!disp) { setErrorString("No DreamColorCtrl plugin found."); return false; } // Go ahead and just re-enumerate now, in case this hasn't happened, // or someone has been re-plugging their displays. disp->enumerate(); // Now check the display to see how its' doing. uint32_t currCsIdx, regValues[4]; if (!disp->getColorSpace(currCsIdx)) { setErrorString("Unable to get color space from display."); return false; } if (!disp->getBacklightRegRaw(regValues[0], regValues[1], regValues[2], regValues[3])) { setErrorString("Unable to get backlight registers from display."); return false; } if (myCalibRec->getPreset() != currCsIdx) { setErrorString("Color space preset does not match calibration."); return false; } if (myCalibRec->getBrightnessReg() != regValues[3]) { setErrorString("Color space brightness does not match calibration."); return false; } return true; } // ------------------------------------- // // protected void Ookala::DreamColorCalib::gatherOptions(PluginChain *chain) { std::vector<Plugin *> plugins; DictHash *hash; Dict *dict; DictItem *item; IntDictItem *intItem; DoubleArrayDictItem *doubleArrayItem; // Reset default values mNumGraySamples = 16; // Look for the proper dict if (!mRegistry) { return; } plugins = mRegistry->queryByName("DictHash"); if (plugins.empty()) { return; } hash = dynamic_cast<DictHash *>(plugins[0]); if (!hash) { return; } dict = hash->getDict(chain->getDictName()); if (dict == NULL) { return; } // Look for the items we care about item = dict->get("DreamColorCalib::graySamples"); intItem = dynamic_cast<IntDictItem *>(item); if (intItem) { mNumGraySamples = intItem->get(); // Just for sanity... if (mNumGraySamples > 1024) { mNumGraySamples = 1024; } } // Figure out measurement tolerances. Look in the provided dictionary for: // // DreamColorCalib::whiteTolerance (vec3, Yxy) -> same value for +- // DreamColorCalib::redTolerance (vec2, xy) -> same value for +- // DreamColorCalib::greenTolerance (vec2, xy) -> same value for +- // DreamColorCalib::blueTolerance (vec2, xy) -> same value for +- // DreamColorCalib::whiteTolerancePlus (vec3, Yxy) -> White + tolerance // DreamColorCalib::whiteToleranceMinus (vec3, Yxy) -> White - tolerance // // DreamColorCalib::redTolerancePlus (vec2, xy) -> Red + tolerance // DreamColorCalib::redToleranceMinus (vec2, xy) -> Red - tolerance // // DreamColorCalib::greenTolerancePlus (vec2, xy) -> Green + tolerance // DreamColorCalib::greenToleranceMinus (vec2, xy) -> Green - tolerance // // DreamColorCalib::blueTolerancePlus (vec2, xy) -> Blue + tolerance // DreamColorCalib::blueToleranceMinus (vec2, xy) -> Blue - tolerance mWhiteTolerancePlus.Y = 1.0; mWhiteToleranceMinus.Y = mWhiteTolerancePlus.x = mWhiteToleranceMinus.x = mWhiteTolerancePlus.y = mWhiteToleranceMinus.y = 0.0025; mRedTolerancePlus.x = mRedToleranceMinus.x = mRedTolerancePlus.y = mRedToleranceMinus.y = 0.0025; mGreenTolerancePlus.x = mGreenToleranceMinus.x = mGreenTolerancePlus.y = mGreenToleranceMinus.y = 0.0025; mBlueTolerancePlus.x = mBlueToleranceMinus.x = mBlueTolerancePlus.y = mBlueToleranceMinus.y = 0.0025; // White user tolerances item = dict->get("DreamColorCalib::whiteTolerance"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 3) { mWhiteTolerancePlus.Y = mWhiteToleranceMinus.Y = (doubleArrayItem->get())[0]; mWhiteTolerancePlus.x = mWhiteToleranceMinus.x = (doubleArrayItem->get())[1]; mWhiteTolerancePlus.y = mWhiteToleranceMinus.y = (doubleArrayItem->get())[2]; } } } item = dict->get("DreamColorCalib::whiteTolerancePlus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 3) { mWhiteTolerancePlus.Y = (doubleArrayItem->get())[0]; mWhiteTolerancePlus.x = (doubleArrayItem->get())[1]; mWhiteTolerancePlus.y = (doubleArrayItem->get())[2]; } } } item = dict->get("DreamColorCalib::whiteToleranceMinus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 3) { mWhiteToleranceMinus.Y = (doubleArrayItem->get())[0]; mWhiteToleranceMinus.x = (doubleArrayItem->get())[1]; mWhiteToleranceMinus.y = (doubleArrayItem->get())[2]; } } } // Red user tolerances item = dict->get("DreamColorCalib::redTolerance"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mRedTolerancePlus.x = mRedToleranceMinus.x = (doubleArrayItem->get())[0]; mRedTolerancePlus.y = mRedToleranceMinus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::redTolerancePlus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mRedTolerancePlus.x = (doubleArrayItem->get())[0]; mRedTolerancePlus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::redToleranceMinus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mRedToleranceMinus.x = (doubleArrayItem->get())[0]; mRedToleranceMinus.y = (doubleArrayItem->get())[1]; } } } // Green user tolerances item = dict->get("DreamColorCalib::greenTolerance"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mGreenTolerancePlus.x = mGreenToleranceMinus.x = (doubleArrayItem->get())[0]; mGreenTolerancePlus.y = mGreenToleranceMinus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::greenTolerancePlus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mGreenTolerancePlus.x = (doubleArrayItem->get())[0]; mGreenTolerancePlus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::greenToleranceMinus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mGreenToleranceMinus.x = (doubleArrayItem->get())[0]; mGreenToleranceMinus.y = (doubleArrayItem->get())[1]; } } } // Blue user tolerances item = dict->get("DreamColorCalib::blueTolerance"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mBlueTolerancePlus.x = mBlueToleranceMinus.x = (doubleArrayItem->get())[0]; mBlueTolerancePlus.y = mBlueToleranceMinus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::blueTolerancePlus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mBlueTolerancePlus.x = (doubleArrayItem->get())[0]; mBlueTolerancePlus.y = (doubleArrayItem->get())[1]; } } } item = dict->get("DreamColorCalib::blueToleranceMinus"); if (item) { doubleArrayItem = dynamic_cast<DoubleArrayDictItem *>(item); if (doubleArrayItem) { if (doubleArrayItem->get().size() >= 2) { mBlueToleranceMinus.x = (doubleArrayItem->get())[0]; mBlueToleranceMinus.y = (doubleArrayItem->get())[1]; } } } } // ------------------------------------- // // protected std::vector<Ookala::DreamColorSpaceInfo> Ookala::DreamColorCalib::gatherTargets(PluginChain *chain) { std::vector<DreamColorSpaceInfo> targets; std::vector<Plugin *> plugins; DictHash *hash; Dict *dict; StringArrayDictItem *nameListItem; std::vector<std::string> nameList; if (!mRegistry) { return targets; } plugins = mRegistry->queryByName("DictHash"); if (plugins.empty()) { setErrorString("No DictHash found"); return targets; } hash = dynamic_cast<DictHash *>(plugins[0]); if (!hash) { setErrorString("No DictHash cast"); return targets; } dict = hash->getDict(chain->getDictName()); if (dict == NULL) { setErrorString("No chain dict found."); return targets; } nameListItem = dynamic_cast<StringArrayDictItem *>( dict->get("DreamColorCalib::targets")); if (!nameListItem) { return targets; } nameList = nameListItem->get(); for (std::vector<std::string>::iterator name = nameList.begin(); name != nameList.end(); ++name) { DreamColorSpaceInfo *targetItem = dynamic_cast<DreamColorSpaceInfo *>(dict->get(*name)); if (!targetItem) { continue; } // If we're not the first one, check the device/connection id if (!targets.empty()) { if (targets[0].getConnId() != targetItem->getConnId()) { continue; } } targets.push_back(*targetItem); } return targets; } // ------------------------------------- // // virtual protected bool Ookala::DreamColorCalib::gatherPlugins(PluginData &pi, PluginChain *chain) { std::vector<Plugin *>plugins; setErrorString(""); if (mRegistry == NULL) { setErrorString("No registry found."); return false; } // Check for a DreamColorCtrl plugins = mRegistry->queryByName("DreamColorCtrl"); if (plugins.empty()) { setErrorString("No DreamColorCtrl plugin found."); return false; } pi.disp = dynamic_cast<DreamColorCtrl *>(plugins[0]); if (!(pi.disp)) { setErrorString("No DreamColorCtrl plugin found."); return false; } pi.dispId = 0; // Check for a sensor in the chain bool testReg = true; plugins = chain->queryByAttribute("sensor"); if (!plugins.empty()) { pi.sensor = dynamic_cast<Sensor *>(plugins[0]); if ((pi.sensor) != NULL) { testReg = false; } } if (testReg) { plugins = mRegistry->queryByAttribute("sensor"); if (!plugins.empty()) { pi.sensor = dynamic_cast<Sensor *>(plugins[0]); if ((pi.sensor) == NULL) { setErrorString("No sensor found."); return false; } } else { setErrorString("No sensor found."); return false; } } // And make sure the sensor is ready to go - it's ok to enumerate // sensors if we haven't done that yet (pi.sensor)->actionTaken(SENSOR_ACTION_DETECT, chain); if ( (pi.sensor)->sensors().empty() ) { setErrorString("No sensors found."); return false; } if (!(pi.sensor)->actionNeeded(chain).empty()) { setErrorString("Sensor is not ready for measuring."); return false; } pi.sensorId = 0; // Check for a color space plugin - it's build it, so it had // best be there, less extreme badness has occurred. plugins = mRegistry->queryByName("Color"); if (plugins.empty()) { setErrorString("No Color plugin found."); return false; } pi.color = dynamic_cast<Color *>(plugins[0]); if (!(pi.color)) { setErrorString("No Color plugin found."); return false; } // Similarly, for an interpolator plugins = mRegistry->queryByName("Interpolate"); if (plugins.empty()) { setErrorString("No Interpolate plugin found."); return false; } pi.interp = dynamic_cast<Interpolate *>(plugins[0]); if (!(pi.interp)) { setErrorString("No Interpolate plugin found."); return false; } // Make sure we have a WsLut plugin as well; and that it // has some data plugins = mRegistry->queryByName("WsLut"); if (plugins.empty()) { setErrorString("No WsLut plugin found."); return false; } pi.lut = dynamic_cast<WsLut *>(plugins[0]); if (!pi.lut) { setErrorString("No WsLut plugin found."); return false; } if (pi.lut->luts().empty()) { setErrorString("WsLut plugin has not Luts available."); return false; } return true; } // ------------------------------------- // // virtual protected bool Ookala::DreamColorCalib::_run(PluginChain *chain) { PluginData pi; DreamColorCalibrationData calib; Yxy goalWhite; Npm panelNpm; uint32_t backlightReg[4]; // Mapping from the display connection id to the preset // state that the device is in when we start out. std::map<uint32_t, uint32_t> origPresets; setErrorString(""); gatherOptions(chain); if (!gatherPlugins(pi, chain)) { return false; } // Gather all the calibration targets we're going to try // and deal with. NOTE: we're not going to accept targets // on different devices for now. std::vector<DreamColorSpaceInfo> targets = gatherTargets(chain); printf("%d targets to calibrate\n", (int)targets.size()); if (targets.size() == 0) { return true; } // Run over all the targets and record the initial state of // the preset for the displays we're going to touch for (std::vector<DreamColorSpaceInfo>::iterator theTarget = targets.begin(); theTarget != targets.end(); ++theTarget) { std::map<uint32_t, uint32_t>::iterator thePreset; thePreset = origPresets.find((*theTarget).getConnId()); if (thePreset == origPresets.end()) { uint32_t csIdx; if (pi.disp->getColorSpace(csIdx, (*theTarget).getConnId(), chain)) { origPresets[(*theTarget).getConnId()] = csIdx; } } } // Run over all our targets. If we have multiple targets, we don't need // to re-measure the gray ramp each time. Just do it once and that should // be sufficient. std::map<double, double> grayRampR, grayRampG, grayRampB; for (uint32_t targetIdx=0; targetIdx<targets.size(); ++targetIdx) { if (wasCancelled(pi, chain, false)) return false; if (chain) { char buf[1024]; #ifdef _WIN32 sprintf_s(buf, 1023, "Calibrating target %d of %d", targetIdx+1, (int)targets.size()); #else sprintf(buf, "Calibrating target %d of %d", targetIdx+1, (int)targets.size()); #endif chain->setUiString("Ui::status_string_major", std::string(buf)); chain->setUiString("Ui::status_string_minor", std::string("")); } // Set the target primaries + white in the display if (chain) { chain->setUiYxy("Ui::target_red_Yxy", targets[targetIdx].getRed()); chain->setUiYxy("Ui::target_green_Yxy", targets[targetIdx].getGreen()); chain->setUiYxy("Ui::target_blue_Yxy", targets[targetIdx].getBlue()); chain->setUiYxy("Ui::target_white_Yxy", targets[targetIdx].getWhite()); } // Restruct data for the approprate format calib.setColorSpaceInfo(targets[targetIdx]); pi.dispId = targets[targetIdx].getConnId(); goalWhite = targets[targetIdx].getWhite(); // Switch into the color space if interest if (!pi.disp->setColorSpace(targets[targetIdx].getPresetId(), pi.dispId)) { setErrorString( std::string("Unable to select calibrated color space. ") + pi.disp->errorString() ); return false; } if (!idle(5, chain)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, false)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Disable color processing if (!pi.disp->setColorProcessingEnabled(false, pi.dispId)) { setErrorString( pi.disp->errorString() ); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (chain) { chain->setUiString("Ui::status_string_minor", "Enabling pattern generator."); } // Turn on the pattern generator - take care to disable // it when we return in this method then. if (!pi.disp->setPatternGeneratorEnabled(true, pi.dispId)) { setErrorString("ERROR: Can't enable pattern generator."); pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } printf("Waiting %d seconds...\n", pi.disp->patternGeneratorEnableTime(pi.dispId)); if (!idle(pi.disp->patternGeneratorEnableTime(pi.dispId), chain)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, NULL); } return false; } if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (chain) { chain->setUiString("Ui::status_string_minor", "Calibrating backlight."); } // Run the backlight processing loop + hang onto the registers if (!backlightLoop(pi, chain, goalWhite, backlightReg, pi.panelWhite)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } calib.setRegP0(backlightReg[0]); calib.setRegP1(backlightReg[1]); calib.setRegP2(backlightReg[2]); calib.setRegBrightness(backlightReg[3]); if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (chain) { chain->setUiString("Ui::status_string_minor", "Measuring primaries for matrix correction."); } // Measure the primaries + find the native NPM if (!measurePrimaries(pi, chain, pi.panelRed, pi.panelGreen, pi.panelBlue)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (!pi.color->computeNpm(pi.panelRed, pi.panelGreen, pi.panelBlue, pi.panelWhite, panelNpm)) { setErrorString("Unable to compute native NPM."); pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } printf("Actual white: %f %f %f\n", pi.panelWhite.Y, pi.panelWhite.x, pi.panelWhite.y); // Compute the 3x3 if (!compute3x3CalibMatrix(pi, calib, panelNpm)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Measure the gray ramp if (targetIdx == 0) { if (!measureGrayRamp(pi, chain, calib, panelNpm, mNumGraySamples, grayRampR, grayRampG, grayRampB, calib.getMatrix())) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } } if (wasCancelled(pi, chain, true)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Turn off the pattern generator if (!pi.disp->setPatternGeneratorEnabled(false, pi.dispId)) { setErrorString( std::string("ERROR: Can't disable pattern generator: ") + pi.disp->errorString()); pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } // If this happens, well, that sucks. I'm not sure we // can recover without power-cycling return false; } idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); computeLuts(pi, calib, grayRampR, grayRampG, grayRampB, panelNpm); if (wasCancelled(pi, chain, false)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Upload! if (!pi.disp->setCalibration(targets[targetIdx].getPresetId(), calib, pi.dispId, chain)) { setErrorString( std::string("Unable to upload calibration data: ") + pi.disp->errorString()); pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, false)) { pi.disp->setColorProcessingEnabled(true, pi.dispId); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // Enable color processing somehow and plop us back // in the right color space if (!pi.disp->setColorProcessingEnabled(true, pi.dispId)) { setErrorString(pi.disp->errorString()); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, false)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // For some reason, we end up in a wierd state on some systems if we don't // re-select the current color space. But just re-selecting does not // seem to be sufficent. We first need to flip the pattern generator // on and off. How odd? Yes indeed. #if 1 // Begin workaround: if (!pi.disp->setPatternGeneratorEnabled(true, targets[targetIdx].getConnId())) { setErrorString("ERROR: Can't enable pattern generator."); return false; } if (!idle(pi.disp->patternGeneratorEnableTime(pi.dispId), chain)) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); printf("Re-selecting color space\n"); if (!pi.disp->setColorSpace(targets[targetIdx].getPresetId(), pi.dispId)) { setErrorString( std::string("Unable to select calibrated color space. ") + pi.disp->errorString() ); return false; } if (!idle(5, chain)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } // End workaround: #else fprintf(stderr, "\tStuck luminance workaround disabled!!\n"); #endif if (chain) { chain->setUiString("Ui::status_string_minor", "Verifing calibration."); } // Reset any other Luts that sit in the way. if (!pi.lut->reset()) { setErrorString(pi.lut->errorString()); for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (!validate(pi, targets[targetIdx], chain)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } if (wasCancelled(pi, chain, false)) { for (std::map<uint32_t, uint32_t>::iterator thePreset=origPresets.begin(); thePreset != origPresets.end(); ++thePreset) { pi.disp->setColorSpace((*thePreset).second, (*thePreset).first, chain); } return false; } } return true; } // ------------------------------------- // // virtual protected bool Ookala::DreamColorCalib::_checkDeps() { std::vector<Plugin *> plugins; if (mRegistry == NULL) { setErrorString("No PluginRegistry found for DreamColorCalib."); return false; } plugins = mRegistry->queryByName("DreamColorCtrl"); if (plugins.empty()) { setErrorString("No DreamColorCtrl plugin found for DreamColorCalib."); return false; } plugins = mRegistry->queryByName("WsLut"); if (plugins.empty()) { setErrorString("No WsLut plugin found for DreamColorCalib."); return false; } return true; } // ------------------------------------- // // Before discussing how to find a good configuration for the // backlight, it's worthwhile to touch upon what /is/ a good // configuration for the backlight. // // With this display, the goal is not necessarily to just minimize // dE of the native backlight Yxy w.r.t. the target Yxy. It's // entirely possible that even with a very small dE, it would // still be impossible to reach the goal Yxy. // // The reason is headroom. Recall that the backlight is not // the sole determinate of white point - the rest of the color // processing chain comes into play. This is handy for the // really fine tweaking to get close to the goal Yxy. // // Consider the 3x3 matrix that maps target colorimetry onto // measured colorimetry. For mapping an incoming (1,1,1) value // all the components of the output value must be less than 1 - // otherwise we're clipping. In other words, if we measure // the panel's native RGB chromaticies and build an NPM // matrix using these and the backlight w.p (NPM = RGB -> XYZ) // we'll see: // // [R] [ ]^-1 [Target White X] // [G] = [ NPM ] [Target White Y] // [B] [ ] [Target White Z] // // (XXX: An example would be good here). // // If the resulting R,G,B > 1, we're out of luck. // // So, a valid backlight white point must allow for the mapping of // the target XYZ back to RGB, where max(R,G,B) <= 1.0. // // Now, that said, we don't want to waste bits. So we also want // to make sure that min(R,G,B) >= some threshold. // // Combining these two conditions, we can classify a "solution" as // a backlight white point where max(R,G,B) <= 1.0 and // min(R,G,B) >= T, where T is some threshold and R,G,B result // from the target XYZ and the NPM matrix formed by the backlight // white point and the native panel chromaticies. // // Ok. So that's a solution. But what's a _good_ solution, and how // to we find it? // // First, we need to give ourselves a better shot at finding a // backlight w.p with max(R,G,B) <= 1.0. This means adding in a little // headroom to the luminance goal we're trying to hit. In our // search, we're not really searching for the target w.p., but // rather the target w.p. plus some Y headroom - say, 2% headroom. // // Now - if we have a target with some headroom, this can become // the object of our dE affection. We'll drive towards this goal, // and we'll stop if we find a valid solution that has a really // good dE (where really good is some threshold that you pick). // // If we've searched for a fair number of iterations, but haven't // found a really good dE, we should stop and not run forever. // But, if we haven't found a really good dE, what should our // backlight white be? It makes sense to pick the best (in a dE sense) // "valid solution" that we found over the course of the iterations. // We'll then force the matrix to re-balance to the eventual target w.p. // If we haven't found any valid solutions, with max(R,G,B) <= 1.0 and // min(R,G,B) >= T), then we're out of luck and we're going to fail. // Alternativly, if this ends up being a problem, increase the max // number of iterations, or increase them only if we don't have any // valid solutions. // // The backlight has a set of 4 registers that control it. One register // is 'brightness' and is tied to the OSD brightness control. It's // a 1-byte register. At 0xff, the OSD reads out 250 cd/m^2. At // 0x51, the OSD reads out 50 cd/m^2. Note that the scaling is not // quite 1 code value / cd/m^2, so we should manually figure out the // OSD setting that maps to a goal luminance. The remaining 3 backlight // registers control (approximately) Y, x, and y. There is some cross // talk. For the x and y controls, there's approx. .001 change per // code value. For the Y control, there's approx 1 cd/m^2 change per // code value when brightness = 0xff. // // To try and approach a good solution, we iterate over adjusting // the Y, x, and y, backlight registers. To figure how far to // move, we keep a running estimate of how much change per register // code value we hit. Then, using this, we estimate how far to // adjust each register. From this, we move the register with the // largest step, and continue the process. // // It's fairly brain-dead, but it usually converges fairly quickly. // We have experimented with gradient-descent type stratagies, but // they're often rather sensitive to measurement noise - which has // a tendency to send us off in the wrong direction and diverge. // // // NOTE: Color processing should be disabled before entering this function. // // NOTE: Pattern generator should be enabled before entering. // // virtual protected bool Ookala::DreamColorCalib::backlightLoop( PluginData &pi, PluginChain *chain, const Yxy &goalWhite, uint32_t *backlightReg, Yxy &currWhite) { uint32_t lastReg[4], origReg[4]; Yxy lastWhite, red, green, blue; Yxy headroomGoal; Rgb linearRgb; int32_t chromaRegStep[3]; double diff[3]; DataPoint point; std::vector<DataPoint> solutions; bool convergedOnGoal = false; // --------------------------------------------------------- // Tweakable parameters: // // We should consider ourselves good enough if a solution // is within some threshold of a dE from our headroom goal. double dEStoppingThreshold = 1; // If we don't converge because of small dE, we should stop // after some fixed number of attempts. uint32_t maxIter = 12; // The amount of luminance headroom to start aiming for. double initialHeadroom = 1.02; // The current lower threshold on the linear RGB of our // goalYxy - given the native RGB of the panel and the current // white of the backlight - is 2.0x the difference from 1 given // 2% headroom. We'll update this below to adapt if // the headroom increases. double lowerLinearRgbThresh = 1. - 2.0*(initialHeadroom - 1.); double upperLinearRgbThresh = 1. - 0.50*(initialHeadroom - 1.); // One step in the Y register is appromatly a change of // 1 cd/m^2 at max brightness. Lets assume that it scales // linearly as brighteness decreases. These are only // initial estimates. As we take steps below, we'll update // these estimates to reflect reality. It won't be perfect, // thanks to noise and cross-channel issues (e.g. we're // really have dX/dRegister, dY/dRegister, dZ/dRegister), // but in practice it works fairly well. double unitsPerStep[3]; // // --------------------------------------------------------- unitsPerStep[0] = goalWhite.Y / 250.0; unitsPerStep[1] = 1./1000.; unitsPerStep[2] = 1./1000.; // The color we _actually_ want to hit in this loop has // some headroom in it. // // For now, we'll pick a fixed % of the goal Y headroomGoal.Y = initialHeadroom * goalWhite.Y; headroomGoal.x = goalWhite.x; headroomGoal.y = goalWhite.y; // Enforce some limits on the goals. We probably don't want to // dip much below 40 cd/m^2, and probably not much above 250 cd/m^2 if ((goalWhite.Y < 40) || (goalWhite.Y > 250)) { setErrorString("Target luminance is out of range [40,250]."); return false; } if (!measurePrimaries(pi, chain, red, green, blue)) { return false; } if (!pi.disp->setPatternGeneratorColor(1023, 1023, 1023, pi.dispId)) { setErrorString( std::string("Can't set pattern generator color: ") + pi.disp->errorString()); return false; } if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } if (wasCancelled(pi, chain, true)) return false; // It's probably best to start the backlight registers in // their current position (except for a change in the // brightness register. if (!pi.disp->getBacklightRegRaw(origReg[0], origReg[1], origReg[2], origReg[3], pi.dispId)) { setErrorString( std::string("Can't read initial backlight registers.") + pi.disp->errorString()); return false; } lastReg[0] = backlightReg[0] = origReg[0]; lastReg[1] = backlightReg[1] = origReg[1]; lastReg[2] = backlightReg[2] = origReg[2]; lastReg[3] = backlightReg[3] = pi.disp->brightnessRegister(goalWhite.Y, pi.dispId); // Set an initial position for the backlight registers if (!pi.disp->setBacklightRegRaw(backlightReg[0], backlightReg[1], backlightReg[2], backlightReg[3], true, true, true, true, pi.dispId)) { setErrorString( std::string("Can't set backlight registers: ") + pi.disp->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; // Wait for the backlight to settle - we could be smarter about // this by examining the current values. It takes ~15-20 sec to // settle over a min -> max brightness swing. But, if we're // not swinging that long, no need to wait that long. if (!idle(pi.disp->backlightBrightnessSettleTime(pi.dispId), chain)) { return false; } for (uint32_t mainIter=0; mainIter<maxIter; ++mainIter) { if (wasCancelled(pi, chain, true)) return false; // Measure where we are lastWhite = currWhite; if (!pi.sensor->measureYxy(currWhite, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; // If our headroom has increased, we'll need to set our lower // tolerance of linear RGB accordingly. This sets it to // 2x the range of being dead on the current head room if (!computeGoalRgb(pi.color, red, green, blue, headroomGoal, goalWhite, linearRgb)) { return false; } lowerLinearRgbThresh = 1.0 - 2.0*(1.0-linearRgb.r); printf( "If dead on headroom goal, real goal rgb: %f [thresh: %f - %f]\n", linearRgb.r, upperLinearRgbThresh, lowerLinearRgbThresh); if (!computeGoalRgb(pi.color, red, green, blue, currWhite, goalWhite, linearRgb)) { return false; } double rgbDat[3]; rgbDat[0] = linearRgb.r; rgbDat[1] = linearRgb.g; rgbDat[2] = linearRgb.b; int minRgb = 0; int maxRgb = 0; for (int idx=1; idx<3; ++idx) { if (rgbDat[idx] > rgbDat[maxRgb]) maxRgb = idx; if (rgbDat[idx] < rgbDat[minRgb]) minRgb = idx; } printf("Linear RGB: %f %f %f\n", linearRgb.r, linearRgb.g, linearRgb.b); // If we have enough head room (that is, all RGB < 1) but yet // aren't wasting too may bits (min RGB is too low), then // stop because we'll fix the rest in the 3x3 matrix. // // The min threshold probably shouldn't be fixed - we should // look at what it would be if we hit our headroom goal // dead-nuts on, and then back off a little. if ((rgbDat[maxRgb] <= upperLinearRgbThresh) && (rgbDat[minRgb] > lowerLinearRgbThresh)) { // If we've found a valid solution which is pretty darn // close to where we want to be, go ahead and stop. // Otherwise, just record the solution so we can // find the best one later on if we get stuck point.linearRgb = linearRgb; point.measuredYxy = currWhite; for (int idx=0; idx<4; ++idx) { point.backlightReg[idx] = backlightReg[idx]; } solutions.push_back(point); if (pi.color->dELab(headroomGoal, currWhite, headroomGoal) < dEStoppingThreshold) { printf("Converged because dE < %f\n", dEStoppingThreshold); convergedOnGoal = true; break; } } printf("%4d %4d %4d %4d %f %f %f\n", backlightReg[0], backlightReg[1], backlightReg[2], backlightReg[3], currWhite.Y, currWhite.x, currWhite.y); // And re-estimate how much the display changes with response // to a given adjustment in value. Only update our estimate // if its a sane value thought. diff[0] = currWhite.Y - lastWhite.Y; diff[1] = currWhite.x - lastWhite.x; diff[2] = currWhite.y - lastWhite.y; for (int idx=0; idx<3; ++idx) { if (backlightReg[idx] != lastReg[idx]) { double dx = (double)backlightReg[idx] - (double)lastReg[idx]; double change = diff[idx] / dx; // Limit the change to .1 Y change / unit for luminance // and .0005/unit in the x,y registers. if ((idx == 0) && (change > .1)) { unitsPerStep[idx] = change; } else if ((idx > 0) && (change > 5e-4)) { unitsPerStep[idx] = change; } } } // Approximate which direction should move the farthest diff[0] = headroomGoal.Y - currWhite.Y; diff[1] = headroomGoal.x - currWhite.x; diff[2] = headroomGoal.y - currWhite.y; chromaRegStep[0] = chromaRegStep[1] = chromaRegStep[2] = 0; int maxIdx = -1; for (int idx=0; idx<3; ++idx) { chromaRegStep[idx] = static_cast<int32_t>(diff[idx] / unitsPerStep[idx] + .5); if (chromaRegStep[idx] != 0) { if (maxIdx == -1) { maxIdx = idx; } else if ( abs(chromaRegStep[idx]) > abs(chromaRegStep[maxIdx])) { maxIdx = idx; } } } printf("\t\t\t\t\tchroma reg step: %d %d %d [%.2f %.4f %.4f]\n", chromaRegStep[0], chromaRegStep[1], chromaRegStep[2], headroomGoal.Y - currWhite.Y, headroomGoal.x - currWhite.x, headroomGoal.y - currWhite.y); printf("\t\t\t\t\tdE: %f\n", pi.color->dELab(headroomGoal, currWhite, headroomGoal)); // If we got stuck and we're still not in a good RGB spot, // then what? Raise the headroom... if (maxIdx == -1) { //printf("Converged because of lack of movement.. breaking for success!\n"); //break; printf("It appears that we got stuck - increasing headroom\n"); headroomGoal.Y += 0.01*goalWhite.Y; } // Only move in the most important direction. for (uint32_t idx=0; idx<3; ++idx) { lastReg[idx] = backlightReg[idx]; } if (maxIdx != -1) { // If we're already close to our goal, be conservative in // our step size so we don't overshoot if (pi.color->dELab(headroomGoal, currWhite, headroomGoal) < 2) { backlightReg[maxIdx] += chromaRegStep[maxIdx] / abs(chromaRegStep[maxIdx]); } else { backlightReg[maxIdx] += chromaRegStep[maxIdx]; } } // These should probably have better upper bounds? if ((backlightReg[0] < 0) || (backlightReg[0] > 400) || //was 350 (backlightReg[1] < 0) || (backlightReg[1] > 2000) || (backlightReg[2] < 0) || (backlightReg[2] > 2000)) { fprintf(stderr, "ERROR: Backlight registers out of range 0<%d<350 0<%d<2000 0<%d<2000\n", backlightReg[0], backlightReg[1], backlightReg[2]); setErrorString("Backlight registers out of range."); return false; } // Update the backlight registers if (!pi.disp->setBacklightRegRaw(backlightReg[0], backlightReg[1], backlightReg[2], backlightReg[3], true, true, true, false)) { fprintf(stderr, "ERROR: Can't set backlight registers\n"); setErrorString( std::string("Can't set backlight register: ") + pi.disp->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->backlightGenericSettleTime(pi.dispId), chain)) { return false; } } // If we didn't happen to stop because we found a good point, // hopefully we at least found some valid solutions (where the // linearRGB of our goal point was within our tolerance. If we // did find some of these "solution" points, pick the one with // the lowest dE to the real goal (not the goal with headroom). // If we didn't find any solutions, then we have to fail. if (!convergedOnGoal) { if (solutions.empty()) { setErrorString("No solutions found."); return false; } std::vector<DataPoint>::iterator bestSoln = solutions.begin(); for (std::vector<DataPoint>::iterator soln = solutions.begin(); soln != solutions.end(); ++soln) { if (pi.color->dELab(goalWhite, (*soln).measuredYxy, goalWhite) < pi.color->dELab(goalWhite, (*bestSoln).measuredYxy, goalWhite)) { bestSoln = soln; } } if (!pi.disp->setBacklightRegRaw((*bestSoln).backlightReg[0], (*bestSoln).backlightReg[1], (*bestSoln).backlightReg[2], 0, true, true, true, false, pi.dispId)) { fprintf(stderr, "ERROR: Can't set backlight registers\n"); setErrorString( std::string("Can't set backlight register: ") + pi.disp->errorString()); return false; } if (!idle(pi.disp->backlightGenericSettleTime(pi.dispId), chain)) { return false; } } return true; } // ------------------------------------------------ // // NOTE: Pattern generator should be enabled before // entering this function. // // virtual bool Ookala::DreamColorCalib::measurePrimaries( PluginData &pi, PluginChain *chain, Yxy &red, Yxy &green, Yxy &blue) { // Setup for measuring red if (!pi.disp->setPatternGeneratorColor(1023, 0, 0, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } if (wasCancelled(pi, chain, true)) return false; // Measure red if (!pi.sensor->measureYxy(red, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; // Setup for measuring green if (!pi.disp->setPatternGeneratorColor(0, 1023, 0, pi.dispId)) { fprintf(stderr, "ERROR: Can't set pattern generator color\n"); return false; } if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } if (wasCancelled(pi, chain, true)) return false; // Measure green if (!pi.sensor->measureYxy(green, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; // Setup for measuring blue if (!pi.disp->setPatternGeneratorColor(0, 0, 1023, pi.dispId)) { fprintf(stderr, "ERROR: Can't set pattern generator color\n"); return false; } if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } if (wasCancelled(pi, chain, true)) return false; // Measure blue if (!pi.sensor->measureYxy(blue, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } if (wasCancelled(pi, chain, true)) return false; return true; } // ------------------------------------------------ // // NOTE: Pattern generator should be enabled and // color processing disabled. // // We'll take the raw grey measurements and conver them // back to panel RGB. Then, we'll store the panel RGB // (linear, not nonlinear) in the maps ramp{R,G,B}. // // This won't measure white - because presumable we've // already done that to get the XYZ->RGB matrix. And // if we process that value, then we're just going // to get 1.0, so there isn't much point!! // // virtual protected bool Ookala::DreamColorCalib::measureGrayRamp( PluginData &pi, PluginChain *chain, DreamColorCalibrationData &calib, const Npm &panelNpm, uint32_t numSteps, std::map<double, double> &rampR, std::map<double, double> &rampG, std::map<double, double> &rampB, Mat33 calibMat) { std::vector<uint32_t> grayVals; int32_t val, max; uint32_t stepSize; Yxy adjMeasure, black; Yxy measure; Rgb linearRgb; // Maximum code value max = (1 << pi.disp->patternGeneratorBitDepth(pi.dispId)) - 1; // Somehow need to set this based on user data. stepSize = (max) / (numSteps-1); // Don't even bother trying to read black, just go ahead and // estimate what it should be. if (!estimateBlack(pi, chain, pi.panelRed, pi.panelGreen, pi.panelBlue, black)) { black.Y = pi.panelWhite.Y / 1100.0; black.x = 0.3333; black.y = 0.3333; } printf("black: %f %f %f\n", black.Y, black.x, black.y); rampR[0.0] = 0.0; rampG[0.0] = 0.0; rampB[0.0] = 0.0; // Don't bother pushing white, just put it where its' supposed to go. //grayVals.push_back(max); rampR[1.0] = 1.0; rampG[1.0] = 1.0; rampB[1.0] = 1.0; // If we have a sane matrix, figure out where 'white' is going // to land, and make sure we sample in that area. Vec3 colorVec; colorVec.v0 = colorVec.v1 = colorVec.v2 = 1.0; Vec3 colorVecAdj = pi.color->mat33VectorMul(calibMat, colorVec); colorVecAdj.v0 = (double)((uint32_t)(max*colorVecAdj.v0 + 0.5)); colorVecAdj.v1 = (double)((uint32_t)(max*colorVecAdj.v1 + 0.5)); colorVecAdj.v2 = (double)((uint32_t)(max*colorVecAdj.v2 + 0.5)); // If someone has passed in an idenity matrix, don't worry // about measuring, because we'll catch the max value below. if (colorVecAdj.v1 < max-5) { val = static_cast<uint32_t>(colorVecAdj.v1); grayVals.push_back(val); } val = max-stepSize; while (val > 0) { if (val > 24) { grayVals.push_back(val); } val -= stepSize; } std::sort(grayVals.begin(), grayVals.end()); std::reverse(grayVals.begin(), grayVals.end()); uint32_t grayCnt = 1; for (std::vector<uint32_t>::iterator theGray = grayVals.begin(); theGray != grayVals.end(); ++theGray) { if (chain) { char buf[1024]; #ifdef _WIN32 sprintf_s(buf, 1023, "Measuring gray ramp, %d of %d", (int)grayCnt, (int)grayVals.size()); #else sprintf(buf, "Measuring gray ramp, %d of %d", (int)grayCnt, (int)grayVals.size()); #endif chain->setUiString("Ui::status_string_minor", std::string(buf)); } val = *theGray; if (!pi.disp->setPatternGeneratorColor(val, val, val, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } // If this fails, it's probably because we're too dark for // the sensor to measure. If we already have some data, this // is probably ok. if (!pi.sensor->measureYxy(measure, chain, pi.sensorId)) { if (rampR.size() < 6) { setErrorString( std::string("Can't read sensor: ") + pi.sensor->errorString()); return false; } else { return true; } } if (wasCancelled(pi, chain, true)) return false; adjMeasure = pi.color->subYxy(measure, black); linearRgb = pi.color->cvtYxyToRgb(adjMeasure, panelNpm); printf("%d -> %f %f %f [%f %f %f]\n", val, adjMeasure.Y, adjMeasure.x, adjMeasure.y, linearRgb.r, linearRgb.g, linearRgb.b); rampR[ static_cast<double>(val) / static_cast<double>(max) ] = linearRgb.r; rampG[ static_cast<double>(val) / static_cast<double>(max) ] = linearRgb.g; rampB[ static_cast<double>(val) / static_cast<double>(max) ] = linearRgb.b; grayCnt++; } return true; } // ------------------------------------------------ // // Call this assuming that the pattern generator is // enabled // // protected bool Ookala::DreamColorCalib::estimateBlack( PluginData &pi, PluginChain *chain, const Yxy &measuredRed, const Yxy &measuredGreen, const Yxy &measuredBlue, Yxy &estimatedBlack) { std::vector<uint32_t> targetPnts; std::vector<Yxy> rampRed, rampGreen, rampBlue; bool readRed, readGreen, readBlue; Yxy curr, newBlack[6]; XYZ tmpXYZ, estimatedBlackXYZ, grad; double err[6], step, delta, currErr, lastErr, len; int32_t count; // Maximum code value uint32_t max = (1 << pi.disp->patternGeneratorBitDepth(pi.dispId)) - 1; for (int32_t i=static_cast<int32_t>(0.2*max); i>static_cast<int32_t>(0.15*max); i-=20) { targetPnts.push_back(i); } readRed = readGreen = readBlue = true; count = 0; for (std::vector<uint32_t>::iterator theVal = targetPnts.begin(); theVal != targetPnts.end(); ++theVal) { if (chain) { char buf[1024]; #ifdef _WIN32 sprintf_s(buf, 1023, "Estimating black point, pass %d of %d", count+1, static_cast<int>(targetPnts.size())); #else sprintf(buf, "Estimating black point, pass %d of %d", count+1, static_cast<int>(targetPnts.size())); #endif chain->setUiString("Ui::status_string_minor", std::string(buf)); } count++; printf("Measuring rgb for %d\n", (*theVal)); // Measure the red. if (readRed) { if (!pi.disp->setPatternGeneratorColor((*theVal), 0, 0, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } printf("Reading red..\n"); if (!pi.sensor->measureYxy(curr, chain, pi.sensorId)) { readRed = false; printf("Failed to read red %d: %s\n", (*theVal), pi.sensor->errorString().c_str()); } else { printf("Read red %d ok (%f %f %f)\n", (*theVal), curr.x, curr.y, curr.Y); rampRed.push_back(curr); } } // Measure the green. if (readGreen) { if (!pi.disp->setPatternGeneratorColor(0, (*theVal), 0, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } printf("Reading green..\n"); if (!pi.sensor->measureYxy(curr, chain, pi.sensorId)) { readGreen = false; printf("Failed to read green %d: %s\n", (*theVal), pi.sensor->errorString().c_str()); } else { rampGreen.push_back(curr); printf("Read green %d ok (%f %f %f)\n", (*theVal), curr.x, curr.y, curr.Y); } } // And measure the blue. if (readBlue) { if (!pi.disp->setPatternGeneratorColor(0, 0, (*theVal), pi.dispId)) { setErrorString("ERROR: Can't set pattern generator color."); return false; } if (wasCancelled(pi, chain, true)) return false; if (!idle(pi.disp->patternGeneratorSettleTime(pi.dispId), chain)) { return false; } printf("Reading blue..\n"); if (!pi.sensor->measureYxy(curr, chain, pi.sensorId)) { readBlue = false; printf("Failed to read blue %d: %s\n", (*theVal), pi.sensor->errorString().c_str()); } else { rampBlue.push_back(curr); printf("Read blue %d ok (%f %f %f)\n", (*theVal), curr.x, curr.y, curr.Y); } } if ((!readRed) && (!readGreen) && (!readBlue)) break; } if (rampRed.size() + rampGreen.size() + rampBlue.size() == 0) { return false; } estimatedBlack.x = 0.333; estimatedBlack.y = 0.333; estimatedBlack.Y = 0.04; step = 0.001; delta = 0.0001; grad.X = grad.Y = grad.Z = 0; lastErr = 1e60; for (uint32_t iter=0; iter<2500; ++iter) { for (int idx=0; idx<6; ++idx) { tmpXYZ = pi.color->cvtYxyToXYZ(estimatedBlack); switch (idx) { case 0: tmpXYZ.X += delta; break; case 1: tmpXYZ.X -= delta; break; case 2: tmpXYZ.Y += delta; break; case 3: tmpXYZ.Y -= delta; break; case 4: tmpXYZ.Z += delta; break; case 5: tmpXYZ.Z -= delta; break; } newBlack[idx] = pi.color->cvtXYZToYxy(tmpXYZ); } // Compute the gradient of the error, using central differences err[0] = err[1] = err[2] = err[3] = err[4] = err[5] = currErr = 0; for (std::vector<Yxy>::iterator theVal = rampRed.begin(); theVal != rampRed.end(); ++theVal) { currErr += estimateBlackError(pi, measuredRed, estimatedBlack, *theVal); for (int idx=0; idx<6; ++idx) { err[idx] += estimateBlackError(pi, measuredRed, newBlack[idx], *theVal); } } for (std::vector<Yxy>::iterator theVal = rampGreen.begin(); theVal != rampGreen.end(); ++theVal) { currErr += estimateBlackError(pi, measuredGreen, estimatedBlack, *theVal); for (int idx=0; idx<6; ++idx) { err[idx] += estimateBlackError(pi, measuredGreen, newBlack[idx], *theVal); } } for (std::vector<Yxy>::iterator theVal = rampBlue.begin(); theVal != rampBlue.end(); ++theVal) { currErr += estimateBlackError(pi, measuredBlue, estimatedBlack, *theVal); for (int idx=0; idx<6; ++idx) { err[idx] += estimateBlackError(pi, measuredBlue, newBlack[idx], *theVal); } } if (currErr > lastErr) { estimatedBlackXYZ = pi.color->cvtYxyToXYZ(estimatedBlack); estimatedBlackXYZ.X -= grad.X; estimatedBlackXYZ.Y -= grad.Y; estimatedBlackXYZ.Z -= grad.Z; estimatedBlack = pi.color->cvtXYZToYxy(estimatedBlackXYZ); step *= 0.5; delta *= 0.5; grad.X = grad.Y = grad.Z = 0; continue; } if (lastErr - currErr < 1e-10) break; lastErr = currErr; // And take a small step towards the gradient grad.X = (err[0] - err[1]) / (2.0*delta); grad.Y = (err[2] - err[3]) / (2.0*delta); grad.Z = (err[4] - err[5]) / (2.0*delta); len = sqrt(grad.X*grad.X + grad.Y*grad.Y + grad.Z*grad.Z); if (fabs(len) > 1e-6) { grad.X = grad.X / len * step; grad.Y = grad.Y / len * step; grad.Z = grad.Z / len * step; } estimatedBlackXYZ = pi.color->cvtYxyToXYZ(estimatedBlack); estimatedBlackXYZ.X -= grad.X; estimatedBlackXYZ.Y -= grad.Y; estimatedBlackXYZ.Z -= grad.Z; estimatedBlack = pi.color->cvtXYZToYxy(estimatedBlackXYZ); } return true; } // ------------------------------------------------ // double Ookala::DreamColorCalib::estimateBlackError( PluginData &pi, const Yxy &goal, const Yxy &estimatedBlack, const Yxy &measurement) { // subtract black from the measurement Yxy measMinusBlack = pi.color->subYxy(measurement, estimatedBlack); // And compute the chromaticity error return sqrt(pow(measMinusBlack.x - goal.x, 2.0) + pow(measMinusBlack.y - goal.y, 2.0)); } // ------------------------------------------------ // // Computes the 3x3 matrix for calibration, and sets it // in the CalibrationData, ready for uploading. // // This assumes that we've already computed the panel // XYZ -> rgb matrix (which we would need for the gray // ramp measurements. bool Ookala::DreamColorCalib::compute3x3CalibMatrix( PluginData &pi, DreamColorCalibrationData &calib, const Npm &panelNpm) { Npm modelNpm; if (!pi.color->computeNpm(calib.getColorSpaceInfo().getRed(), calib.getColorSpaceInfo().getGreen(), calib.getColorSpaceInfo().getBlue(), calib.getColorSpaceInfo().getWhite(), modelNpm)) { setErrorString("Unable to compute model NPM."); return false; } // Now, the calibration matrix is just: // // [ ] [ panel ] [ model ] // [ calib ] = [ XYZ -> ] [ rgb -> ] // [ ] [ rgb ] [ XYZ ] calib.setMatrix(pi.color->mat33MatMul( panelNpm.invRgbToXYZ, modelNpm.rgbToXYZ)); printf("Model RGB -> XYZ:\n"); printf("%f %f %f\n", modelNpm.rgbToXYZ.m00, modelNpm.rgbToXYZ.m01, modelNpm.rgbToXYZ.m02); printf("%f %f %f\n", modelNpm.rgbToXYZ.m10, modelNpm.rgbToXYZ.m11, modelNpm.rgbToXYZ.m12); printf("%f %f %f\n", modelNpm.rgbToXYZ.m20, modelNpm.rgbToXYZ.m21, modelNpm.rgbToXYZ.m22); printf("Panel XYZ -> RGB:\n"); printf("%f %f %f\n", panelNpm.invRgbToXYZ.m00, panelNpm.invRgbToXYZ.m01, panelNpm.invRgbToXYZ.m02); printf("%f %f %f\n", panelNpm.invRgbToXYZ.m10, panelNpm.invRgbToXYZ.m11, panelNpm.invRgbToXYZ.m12); printf("%f %f %f\n", panelNpm.invRgbToXYZ.m20, panelNpm.invRgbToXYZ.m21, panelNpm.invRgbToXYZ.m22); printf("Calib 3x3 matrix:\n"); printf("%f %f %f [%f]\n", calib.getMatrix().m00, calib.getMatrix().m01, calib.getMatrix().m02, calib.getMatrix().m00 + calib.getMatrix().m01 + calib.getMatrix().m02); printf("%f %f %f [%f]\n", calib.getMatrix().m10, calib.getMatrix().m11, calib.getMatrix().m12, calib.getMatrix().m10 + calib.getMatrix().m11 + calib.getMatrix().m12); printf("%f %f %f [%f]\n", calib.getMatrix().m20, calib.getMatrix().m21, calib.getMatrix().m22, calib.getMatrix().m20 + calib.getMatrix().m21 + calib.getMatrix().m22); return true; } // ------------------------------------------------ // // Compute the pre and post luts, and store them in // the CalibrationData struct. bool Ookala::DreamColorCalib::computeLuts( PluginData &pi, DreamColorCalibrationData &calib, std::map<double, double> &rampR, std::map<double, double> &rampG, std::map<double, double> &rampB, const Npm &panelNpm) { std::vector<uint32_t> preLut[3], postLut[3]; // Compute the pre-lut for (uint32_t cv=0; cv<pi.disp->getPreLutLength(pi.dispId); ++cv) { double max = static_cast<double>( (1 << pi.disp->getPreLutBitDepth(pi.dispId)) - 1); double x = static_cast<double>(cv) / static_cast<double>(pi.disp->getPreLutLength(pi.dispId)-1); uint32_t val = static_cast<uint32_t>( 0.5 + max * pi.disp->evalTrcToLinear(x, calib.getColorSpaceInfo(), pi.dispId)); preLut[0].push_back(val); preLut[1].push_back(val); preLut[2].push_back(val); } // If we want, try and figure out Ro,Go,Bo that maintains // the neutral chromaticity. Rgb minRgb; minRgb.r = minRgb.g = minRgb.b = 0; for (uint32_t cv=0; cv<pi.disp->getPostLutLength(pi.dispId); ++cv) { double rgb[3]; double max = static_cast<double>( (1 << pi.disp->getPostLutBitDepth(pi.dispId)) - 1); double x = static_cast<double>(cv) / static_cast<double>(pi.disp->getPostLutLength(pi.dispId)-1); if (x > 1) x = 1; if (x < 0) x = 0; rgb[0] = max * pi.interp->catmullRomInverseInterp(x, rampR); rgb[1] = max * pi.interp->catmullRomInverseInterp(x, rampG); rgb[2] = max * pi.interp->catmullRomInverseInterp(x, rampB); if (cv == 0) { printf("postlut black goes to %f %f %f\n", rgb[0], rgb[1], rgb[2]); } for (int idx=0; idx<3; ++idx) { if (rgb[idx] < 0) rgb[idx] = 0; if (rgb[idx] > max) rgb[idx] = max; } postLut[0].push_back( static_cast<uint32_t>(rgb[0] + 0.5) ); postLut[1].push_back( static_cast<uint32_t>(rgb[1] + 0.5) ); postLut[2].push_back( static_cast<uint32_t>(rgb[2] + 0.5) ); } calib.setPreLutRed(preLut[0]); calib.setPreLutGreen(preLut[1]); calib.setPreLutBlue(preLut[2]); calib.setPostLutRed(postLut[0]); calib.setPostLutGreen(postLut[1]); calib.setPostLutBlue(postLut[2]); return true; } // ---------------------------------------- // bool Ookala::DreamColorCalib::computeGoalRgb( Color *color, const Yxy &red, const Yxy &green, const Yxy &blue, const Yxy &white, const Yxy &goalWhite, Rgb &rgb) { Npm npm; if (!color->computeNpm(red, green, blue, white, npm)) { return false; } rgb = color->cvtYxyToRgb(goalWhite, npm); return true; } // ---------------------------------------- // bool Ookala::DreamColorCalib::validate( PluginData &pi, DreamColorSpaceInfo target, PluginChain *chain) { Yxy actualWhite, actualRed, actualGreen, actualBlue; Yxy minWhite, maxWhite, minRed, maxRed, minGreen, maxGreen, minBlue, maxBlue; Npm panelNpm; std::map<double, double> grayRampR, grayRampG, grayRampB; setErrorString(""); // Figure out some limits for the color target we're trying to hit. minWhite = target.getWhite(); minRed = target.getRed(); minGreen = target.getGreen(); minBlue = target.getBlue(); maxWhite = target.getWhite(); maxRed = target.getRed(); maxGreen = target.getGreen(); maxBlue = target.getBlue(); minWhite.Y -= mWhiteToleranceMinus.Y; maxWhite.Y += mWhiteTolerancePlus.Y; minWhite.x -= mWhiteToleranceMinus.x; maxWhite.x += mWhiteTolerancePlus.x; minRed.x -= mRedToleranceMinus.x; maxRed.x += mRedTolerancePlus.x; minGreen.x -= mGreenToleranceMinus.x; maxGreen.x += mGreenTolerancePlus.x; minBlue.x -= mBlueToleranceMinus.x; maxBlue.x += mBlueTolerancePlus.x; minWhite.y -= mWhiteToleranceMinus.y; maxWhite.y += mWhiteTolerancePlus.y; minRed.y -= mRedToleranceMinus.y; maxRed.y += mRedTolerancePlus.y; minGreen.y -= mGreenToleranceMinus.y; maxGreen.y += mGreenTolerancePlus.y; minBlue.y -= mBlueToleranceMinus.y; maxBlue.y += mBlueTolerancePlus.y; // Turn on the pattern generator - take care to disable // it when we return in this method then. if (!pi.disp->setPatternGeneratorEnabled(true, target.getConnId())) { setErrorString("ERROR: Can't enable pattern generator."); return false; } if (!idle(pi.disp->patternGeneratorEnableTime(pi.dispId), chain)) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!pi.disp->setPatternGeneratorColor(1023, 1023, 1023, pi.dispId)) { setErrorString("ERROR: Can't set pattern generator."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!idle(3, chain)) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!pi.sensor->measureYxy(actualWhite, chain, pi.sensorId)) { setErrorString( std::string("Can't read sensor [white]: ") + pi.sensor->errorString()); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!measurePrimaries(pi, chain, actualRed, actualGreen, actualBlue)) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } printf("Measured wht: %f %f %f\n", actualWhite.x, actualWhite.y, actualWhite.Y); printf("Measured red: %f %f\n", actualRed.x, actualRed.y); printf("Measured grn: %f %f\n", actualGreen.x, actualGreen.y); printf("Measured blu: %f %f\n", actualBlue.x, actualBlue.y); printf("\n"); printf("Target wht: %f %f %f\n", target.getWhite().x, target.getWhite().y, target.getWhite().Y); printf("Target red: %f %f\n", target.getRed().x, target.getRed().y); printf("Target grn: %f %f\n", target.getGreen().x, target.getGreen().y); printf("Target blu: %f %f\n", target.getBlue().x, target.getBlue().y); // Test against our target threshold if ((actualWhite.Y < minWhite.Y) || (actualWhite.Y > maxWhite.Y)) { setErrorString("WhitelLuminance out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if ((actualWhite.x < minWhite.x) || (actualWhite.x > maxWhite.x) || (actualWhite.y < minWhite.y) || (actualWhite.y > maxWhite.y)) { setErrorString("White chromaticity out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if ((actualRed.x < minRed.x) || (actualRed.x > maxRed.x) || (actualRed.y < minRed.y) || (actualRed.y > maxRed.y)) { setErrorString("Red chromaticity out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if ((actualGreen.x < minGreen.x) || (actualGreen.x > maxGreen.x) || (actualGreen.y < minGreen.y) || (actualGreen.y > maxGreen.y)) { setErrorString("Green chromaticity out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if ((actualBlue.x < minBlue.x) || (actualBlue.x > maxBlue.x) || (actualBlue.y < minBlue.y) || (actualBlue.y > maxBlue.y)) { setErrorString("Blue chromaticity out of range."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } if (!pi.color->computeNpm(actualRed, actualGreen, actualBlue, actualWhite, panelNpm)) { setErrorString("Unable to compute native NPM."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } printf("Actual white: %f %f %f\n", actualWhite.Y, actualWhite.x, actualWhite.y); // Drop a calibration record in the approprate spot so people // can track this later on DictItem *item = NULL; DreamColorCalibRecord *calibRec = NULL; //item = mRegistry->createDictItem("calibRecord"); item = mRegistry->createDictItem("DreamColorCalibRecord"); if (item) { std::vector<uint32_t> redLut, greenLut, blueLut; if (!pi.lut->get(redLut, greenLut, blueLut)) { setErrorString("Unable to retrieve luts."); pi.disp->setPatternGeneratorEnabled(false, pi.dispId); idle(pi.disp->patternGeneratorDisableTime(pi.dispId), NULL); return false; } calibRec = (DreamColorCalibRecord *)(item); if (calibRec) { DictHash *hash = NULL; Dict *chainDict = NULL; Dict *dstDict = NULL; std::vector<Plugin *> plugins = mRegistry->queryByName("DictHash"); if (!plugins.empty()) { hash = dynamic_cast<DictHash *>(plugins[0]); if (hash) { chainDict = hash->getDict(chain->getDictName()); if (chainDict) { StringDictItem *stringItem; stringItem = static_cast<StringDictItem *>( chainDict->get("DreamColorCalib::calibRecordDict")); if (stringItem) { dstDict = hash->newDict(stringItem->get()); } } } } // How do we get a meaningful device id? calibRec->setDeviceId("none"); calibRec->setCalibrationTime(time(NULL)); calibRec->setCalibrationPluginName("DreamColorCalib"); calibRec->setPreset(target.getPresetId()); calibRec->setPresetName(target.getName()); calibRec->setTargetWhite(target.getWhite()); calibRec->setTargetRed(target.getRed()); calibRec->setTargetGreen(target.getGreen()); calibRec->setTargetBlue(target.getBlue()); calibRec->setMeasuredWhite(actualWhite); calibRec->setMeasuredRed(actualRed); calibRec->setMeasuredGreen(actualGreen); calibRec->setMeasuredBlue(actualBlue); calibRec->setLut("red", redLut); calibRec->setLut("green", greenLut); calibRec->setLut("blue", blueLut); if (pi.disp) { uint32_t regValues[4]; if (pi.disp->getBacklightRegRaw(regValues[0], regValues[1], regValues[2], regValues[3], pi.dispId, chain)) { calibRec->setBrightnessReg(regValues[3]); } } if ((dstDict) && (target.getCalibRecordName() != std::string(""))) { dstDict->set(target.getCalibRecordName(), calibRec); dstDict->debug(); } } } // Turn off the pattern generator if (!pi.disp->setPatternGeneratorEnabled(false, pi.dispId)) { // If this happens, well, that sucks. I'm not sure we // can recover without power-cycling setErrorString("ERROR: Can't disable pattern generator."); return false; } if (!idle(pi.disp->patternGeneratorDisableTime(pi.dispId), chain)) { return false; } return true; } // ---------------------------------------- // // protected bool Ookala::DreamColorCalib::wasCancelled( PluginData &pi, PluginChain *chain, bool patternGenEnabled) { if (chain->wasCancelled()) { setErrorString("Execution cancelled."); if (patternGenEnabled) { pi.disp->setPatternGeneratorEnabled(false, pi.dispId); } return true; } return false; } // ------------------------------------- // // Periodically test if we've been cancelled or not. If so, // return false. // // protected bool Ookala::DreamColorCalib::idle(double seconds, PluginChain *chain) { uint32_t sleepUs = static_cast<uint32_t>( (seconds - floor(seconds)) * 1000000.0); #ifdef _WIN32 Sleep(sleepUs / 1000.0); #else usleep(sleepUs); #endif if (chain) { if (chain->wasCancelled()) { setErrorString("Execution cancelled."); return false; } } for (uint32_t i=0; i<static_cast<uint32_t>(floor(seconds)); ++i) { #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif if (chain) { if (chain->wasCancelled()) { setErrorString("Execution cancelled."); return false; } } } if (chain) { if (chain->wasCancelled()) { setErrorString("Execution cancelled."); return false; } } return true; }
35.813853
153
0.54941
SchademanK
c51e70df53ff4ef05d75a898a1bccdcaab7a530b
585
cpp
C++
src/Model/DerivedObjects/Bullet.cpp
Raffson/Space-Invaders
5c390f0989e7354943c384059ce5d1d63d0a6100
[ "MIT" ]
1
2020-05-24T02:42:47.000Z
2020-05-24T02:42:47.000Z
src/Model/DerivedObjects/Bullet.cpp
Raffson/Space-Invaders
5c390f0989e7354943c384059ce5d1d63d0a6100
[ "MIT" ]
null
null
null
src/Model/DerivedObjects/Bullet.cpp
Raffson/Space-Invaders
5c390f0989e7354943c384059ce5d1d63d0a6100
[ "MIT" ]
null
null
null
/* * Bullet.cpp * * Created on: Nov 21, 2013 * Author: raffson */ #include "Bullet.h" namespace AR { Bullet::Bullet(const Location& loc, const float& s) : Object(loc, s) { } Bullet::~Bullet() { } void Bullet::MoveLeft() { //should not be able to move left } void Bullet::MoveRight() { //should not be able to move right } void Bullet::MoveUp() { if(pos.y < 150) pos.y += speed; } void Bullet::MoveDown() { if(pos.y > -725) pos.y -= speed; } const bool Bullet::Alive() const { return false; } void Bullet::Revive() { } void Bullet::Die() { } } // namespace AR
14.268293
72
0.615385
Raffson
c520886c21dbd449c1f42be232463c022b1d0384
3,281
cpp
C++
src/physics/island.cpp
N500/D3D12Renderer
7a0d247564800a0e09f02c37e6e26c557723fe3a
[ "MIT" ]
18
2021-01-27T09:50:49.000Z
2022-03-17T19:03:43.000Z
src/physics/island.cpp
N500/D3D12Renderer
7a0d247564800a0e09f02c37e6e26c557723fe3a
[ "MIT" ]
1
2021-04-18T10:38:36.000Z
2021-04-18T10:38:36.000Z
src/physics/island.cpp
N500/D3D12Renderer
7a0d247564800a0e09f02c37e6e26c557723fe3a
[ "MIT" ]
2
2022-01-09T13:16:09.000Z
2022-01-12T18:52:31.000Z
#include "pch.h" #include "island.h" #include "core/cpu_profiling.h" void buildIslands(memory_arena& arena, constraint_body_pair* bodyPairs, uint32 numBodyPairs, uint32 numRigidBodies, uint16 dummyRigidBodyIndex, const constraint_offsets& offsets) { CPU_PROFILE_BLOCK("Build islands"); uint32 islandCapacity = numBodyPairs; uint16* allIslands = arena.allocate<uint16>(islandCapacity); memory_marker marker = arena.getMarker(); uint32 count = numRigidBodies + 1; // 1 for the dummy. uint16* numConstraintsPerBody = arena.allocate<uint16>(count, true); for (uint32 i = 0; i < numBodyPairs; ++i) { constraint_body_pair pair = bodyPairs[i]; ++numConstraintsPerBody[pair.rbA]; ++numConstraintsPerBody[pair.rbB]; } uint16* offsetToFirstConstraintPerBody = arena.allocate<uint16>(count); uint16 currentOffset = 0; for (uint32 i = 0; i < count; ++i) { offsetToFirstConstraintPerBody[i] = currentOffset; currentOffset += numConstraintsPerBody[i]; } struct body_pair_reference { uint16 otherBody; uint16 pairIndex; }; body_pair_reference* pairReferences = arena.allocate<body_pair_reference>(numBodyPairs * 2); uint16* counter = arena.allocate<uint16>(count); memcpy(counter, offsetToFirstConstraintPerBody, sizeof(uint16) * count); for (uint32 i = 0; i < numBodyPairs; ++i) { constraint_body_pair pair = bodyPairs[i]; pairReferences[counter[pair.rbA]++] = { pair.rbB, (uint16)i }; pairReferences[counter[pair.rbB]++] = { pair.rbA, (uint16)i }; } uint16* rbStack = arena.allocate<uint16>(count); uint32 stackPtr; bool* alreadyVisited = arena.allocate<bool>(count, true); bool* alreadyOnStack = arena.allocate<bool>(count, true); uint32 islandPtr = 0; for (uint16 rbIndexOuter = 0; rbIndexOuter < (uint16)numRigidBodies; ++rbIndexOuter) { if (alreadyVisited[rbIndexOuter] || rbIndexOuter == dummyRigidBodyIndex) { continue; } // Reset island. uint32 islandStart = islandPtr; rbStack[0] = rbIndexOuter; alreadyOnStack[rbIndexOuter] = true; stackPtr = 1; while (stackPtr != 0) { uint16 rbIndex = rbStack[--stackPtr]; assert(rbIndex != dummyRigidBodyIndex); assert(!alreadyVisited[rbIndex]); alreadyVisited[rbIndex] = true; // Push connected bodies. uint32 startIndex = offsetToFirstConstraintPerBody[rbIndex]; uint32 count = numConstraintsPerBody[rbIndex]; for (uint32 i = startIndex; i < startIndex + count; ++i) { body_pair_reference ref = pairReferences[i]; uint16 other = ref.otherBody; if (!alreadyOnStack[other] && other != dummyRigidBodyIndex) // Don't push dummy to stack. We don't want to grow islands over the dummy. { alreadyOnStack[other] = true; rbStack[stackPtr++] = other; } if (!alreadyVisited[other]) { // Add constraint to island. assert(islandPtr < islandCapacity); allIslands[islandPtr++] = ref.pairIndex; } } } // Process island. uint32 islandSize = islandPtr - islandStart; if (islandSize > 0) { uint16* islandPairs = allIslands + islandStart; std::sort(islandPairs, islandPairs + islandSize); } } #if 0 assert(islandPtr == islandCapacity); for (uint32 i = 0; i < numRigidBodies; ++i) { assert(alreadyVisited[i]); } #endif arena.resetToMarker(marker); }
25.238462
178
0.706187
N500
c523658548de1ac5bde7283a1cdcabe837a4ba7b
1,069
cpp
C++
hackerrank/algorithms/search/missing-numbers.cpp
maximg/comp-prog
3d7a3e936becb0bc25b890396fa2950ac072ffb8
[ "MIT" ]
null
null
null
hackerrank/algorithms/search/missing-numbers.cpp
maximg/comp-prog
3d7a3e936becb0bc25b890396fa2950ac072ffb8
[ "MIT" ]
null
null
null
hackerrank/algorithms/search/missing-numbers.cpp
maximg/comp-prog
3d7a3e936becb0bc25b890396fa2950ac072ffb8
[ "MIT" ]
null
null
null
// https://www.hackerrank.com/challenges/missing-numbers/problem #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; vector <int> missingNumbers(vector <int> arr, vector <int> brr) { vector<int> missing(100); int bmin{brr[0]}; for (auto x: brr) { ++missing[x % 100]; bmin = min(bmin, x); } for (auto x: arr) --missing[x % 100]; vector<int> result; for (int x = bmin; x < bmin + 100; ++x) { if (missing[x % 100] > 0) result.push_back(x); } return result; } int main() { int n; cin >> n; vector<int> arr(n); for(int arr_i = 0; arr_i < n; arr_i++){ cin >> arr[arr_i]; } int m; cin >> m; vector<int> brr(m); for(int brr_i = 0; brr_i < m; brr_i++){ cin >> brr[brr_i]; } vector <int> result = missingNumbers(arr, brr); for (ssize_t i = 0; i < result.size(); i++) { cout << result[i] << (i != result.size() - 1 ? " " : ""); } cout << endl; return 0; }
21.38
65
0.525725
maximg
c527ea2dc845956f912c85f6b9d7da344ff93f3b
3,333
cpp
C++
src/Graphics.cpp
HerrNamenlos123/BatteryEngine
bef5f1b81baf144176653a928c9e8ac138888b3a
[ "MIT" ]
null
null
null
src/Graphics.cpp
HerrNamenlos123/BatteryEngine
bef5f1b81baf144176653a928c9e8ac138888b3a
[ "MIT" ]
1
2021-10-07T09:59:58.000Z
2021-10-07T10:06:53.000Z
src/Graphics.cpp
HerrNamenlos123/BatteryEngine
bef5f1b81baf144176653a928c9e8ac138888b3a
[ "MIT" ]
null
null
null
#include "Battery/pch.h" #include "Battery/Graphics.h" // ImGui library #include "imgui/imgui.h" #include "imgui/imgui_internal.h" #include "imgui.h" #include "imgui_impl_allegro5.h" namespace Battery { namespace Graphics { glm::vec3 __fillcolor = { 255, 255, 255 }; glm::vec3 __strokecolor = { 0, 0, 0 }; double __thickness = 3; bool __fillenabled = true; bool __strokeenabled = true; enum class LINECAP __linecap = LINECAP::ROUND; enum class LINEJOIN __linejoin = LINEJOIN::ROUND; void DrawBackground(glm::vec3 color) { al_clear_to_color(ConvertAllegroColor(color)); } void DrawBackground(glm::vec4 color) { al_clear_to_color(ConvertAllegroColor(color)); } void Fill(glm::vec3 color) { __fillcolor = color; __fillenabled = true; } void Stroke(glm::vec3 color, double thickness) { __strokecolor = color; __thickness = thickness; __strokeenabled = true; } void NoFill() { __fillenabled = false; } void NoStroke() { __strokeenabled = false; } void UseLineCap(enum class LINECAP linecap) { __linecap = linecap; } void UseLineJoin(enum class LINEJOIN linejoin) { __linejoin = linejoin; } void DrawLine(glm::vec2 p1, glm::vec2 p2) { if (__strokeenabled) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(__strokecolor), static_cast<float>(__thickness)); } } void DrawTriangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawFilledTriangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawRectangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawFilledRectangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawRoundedRectangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawFilledRoundedRectangle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawCircle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } void DrawFilledCircle(glm::vec2 p1, glm::vec2 p2, double thickness, glm::vec3 color) { al_draw_line(p1.x, p1.y, p2.x, p2.y, ConvertAllegroColor(color), static_cast<float>(thickness)); } ALLEGRO_COLOR ConvertAllegroColor(glm::vec3 color) { return al_map_rgb(color.r, color.g, color.b); } ALLEGRO_COLOR ConvertAllegroColor(glm::vec4 color) { return al_map_rgba(color.r, color.g, color.b, color.a); } glm::vec4 ConvertAllegroColor(ALLEGRO_COLOR color) { unsigned char r, g, b, a; al_unmap_rgba(color, &r, &g, &b, &a); return glm::vec4(r, g, b, a); } } }
28.008403
110
0.69667
HerrNamenlos123
c52aa1f923212c0b4ae0d12329313cd1edf83658
1,163
cpp
C++
AIC/AIC'20 - Level 2 Training Contests/Contest #3/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AIC/AIC'20 - Level 2 Training Contests/Contest #3/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AIC/AIC'20 - Level 2 Training Contests/Contest #3/B.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
//https://vjudge.net/contest/416541#problem/B #include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; ll mod = 1e9 + 7; ll bs (vector<pair<ll, ll>> &v, ll f) { ll l = 0, r = v.size () - 1, ans = 0; while (l <= r) { ll mid = l + (r - l) / 2; if (v[mid].F <= f) l = mid + 1, ans = v[mid].S; else r = mid - 1; } return ans; } void solve () { ll n, q; cin >> n >> q; map<ll, ll> a; for (ll i = 0; i < n; ++i) { ll d, h, m, r; cin >> d >> h >> m >> r; ll start = (d * 60 * 60) + (h * 60) + m; ll end = start + (r * 60 * 60); a[start]++, a[end]--; } vector<pair<ll, ll>> dp; for (auto& x : a) dp.push_back (make_pair (x.F, x.S)); for (ll i = 1; i < dp.size (); ++i) dp[i].S += dp[i - 1].S; while (q--) { ll d, h, m; cin >> d >> h >> m; ll f = (d * 60 * 60) + (h * 60) + m; cout << bs (dp, f) << "\n"; } } int main () { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); ll t; cin >> t; while (t--) solve (); }
21.943396
63
0.426483
MaGnsio
c52de22bc9c35eeee3a86a15ad2c70a26233f2f7
516
cpp
C++
res/src/PicSeeOne/Tool_Place/PicTool.cpp
jxcjxcjzx/picSeeOne
171f3a4588d34ffbe3c43f17f5cc906e6eca5b62
[ "Apache-2.0" ]
null
null
null
res/src/PicSeeOne/Tool_Place/PicTool.cpp
jxcjxcjzx/picSeeOne
171f3a4588d34ffbe3c43f17f5cc906e6eca5b62
[ "Apache-2.0" ]
null
null
null
res/src/PicSeeOne/Tool_Place/PicTool.cpp
jxcjxcjzx/picSeeOne
171f3a4588d34ffbe3c43f17f5cc906e6eca5b62
[ "Apache-2.0" ]
null
null
null
template <class BeingCounted> class Counted { public: class TooManyObjects{}; // used to be throwed out static int objectCount(){return numObjects;} protected: Counted(); Counted(const Counted& rhs); ~Counted(){--numObjects;} private: static int numObjects; static const size_t maxObjects; void init(); }; template<class BeingCounted> Counted<BeingCounted>::Counted() { init(); } template<class BeingCounted> void Counted<BeingCounted>::init() { if(numObjects>=maxObjects) throw TooManyObjects(); ++numObjects; }
17.793103
50
0.755814
jxcjxcjzx
c5346eaff5201f731e266b53b16c2b0dd1d97d8d
688
cpp
C++
src/Pipeline/TimedWorkWrapper_Test.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
2
2021-12-17T17:35:07.000Z
2022-01-11T12:38:00.000Z
src/Pipeline/TimedWorkWrapper_Test.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
null
null
null
src/Pipeline/TimedWorkWrapper_Test.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
2
2018-01-15T06:10:07.000Z
2021-07-08T19:40:49.000Z
/* * TimedWorkWrapper_Test.cpp * * Created on: Aug 27, 2017 * Author: Richard * * Copyright 2017 Richard Stilborn * Licensed under the MIT License */ #include "TimedWorkWrapper.h" #include <gtest/gtest.h> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <memory> void ttw_test_function(const int i) { if (i < 0) return; } TEST(TimedWorkWrapperConstruct, Success) { boost::asio::io_service io_service; std::shared_ptr<pipeline::TimeStatsQueue> tsq(new pipeline::TimeStatsQueue()); try { pipeline::TimedWorkWrapper<const int> tww(io_service, boost::bind(ttw_test_function, 1), 11, tsq); } catch (const char* msg) { FAIL() << msg; } }
21.5
102
0.688953
rcstilborn
c534fb6ca70c053d8e069d69de9822e139d0a52d
4,442
cpp
C++
Axis.Capsicum/foundation/computing/GPUManager.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Capsicum/foundation/computing/GPUManager.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Capsicum/foundation/computing/GPUManager.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#include "GPUManager.hpp" #include <cuda_runtime.h> #include <cuda.h> #include <vector> namespace afc = axis::foundation::computing; #define ERR_CHECK(x) {cudaError_t errId = x; if (errId != CUDA_SUCCESS) throw errId;} #define AXIS_MIN_CUDA_COMPUTE_MAJOR_VERSION 2 #define AXIS_MIN_CUDA_COMPUTE_MINOR_VERSION 0 namespace { /** * Returns if, for a given device, the capabilities required by this * application are present. * * @param gpuProp The GPU properties descriptor. * * @return true if it is a compatible device, false otherwise. **/ inline bool IsCompatibleDevice(const cudaDeviceProp& gpuProp) { bool versionCompatible = ((gpuProp.major == AXIS_MIN_CUDA_COMPUTE_MAJOR_VERSION && gpuProp.minor >= AXIS_MIN_CUDA_COMPUTE_MINOR_VERSION) || (gpuProp.major > AXIS_MIN_CUDA_COMPUTE_MAJOR_VERSION)); bool deviceAvailable = gpuProp.computeMode != cudaComputeMode::cudaComputeModeProhibited; return (versionCompatible && deviceAvailable); } } afc::GPUManager::GPUManager( void ) { gpuCount_ = 0; realGpuIndex_ = nullptr; gpuCapabilities_ = nullptr; } afc::GPUManager::~GPUManager( void ) { if (realGpuIndex_) delete [] realGpuIndex_; if (gpuCapabilities_) delete [] gpuCapabilities_; } void afc::GPUManager::Rescan( void ) { std::lock_guard<std::mutex> guard(mutex_); PopulateGPU(); for (int i = 0; i < gpuCount_; i++) { int gpuIndex = realGpuIndex_[i]; gpuCapabilities_[i] = ReadGPUCapability(gpuIndex); } } int afc::GPUManager::GetAvailableGPUCount( void ) const { std::lock_guard<std::mutex> guard(mutex_); return gpuCount_; } afc::GPUCapability afc::GPUManager::GetGPUCapabilities( int gpuIndex ) const { return gpuCapabilities_[gpuIndex]; } void afc::GPUManager::PopulateGPU( void ) { int totalGpuCount = 0; std::vector<int> indexes; try { // scan for available devices cudaError_t errId = cudaGetDeviceCount(&totalGpuCount); if (errId == cudaErrorInsufficientDriver || errId == cudaErrorNoDevice) { // there are no compatible GPUs in the system totalGpuCount = 0; } for (int i = 0; i < totalGpuCount; i++) { cudaDeviceProp gpuProp; ERR_CHECK(cudaGetDeviceProperties(&gpuProp, i)); if (IsCompatibleDevice(gpuProp)) { indexes.push_back(i); } } } catch (int&) { // an error occurred // TODO: warn it } // add all gathered devices gpuCount_ = (int)indexes.size(); if (realGpuIndex_) delete [] realGpuIndex_; if (gpuCapabilities_) delete [] gpuCapabilities_; realGpuIndex_ = new int[gpuCount_]; gpuCapabilities_ = new GPUCapability[gpuCount_]; for (int i = 0; i < gpuCount_; i++) { realGpuIndex_[i] = indexes[i]; } } afc::GPUCapability afc::GPUManager::ReadGPUCapability( int index ) { try { cudaDeviceProp gpuProp; ERR_CHECK(cudaGetDeviceProperties(&gpuProp, index)); String devName; StringEncoding::AssignFromASCII(gpuProp.name, devName); afc::GPUCapability caps(index); caps.Name() = devName; caps.GlobalMemorySize() = gpuProp.totalGlobalMem; caps.ConstantMemorySize() = gpuProp.totalConstMem; caps.MaxSharedMemoryPerBlock() = gpuProp.sharedMemPerBlock; caps.PCIDeviceId() = gpuProp.pciDeviceID; caps.PCIBusId() = gpuProp.pciBusID; caps.PCIDomainId() = gpuProp.pciDomainID; caps.MaxThreadPerMultiprocessor() = gpuProp.maxThreadsPerMultiProcessor; caps.MaxThreadPerBlock() = gpuProp.maxThreadsPerBlock; caps.MaxThreadDimX() = gpuProp.maxThreadsDim[0]; caps.MaxThreadDimY() = gpuProp.maxThreadsDim[1]; caps.MaxThreadDimZ() = gpuProp.maxThreadsDim[2]; caps.MaxGridDimX() = gpuProp.maxGridSize[0]; caps.MaxGridDimY() = gpuProp.maxGridSize[1]; caps.MaxGridDimZ() = gpuProp.maxGridSize[2]; caps.MaxAsynchronousOperationCount() = gpuProp.asyncEngineCount; caps.IsWatchdogTimerEnabled() = (gpuProp.kernelExecTimeoutEnabled != 0); caps.IsTeslaComputeClusterEnabled() = (gpuProp.tccDriver != 0); caps.IsUnifiedAddressEnabled() = (gpuProp.unifiedAddressing != 0); caps.IsECCEnabled() = (gpuProp.ECCEnabled != 0); caps.IsDiscreteDevice() = (gpuProp.integrated == 0); caps.MaxThreadsInGPU() = (gpuProp.maxGridSize[0]*gpuProp.maxGridSize[1]*gpuProp.maxGridSize[2]*gpuProp.maxThreadsPerBlock); return caps; } catch (int&) { // an error occurred calling CUDA runtime functions return GPUCapability(index); } }
30.634483
127
0.708915
renato-yuzup
c53744556267aefd9647f1eb957ceca53b9cf48b
13,529
cpp
C++
lib/sck/server.cpp
TheMarlboroMan/listener_service
955b952a9c36d4a1ba3704551a9b1ac1d3dd2fb8
[ "MIT" ]
null
null
null
lib/sck/server.cpp
TheMarlboroMan/listener_service
955b952a9c36d4a1ba3704551a9b1ac1d3dd2fb8
[ "MIT" ]
null
null
null
lib/sck/server.cpp
TheMarlboroMan/listener_service
955b952a9c36d4a1ba3704551a9b1ac1d3dd2fb8
[ "MIT" ]
null
null
null
#include <sck/server.h> #include <sck/exception.h> #include <lm/sentry.h> #include <cstring> //Memset. #include <arpa/inet.h> //inet_ntop. #include <signal.h> //Memset. #include <sys/un.h> //Local sockets... #include <iostream> /* struct addrinfo { int ai_flags; // AI_PASSIVE, AI_CANONNAME, etc. int ai_family; // AF_INET, AF_INET6, AF_UNSPEC int ai_socktype; // SOCK_STREAM, SOCK_DGRAM int ai_protocol; // use 0 for "any" size_t ai_addrlen; // size of ai_addr in bytes struct sockaddr *ai_addr; // struct sockaddr_in or _in6 char *ai_canonname; // full canonical hostname struct addrinfo *ai_next; // linked list, next node }; struct sockaddr { unsigned short sa_family; // address family, AF_xxx char sa_data[14]; // 14 bytes of protocol address }; struct sockaddr_in { short int sin_family; // Address family, AF_INET unsigned short int sin_port; // Port number struct in_addr sin_addr; // Internet address unsigned char sin_zero[8]; // Same size as struct sockaddr }; */ using namespace sck; server::server(const server_config& _sc, lm::logger * _log) : //TODO: Why don't just keep the sc instance and refer to it????? ssl_wrapper(_sc.use_ssl_tls ? new openssl_wrapper(_sc.ssl_tls_cert_path, _sc.ssl_tls_key_path, _log) : nullptr), reader{_sc.blocksize, ssl_wrapper.get()}, config(_sc), log(_log), security_thread_count{0} { } server::~server() { if(log) { lm::log(*log, lm::lvl::info)<<"Cleaning up clients..."<<std::endl; } for(int i=0; i<=in_sockets.max_descriptor; i++) { if(clients.count(i)) { disconnect_client(clients.at(i)); } } ssl_wrapper.reset(nullptr); if(server_config::type::sock_unix==config.socktype) { unlink(config.unix_sock_path.c_str()); } if(log) { lm::log(*log, lm::lvl::info)<<"Cleanup completed..."<<std::endl; } } bool server::is_secure() const { return nullptr!=ssl_wrapper; } /* From man getaddrinfo: If the AI_PASSIVE flag is specified in hints.ai_flags, and node is NULL, then the returned socket addresses will be suitable for bind(2)ing a socket that will accept(2) connections. The returned socket address will contain the "wildcard address" (INADDR_ANY for IPv4 addresses, IN6ADDR_ANY_INIT for IPv6 address). The wildcard address is used by applications (typically servers) that intend to accept connections on any of the hosts's network addresses. If node is not NULL, then the AI_PASSIVE flag is ignored. If the AI_PASSIVE flag is not set in hints.ai_flags, then the returned socket addresses will be suitable for use with connect(2), sendto(2), or sendmsg(2). If node is NULL, then the network address will be set to the loopback interface address (INADDR_LOOPBACK for IPv4 addresses, IN6ADDR_LOOPBACK_INIT for IPv6 address); this is used by applications that intend to communicate with peers running on the same host. */ void server::start() { switch(config.socktype) { case server_config::type::sock_unix: setup_unix(); break; case server_config::type::sock_inet: setup_inet(); break; } if(::listen(file_descriptor, config.backlog)==-1) { throw std::runtime_error("Could not set the server to listen"); } in_sockets.max_descriptor=file_descriptor > in_sockets.max_descriptor ? file_descriptor : in_sockets.max_descriptor; FD_ZERO(&in_sockets.set); FD_SET(file_descriptor, &in_sockets.set); if(file_descriptor==-1) { throw std::runtime_error("Cannot run if server is not started"); } loop(); } void server::setup_inet() { //Fill up the hints... addrinfo hints; memset(&hints, 0, sizeof hints); hints.ai_family=AF_UNSPEC; hints.ai_socktype=SOCK_STREAM; hints.ai_flags=AI_PASSIVE; //Get the address info. addrinfo *servinfo=nullptr; //TODO: Specify the IP in which we are listening... //We could use "127.0.0.1", it would not give us the wildcard 0.0.0.0. int getaddrinfo_res=getaddrinfo(nullptr, std::to_string(config.port).c_str(), &hints, &servinfo); if(getaddrinfo_res != 0) { throw std::runtime_error("Failed to get address info :"+std::string(gai_strerror(getaddrinfo_res))); } //Bind to the first good result. addrinfo *p=servinfo; while(nullptr!=p) { file_descriptor=socket(p->ai_family, p->ai_socktype, p->ai_protocol); if(-1!=file_descriptor) { //Force adress reuse, in case a previous process is still hogging the port. int optval=1; if(setsockopt(file_descriptor, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int))==-1) { throw std::runtime_error("Unable to force address reuse"); } if(0==bind(file_descriptor, p->ai_addr, p->ai_addrlen)) { address=ip_from_addrinfo(*p); break; //Everything is ok... Break the loop!. } close(file_descriptor); } p=p->ai_next; } freeaddrinfo(servinfo); if(!p) { throw std::runtime_error("Could not bind socket! Perhaps the port is still in use?"); } if(log) { lm::log(*log, lm::lvl::info)<<"Inet server started on "<<address<<":"<<config.port<<" with FD "<<file_descriptor<<std::endl; } } void server::setup_unix() { file_descriptor=socket(AF_UNIX, SOCK_STREAM, 0); if(-1==file_descriptor) { throw std::runtime_error("Could not generate file descriptor for local socket"); } //Directly from the man pages. struct sockaddr_un my_addr; memset(&my_addr, 0, sizeof(struct sockaddr_un)); my_addr.sun_family=AF_UNIX; strncpy(my_addr.sun_path, config.unix_sock_path.c_str(), sizeof(my_addr.sun_path) - 1); if(bind(file_descriptor, (struct sockaddr *) &my_addr, sizeof(struct sockaddr_un)) == -1) { throw std::runtime_error("Could not bind local socket"); } if(log) { lm::log(*log, lm::lvl::info)<<"Unix server started on "<<config.unix_sock_path<<" with FD "<<file_descriptor<<std::endl; } } void server::stop() { running=false; if(security_thread_count) { if(log) { lm::log(*log, lm::lvl::info)<<"Dangling client security threads detected... waiting. "<<security_thread_count<<" threads remain..."<<std::endl; } std::this_thread::sleep_for(std::chrono::milliseconds(150)); } if(log) { lm::log(*log, lm::lvl::info)<<"Stopping server now. Will complete the current listening cycle."<<std::endl; } } void server::loop() { fd_set copy_in; //timeval timeout{0, 100000}; //Struct of 0.1 seconds. timeval timeout{1, 0}; //Struct of 1 seconds. Select will exit once anything is ready, regardless of the timeout. if(log) { lm::log(*log, lm::lvl::info)<<"Starting to listen now"<<std::endl; } running=true; while(running) { try { copy_in=in_sockets.set; //Swap... select may change its values!. timeout.tv_sec=5; timeout.tv_usec=0; //select MAY write on these values and cause us to hog CPU. int select_res=select(in_sockets.max_descriptor+1, &copy_in, nullptr, nullptr, &timeout); if(select_res==-1) { throw std::runtime_error("Select failed!"); } if(select_res > 0) { //TODO: This happens to be reading in stdin and out too :D. for(int i=0; i<=in_sockets.max_descriptor; i++) { if(FD_ISSET(i, &copy_in)) { if(i==file_descriptor) { //New connection on listener file_descriptor. handle_new_connection(); } else { //New data on client file descriptor. handle_client_data(clients.at(i)); } } } } } catch(std::exception &e) { if(log) { lm::log(*log, lm::lvl::info)<<"Listener thread caused an exception: "<<e.what()<<std::endl; } } } if(log) { lm::log(*log, lm::lvl::info)<<"Listening stopped"<<std::endl; } if(nullptr!=logic) { logic->handle_server_shutdown(); } } void server::handle_new_connection() { sockaddr_in client_address; socklen_t l=sizeof(client_address); int client_descriptor=accept(file_descriptor, (sockaddr *) &client_address, &l); if(client_descriptor==-1) { throw std::runtime_error("Failed on accept for new connection"); } clients.insert( { client_descriptor, connected_client( client_descriptor, server_config::type::sock_unix==config.socktype ? "LOCAL" : ip_from_sockaddr_in(client_address) ) } ); FD_SET(client_descriptor, &in_sockets.set); in_sockets.max_descriptor=client_descriptor > in_sockets.max_descriptor ? client_descriptor : in_sockets.max_descriptor; auto& client=clients.at(client_descriptor); std::thread client_security_thread(&sck::server::set_client_security, this, std::ref(client)); client_security_thread.detach(); if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<client.descriptor<<" from "<<client.ip<<" status: "<<client.get_readable_status()<<std::endl; } if(logic) { logic->handle_new_connection(client); } } void server::set_client_security(connected_client& _client) { if(log) { lm::log(*log, lm::lvl::info)<<"Starting thread to determine client " <<_client.descriptor<<":"<<_client.ip <<" security level, max timeout of " <<config.ssl_set_security_seconds<<"sec and " <<config.ssl_set_security_milliseconds<<"ms"<<std::endl; } security_thread_count_guard guard(security_thread_count); //A timeout is be used to try and see if the client says something. //In the case of SSL/TLS connections the client will speak right away to //negotiate the handshake and everything will work out, but not secure //clients will stay silent, hence this timeout. struct timeval tv; tv.tv_sec=config.ssl_set_security_seconds; tv.tv_usec=config.ssl_set_security_milliseconds; setsockopt(_client.descriptor, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv); char head=0; auto recvres=recv(_client.descriptor, &head, 1, MSG_PEEK); //Of course, let us reset the timeout. tv.tv_sec=0; setsockopt(_client.descriptor, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv); //The client did not speak, we just know it is not secure. if(-1==recvres) { if(log) { lm::log(*log, lm::lvl::info)<<"Client " <<_client.descriptor<<":"<<_client.ip <<" is deemed not to use TLS by timeout"<<std::endl; } secure_client(_client, false); return; } try { //22 means start of SSL/TLS handshake. if(22==head) { //Secure clients connecting to non-secure servers are rejected. if(!is_secure()) { throw incompatible_client_exception(); } if(log) { lm::log(*log, lm::lvl::info)<<"Client " <<_client.descriptor<<":"<<_client.ip <<" uses TLS"<<std::endl; } secure_client(_client, true); ssl_wrapper->accept(_client.descriptor); } else { //A client with no secure capabilities spoke before the timeout... if(log) { lm::log(*log, lm::lvl::info)<<"Client " <<_client.descriptor<<":"<<_client.ip <<" is deemed not to use TLS by invalid handshake sequence"<<std::endl; } secure_client(_client, false); } } catch(incompatible_client_exception& e) { if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<_client.descriptor<<" from "<<_client.ip<<" rejected, uses SSL/TLS when server cannot and will be disconnected"<<std::endl; } disconnect_client(_client); } catch(openssl_exception &e) { if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<_client.descriptor<<" from "<<_client.ip<<" caused SSL/TLS exception and will be disconnected: "<<e.what()<<std::endl; } disconnect_client(_client); } } void server::secure_client(connected_client& _client, bool _secure) { if(_secure) { _client.set_secure(); } else { _client.set_not_secure(); } if(logic) { logic->handle_client_security(_client, _secure); } } void server::handle_client_data(connected_client& _client) { //Clients that haven't been validated yet should have their messages //ignored. try { std::string message=reader.read(_client); if(logic) { logic->handle_client_data(message, _client); } } catch(read_exception& e) { if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<_client.descriptor<<" read failure: "<<e.what()<<std::endl; } if(logic) { logic->handle_exception(e, _client); } } catch(client_disconnected_exception& e) { if(log) { lm::log(*log, lm::lvl::info)<<"Client "<<_client.descriptor<<" disconnected on client side..."<<std::endl; } if(logic) { logic->handle_exception(e, _client); } } } void server::disconnect_client(const sck::connected_client& _cl) { int client_key=_cl.descriptor; if(!clients.count(client_key)) { throw std::runtime_error("Attempted to disconnect invalid client"); } if(logic) { logic->handle_dissconection(clients.at(client_key)); } //Well, the key is actually the file descriptor, but that could change. int client_fd=clients.at(client_key).descriptor; close(client_fd); FD_CLR(client_fd, &in_sockets.set); clients.erase(client_key); if(log) { lm::log(*log, lm::lvl::info) << "Client " << client_fd << " disconnected" << std::endl; } } void server::set_logic(logic_interface& _li) { logic=&_li; } client_writer server::create_writer() { return client_writer(ssl_wrapper.get()); } //TODO: Suckage: fix the calling point and pass the ai_addr damn it... std::string sck::ip_from_addrinfo(const addrinfo& p) { //gethostname... char ip[INET6_ADDRSTRLEN]; inet_ntop(p.ai_family, &(reinterpret_cast<sockaddr_in*>(p.ai_addr))->sin_addr, ip, sizeof ip); return std::string(ip); } std::string sck::ip_from_sockaddr_in(const sockaddr_in& p) { //getpeername... char ip[INET6_ADDRSTRLEN]; inet_ntop(p.sin_family, &(p.sin_addr), ip, sizeof ip); return std::string(ip); }
27.058
167
0.688151
TheMarlboroMan
c53e306b453a4b49d262e15673de0b6d7baca7c2
1,589
hpp
C++
engine/src/engine/input/InputManager.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
1
2018-08-14T05:45:29.000Z
2018-08-14T05:45:29.000Z
engine/src/engine/input/InputManager.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
null
null
null
engine/src/engine/input/InputManager.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
null
null
null
// This file is part of CaptureTheBanana++. // // Copyright (c) 2018 the CaptureTheBanana++ contributors (see CONTRIBUTORS.md) // This file is licensed under the MIT license; see LICENSE file in the root of this // project for details. #ifndef ENGINE_KEYBOARDMANAGER_HPP #define ENGINE_KEYBOARDMANAGER_HPP #include <string> #include <vector> namespace ctb { namespace parser { class GameConfig; } namespace engine { class Input; class Keyboard; /// Class that handles user input class InputManager { public: InputManager(parser::GameConfig* config); virtual ~InputManager(); bool update(); /// Check, if the keyboard is in the inputs bool hasKeyboard() const { return m_keyboard != 0 && !m_addKeyboard; } /// Return the keyboard pointer. May be null! Keyboard* getKeyboard() const { return m_keyboard; } /// Returns a list of input devices std::vector<Input*>& getInputs() { return m_inputs; } /// Add a keyboard to the inputs void addKeyboard(); /// Remove the keyboard from the inputs void removeKeyboard(); private: /// Initialize all inputs found on execution void setupDefaultInputs(const std::string& controllerMapFile); /// A flag that indicates, if m_keyboard should be added to m_inputs after /// the iteration over m_inputs is done. bool m_addKeyboard; /// A Vector of all registered inputs std::vector<Input*> m_inputs; /// To control the keyboard in m_inputs Keyboard* m_keyboard; }; } // namespace engine } // namespace ctb #endif // ENGINE_KEYBOARDMANAGER_HPP
24.446154
84
0.702329
CaptureTheBanana
c53ff2426e6f9f7a26a85f6cfc6dda4cac796a33
2,690
hpp
C++
routing/car_directions.hpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
1
2022-02-18T17:26:50.000Z
2022-02-18T17:26:50.000Z
routing/car_directions.hpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
null
null
null
routing/car_directions.hpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
null
null
null
#pragma once #include "routing/directions_engine.hpp" #include "routing_common/num_mwm_id.hpp" #include <map> #include <memory> #include <vector> namespace routing { class CarDirectionsEngine : public DirectionsEngine { public: CarDirectionsEngine(MwmDataSource & dataSource, std::shared_ptr<NumMwmIds> numMwmIds); protected: virtual size_t GetTurnDirection(turns::IRoutingResult const & result, size_t const outgoingSegmentIndex, NumMwmIds const & numMwmIds, RoutingSettings const & vehicleSettings, turns::TurnItem & turn); virtual void FixupTurns(std::vector<geometry::PointWithAltitude> const & junctions, Route::TTurns & turnsDir); }; /*! * \brief Selects lanes which are recommended for an end user. */ void SelectRecommendedLanes(Route::TTurns & turnsDir); void FixupCarTurns(std::vector<geometry::PointWithAltitude> const & junctions, Route::TTurns & turnsDir); /*! * \brief Finds an U-turn that starts from master segment and returns how many segments it lasts. * \returns an index in |segments| that has the opposite direction with master segment * (|segments[currentSegment - 1]|) and 0 if there is no UTurn. * \warning |currentSegment| must be greater than 0. */ size_t CheckUTurnOnRoute(turns::IRoutingResult const & result, size_t const outgoingSegmentIndex, NumMwmIds const & numMwmIds, RoutingSettings const & vehicleSettings, turns::TurnItem & turn); /*! * \brief Calculates a turn instruction if the ingoing edge or (and) the outgoing edge belongs to a * roundabout. * \return Returns one of the following results: * - TurnDirection::EnterRoundAbout if the ingoing edge does not belong to a roundabout * and the outgoing edge belongs to a roundabout. * - TurnDirection::StayOnRoundAbout if the ingoing edge and the outgoing edge belong to a * roundabout * and there is a reasonalbe way to leave the junction besides the outgoing edge. * This function does not return TurnDirection::StayOnRoundAbout for small ways to leave the * roundabout. * - TurnDirection::NoTurn if the ingoing edge and the outgoing edge belong to a roundabout * (a) and there is a single way (outgoing edge) to leave the junction. * (b) and there is a way(s) besides outgoing edge to leave the junction (the roundabout) * but it is (they are) relevantly small. */ turns::CarDirection GetRoundaboutDirectionBasic(bool isIngoingEdgeRoundabout, bool isOutgoingEdgeRoundabout, bool isMultiTurnJunction, bool keepTurnByHighwayClass); } // namespace routing
42.03125
108
0.715613
dbf256
c543bf36206b1938e768f1f7dd2e8d1c2d5e72cc
17,816
cpp
C++
bwchart/common/sysinfo.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/common/sysinfo.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/common/sysinfo.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
// #include "stdafx.h" #include <windows.h> #include <wincon.h> #include <stdlib.h> #include <stdio.h> #include <io.h> #include <time.h> #include "sysinfo.h" static char MACP[17+1]; static char MAC[12+1]; static int nMACSearched = 0; static int gnCodingMethod = 0; static char ipconfig[32]="bwrecorder.dta"; #include<Iprtrmib.h> #include<Iphlpapi.h> //------------------------------------------------------------------------------------ static const char *_GetAdapterMAC(bool bPrettyPrint) { // get adapter info IP_ADAPTER_INFO *pInfo; IP_ADAPTER_INFO AdapterInfo[8]; ULONG size=sizeof(AdapterInfo); DWORD err = GetAdaptersInfo(&AdapterInfo[0], &size); pInfo = err == 0 ? &AdapterInfo[0] : 0; //char msg[255]; //sprintf(msg,"%lu need=%lu oneis=%lu",err,size,sizeof(AdapterInfo[0])); //if(err!=0) ::MessageBox(0,msg,"error",MB_OK); //else ::MessageBox(0,msg,"ok",MB_OK); // read all adapters info searching for the right one int i=0; int pref[8]; int maxpref=-999,maxidx=-1; memset(pref,0,sizeof(pref)); while(pInfo!=0) { // build MAC sprintf(MAC,"%02X%02X%02X%02X%02X%02X", pInfo->Address[0], pInfo->Address[1], pInfo->Address[2], pInfo->Address[3], pInfo->Address[4], pInfo->Address[5]); // count zeros in address int zeros=0; for(int j=0;j<6;j++) if(pInfo->Address[j]==0) zeros++; if(zeros>=3) pref[i]-=10; // compare to "no adapter" value if(strcmp(MAC,"444553540000")==0) pref[i]-=5; // check ip const char *pIP = &pInfo->IpAddressList.IpAddress.String[0]; if(atoi(pIP)!=0 && atoi(pIP)!=255) pref[i]++; // update max if(pref[i]>maxpref) {maxpref=pref[i]; maxidx=i;} //strcpy(msg,pInfo->AdapterName); //strcat(msg,"\r\n"); //strcat(msg,pIP); //strcat(msg,"\r\n"); //strcat(msg,MAC); //::MessageBox(0,msg,"info",MB_OK); // try next adapter pInfo = pInfo->Next; i++; } if(maxidx>=0) { // if we have a valid ip address pInfo = &AdapterInfo[maxidx]; // return MAC sprintf(MACP,"%02X-%02X-%02X-%02X-%02X-%02X", pInfo->Address[0], pInfo->Address[1], pInfo->Address[2], pInfo->Address[3], pInfo->Address[4], pInfo->Address[5]); sprintf(MAC,"%02X%02X%02X%02X%02X%02X", pInfo->Address[0], pInfo->Address[1], pInfo->Address[2], pInfo->Address[3], pInfo->Address[4], pInfo->Address[5]); return bPrettyPrint?MACP:MAC; } return 0; } //------------------------------------------------------------------------------------ // set file name for ipconfig results void NumericCoding::SetIpConfigFileName(const char *file) { strcpy(ipconfig,file); } //------------------------------------------------------------------------------------ // launch a different process static int _StartProcess(const char *pszExe, const char *pszCmdLine) { #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"_StartProcess(%s,%s)",pszExe,pszCmdLine); #endif int nvErr=-1; char *pszTmpCmdLine; STARTUPINFO si; PROCESS_INFORMATION pi; // init structures ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; // make a tmp copy of the command line because CreateProcess will modify it pszTmpCmdLine = new char[(strlen(pszExe)+ (pszCmdLine!=0 ? strlen(pszCmdLine) : 0) + 4)]; if(pszTmpCmdLine == 0) return -1; strcpy(pszTmpCmdLine,pszExe); if(pszCmdLine!=0) strcat(pszTmpCmdLine," "); if(pszCmdLine!=0) strcat(pszTmpCmdLine,pszCmdLine); // start process if(CreateProcess(NULL,pszTmpCmdLine,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi)) { // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); nvErr=0; } else { nvErr=GetLastError(); #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"CreateProcess error %lu",GetLastError()); #endif } // delete temporary command line if(pszTmpCmdLine!=0) delete []pszTmpCmdLine; return nvErr; } //------------------------------------------------------------------------------------ #define VERS_UNKNOWN 0 #define VERS_WINNT 1 #define VERS_WIN98 2 #define VERS_WIN95 3 #define VERS_WIN31 4 static int SystemVersion() { OSVERSIONINFOEX osvi; BOOL bOsVersionInfoEx; // Try calling GetVersionEx using the OSVERSIONINFOEX structure, // If that fails, try using the OSVERSIONINFO structure. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if((bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi))==0) { // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO. osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) return VERS_UNKNOWN; } switch (osvi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: return VERS_WINNT; case VER_PLATFORM_WIN32_WINDOWS: if ((osvi.dwMajorVersion > 4) || ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion > 0))) return VERS_WIN98; else return VERS_WIN95; case VER_PLATFORM_WIN32s: return VERS_WIN31; } return VERS_UNKNOWN; } //------------------------------------------------------------------------------------ // dump file will be located in same directory than executable static const char *DumpFileName() { static char DumpFile[255+1]; if ( GetModuleFileName( NULL, DumpFile, 255 ) != 0) { char *p=strrchr(DumpFile,'\\'); if(p!=0) p[1]=0; strcat(DumpFile,ipconfig); } return DumpFile; } //------------------------------------------------------------------------------------ const char *GetMACAddressUsingIPCONFIG(bool bPrettyPrint) { #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"GetMACAddressUsingIPCONFIG"); #endif // try to make sure dump file does not already exist #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"pre-remove dump file"); #endif const char *dump = DumpFileName(); remove(dump); if(access(dump,00)==0 && access(dump,06)!=0) { // if it does, maybe someone is trying to force the MAC address // so we simulate failure #ifndef ISMAGIC LOG.Print(LOG_ERROR,"Dump file is write protected"); #endif return bPrettyPrint?MACP:MAC; } // execute ipconfig in a hidden command window char cmdParam[255]; sprintf(cmdParam,"/C ipconfig /all > \"%s\"",dump); const char *cmdexe = (SystemVersion()==VERS_WINNT) ? "cmd.exe":"command.com"; _StartProcess(cmdexe, cmdParam); // open result file FILE * fp = 0; for(int i=0; i<3; i++) { // we try multiple times fp = fopen(dump,"rb"); #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"fp=%x",fp); #endif if(fp!=0) break; Sleep(1000); } if(fp==0) { #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"cant open dump file"); #endif goto Exit; } for(i=0; i<3; i++) { // read content fseek(fp,SEEK_END,0); int size = ftell(fp); if(size>0) break; Sleep(1000); } fseek(fp,SEEK_SET,0); // read content char szBuf[4096+1]; int read; read=fread(szBuf,1,sizeof(szBuf)-1,fp); szBuf[read]=0; // close file fclose(fp); // browse physical addresses char *pCur; pCur = szBuf; while(true) { // search for physical address char *p=strstr(pCur,"Physical Address"); if(p==0) p=strstr(pCur,"Adresse physique"); if(p==0) goto Exit; // if found #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"found Physical Address"); #endif // skip title while(*p!=':' && *p!=0) p++; if(*p==0) goto Exit; p++; // skip blanks while(*p==' ') p++; if(*p==0) goto Exit; //extract MAC address strncpy(MACP,p,17); MACP[17]=0; #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"Extracted MAC %s",MACP); #endif // remove dash if needed if(!bPrettyPrint) { // pair 1 MAC[0]=MACP[0]; MAC[1]=MACP[1]; // pair 2 MAC[2]=MACP[3]; MAC[3]=MACP[4]; // pair 3 MAC[4]=MACP[6]; MAC[5]=MACP[7]; // pair 4 MAC[6]=MACP[9]; MAC[7]=MACP[10]; // pair 5 MAC[8]=MACP[12]; MAC[9]=MACP[13]; // pair 6 MAC[10]=MACP[15]; MAC[11]=MACP[16]; MAC[12]=0; } // count zeros for(int i=0, zeros=0; i<6; i++) { int val; sscanf(&MACP[i*3],"%x",&val); if(val==0) zeros++; } // do we have a reasonable amount of zeros? if(zeros<=3) break; // if not, keep searching pCur = p; } Exit: #ifndef ISMAGIC LOG.Print(LOG_DEBUG1,"remove dump file"); #endif remove(dump); return bPrettyPrint?MACP:MAC; } //------------------------------------------------------------------------------------ static const char *__GetMACAddress(bool bPrettyPrint) { //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"GetMACAddress"); //#endif if(nMACSearched>1) return bPrettyPrint?MACP:MAC; nMACSearched++; strcpy(MACP,"00-00-00-00-00-00"); strcpy(MAC,"000000000000"); // get adapter info const char *macapi = _GetAdapterMAC(bPrettyPrint); if(macapi!=0) return macapi; return GetMACAddressUsingIPCONFIG(bPrettyPrint); } //------------------------------------------------------------------------------------ const char *GetMACAddress(bool bPrettyPrint) { //try once const char *mac = __GetMACAddress(bPrettyPrint); // if mac is empty if(strcmp(MAC,"000000000000")==0) { //wait a bit and try again Sleep(1000); mac = __GetMACAddress(bPrettyPrint); } else nMACSearched++; return mac; } //------------------------------------------------------------------------------------ // convert an hexadecimal letter into a digit between 0 and 15 #define VALX(ch) ((ch>='0' && ch<='9') ? (int)ch-(int)'0' : 10 + (int)ch - (int)'A') // build a magic code from: // the user name: XXXXXXXXXXX // the shop name: YYYYYYYYYYY // and the MAC : xx-xx-xx-xx-xx-xx or xxxxxxxxxxxx // Magic code is a 24 letter string. We create one unsigned word for the user name, // and the shop, and 3 unsigned words for the MAC // // return true if we builded a valid code, false if the input was wrong or MAC empty // static bool BuildCode(const char *user, const char *shop, const char *MAC, char *code) { if(user==0 || user[0]==0) return false; if(shop==0 || shop[0]==0) return false; // for newer codings we change the last long and use more of the MAC address if(stricmp(shop,"labmusic")!=0 && stricmp(user,"netcast")!=0) gnCodingMethod = 1; else gnCodingMethod = 0; // get MAC char szMAC[12+1]; if(MAC!=0) { if(MAC[2]=='-') { szMAC[0]=MAC[0]; szMAC[1]=MAC[1]; szMAC[2]=MAC[3]; szMAC[3]=MAC[4]; szMAC[4]=MAC[6]; szMAC[5]=MAC[7]; szMAC[6]=MAC[9]; szMAC[7]=MAC[10]; szMAC[8]=MAC[12]; szMAC[9]=MAC[13]; szMAC[10]=MAC[15]; szMAC[11]=MAC[16]; } else strncpy(szMAC,MAC,12); szMAC[12]=0; } else { strcpy(szMAC,GetMACAddress(false)); } if(szMAC[0]==0) return false; #ifndef ISMAGIC static int once=0; if(!once) LOG.Print(LOG_DEBUG1,"BuildCode u=[%s] s=[%s] m=[%s]",user,shop,szMAC); once=1; #endif // use last digits of MAC to build an unsigned long unsigned long ul1 = VALX(szMAC[0]); ul1 <<= 4; ul1 += VALX(szMAC[7]); ul1 <<= 4; ul1 += VALX(szMAC[5]); ul1 <<= 4; ul1 += VALX(szMAC[3]); ul1 <<= 4; ul1 += VALX(szMAC[10]); ul1 <<= 4; ul1 += VALX(szMAC[2]); ul1 <<= 4; ul1 += VALX(szMAC[6]); ul1 <<= 4; ul1 += VALX(szMAC[1]); // use last digits of MAC to build an unsigned long unsigned long ul2 = VALX(szMAC[11]); ul2 <<= 4; ul2 += VALX(szMAC[9]); ul2 <<= 4; ul2 += VALX(szMAC[4]); ul2 <<= 4; ul2 += VALX(szMAC[8]); ul2 <<= 4; ul2 += VALX(user[0]); ul2 <<= 4; ul2 += VALX(shop[0]); ul2 <<= 4; ul2 += VALX(user[1]); ul2 <<= 4; ul2 += VALX(shop[1]); // use letters of user and shop to build an unsigned long unsigned long val1=0UL; for(int i=0;i<(int)strlen(user); i++, val1+=(unsigned long)toupper(user[i]), val1<<=1); unsigned long val2=0UL; for(i=0;i<(int)strlen(shop); i++, val2+=(unsigned long)toupper(shop[i]), val2<<=1); unsigned long ul3 = (val1<<16) + (val2%0x00FF); // for newer codings we change the last long and use more of the MAC address if(gnCodingMethod==1) { unsigned short word = (unsigned short)(VALX(szMAC[2])); word <<= 4; word = (unsigned short)(word + (unsigned short)(VALX(szMAC[9]))); word <<= 4; word = (unsigned short)(word + (unsigned short)(VALX(szMAC[10]))); word <<= 4; word = (unsigned short)(word + (unsigned short)(VALX(szMAC[11]))); ul3 &= 0xFFFF0000; ul3 += word; } //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"ul1=%lu ul2=%lu ul3=%lu",ul1,ul2,ul3); //#endif // create some noise ul1+= ul3; ul2-= ul3; //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"ul1=%lu ul2=%lu ul3=%lu",ul1,ul2,ul3); //#endif // convert longs to strings NumericCoding::CodeNumeric(ul1, code); NumericCoding::CodeNumeric(ul2, code+8); NumericCoding::CodeNumeric(ul3, code+16); code[24]=0; return true; } //------------------------------------------------------------------------------------ // return 0 if ok int ComputeCodeCRC(int crc, const char *user, const char *shop, const char *code) { int res=0; CString strUser = AfxGetApp()->GetProfileString("LOGIN","USER","NETCAST"); if(user==0) user = strUser; CString strShop = AfxGetApp()->GetProfileString("LOGIN","SHOP","LABMUSIC"); if(shop==0) shop = strShop; CString AllCode; CString strCode = AfxGetApp()->GetProfileString("LOGIN","CODE1",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE2",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE3",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE4",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE5",""); AllCode=AllCode+strCode.Left(4); strCode = AfxGetApp()->GetProfileString("LOGIN","CODE6",""); AllCode=AllCode+strCode.Left(4); if(code==0) code = AllCode; //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"current code [%s]",(const char*)AllCode); //#endif // build magic code char magic[24+1]; if(!BuildCode(user, shop, 0, magic)) res += 4; //#ifndef ISMAGIC //LOG.Print(LOG_DEBUG1,"magic code [%s]",magic); //#endif // compare with the one entered by user res += strcmp(code,magic); return res==0 ? res+crc : res+crc%8; } //------------------------------------------------------------------------------------ bool BuildMagicCode(const char *user, const char *shop, const char *MAC, char *code) { return BuildCode(user, shop, MAC, code); } //------------------------------------------------------------------------------------ // !! THOSE 2 ALPHABETS (STRINGS) MUST NOT SHARE ANY LETTER !! const char *NumericCoding::m_gszNull[2] = { "ZA9M", "4AO0" }; const char *NumericCoding::m_gszAlphabet[2] = { "RSTUFGHVXY86BCW012KL7NOPQ34DEIJ5", "VX3MDEIJ5RS91Y86BCWQ2KL7NZPTUFGH" }; // Coding: pszNumeric is a 8 char string. For each 5 bits, we pick a char from the // 2^5=32 letters alphabet and place it in the string. We add an 8th char with a checksum. // For the value 0, we use a different alphabet and place random chars and a random crc. // void NumericCoding::CodeNumeric( unsigned long dwNumeric, char *pszNumeric) { unsigned long dwOffset = 0; unsigned long dwID; unsigned long dwValBase32; int i,nChecksum=0; // is it a null player ID? if( dwNumeric == 0) { //null player ID are coded with a different alphabet srand(GetTickCount()); for(i=0; i<7; i++) pszNumeric[i]=m_gszNull[gnCodingMethod][rand()%(strlen(m_gszNull[gnCodingMethod]))]; sprintf(&pszNumeric[7],"%d",rand()%2000); } else { // normal player ID dwID = dwNumeric; for(i=0; i<7; i++) { dwValBase32 = dwID&0x1F; dwID >>= 5; pszNumeric[i]=m_gszAlphabet[gnCodingMethod][(dwOffset+dwValBase32)%32]; nChecksum += (int)i*pszNumeric[i]; dwOffset += i; } sprintf(&pszNumeric[7],"%d",nChecksum); } } //------------------------------------------------------------------------------------ // Decoding: returns true if the player ID is valid // /* bool NumericCoding::bDecodeNumeric( unsigned long *pdwNumeric, const char *pszNumeric) { unsigned long dwOffset = 0; unsigned long dwID; unsigned long dwValBase32; int i,nChecksum=0; bool bValid=true; // is it long enough? if(strlen(pszNumeric)<8) bValid=false; // does it belong to one of our alphabets? bool bAllNull=true; bool bAllNonNull=true; for(i=0; i<7; i++) { if(strchr(m_gszNull,pszNumeric[i])==0) bAllNull=false; if(strchr(m_gszAlphabet,pszNumeric[i])==0) bAllNonNull=false; } if(!bAllNull && !bAllNonNull) bValid=false; if(bAllNull && bAllNonNull) bValid=false; // if it is not a null value dwID = 0; if(!bAllNull) { for(i=0, dwOffset=0; i<7; i++) {dwOffset += i;} for(i=0; i<7 && bValid; i++) { char *p=strchr(m_gszAlphabet,pszNumeric[7-i-1]); if(p==0) {bValid=false; break;} dwValBase32 = (unsigned long)(p-&m_gszAlphabet[0]); dwOffset -= 7-i-1; nChecksum += (7-i-1)*(int)pszNumeric[7-i-1]; dwValBase32 = (dwValBase32+32-dwOffset)%32; dwID <<= 5; dwID += dwValBase32; } if(nChecksum!=atoi(&pszNumeric[7])) bValid=false; } *pdwNumeric = dwID; if(!bValid) { // INVALID PLAYER ID ASSERT(false); *pdwNumeric=0; } return bValid; } */ //------------------------------------------------------------------------------------
25.933042
106
0.584082
udonyang
c546ecb9d78c548501323f1c49a45f0ae83a872f
3,550
cpp
C++
MineCloneProject/src/MCP/Renderer/Shader/Shader.cpp
didimojuni/MineClone
68efadc775c324d64f61094b7bbeb3855d2df901
[ "Apache-2.0" ]
3
2019-12-07T03:57:55.000Z
2021-01-26T15:40:19.000Z
MineCloneProject/src/MCP/Renderer/Shader/Shader.cpp
dindii/MineClone
68efadc775c324d64f61094b7bbeb3855d2df901
[ "Apache-2.0" ]
null
null
null
MineCloneProject/src/MCP/Renderer/Shader/Shader.cpp
dindii/MineClone
68efadc775c324d64f61094b7bbeb3855d2df901
[ "Apache-2.0" ]
null
null
null
#include "mcpch.h" #include "Shader.h" #include <glad/glad.h> #include "MCP/Utils/Logger.h" #include <fstream> #include <sstream> namespace MC { Shader::Shader(const std::string& vertexSource, const std::string& fragmentSource) { Init(vertexSource, fragmentSource); } void Shader::Init(const std::string& vertexSource, const std::string& fragmentSource) { ParseShaderFiles(vertexSource, fragmentSource); } void Shader::ParseShaderFiles(const std::string& vertexShaderPath, const std::string& fragmentShaderPath) { std::ifstream vertexShader, fragmentShader; vertexShader.exceptions(std::ifstream::failbit | std::ifstream::badbit); fragmentShader.exceptions(std::ifstream::failbit | std::ifstream::badbit); vertexShader.open(vertexShaderPath); fragmentShader.open(fragmentShaderPath); if(vertexShader && fragmentShader) { std::stringstream vertexShaderStream, fragmentShaderStream; vertexShaderStream << vertexShader.rdbuf(); fragmentShaderStream << fragmentShader.rdbuf(); vertexShader.close(); fragmentShader.close(); CreateShader(vertexShaderStream.str(), fragmentShaderStream.str()); } else { MC_LOG_ERROR("ERROR READING SHADER FILES!"); } } void Shader::CreateShader(const std::string& vertexShaderSource, const std::string& fragmentShaderSource) { unsigned int program = glCreateProgram(); unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexShaderSource); unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShaderSource); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glValidateProgram(program); //@TODO: DETTACH m_RendererID = program; glDeleteShader(vs); glDeleteShader(fs); } unsigned int Shader::CompileShader(unsigned int type, const std::string& source) { unsigned int shaderId = glCreateShader(type); const char* src = source.c_str(); glShaderSource(shaderId, 1, &src, nullptr); glCompileShader(shaderId); int compileResult; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &compileResult); if (!compileResult) { int length; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &length); char* message = new char[length]; glGetShaderInfoLog(shaderId, length, &length, message); if (type == GL_FRAGMENT_SHADER) MC_LOG_ERROR("Failed to compile Fragment Shader: ", message); else if (type == GL_VERTEX_SHADER) MC_LOG_ERROR("Failed to compile Vertex Shader: ", message); else if (type == GL_GEOMETRY_SHADER) MC_LOG_ERROR("Failed to compile Geometry Shader: ", message); glDeleteShader(shaderId); delete[] message; return 0; } return shaderId; } Shader::~Shader() { glDeleteProgram(m_RendererID); } void Shader::Bind() { glUseProgram(m_RendererID); } void Shader::UnBind() { glUseProgram(0); } void Shader::UploadUniformMat4(const std::string& name, const mat4& mat) { GLint location = glGetUniformLocation(m_RendererID, name.c_str()); //@TODO: Cache those locations glUniformMatrix4fv(location, 1, GL_FALSE, &mat.elements[0]); } void Shader::UploadUniformFloat4(const std::string& name, const vec4& mat) { GLint location = glGetUniformLocation(m_RendererID, name.c_str()); //@TODO: Cache those locations glUniform4f(location, mat.x, mat.y, mat.z, mat.w); } void Shader::UploadIntArray(const std::string& name, int* data, uint32_t count) { GLint location = glGetUniformLocation(m_RendererID, name.c_str()); //@TODO: Cache those locations glUniform1iv(location, count, data); } }
25.177305
106
0.729577
didimojuni
c5474079ac031b8a30e3f6e686c2ba4e14a8c971
415
hpp
C++
phantom/include/phantom/inputs/linux_input.hpp
karanvivekbhargava/phantom
35accd85cbbfd793b9c2988af27b6cf3a8d0c76f
[ "Apache-2.0" ]
null
null
null
phantom/include/phantom/inputs/linux_input.hpp
karanvivekbhargava/phantom
35accd85cbbfd793b9c2988af27b6cf3a8d0c76f
[ "Apache-2.0" ]
null
null
null
phantom/include/phantom/inputs/linux_input.hpp
karanvivekbhargava/phantom
35accd85cbbfd793b9c2988af27b6cf3a8d0c76f
[ "Apache-2.0" ]
null
null
null
#pragma once #include "GLFW/glfw3.h" #include "phantom/application.hpp" #include "phantom/inputs/input.hpp" namespace Phantom { class LinuxInput : public Input { protected: virtual bool IsKeyPressedImpl(int32_t keycode) override; virtual bool IsMouseButtonPressedImpl(int32_t button) override; virtual std::pair<float32_t, float32_t> GetMousePositionImpl() override; }; }
23.055556
80
0.720482
karanvivekbhargava
c5476e04f7ae4d07121f07ea3a27412a9942cac8
8,453
hpp
C++
src/client/headers/client/sqf/camera.hpp
TheWillard/intercept
7bd96f4b0cec66f5ef1f3cbef7c4abe35e4f8fda
[ "MIT" ]
166
2016-02-11T09:21:26.000Z
2022-01-01T10:34:38.000Z
src/client/headers/client/sqf/camera.hpp
TheWillard/intercept
7bd96f4b0cec66f5ef1f3cbef7c4abe35e4f8fda
[ "MIT" ]
104
2016-02-10T14:34:27.000Z
2022-03-26T18:03:47.000Z
src/client/headers/client/sqf/camera.hpp
TheWillard/intercept
7bd96f4b0cec66f5ef1f3cbef7c4abe35e4f8fda
[ "MIT" ]
85
2016-02-11T23:14:23.000Z
2022-03-18T05:03:09.000Z
/*! @file @author Verox (verox.averre@gmail.com) @author Nou (korewananda@gmail.com) @author Glowbal (thomasskooi@live.nl) @author Dedmen (dedmen@dedmen.de) @brief Camera related Function wrappers. https://github.com/NouberNou/intercept */ #pragma once #include "shared/client_types.hpp" using namespace intercept::types; namespace intercept { namespace sqf { struct rv_apperture_params { float current_aperture{}; //Current aperture float approx_aperture{}; //Engine estimated aperture for the scene float approx_luminance{}; //Engine estimated luminance float min_aperture{}; //Minimal custom aperture{}; see setApertureNew float std_aperture{}; //Standard custom aperture{}; see setApertureNew float max_aperture{}; //Maximal custom aperture {}; see setApertureNew float custom_lumi{}; //Custom luminance{}; see setApertureNew float light_intensity{}; //Blinding intensity of the light bool forced{}; //Whether aperture was forced by setAperture bool custom_forced{}; //Whether custom values were forced rv_apperture_params(const game_value &gv_) : current_aperture(gv_[0]), forced(gv_[1]), approx_aperture(gv_[2]), approx_luminance(gv_[3]), min_aperture(gv_[4]), std_aperture(gv_[5]), max_aperture(gv_[6]), custom_lumi(gv_[7]), custom_forced(gv_[8]), light_intensity(gv_[9]) {} }; /* potential namespace: camera */ void add_cam_shake(float power_, float duration_, float frequency_); void reset_cam_shake(); void enable_cam_shake(bool value_); /* potential namespace: camera */ bool cam_committed(const object &camera_); void cam_destroy(const object &camera_); bool cam_preloaded(const object &camera_); object cam_target(const object &camera_); void cam_use_nvg(bool use_nvg_); void camera_effect_enable_hud(bool enable_hud_); float camera_interest(const object &entity_); void cam_constuction_set_params(const object &camera_, const vector3 &position_, float radius, float max_above_land_); object cam_create(sqf_string_const_ref type_, const vector3 &position_); void camera_effect(const object &camera_, sqf_string_const_ref name_, sqf_string_const_ref position_); void camera_effect(const object &camera_, sqf_string_const_ref name_, sqf_string_const_ref position_, sqf_string_const_ref rtt_); void cam_prepare_focus(const object &camera_, float distance_, float blur_); void cam_prepare_fov_range(const object &camera_, float min_, float max_); void cam_prepare_pos(const object &camera_, const vector3 &position_); void cam_prepare_rel_pos(const object &camera_, const vector3 &relative_position_); void cam_prepare_target(const object &camera_, const object &target_); void cam_prepare_target(const object &camera_, const vector3 &target_); // Broken command cam_set_dir void cam_set_focus(const object &camera_, float distance_, float blur_); void cam_set_fov_range(const object &camera_, float min_, float max_); void cam_set_pos(const object &camera_, const vector3 &position_); void cam_set_relative_pos(const object &camera_, const vector3 &relative_position_); void cam_set_target(const object &camera_, const object &target_); void cam_set_target(const object &camera_, const vector3 &target_); void cam_command(const object &value0_, sqf_string_const_ref value1_); void cam_commit(const object &value0_, float value1_); void cam_commit_prepared(const object &value0_, float value1_); void cam_preload(const object &value0_, float value1_); void cam_prepare_bank(const object &value0_, float value1_); void cam_prepare_dir(const object &value0_, float value1_); void cam_prepare_dive(const object &value0_, float value1_); void cam_prepare_fov(const object &value0_, float value1_); void cam_set_bank(const object &value0_, float value1_); void cam_set_dive(const object &value0_, float value1_); void cam_set_fov(const object &value0_, float value1_); enum class thermal_modes { white_hot = 0, black_hot = 1, lightgreen_hot = 2, ///< Light Green Hot / Darker Green cold black_hot_green_cold = 3, ///< Black Hot / Darker Green cold red_hot = 4, ///< Light Red Hot / Darker Red Cold black_hot_red_cold = 5, ///< Black Hot / Darker Red Cold white_hot_red_cold = 6, ///< White Hot.Darker Red Cold thermal = 7 ///< Shade of Red and Green, Bodies are white }; void set_cam_use_ti(thermal_modes mode_, bool value1_); void set_aperture(float value_); void set_aperture_new(float min_, float std_, float max_, float std_lum_); void set_cam_shake_def_params(float power_, float duration_, float freq_, float min_speed_, float min_mass_, float caliber_coef_hit_, float vehicle_coef_); void set_cam_shake_params(float pos_coef_, float vert_coef_, float horz_coef_, float bank_coef_, bool interpolate_); bool preload_camera(const vector3 &pos_); void set_default_camera(const vector3 &pos_, const vector3 &dir_); vector3 get_camera_view_direction(const object &obj_); void switch_camera(const object &value0_, sqf_string_const_ref value1_); void set_camera_interest(const object &value0_, float value1_); sqf_return_string camera_view(); //postprocessing effects struct rv_pp_effect { std::string name; float priority; operator game_value() { return game_value(std::vector<game_value>({name, priority})); } operator game_value() const { return game_value(std::vector<game_value>({name, priority})); } }; float pp_effect_create(sqf_string_const_ref name_, const float &priority_); std::vector<float> pp_effect_create(const std::vector<rv_pp_effect> &effects_); bool pp_effect_committed(sqf_string_const_ref value_); bool pp_effect_committed(float value_); void pp_effect_destroy(float value_); bool pp_effect_enabled(float value_); bool pp_effect_enabled(sqf_string_const_ref value_); void pp_effect_commit(float value0_, sqf_string_const_ref value1_); void pp_effect_enable(bool value0_, sqf_string_const_ref value1_); void pp_effect_enable(float value0_, bool value1_); void pp_effect_force_in_nvg(float value0_, bool value1_); void pp_effect_destroy(std::vector<float> effect_handles_); //#TODO: Replace &settings_ with the right pp_effect_parameters void pp_effect_adjust(std::variant<sqf_string_const_ref_wrapper, std::reference_wrapper<int>> effect_, const game_value &settings_); void pp_effect_commit(std::variant<std::reference_wrapper<const std::vector<int>>, std::reference_wrapper<int>> effect_, const float &duration_); void pp_effect_enable(const std::vector<int> &effets_, bool enable_); struct rv_camera_target { bool is_tracking; vector3 target_position; object target_object; }; vector3 get_pilot_camera_direction(const object &object_); vector3 get_pilot_camera_position(const object &object_); vector3 get_pilot_camera_rotation(const object &object_); rv_camera_target get_pilot_camera_target(const object &object_); bool has_pilot_camera(const object &object_); void cam_set_dir(const object &camera_, const vector3 &direction_); rv_apperture_params aperture_params(); } // namespace sqf } // namespace intercept
51.230303
164
0.653969
TheWillard
c55010c9b7c513f7fd8ab4e172072e12a9a4f3fd
7,704
cpp
C++
dp/rix/gl/src/SamplerStateGL.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
217
2015-01-06T09:26:53.000Z
2022-03-23T14:03:18.000Z
dp/rix/gl/src/SamplerStateGL.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
10
2015-01-25T12:42:05.000Z
2017-11-28T16:10:16.000Z
dp/rix/gl/src/SamplerStateGL.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
44
2015-01-13T01:19:41.000Z
2022-02-21T21:35:08.000Z
// Copyright (c) 2011-2016, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 <cstring> #include <dp/rix/gl/inc/SamplerStateGL.h> #include <dp/rix/gl/inc/DataTypeConversionGL.h> namespace dp { namespace rix { namespace gl { using namespace dp::rix::core; SamplerStateGL::SamplerStateGL() { m_borderColorDataType = SamplerBorderColorDataType::FLOAT; m_borderColor.f[0] = 0.0f; m_borderColor.f[1] = 0.0f; m_borderColor.f[2] = 0.0f; m_borderColor.f[3] = 0.0f; m_minFilterModeGL = GL_NEAREST; m_magFilterModeGL = GL_NEAREST; m_wrapSModeGL = GL_CLAMP_TO_EDGE; m_wrapTModeGL = GL_CLAMP_TO_EDGE; m_wrapRModeGL = GL_CLAMP_TO_EDGE; m_minLOD = -1000.0f; m_maxLOD = 1000.0f; m_LODBias = 0.0f; m_compareModeGL = GL_NONE; m_compareFuncGL = GL_LEQUAL; m_maxAnisotropy = 1.0f; #if RIX_GL_SAMPLEROBJECT_SUPPORT glGenSamplers( 1, &m_id ); assert( m_id && "Couldn't create OpenGL sampler object" ); updateSamplerObject(); #endif } SamplerStateGL::~SamplerStateGL() { #if RIX_GL_SAMPLEROBJECT_SUPPORT if( m_id ) { glDeleteSamplers( 1, &m_id ); } #else // nothing to clean up #endif } SamplerStateHandle SamplerStateGL::create( const SamplerStateData& samplerStateData ) { SamplerStateGLHandle samplerStateGL = new SamplerStateGL; switch( samplerStateData.getSamplerStateDataType() ) { case dp::rix::core::SamplerStateDataType::COMMON: { assert( dynamic_cast<const dp::rix::core::SamplerStateDataCommon*>(&samplerStateData) ); const SamplerStateDataCommon& samplerStateDataCommon = static_cast<const SamplerStateDataCommon&>(samplerStateData); samplerStateGL->m_minFilterModeGL = getGLFilterMode( samplerStateDataCommon.m_minFilterMode ); samplerStateGL->m_magFilterModeGL = getGLFilterMode( samplerStateDataCommon.m_magFilterMode ); samplerStateGL->m_wrapSModeGL = getGLWrapMode( samplerStateDataCommon.m_wrapSMode ); samplerStateGL->m_wrapTModeGL = getGLWrapMode( samplerStateDataCommon.m_wrapTMode ); samplerStateGL->m_wrapRModeGL = getGLWrapMode( samplerStateDataCommon.m_wrapRMode ); samplerStateGL->m_compareModeGL = getGLCompareMode( samplerStateDataCommon.m_compareMode ); } break; case dp::rix::core::SamplerStateDataType::NATIVE: { assert( dynamic_cast<const SamplerStateDataGL*>(&samplerStateData) ); const SamplerStateDataGL& samplerStateDataGL = static_cast<const SamplerStateDataGL&>(samplerStateData); samplerStateGL->m_borderColorDataType = samplerStateDataGL.m_borderColorDataType; // either this or a switch case copying all data one by one memcpy( &samplerStateGL->m_borderColor, &samplerStateDataGL.m_borderColor, sizeof(samplerStateGL->m_borderColor ) ); samplerStateGL->m_minFilterModeGL = samplerStateDataGL.m_minFilterModeGL; samplerStateGL->m_magFilterModeGL = samplerStateDataGL.m_magFilterModeGL; samplerStateGL->m_wrapSModeGL = samplerStateDataGL.m_wrapSModeGL; samplerStateGL->m_wrapTModeGL = samplerStateDataGL.m_wrapTModeGL; samplerStateGL->m_wrapRModeGL = samplerStateDataGL.m_wrapRModeGL; samplerStateGL->m_minLOD = samplerStateDataGL.m_minLOD; samplerStateGL->m_maxLOD = samplerStateDataGL.m_maxLOD; samplerStateGL->m_LODBias = samplerStateDataGL.m_LODBias; samplerStateGL->m_compareModeGL = samplerStateDataGL.m_compareModeGL; samplerStateGL->m_compareFuncGL = samplerStateDataGL.m_compareFuncGL; samplerStateGL->m_maxAnisotropy = samplerStateDataGL.m_maxAnisotropy; } break; default: { assert( !"unsupported sampler state data type" ); delete samplerStateGL; return nullptr; } break; } #if RIX_GL_SAMPLEROBJECT_SUPPORT samplerStateGL->updateSamplerObject(); #endif return handleCast<SamplerState>(samplerStateGL); } #if RIX_GL_SAMPLEROBJECT_SUPPORT void SamplerStateGL::updateSamplerObject() { switch( m_borderColorDataType ) { case SamplerBorderColorDataType::FLOAT: glSamplerParameterfv( m_id, GL_TEXTURE_BORDER_COLOR, m_borderColor.f ); break; case SamplerBorderColorDataType::UINT: glSamplerParameterIuiv( m_id, GL_TEXTURE_BORDER_COLOR, m_borderColor.ui ); break; case SamplerBorderColorDataType::INT: glSamplerParameterIiv( m_id, GL_TEXTURE_BORDER_COLOR, m_borderColor.i ); break; default: assert( !"unknown sampler border color data type" ); break; } glSamplerParameteri( m_id, GL_TEXTURE_MIN_FILTER, m_minFilterModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_MAG_FILTER, m_magFilterModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_WRAP_S, m_wrapSModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_WRAP_T, m_wrapTModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_WRAP_R, m_wrapRModeGL ); glSamplerParameterf( m_id, GL_TEXTURE_MIN_LOD, m_minLOD ); glSamplerParameterf( m_id, GL_TEXTURE_MAX_LOD, m_maxLOD ); glSamplerParameterf( m_id, GL_TEXTURE_LOD_BIAS, m_LODBias ); glSamplerParameteri( m_id, GL_TEXTURE_COMPARE_MODE, m_compareModeGL ); glSamplerParameteri( m_id, GL_TEXTURE_COMPARE_FUNC, m_compareFuncGL ); glSamplerParameterf( m_id, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy ); } #endif } // namespace gl } // namespace rix } // namespace dp
42.098361
129
0.670042
asuessenbach
c5533ca349bab1fc8faf4fe99ac9d68e54830ce6
3,444
cpp
C++
Src/GeometryShop/AMReX_IFData.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
1
2021-05-20T13:04:05.000Z
2021-05-20T13:04:05.000Z
Src/GeometryShop/AMReX_IFData.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
null
null
null
Src/GeometryShop/AMReX_IFData.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <iostream> #include <iomanip> #include "AMReX_NormalDerivative.H" #include "AMReX_IFData.H" //leave to default faulse. Moving the coords works better //but makes for weird convergence tests bool LocalCoordMoveSwitch::s_turnOffMoveLocalCoords = true; // empty constructor (dim == 1) IFData<1>::IFData() { } IFData<1>::IFData(const IFData<1>& a_IFData) :m_cornerSigns (a_IFData.m_cornerSigns), m_intersection (a_IFData.m_intersection), m_globalCoord (a_IFData.m_globalCoord), m_cellCenterCoord(a_IFData.m_cellCenterCoord), m_parentCoord (a_IFData.m_parentCoord), m_allVerticesIn (a_IFData.m_allVerticesIn), m_allVerticesOut (a_IFData.m_allVerticesOut), m_allVerticesOn (a_IFData.m_allVerticesOn), m_badNormal (a_IFData.m_badNormal) { } // Constructor from the implicit function IFData<1>::IFData(const IFData<2> & a_2DIFData, const int & a_maxOrder, const int & a_idir, const int & a_hilo) :m_globalCoord(a_2DIFData.m_globalCoord,a_idir), m_cellCenterCoord(a_2DIFData.m_cellCenterCoord,a_idir), m_parentCoord(a_2DIFData.m_localCoord,a_idir) { // we want the edge on the a_hilo side of the square with normal in the // a_idir direction IFData<2>localInfo = a_2DIFData; // This 2D edgeIndex locates the 1D edge in the edgeIntersection map IndexTM<int,2>twoDEdge; twoDEdge[0] = (a_idir + 1)%2; twoDEdge[1] = a_hilo; m_intersection = LARGEREALVAL; if (localInfo.m_intersections.find(twoDEdge) != localInfo.m_intersections.end()) { m_intersection = localInfo.m_intersections[twoDEdge]; } // This 2D vertex locates the hi and lo ends of the 1D segment in the // cornerSigns map IndexTM<int,2>loPt2D; loPt2D[(a_idir + 1)%2] = 0; loPt2D[a_idir] = a_hilo; IndexTM<int,2>hiPt2D; hiPt2D[(a_idir+ 1)%2] = 1; hiPt2D[a_idir] = a_hilo; if (localInfo.m_cornerSigns.find(loPt2D) != localInfo.m_cornerSigns.end()) { m_cornerSigns[0] = localInfo.m_cornerSigns[loPt2D]; } else { amrex::Abort("Lo endpoint not in Map"); } if (localInfo.m_cornerSigns.find(hiPt2D) != localInfo.m_cornerSigns.end()) { m_cornerSigns[1] = localInfo.m_cornerSigns[hiPt2D]; } else { amrex::Abort("Hi endpoint not in Map"); } // set bools m_allVerticesIn = true; m_allVerticesOut = true; m_allVerticesOn = true; if (m_cornerSigns[0] != ON || m_cornerSigns[1] != ON) { m_allVerticesOn = false; } if (m_cornerSigns[0] == IN || m_cornerSigns[1] == IN) { m_allVerticesOut = false; } if (m_cornerSigns[0] == OUT || m_cornerSigns[1] == OUT) { m_allVerticesIn = false; } //there is no normal in one dimension. However, if m_badNormal = true at a lower dimension, then the higher dimension refines. m_badNormal = false; } // Destructor (dim == 1) IFData<1>::~IFData() { } // equals operator void IFData<1>::operator=(const IFData & a_IFData) { if (this != &a_IFData) { m_cornerSigns = a_IFData.m_cornerSigns; m_intersection = a_IFData.m_intersection; m_globalCoord = a_IFData.m_globalCoord; m_cellCenterCoord = a_IFData.m_cellCenterCoord; m_parentCoord = a_IFData.m_parentCoord; m_allVerticesIn = a_IFData.m_allVerticesIn; m_allVerticesOut = a_IFData.m_allVerticesOut; m_allVerticesOn = a_IFData.m_allVerticesOn; m_badNormal = a_IFData.m_badNormal; } }
26.90625
128
0.692218
malvarado27
c554d4d723a44de8e0d5e7353c212ecf0e6e1f61
1,872
cc
C++
shell/renderer/printing/print_render_frame_helper_delegate.cc
lingxiao-Zhu/electron
2d85b1f8f527d55f884904dbfdde50ee66a49830
[ "MIT" ]
40
2020-05-04T12:34:43.000Z
2022-02-18T22:59:17.000Z
shell/renderer/printing/print_render_frame_helper_delegate.cc
lingxiao-Zhu/electron
2d85b1f8f527d55f884904dbfdde50ee66a49830
[ "MIT" ]
4
2020-07-19T04:26:04.000Z
2021-05-12T22:25:03.000Z
shell/renderer/printing/print_render_frame_helper_delegate.cc
lingxiao-Zhu/electron
2d85b1f8f527d55f884904dbfdde50ee66a49830
[ "MIT" ]
18
2020-06-22T01:04:59.000Z
2022-01-02T14:01:20.000Z
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/renderer/printing/print_render_frame_helper_delegate.h" #include "content/public/renderer/render_frame.h" #include "extensions/buildflags/buildflags.h" #include "third_party/blink/public/web/web_element.h" #include "third_party/blink/public/web/web_local_frame.h" #if BUILDFLAG(ENABLE_EXTENSIONS) #include "extensions/common/constants.h" #endif // BUILDFLAG(ENABLE_EXTENSIONS) namespace electron { PrintRenderFrameHelperDelegate::PrintRenderFrameHelperDelegate() = default; PrintRenderFrameHelperDelegate::~PrintRenderFrameHelperDelegate() = default; // Return the PDF object element if |frame| is the out of process PDF extension. blink::WebElement PrintRenderFrameHelperDelegate::GetPdfElement( blink::WebLocalFrame* frame) { #if BUILDFLAG(ENABLE_EXTENSIONS) GURL url = frame->GetDocument().Url(); bool inside_pdf_extension = url.SchemeIs(extensions::kExtensionScheme) && url.host_piece() == extension_misc::kPdfExtensionId; if (inside_pdf_extension) { // <object> with id="plugin" is created in // chrome/browser/resources/pdf/pdf_viewer_base.js. auto viewer_element = frame->GetDocument().GetElementById("viewer"); if (!viewer_element.IsNull() && !viewer_element.ShadowRoot().IsNull()) { auto plugin_element = viewer_element.ShadowRoot().QuerySelector("#plugin"); if (!plugin_element.IsNull()) { return plugin_element; } } NOTREACHED(); } #endif // BUILDFLAG(ENABLE_EXTENSIONS) return blink::WebElement(); } bool PrintRenderFrameHelperDelegate::IsPrintPreviewEnabled() { return false; } bool PrintRenderFrameHelperDelegate::OverridePrint( blink::WebLocalFrame* frame) { return false; } } // namespace electron
32.842105
80
0.748397
lingxiao-Zhu
c5557bc89b09fff49b0d2ce31d46af36e4e256e6
12,844
cpp
C++
test/function/string_functions_test.cpp
aaron-tian/peloton
2406b763b91d9cee2a5d9f4dee01c761b476cef6
[ "Apache-2.0" ]
3
2018-01-08T01:06:17.000Z
2019-06-17T23:14:36.000Z
test/function/string_functions_test.cpp
aaron-tian/peloton
2406b763b91d9cee2a5d9f4dee01c761b476cef6
[ "Apache-2.0" ]
1
2020-04-30T09:54:37.000Z
2020-04-30T09:54:37.000Z
test/function/string_functions_test.cpp
aaron-tian/peloton
2406b763b91d9cee2a5d9f4dee01c761b476cef6
[ "Apache-2.0" ]
3
2018-02-25T23:30:33.000Z
2018-04-08T10:11:42.000Z
//===----------------------------------------------------------------------===// // // Peloton // // string_functions_test.cpp // // Identification: test/expression/string_functions_test.cpp // // Copyright (c) 2015-2018, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <set> #include <string> #include <vector> #include "common/harness.h" #include "executor/executor_context.h" #include "function/string_functions.h" #include "function/old_engine_string_functions.h" using ::testing::NotNull; using ::testing::Return; namespace peloton { namespace test { class StringFunctionsTests : public PelotonTest { public: StringFunctionsTests() : test_ctx_(nullptr) {} executor::ExecutorContext &GetExecutorContext() { return test_ctx_; } private: executor::ExecutorContext test_ctx_; }; TEST_F(StringFunctionsTests, LikeTest) { //-------------- match ---------------- // std::string s1 = "forbes \\avenue"; // "forbes \avenue" std::string p1 = "%b_s \\\\avenue"; // "%b_s \\avenue" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s1.c_str(), s1.size(), p1.c_str(), p1.size())); std::string s2 = "for%bes avenue%"; // "for%bes avenue%" std::string p2 = "for%bes a_enue\\%"; // "for%bes a_enue%" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s2.c_str(), s2.size(), p2.c_str(), p2.size())); std::string s3 = "Allison"; // "Allison" std::string p3 = "%lison"; // "%lison" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s3.c_str(), s3.size(), p3.c_str(), p3.size())); //----------Exact Match------------// std::string s5 = "Allison"; // "Allison" std::string p5 = "Allison"; // "Allison" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s5.c_str(), s5.size(), p5.c_str(), p5.size())); //----------Exact Match------------// std::string s6 = "Allison"; // "Allison" std::string p6 = "A%llison"; // "A%llison" EXPECT_TRUE(function::StringFunctions::Like( GetExecutorContext(), s6.c_str(), s6.size(), p6.c_str(), p6.size())); //-------------- not match ----------------// std::string s4 = "forbes avenue"; // "forbes avenue" std::string p4 = "f_bes avenue"; // "f_bes avenue" EXPECT_FALSE(function::StringFunctions::Like( GetExecutorContext(), s4.c_str(), s4.size(), p4.c_str(), p4.size())); } TEST_F(StringFunctionsTests, AsciiTest) { const char column_char = 'A'; for (int i = 0; i < 52; i++) { auto expected = static_cast<uint32_t>(column_char + i); std::ostringstream os; os << static_cast<char>(expected); std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue(os.str())}; auto result = function::OldEngineStringFunctions::Ascii(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.GetAs<int>()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR)}; auto result = function::OldEngineStringFunctions::Ascii(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, ChrTest) { const char column_char = 'A'; for (int i = 0; i < 52; i++) { int char_int = (int)column_char + i; std::ostringstream os; os << static_cast<char>(char_int); std::string expected = os.str(); std::vector<type::Value> args = { type::ValueFactory::GetIntegerValue(char_int)}; auto result = function::OldEngineStringFunctions::Chr(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER)}; auto result = function::OldEngineStringFunctions::Chr(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, SubstrTest) { std::vector<std::string> words = {"Fuck", "yo", "couch"}; std::ostringstream os; for (auto w : words) { os << w; } int from = words[0].size() + 1; int len = words[1].size(); const std::string expected = words[1]; std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue(os.str()), type::ValueFactory::GetIntegerValue(from), type::ValueFactory::GetIntegerValue(len), }; auto result = function::OldEngineStringFunctions::Substr(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 3; i++) { std::vector<type::Value> nullargs = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), type::ValueFactory::GetVarcharValue("ccc"), }; nullargs[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::Substr(nullargs); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, CharLengthTest) { const std::string str = "A"; for (int i = 0; i < 100; i++) { std::string input = StringUtil::Repeat(str, i); std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue(input)}; auto result = function::OldEngineStringFunctions::CharLength(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(i, result.GetAs<int>()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR)}; auto result = function::OldEngineStringFunctions::CharLength(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, RepeatTest) { const std::string str = "A"; for (int i = 0; i < 100; i++) { std::string expected = StringUtil::Repeat(str, i); EXPECT_EQ(i, expected.size()); std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(str), type::ValueFactory::GetIntegerValue(i)}; auto result = function::OldEngineStringFunctions::Repeat(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR), type::ValueFactory::GetVarcharValue(str), }; auto result = function::OldEngineStringFunctions::Repeat(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, ReplaceTest) { const std::string origChar = "A"; const std::string replaceChar = "X"; const std::string prefix = "**PAVLO**"; for (int i = 0; i < 100; i++) { std::string expected = prefix + StringUtil::Repeat(origChar, i); EXPECT_EQ(i + prefix.size(), expected.size()); std::string input = prefix + StringUtil::Repeat(replaceChar, i); EXPECT_EQ(i + prefix.size(), expected.size()); std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue(input), type::ValueFactory::GetVarcharValue(replaceChar), type::ValueFactory::GetVarcharValue(origChar)}; auto result = function::OldEngineStringFunctions::Replace(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); } // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 3; i++) { std::vector<type::Value> args = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), type::ValueFactory::GetVarcharValue("ccc"), }; args[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::Replace(args); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, LTrimTest) { const std::string message = "This is a string with spaces"; const std::string spaces = " "; const std::string origStr = spaces + message + spaces; const std::string expected = message + spaces; std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(origStr), type::ValueFactory::GetVarcharValue(" ")}; auto result = function::OldEngineStringFunctions::LTrim(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 2; i++) { std::vector<type::Value> nullargs = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), }; nullargs[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::LTrim(nullargs); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, RTrimTest) { const std::string message = "This is a string with spaces"; const std::string spaces = " "; const std::string origStr = spaces + message + spaces; const std::string expected = spaces + message; std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(origStr), type::ValueFactory::GetVarcharValue(" ")}; auto result = function::OldEngineStringFunctions::RTrim(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 2; i++) { std::vector<type::Value> nullargs = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), }; nullargs[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::RTrim(nullargs); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, BTrimTest) { const std::string message = "This is a string with spaces"; const std::string spaces = " "; const std::string origStr = spaces + message + spaces; const std::string expected = message; std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(origStr), type::ValueFactory::GetVarcharValue(" ")}; auto result = function::OldEngineStringFunctions::BTrim(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); result = function::OldEngineStringFunctions::Trim( {type::ValueFactory::GetVarcharValue(origStr)}); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.ToString()); // Use NULL for every argument and make sure that it always returns NULL. for (int i = 0; i < 2; i++) { std::vector<type::Value> nullargs = { type::ValueFactory::GetVarcharValue("aaa"), type::ValueFactory::GetVarcharValue("bbb"), }; nullargs[i] = type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); auto result = function::OldEngineStringFunctions::BTrim(nullargs); EXPECT_TRUE(result.IsNull()); } } TEST_F(StringFunctionsTests, LengthTest) { const char column_char = 'A'; int expected = 1; std::string str = ""; for (int i = 0; i < 52; i++) { str += (char)(column_char + i); expected++; std::vector<type::Value> args = {type::ValueFactory::GetVarcharValue(str)}; auto result = function::OldEngineStringFunctions::Length(args); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(expected, result.GetAs<int>()); } // NULL CHECK std::vector<type::Value> args = { type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR)}; auto result = function::OldEngineStringFunctions::Length(args); EXPECT_TRUE(result.IsNull()); } TEST_F(StringFunctionsTests, CodegenSubstrTest) { const std::string message = "1234567"; int from = 1; int len = 5; std::string expected = message.substr(from - 1, len); auto res = function::StringFunctions::Substr( GetExecutorContext(), message.c_str(), message.length(), from, len); EXPECT_EQ(len + 1, res.length); EXPECT_EQ(expected, std::string(res.str, len)); from = 7; len = 1; expected = message.substr(from - 1, len); res = function::StringFunctions::Substr(GetExecutorContext(), message.c_str(), message.length(), from, len); EXPECT_EQ(len + 1, res.length); EXPECT_EQ(expected, std::string(res.str, len)); from = -2; len = 4; expected = message.substr(0, 1); res = function::StringFunctions::Substr(GetExecutorContext(), message.c_str(), message.length(), from, len); EXPECT_EQ(2, res.length); EXPECT_EQ(expected, std::string(res.str, 1)); from = -2; len = 2; expected = ""; res = function::StringFunctions::Substr(GetExecutorContext(), message.c_str(), message.length(), from, len); EXPECT_EQ(0, res.length); EXPECT_EQ(nullptr, res.str); } } // namespace test } // namespace peloton
36.282486
80
0.645905
aaron-tian
c557875997d78542cb0593c52ceed50ff6fef5f2
372
cpp
C++
BOJ/1699.cpp
ReinforceIII/Algorithm
355f6e19f8deb6a76f82f5283d7c1987acd699a6
[ "MIT" ]
null
null
null
BOJ/1699.cpp
ReinforceIII/Algorithm
355f6e19f8deb6a76f82f5283d7c1987acd699a6
[ "MIT" ]
null
null
null
BOJ/1699.cpp
ReinforceIII/Algorithm
355f6e19f8deb6a76f82f5283d7c1987acd699a6
[ "MIT" ]
null
null
null
/* 1699 제곱수의 합 */ #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int n; cin>>n; vector<int> number(n+1); vector<int> memo(n+1); for(int i=1; i<=n; i++) { memo[i] = i; for(int j=1; j*j<=i; j++) { if(memo[i] > memo[i-j*j] + 1) memo[i] = memo[i-j*j] + 1; } } cout<<memo[n]; return 0; }
17.714286
64
0.510753
ReinforceIII
c55fffd11d11540757b91a2786112889d990257e
2,084
cpp
C++
liupeng/src/main/java/liupeng/Ch2_HDFS/liveMedia/H264VideoFileSink.cpp
jayfans3/example
6982e33d760dd8e4d94de40c81ae733434bf3f1b
[ "BSD-2-Clause" ]
null
null
null
liupeng/src/main/java/liupeng/Ch2_HDFS/liveMedia/H264VideoFileSink.cpp
jayfans3/example
6982e33d760dd8e4d94de40c81ae733434bf3f1b
[ "BSD-2-Clause" ]
null
null
null
liupeng/src/main/java/liupeng/Ch2_HDFS/liveMedia/H264VideoFileSink.cpp
jayfans3/example
6982e33d760dd8e4d94de40c81ae733434bf3f1b
[ "BSD-2-Clause" ]
null
null
null
#include "H264VideoFileSink.hh" #include "OutputFile.hh" #include "H264VideoRTPSource.hh" ////////// H264VideoFileSink ////////// H264VideoFileSink::H264VideoFileSink(UsageEnvironment& env, FILE* fid,char const* sPropParameterSetsStr,unsigned bufferSize, char const* perFrameFileNamePrefix) : FileSink(env, fid, bufferSize, perFrameFileNamePrefix),fSPropParameterSetsStr(sPropParameterSetsStr), fHaveWrittenFirstFrame(False) { } H264VideoFileSink::~H264VideoFileSink() { } H264VideoFileSink*H264VideoFileSink::createNew(UsageEnvironment& env, char const* fileName, char const* sPropParameterSetsStr, unsigned bufferSize, Boolean oneFilePerFrame) { do { FILE* fid; char const* perFrameFileNamePrefix; if (oneFilePerFrame) { // Create the fid for each frame fid = NULL; perFrameFileNamePrefix = fileName; } else { // Normal case: create the fid once fid = OpenOutputFile(env, fileName); if (fid == NULL) break; perFrameFileNamePrefix = NULL; } return new H264VideoFileSink(env, fid, sPropParameterSetsStr, bufferSize, perFrameFileNamePrefix); } while (0); return NULL; } void H264VideoFileSink::afterGettingFrame1(unsigned frameSize, struct timeval presentationTime) { unsigned char const start_code[4] = {0x00, 0x00, 0x00, 0x01}; if (!fHaveWrittenFirstFrame) { // If we have PPS/SPS NAL units encoded in a "sprop parameter string", prepend these to the file: unsigned numSPropRecords; SPropRecord* sPropRecords = parseSPropParameterSets(fSPropParameterSetsStr, numSPropRecords); for (unsigned i = 0; i < numSPropRecords; ++i) { addData(start_code, 4, presentationTime); addData(sPropRecords[i].sPropBytes, sPropRecords[i].sPropLength, presentationTime); } delete[] sPropRecords; fHaveWrittenFirstFrame = True; // for next time } //Write the input data to the file, with the start code in front: addData(start_code, 4, presentationTime); //Call the parent class to complete the normal file write with the input data: FileSink::afterGettingFrame1(frameSize, presentationTime); }
32.061538
160
0.74904
jayfans3
c561ca10519214a918976548c93ead4cba1cb998
5,532
cpp
C++
src/main.cpp
LordIdra/orbit
0830adb984586b7de820fbc00979f5083d3a98b9
[ "MIT" ]
null
null
null
src/main.cpp
LordIdra/orbit
0830adb984586b7de820fbc00979f5083d3a98b9
[ "MIT" ]
null
null
null
src/main.cpp
LordIdra/orbit
0830adb984586b7de820fbc00979f5083d3a98b9
[ "MIT" ]
null
null
null
#define _WIN32_WINNT 0x0601 #define SDL_MAIN_HANDLED #include <iostream> #include <vector> #include <windows.h> #include "Shader.h" #include "Text.h" #include "Geometry.h" #include "WindowInformation.h" #include "SolarSystem.h" #include "OrbitPrediction.h" using std::vector; /* https://www.pluralsight.com/blog/software-development/how-to-measure-execution-time-intervals-in-c-- */ /* https://www.libsdl.org/release/SDL-1.2.15/docs/html/guidevideoopengl.html */ /* https://gist.github.com/sherjilozair/ac2ac5e3002b6f3becaef214ebe3cd7a */ double zoom = 500000000; double mouse_x = 0; double mouse_y = 0; double mouse_x_previous = 0; double mouse_y_previous = 0; int window_x = 0; int window_y = 0; double offset_x = 0; double offset_y = 0; bool is_running = true; bool mouse_down = false; double step = 10000; SDL_Event event; void handle_input() { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: // Quit is_running = false; break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) { // Quit is_running = false; } break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) mouse_down = true; // Left mouse button down break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT) mouse_down = false; // Left mouse button up break; case SDL_MOUSEWHEEL: // Zoom in/out double old_zoom = zoom; zoom *= 1 - (event.wheel.y*0.1); offset_x -= (mouse_x - (window_x/2)) * (old_zoom - zoom) * 2; offset_y -= (mouse_y - (window_y/2)) * (old_zoom - zoom) * 2; break; } } } int main(int argv, char** args) { // Pre-window initialization Star sun = GetSun(); SetProcessDPIAware(); SDL_Init(SDL_INIT_VIDEO); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,16); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); // Window creation SDL_Window *window = SDL_CreateWindow("Orbit", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 10000, 10000, SDL_WINDOW_ALLOW_HIGHDPI| SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP); SDL_GLContext context = SDL_GL_CreateContext(window); // Post-window initialization SDL_GetWindowSize(window, &window_x, &window_y); int mouse_cache_x; int mouse_cache_y; SDL_GetMouseState(&mouse_cache_x, &mouse_cache_y); mouse_x = mouse_cache_x; mouse_y = mouse_cache_y; gladLoadGLLoader(SDL_GL_GetProcAddress); SDL_GL_SetSwapInterval(1); // Enable multisampling glViewport(0, 0, window_x, window_y); glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_MULTISAMPLE); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // Load fonts Fonts::InitializeFonts(); Geometry::Init(); Text::Init(); // Mainloop while (is_running) { // Handle events handle_input(); // Handle mouse int mouse_cache_x; int mouse_cache_y; SDL_GetMouseState(&mouse_cache_x, &mouse_cache_y); mouse_x = mouse_cache_x; mouse_y = mouse_cache_y; if (mouse_down) { offset_x -= (mouse_x_previous - mouse_x) * zoom * 2; offset_y -= (mouse_y_previous - mouse_y) * zoom * 2; } mouse_x_previous = mouse_x; mouse_y_previous = mouse_y; // Update dimension variables SDL_GetWindowSize(window, &window_x, &window_y); WindowInformation::Update(window_x, window_y, offset_x, offset_y, zoom); // Create a vector of all the bodies vector<Body> system_bodies; system_bodies.push_back(sun); for (Body planet : sun.planets) { system_bodies.push_back(planet); } // Simulate orbits vector<vector<OrbitPoint>> orbit_points = PredictOrbits(10000, step, system_bodies); // Clear screen glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); // Draw paths for (vector<OrbitPoint> orbit_point_vector : orbit_points) { for (int i = 0; i < orbit_point_vector.size()-1; i++) { OrbitPoint orbit_point_1 = orbit_point_vector[i]; OrbitPoint orbit_point_2 = orbit_point_vector[i+1]; Geometry::DrawLine( orbit_point_1.pos_x, orbit_point_1.pos_y, orbit_point_2.pos_x, orbit_point_2.pos_y, zoom, 1.0, 1.0, 1.0, 0.6); } } // Draw bodies sun.Render(zoom, window_x); // Update window Geometry::Render(); Text::Render(); SDL_GL_SwapWindow(window); } // Clean up SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); exit(0); // Indicate successful execution return 0; }
24.370044
113
0.622379
LordIdra
c563dfeda280a9c5ef8c980ece6a94fb77f83bed
437
hpp
C++
client/src/ui/ui_microphone_sensitivity_layout.hpp
Grarak/NXCord
7ba09804c79cdc74da0d4f4766e6d8a1a8a10279
[ "MIT" ]
36
2019-12-11T15:46:34.000Z
2021-12-18T10:14:36.000Z
client/src/ui/ui_microphone_sensitivity_layout.hpp
Grarak/NXCord
7ba09804c79cdc74da0d4f4766e6d8a1a8a10279
[ "MIT" ]
10
2020-01-26T11:38:13.000Z
2020-10-10T22:04:20.000Z
client/src/ui/ui_microphone_sensitivity_layout.hpp
Grarak/NXCord
7ba09804c79cdc74da0d4f4766e6d8a1a8a10279
[ "MIT" ]
7
2020-01-23T13:33:40.000Z
2021-03-23T21:54:08.000Z
#pragma once #include <common/utils.hpp> #include "ui_custom_layout.hpp" using pu::ui::elm::Button; using pu::ui::elm::Rectangle; using pu::ui::elm::TextBlock; class UIMicrophoneSensitivityLayout : public UICustomLayout { private: time_t _sensitivity_looked_up = 0; size_t _current_threshold = 0; public: explicit UIMicrophoneSensitivityLayout(const Interface &interface); PU_SMART_CTOR(UIMicrophoneSensitivityLayout) };
20.809524
69
0.778032
Grarak
c565b5546aa51e3ffd187c3712cacec6dda6caa4
920
cpp
C++
src/utils.cpp
LiamTyler/LTEngine
b1697a63546516debfeb4f32e888484e37cd5e06
[ "MIT" ]
null
null
null
src/utils.cpp
LiamTyler/LTEngine
b1697a63546516debfeb4f32e888484e37cd5e06
[ "MIT" ]
null
null
null
src/utils.cpp
LiamTyler/LTEngine
b1697a63546516debfeb4f32e888484e37cd5e06
[ "MIT" ]
null
null
null
#include "include/utils.h" #include "include/renderer.h" #include "include/input.h" #include "include/resource_manager.h" Renderer* renderer; Input* input; ResourceManager* resourceManager; void InitEngine() { // Init SDL2 if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cerr << "Failed to init SDL" << std::endl; exit(EXIT_FAILURE); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); input = nullptr; renderer = nullptr; resourceManager = nullptr; } void InitEngineAfterWindow() { if (input == nullptr) { input = new Input; renderer = new Renderer; resourceManager = new ResourceManager; } } void QuitEngine() { delete input; delete renderer; delete resourceManager; SDL_Quit(); }
23
82
0.686957
LiamTyler
c56d6ed2a9310b1fd70492be5826329ec0309abd
2,284
cpp
C++
src/ossimPlanet/ossimPlanetVisitors.cpp
ossimlabs/ossim-planet
ba37375aaab4dcc4b01d55d297c8d1f2b2dbbef8
[ "MIT" ]
11
2015-12-24T03:25:01.000Z
2021-01-09T18:22:56.000Z
src/ossimPlanet/ossimPlanetVisitors.cpp
ossimlabs/ossim-planet
ba37375aaab4dcc4b01d55d297c8d1f2b2dbbef8
[ "MIT" ]
3
2016-01-24T10:30:35.000Z
2018-03-31T15:07:16.000Z
src/ossimPlanet/ossimPlanetVisitors.cpp
ossimlabs/ossim-planet
ba37375aaab4dcc4b01d55d297c8d1f2b2dbbef8
[ "MIT" ]
5
2015-12-16T13:10:16.000Z
2021-11-12T19:23:31.000Z
#include <ossimPlanet/ossimPlanetVisitors.h> #include <ossimPlanet/ossimPlanetLayer.h> #include <ossimPlanet/ossimPlanetNode.h> void ossimPlanetLayerNameIdSearchVisitor::apply(osg::Node& node) { ossimPlanetLayer* layer = dynamic_cast<ossimPlanetLayer*>(&node); ossimPlanetNode* layerNode = dynamic_cast<ossimPlanetNode*>(&node); if(theId.empty() && theName.empty()) return; if(layer) { if(!theName.empty()&&!theId.empty()) { if((layer->name() == theName)&& (layer->id() == theId)) { theNode = &node; } } else if(!theName.empty()) { if(layer->name() == theName) { theNode = &node; } } else if(!theId.empty()) { if(layer->id() == theId) { theNode = &node; } } } else if(layerNode) { if(!theName.empty()&&!theId.empty()) { if((layerNode->name() == theName)&& (layerNode->id() == theId)) { theNode = &node; } } else if(!theName.empty()) { if(layerNode->name() == theName) { theNode = &node; } } else if(!theId.empty()) { if(layerNode->id() == theId) { theNode = &node; } } } if(theNode.valid()) return; traverse(node); }; ossimPlanetUpdateVisitor::ossimPlanetUpdateVisitor() :osgUtil::UpdateVisitor(), theRedrawFlag(false) { } void ossimPlanetUpdateVisitor::reset() { theRedrawFlag = false; } bool ossimPlanetUpdateVisitor::redrawFlag()const { return theRedrawFlag; } void ossimPlanetUpdateVisitor::apply(osg::Node& node) { ossimPlanetNode* n = dynamic_cast<ossimPlanetNode*>(&node); if(n) { if(n->redrawFlag()) { n->setRedrawFlag(false); theRedrawFlag = true; } } UpdateVisitor::apply(node); } void ossimPlanetUpdateVisitor::apply(osg::Group& node) { ossimPlanetNode* n = dynamic_cast<ossimPlanetNode*>(&node); if(n) { if(n->redrawFlag()) { n->setRedrawFlag(false); theRedrawFlag = true; } } UpdateVisitor::apply(node); }
20.212389
70
0.528021
ossimlabs
c56ddedb6dc095f70df3d91e1b1a86922bcba0fe
2,252
hpp
C++
src/ReteVisualSerialization.hpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
src/ReteVisualSerialization.hpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
src/ReteVisualSerialization.hpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
#ifndef SEMPR_GUI_RETEVISUALSERIALIZATION_HPP_ #define SEMPR_GUI_RETEVISUALSERIALIZATION_HPP_ #include <cereal/cereal.hpp> #include <cereal/types/set.hpp> #include <rete-core/NodeVisitor.hpp> #include <string> #include <set> /* This file provides a few classes to help with creating and transmitting a visual representation of a rete network. Some helper structs for the basic representation, which can be created through the use of a node visitor which traverses the graph. These can be serialized to send them over the network. */ namespace sempr { namespace gui { struct Node { enum Type { CONDITION, MEMORY, PRODUCTION }; Type type; std::string id; std::string label; bool operator < (const Node& other) const; template <class Archive> void serialize(Archive& ar) { ar( cereal::make_nvp<Archive>("id", id), cereal::make_nvp<Archive>("label", label), cereal::make_nvp<Archive>("type", type) ); } }; struct Edge { std::string from; std::string to; bool operator < (const Edge& other) const; template <class Archive> void serialize(Archive& ar) { ar( cereal::make_nvp<Archive>("from", from), cereal::make_nvp<Archive>("to", to) ); } }; struct Graph { std::set<Node> nodes; std::set<Edge> edges; template <class Archive> void serialize(Archive& ar) { ar( cereal::make_nvp<Archive>("nodes", nodes), cereal::make_nvp<Archive>("edges", edges) ); } }; class CreateVisualGraphVisitor : public rete::NodeVisitor { Graph graph_; // a set of already visited nodes, to not visit them twice std::set<std::string> visited_; void addNode(Node::Type type, const std::string& id, const std::string& label); void addEdge(const std::string& from, const std::string& to); public: void visit(rete::AlphaNode*) override; void visit(rete::AlphaMemory*) override; void visit(rete::BetaNode*) override; void visit(rete::BetaMemory*) override; void visit(rete::BetaBetaNode*) override; void visit(rete::ProductionNode*) override; Graph graph() const; }; }} #endif /* include guard: SEMPR_GUI_RETEVISUALSERIALIZATION_HPP_ */
24.747253
83
0.666963
sempr-tk
c5706c0899bfe77334fc6b2eedb54176f2304505
32,041
hh
C++
bayehem/rsem/detonate-1.11/ref-eval/re_help.hh
fmaguire/BayeHem
f4594926e672a7af596716cb40464ccc06567c15
[ "Apache-2.0" ]
null
null
null
bayehem/rsem/detonate-1.11/ref-eval/re_help.hh
fmaguire/BayeHem
f4594926e672a7af596716cb40464ccc06567c15
[ "Apache-2.0" ]
null
null
null
bayehem/rsem/detonate-1.11/ref-eval/re_help.hh
fmaguire/BayeHem
f4594926e672a7af596716cb40464ccc06567c15
[ "Apache-2.0" ]
null
null
null
// This file is autogenerated. Edit the template instead. std::string get_help_string() { return " REF-EVAL: A toolkit of reference-based scores for de novo transcriptome\n" " sequence assembly evaluation\n" "\n" "Overview\n" "\n" " REF-EVAL computes a number of reference-based scores. These scores\n" " measure the quality of a transcriptome assembly relative to a\n" " collection of reference sequences. For information about how to run\n" " REF-EVAL, see \"Usage\" and the sections following it below. For\n" " information about the score definitions, see \"Score definitions\" and\n" " the sections following it below.\n" "\n" "Usage\n" "\n" " As an optional first step, estimate the \"true\" assembly, using\n" " [1]REF-EVAL-ESTIMATE-TRUE-ASSEMBLY. Alternatively, you can use the\n" " full-length reference transcript sequences directly as a reference.\n" "\n" " From now on, we will call the estimated \"true\" assembly or the\n" " collection of full-length reference sequences (whichever you choose\n" " to use) the reference. Let's assume that the assembly of interest is\n" " in A.fa, and the reference is in B.fa.\n" "\n" " If you want to compute alignment-based scores (see --scores below for\n" " more info), align the assembly to the reference and vice versa using\n" " [2]Blat. We recommend fairly unrestrictive settings, in order to\n" " generate many candidate alignments.\n" "\n" " $ blat -minIdentity=80 B.fa A.fa A_to_B.psl\n" " $ blat -minIdentity=80 A.fa B.fa B_to_A.psl\n" "\n" " If you want to compute weighted variants of scores, use [3]RSEM to\n" " compute the expression of the assembly and reference relative to the\n" " given reads. Let's assume that the reads are in reads.fq.\n" "\n" " $ rsem-prepare-reference --no-polyA A.fa A_ref\n" " $ rsem-prepare-reference --no-polyA B.fa B_ref\n" " $ rsem-calculate-expression -p 24 --no-bam-output reads.fq A_ref A_expr\n" " $ rsem-calculate-expression -p 24 --no-bam-output reads.fq B_ref B_expr\n" "\n" " Finally, run REF-EVAL. To compute everything, run:\n" "\n" " $ ./ref-eval --scores=nucl,pair,contig,kmer,kc \\\n" " --weighted=both \\\n" " --A-seqs A.fa \\\n" " --B-seqs B.fa \\\n" " --A-expr A_expr.isoforms.results \\\n" " --B-expr B_expr.isoforms.results \\\n" " --A-to-B A_to_B.psl \\\n" " --B-to-A B_to_A.psl \\\n" " --num-reads 5000000 \\\n" " --readlen 76 \\\n" " --kmerlen 76 \\\n" " | tee scores.txt\n" "\n" " To only compute the kmer compression score (and its dependencies),\n" " run:\n" "\n" " $ ./ref-eval --scores=kc \\\n" " --A-seqs A.fa \\\n" " --B-seqs B.fa \\\n" " --B-expr B_expr.isoforms.results \\\n" " --num-reads 5000000 \\\n" " --readlen 76 \\\n" " --kmerlen 76 \\\n" " | tee scores.txt\n" "\n" " To only compute the unweighted reference-based scores, run:\n" "\n" " $ ./ref-eval --scores=nucl,pair,contig \\\n" " --weighted=no \\\n" " --A-seqs A.fa \\\n" " --B-seqs B.fa \\\n" " --A-to-B A_to_B.psl \\\n" " --B-to-A B_to_A.psl \\\n" " | tee scores.txt\n" "\n" " To only compute the scores discussed in the DETONATE paper, run:\n" "\n" " $ ./ref-eval --paper \\\n" " --A-seqs A.fa \\\n" " --B-seqs B.fa \\\n" " --B-expr B_expr.isoforms.results \\\n" " --A-to-B A_to_B.psl \\\n" " --B-to-A B_to_A.psl \\\n" " --num-reads 5000000 \\\n" " --readlen 76 \\\n" " --kmerlen 76 \\\n" " | tee scores.txt\n" "\n" " The scores will be written to standard output (hence, above, to\n" " scores.txt). Progress information is written to standard error.\n" " Further details about the arguments to REF-EVAL are described below.\n" " Further details about the scores themselves are given under \"Score\n" " definitions\" below.\n" "\n" "Usage: Score specification\n" "\n" " --scores arg\n" "\n" " The groups of scores to compute, separated by commas (e.g.,\n" " --scores=nucl,contig,kc). It is more efficient to compute all\n" " the scores you are interested in using one invocation of\n" " REF-EVAL instead of using multiple invocations that each\n" " compute one score. The available score groups are as follows:\n" "\n" " Alignment-based score groups:\n" "\n" " * nucl: nucleotide precision, recall, and F1.\n" " * contig: contig precision, recall, and F1.\n" " * pair: pair precision, recall, and F1.\n" "\n" " Alignment-free score groups:\n" "\n" " * kmer: kmer Kullback-Leibler divergence, Jensen-Shannon\n" " divergence, and Hellinger distance.\n" " * kc: kmer recall, number of nucleotides, and kmer\n" " compression score.\n" "\n" " Required unless --paper is given.\n" "\n" " --weighted arg\n" "\n" " A string indicating whether to compute weighted or unweighted\n" " variants of scores, or both (e.g., --weighted=yes):\n" "\n" " * yes: compute weighted variants of scores.\n" " * no: compute unweighted variants of scores.\n" " * both: compute both weighted and unweighted variants of\n" " scores.\n" "\n" " In weighted variants, the expression levels (TPM) of the\n" " assembly and reference sequences are taken into account, and\n" " hence need to be specified using --A-expr and --B-expr.\n" " Unweighted variants are equivalent to weighted variants with\n" " uniform expression.\n" "\n" " The distinction between weighted and unweighted variants\n" " doesn't make sense for the KC score, so this option is\n" " ignored by the KC score.\n" "\n" " Required unless --paper or only --score=kc is given.\n" "\n" " --paper\n" "\n" " As an alternative to the above, if you are only interested in\n" " computing the scores described in the main text of our paper\n" " [1], you can pass the --paper flag instead of the --scores\n" " and --weighted options. In that case, the following scores\n" " will be computed:\n" "\n" " Alignment-based scores:\n" "\n" " * unweighted nucleotide F1\n" " * unweighted contig F1\n" "\n" " Alignment-free score groups:\n" "\n" " * weighted kmer compression score\n" "\n" " For obvious reasons, the --scores and --weighted options are\n" " incompatible with this flag.\n" "\n" " [1] Bo Li*, Nathanael Fillmore*, Yongsheng Bai, Mike Collins,\n" " James A. Thompson, Ron Stewart, Colin N. Dewey. Evaluation of\n" " de novo transcriptome assemblies from RNA-Seq data.\n" "\n" "Usage: Input and output specification\n" "\n" " --A-seqs arg\n" "\n" " The assembly sequences, in FASTA format. Required.\n" "\n" " --B-seqs arg\n" "\n" " The reference sequences, in FASTA format. Required.\n" "\n" " --A-expr arg\n" "\n" " The assembly expression, for use in weighted scores, as\n" " produced by RSEM in a file called *.isoforms.results.\n" " Required for weighted variants of scores.\n" "\n" " --B-expr arg\n" "\n" " The reference expression, for use in weighted scores, as\n" " produced by RSEM in a file called *.isoforms.results.\n" " Required for weighted variants of scores.\n" "\n" " --A-to-B arg\n" "\n" " The alignments of the assembly to the reference. The file\n" " format is specified by --alignment-type. Required for\n" " alignment-based scores.\n" "\n" " --B-to-A arg\n" "\n" " The alignments of the reference to the assembly. The file\n" " format is specified by --alignment-type. Required for\n" " alignment-based scores.\n" "\n" " --alignment-type arg\n" "\n" " The type of alignments used, either blast or psl. Default:\n" " psl. Currently BLAST support is experimental, not well\n" " tested, and not recommended.\n" "\n" "Usage: Options that modify the score definitions (and hence output)\n" "\n" " --strand-specific\n" "\n" " If this flag is present, it is assumed that all the assembly\n" " and reference sequences have the same orientation. Thus,\n" " alignments or kmer matches that are to the reverse strand are\n" " ignored.\n" "\n" " --readlen arg\n" "\n" " This option only applies to the KC scores. The read length of\n" " the reads used to build the assembly, used in the denominator\n" " of the ICR. Required for KC scores.\n" "\n" " --num-reads arg\n" "\n" " This option only applies to the KC scores. The number of\n" " reads used to build the assembly, used in the denominator of\n" " the ICR. Required for KC scores.\n" "\n" " --kmerlen arg\n" "\n" " This option only applies to the kmer and KC scores. This is\n" " the length (\"k\") of the kmers used in the definition of the\n" " KC and kmer scores. Required for KC and kmer scores.\n" "\n" " --min-frac-identity arg\n" "\n" " This option only applies to contig scores. Alignments with\n" " fraction identity less than this threshold are ignored. The\n" " fraction identity of an alignment is min(x/y, x/z), where\n" "\n" " * $x$ is the number of bases in the assembly sequence that\n" " are aligned to an identical base in the reference\n" " sequence, according to the alignment,\n" " * $y$ is the number of bases in the assembly sequence, and\n" " * $z$ is the number of bases in the reference sequence.\n" "\n" " Default: 0.99.\n" "\n" " --max-frac-indel arg\n" "\n" " This option only applies to contig scores. Alignments with\n" " fraction indel greater than this threshold are ignored. For\n" " psl alignments, the fraction indel of an alignment is\n" " $\\max(w/y, x/z)$, where\n" "\n" " * $w$ is the number of bases that are inserted in the\n" " assembly sequence, according to the alignment (\"Q gap\n" " bases\"),\n" " * $x$ is the number of bases that are inserted in the\n" " reference sequence, according to the alignment (\"T gap\n" " bases\"),\n" " * $y$ is the number of bases in the assembly sequence, and\n" " * $z$ is the number of bases in the reference sequence.\n" "\n" " For blast alignments, the fraction indel of an alignment is\n" " $\\max(x/y, x/z)$, where\n" "\n" " * $x$ is the number of gaps bases that are inserted in the\n" " reference sequence, according to the alignment (\"gaps\"),\n" " * $y$ is the number of bases in the assembly sequence, and\n" " * $z$ is the number of bases in the reference sequence.\n" "\n" " Default: 0.01.\n" "\n" " --min-segment-len arg\n" "\n" " This option only applies to nucleotide and pair scores.\n" " Alignment segments that contain fewer than this number of\n" " bases will be discarded. Default: 100. In the DETONATE paper,\n" " this was set to the read length.\n" "\n" "Usage: Options that modify the algorithm, but not the score definitions\n" "\n" " --hash-table-type arg\n" "\n" " The type of hash table to use, either \"sparse\" or \"dense\".\n" " This is only relevant for KC and kmer scores. The sparse\n" " table is slower but uses less memory. The dense table is\n" " faster but uses more memory. Default: \"sparse\".\n" "\n" " --hash-table-numeric-type arg\n" "\n" " The numeric type to use to store values in the hash table,\n" " either \"double\" or \"float\". This is only relevant for KC and\n" " kmer scores. Using single-precision floating point numbers\n" " (\"float\") requires less memory than using double-precision\n" " (\"double\"), but may also result in more numerical error. Note\n" " that we use double-precision numbers throughout our\n" " calculations even if single-precision numbers are stored in\n" " the table, so the additional error should be minimal.\n" " Default: \"double\".\n" "\n" " --hash-table-fudge-factor arg\n" "\n" " This is only relevant for KC and kmer scores. When the hash\n" " table is created, its initial capacity is set as the total\n" " worst-case number of possible kmers in the assembly and\n" " reference, based on each sequence's length, divided by the\n" " fudge factor. The default, 2.0, is often reasonable because\n" " (1) most kmers should be shared by the assembly and the\n" " reference, and (2) many kmers will be repeated several times.\n" " However, if you have a lot of memory or a really bad\n" " assembly, you could try a smaller number. Default: 2.0.\n" "\n" "Usage: Options to include additional output\n" "\n" " --trace arg\n" "\n" " If given, the prefix for additional output that provides\n" " details about the REF-EVAL scores; if not given, no such\n" " output is produced. Currently, the only such output is as\n" " follows.\n" "\n" " * (--trace).{weighted,unweighted}_contig_{precision,recall}_matching\n" " is a TSV file that describes the matching used to\n" " compute the weighted or unweighted contig precision or\n" " recall. (Details about the matching are given in the\n" " section on score definitions below.) For recall, each\n" " row corresponds to a reference sequence $b$. Column 1\n" " contains $b$'s name. If $b$ is matched to a contig $a$,\n" " then the remaining columns are as follows:\n" "\n" " * Column 2 contains $a$'s name.\n" " * Column 3 contains the weight of the edge between\n" " $b$ and $a$. (This is set to the uniform weights\n" " $1/|B|$ in the unweighted case, although the\n" " maximum cardinality matching algorithm does not\n" " actually use these weights.)\n" " * Column 4 contains the names of all the contigs $a'$\n" " that are adjacent to $b$ in the bipartite graph\n" " that the matching is based on, separated by commas.\n" " Thus, this column lists all the contigs $a'$ that\n" " have a \"good enough\" match with the reference\n" " sequence $b$, according to the criteria used to\n" " build the bipartite graph. (See the section below\n" " on score definitions for details.)\n" "\n" " Otherwise, if $b$ is not matched to any contig, columns\n" " 2 and 3 contain \"NA\". For precision, the file has the\n" " same format, but with the reference and the assembly\n" " interchanged. In other words, each row corresponds to a\n" " contig $a$ and contains information about its matching\n" " to a reference sequence $b$, or all \"NA\" values if $a$\n" " was not matched.\n" "\n" "Usage: General options\n" "\n" " -? [ --help ]\n" "\n" " Display this information.\n" "\n" "Score definitions\n" "\n" " In the next few sections, we define the scores computed by REF-EVAL.\n" " Throughout, $A$ denotes the assembly, and $B$ denotes the reference.\n" " (As discussed under \"Usage\" above, the reference can be either an\n" " estimate of the \"true\" assembly or a collection of full-length\n" " reference transcripts.) Both $A$ and $B$ are thought of as sets of\n" " sequences. $A$ is a set of contigs, and $B$ is a set of reference\n" " sequences.\n" "\n" "Score definitions: contig precision, recall, and F1\n" "\n" " The contig recall is defined as follows:\n" "\n" " * Align the assembly $A$ to the reference $B$. Notation: each\n" " alignment $l$ is between a contig $a$ in $A$ and an reference\n" " sequence $b$ in $B$.\n" " * Throw out alignments that are to the reverse strand, if\n" " --strand-specific is present.\n" " * Throw out alignments whose fraction identity is less than\n" " --min-frac-identity (q.v.\\ for the definition of \"fraction\n" " identity\").\n" " * Throw out alignments whose fraction indel is greater than\n" " --max-frac-indel (q.v.\\ for the definition of \"fraction indel\").\n" " * Construct a bipartite graph from the remaining alignments, in\n" " which there is an edge between $a$ and $b$ iff there is a\n" " remaining alignment $l$ of $a$ to $b$.\n" " * If --weighted=yes, specify a weight for each edge between $a$ and\n" " $b$, namely $\\tau(b)$, the relative abundance of $b$ within the\n" " reference, as specified in --B-expr.\n" " * The unweighted contig recall is the number of edges in the\n" " maximum cardinality matching of this graph, divided by the number\n" " of sequences in the reference $B$.\n" " * The weighted contig recall is the weight of the maximum weight\n" " matching of this graph.\n" "\n" " The contig precision is defined as follows: Interchange the assembly\n" " and the reference, and compute the contig recall.\n" "\n" " The contig F1 is the harmonic mean of the precision and recall.\n" "\n" "Score definitions: nucleotide precision, recall, and F1\n" "\n" " The nucleotide recall is defined as follows:\n" "\n" " * Align the assembly $A$ to the reference $B$. Notation: each\n" " alignment $l$ is between a contig $a \\in A$ and an reference\n" " element $b \\in B$.\n" " * Throw out alignments that are to the reverse strand, if\n" " --strand-specific is present.\n" " * Throw out alignments that are shorter than --min-fragment-length.\n" " * Add each remaining alignment to a priority queue, with priority\n" " equal to the number of identical bases in the alignment.\n" " * Let numer = 0.\n" " * While the priority queue is not empty:\n" "\n" " * Pop the alignment $l$ with highest priority.\n" " * Add the number of identical bases in the alignment to numer.\n" " * Subtract $l$ from all the other alignments in the queue and\n" " update their priorities (see below).\n" "\n" " * Let denom be the total number of bases in the reference $B$.\n" " * The unweighted nucleotide recall is numer/denom.\n" "\n" " The actual implementation uses a more complicated and efficient\n" " algorithm than the one above.\n" "\n" " If --weighted=yes, then (i) \"the number of identical bases\" above is\n" " replaced by \"the number of identical bases, times $\\tau(b)$\", in the\n" " definition of the priority and the numer, and (ii) \"total number of\n" " bases in the reference $B$\" is replaced by \"$\\sum_{b \\in B} \\tau(b)\n" " length(b)$\". In other words, each base (of a reference sequence),\n" " throughout the computation, is weighted by the expression level of\n" " its parent sequence.\n" "\n" " The nucleotide precision is defined as follows: Interchange the\n" " assembly and the reference, and compute the nucleotide recall.\n" "\n" " The nucleotide F1 is the harmonic mean of the precision and recall.\n" "\n" " Alignment subtraction is defined as follows.\n" "\n" " * An alignment $l$ from $a$ to $b$ can be thought of as a set of\n" " pairs of disjoint intervals\n" " $$ \\{ ([s_1(a), e_1(a)], [s_1(b), e_1(b)]), \\dots, ([s_n(a),\n" " e_n(a)], [s_n(b), e_n(b)]) \\}, $$\n" " where each pair $([s_i(a), e_i(a)], [s_i(b), e_i(b)])$\n" " corresponds to an ungapped segment of the alignment: $s_i(a)$ and\n" " $e_i(a)$ are the segment's start and end positions within a, and\n" " $s_i(b)$ and $e_i(b)$ are the segment's start and end positions\n" " within b. In the case of non-strand-specific alignments, $s_i(b)$\n" " might be greater than $e_i(b)$.\n" " * If $l$ is an alignment from $a$ to $b$, $l'$ is an alignment from\n" " $a'$ to $b'$, $a \\neq a'$, and $b \\neq b'$, then the difference\n" " $l - l' = l$.\n" " * If $l$ is an alignment from $a$ to $b$, $l'$ is an alignment from\n" " $a'$ to $b'$, $a = a'$, and $b \\neq b'$, then the difference $l -\n" " l' = l''$, defined as follows. Each alignment segment of $l$ is\n" " compared to the alignment segments of $l'$. If a segment of $l$\n" " overlaps one of the segments of $l'$ wrt $a$, it is truncated so\n" " as to avoid the overlap. This truncation may result in zero, one,\n" " or two replacement alignment segments. (If the overlapping\n" " alignment segment of $l'$ is contained strictly within the\n" " segment of $l$, wrt $a$, two segments will result.)\n" " * If $l$ is an alignment from $a$ to $b$, $l'$ is an alignment from\n" " $a'$ to $b'$, $a \\neq a'$, and $b = b'$, then the difference $l -\n" " l' = l''$, defined similarly as in the previous item, except\n" " overlaps are examined and resolved wrt $b$.\n" "\n" " A couple of examples of the above are as follows. The comments in\n" " [4]test_re_matched.cpp contain even more examples.\n" "\n" " As a first example, consider alignments of an assembly $A = \\{a_0,\n" " a_1, a_2\\}$ to a reference $B = \\{b_0, b_1\\}$. In the pictures below,\n" " each alignment segment is indicated by a pair diagonal or vertical\n" " lines, with its name (initially $x$, $y$, $z$, $w$) in between the\n" " two lines.\n" "\n" " b0 b1\n" " B ----------------- -------------\n" " / \\ / \\ / | / |\n" " / \\ / \\ / |/ |\n" " / x / y \\ z / w |\n" " / / \\ / \\ /| |\n" " A --------- --------- ---------\n" " a0 a1 a2\n" "\n" " Assume:\n" "\n" " * $x > y > z > w$, where $>$ compares alignment size measured by\n" " the number of identical bases.\n" " * $y - x < z$.\n" " * $y - x$ is contained in $z$, wrt $A$.\n" "\n" " Step 1: Process alignment $x$, resulting in\n" "\n" " b0 b1\n" " B ------------------ --------------\n" " / /\\ \\ / | / |\n" " / / \\ \\ / |/ |\n" " / x / \\*\\ z / w | * = y - x\n" " / / / \\ /| |\n" " A --------- --------- ---------\n" " a0 a1 a2\n" "\n" " Step 2: Process alignment $z$, resulting in\n" "\n" " b0 b1\n" " B ----------------- --------------\n" " / / / /||\n" " / / / / ||\n" " / x / / z / *| * = w - z\n" " / / / / ||\n" " A --------- --------- ---------\n" " a0 a1 a2\n" "\n" " Now we have a 1-1 mathing. The intervals of $B$ used to compute\n" " recall are as follows:\n" "\n" " b0 b1\n" " B -----[--------]-- [----][]------\n" " / / / /||\n" " ...\n" "\n" " As a second example, we start with the same initial set of\n" " alignments:\n" "\n" " b0 b1\n" " B ----------------- -------------\n" " / \\ / \\ / | / |\n" " / \\ / \\ / |/ |\n" " / x / y \\ z / w |\n" " / / \\ / \\ /| |\n" " A --------- --------- ---------\n" " a0 a1 a2\n" "\n" " But we make a slightly different set of assumptions:\n" "\n" " * $x > y > w > z$ ($w$ and $z$ are interchanged, compared to the\n" " first example).\n" " * $y - x < w$.\n" " * $y - x > z - w$.\n" " * $y - x$ is contained in $z$, wrt $A$.\n" "\n" " Step 1: Process alignment $x$, resulting in\n" "\n" " b0 b1\n" " B ------------------ --------------\n" " / /\\ \\ / | / |\n" " / / \\ \\ / |/ |\n" " / x / \\*\\ z / w | * = y - x\n" " / / / \\ /| |\n" " A --------- --------- ---------\n" " a0 a1 a2\n" "\n" " Step 2: Process alignment w, resulting in\n" "\n" " b0 b1\n" " B ------------------ --------------\n" " / /\\ \\ / | |\n" " / / \\ \\ / /| |\n" " / x / \\*\\ +/ | w | * = y - x\n" " / / / \\/ | | + = z - w\n" " A --------- --------- ---------\n" " a0 a1 a2\n" "\n" " Step 3: Process alignment $y - x$, resulting in\n" "\n" " b0 b1\n" " B ------------------ --------------\n" " / /\\ \\ +/ | |\n" " / / \\*\\// | |\n" " / x / \\ \\ | w | * = y - x\n" " / / // \\ | | + = (z - w) - (y - x)\n" " A --------- --------- ---------\n" " a0 a1 a2\n" "\n" " Now we have a 1-1 mathing. The intervals of $B$ used to compute\n" " recall are:\n" "\n" " b0 b1\n" " B -----[--------][-] []-[---]------\n" " / /\\ \\ // | | * = y - x\n" " x * + w + = (z - w) - (y - x)\n" " ...\n" "\n" "Score definitions: pair precision, recall, and F1\n" "\n" " The definitions for pair precision, recall, and F1 are exactly the\n" " same as for nucleotide precision, recall, and F1, except that instead\n" " of bases, we operate on pairs of bases.\n" "\n" " For example, consider the reference $B$ (with one transcript) and\n" " assembly $A$ (with two contigs), where horizontal position indicates\n" " alignment.\n" "\n" " B: b = AGCTCGACGT\n" " A: a_1 = AGCT\n" " a_2 = CGACGT\n" "\n" " Here, the transcript recall is 0 (because neither $a_1$ nor $a_2$\n" " covers $b$ to $\\geq$ 99 percent), but the nucleotide recall is 1\n" " (because $a_1$ and $a_2$ jointly cover $b$ completely). The pair\n" " recall is somewhere in between, because the following pairs of $b$\n" " are correctly predicted (represented by an upper triangular indicator\n" " matrix):\n" "\n" " First base\n" " S AGCTCGACGT\n" " e A 1111\n" " c G 111\n" " o C 11\n" " n T 1\n" " d C 111111\n" " G 11111\n" " b A 1111\n" " a C 111\n" " s G 11\n" " e T 1\n" "\n" "Score definitions: KC and related scores\n" "\n" " The kmer compression score (KC score) is a combination of two\n" " measures, weighted kmer recall (WKR) and inverse compression rate\n" " (ICR), and is simply\n" "\n" " $$ KC = WKR - ICR. $$\n" "\n" " The WKR measures the fidelity with which a particular assembly\n" " represents the kmer content of the reference sequences. Balancing the\n" " WKR, the ICR measures the degree to which the assembly compresses the\n" " RNA-Seq data. The details of the WKR and ICR measures are provided\n" " below.\n" "\n" " To compute the WKR, the relative abundances of the reference elements\n" " are required, as specified by --B-expr. Given the reference sequences\n" " and their abundances, a kmer occurrence frequency profile, $p$, is\n" " computed, with individual kmer occurrences weighted by their parent\n" " sequences' abundances: for each kmer $r$, we define\n" "\n" " $$ p(r) = \\frac{ \\sum_{b \\in B} n(r,b) \\tau(b) } { \\sum_{b \\in B}\n" " n(b) \\tau(b) } $$\n" "\n" " where $B$ is the set of reference sequences, and for each reference\n" " sequence $b \\in B$:\n" "\n" " * $n(r,b)$ is the number of times the kmer $r$ occurs in $b$,\n" " * $n(b) $ is the total number of kmers in $b$, and\n" " * $\\tau(b)$ is the relative abundance of $b$.\n" "\n" " Letting $R(A)$ be the set of all kmers in the assembly $A$, the\n" " weighted kmer recall (WKR) is defined as\n" "\n" " $$ WKR = \\sum_{r \\in R(A)} p(r). $$\n" "\n" " REF-EVAL currently uses --readlen as the kmer length.\n" "\n" " Since recall measures only tell half of the story regarding accuracy,\n" " the KC score includes a second term, the ICR, which serves to\n" " penalize large assemblies. We define the inverse compression rate\n" " (ICR) of an assembly as\n" "\n" " $$ ICR = n_A/(N L), $$\n" "\n" " where\n" "\n" " * $n_A$ is the total number of bases in the assembly $A$,\n" " * $N$ is the total number of reads, as specified by --num-reads,\n" " and\n" " * $L$ is the read length, as specified by --readlen.\n" "\n" "Score definitions: kmer scores\n" "\n" " If --weighted=yes, we construct a kmer occurrence frequency profile\n" " $p_B$ for $B$ exactly as described in the previous section (about the\n" " KC score). We construct a kmer occurrence frequency profile $p_A$ for\n" " $A$ similarly. The relative abundances are specified by --A-expr and\n" " --B-expr.\n" "\n" " If --weighted=no, we construct the kmer occurrence frequency profiles\n" " $p_A$ and $p_B$ in the same way, except that uniform relative\n" " abundances are used, i.e., $\\tau(a) = 1/|A|$ for all $a$ in $A$, and\n" " $\\tau(b) = 1/|B|$ for all $b$ in $B$, where $|A|$ is the number of\n" " contigs in $A$, and $|B|$ is the number of reference sequences in\n" " $B$.\n" "\n" " Let $m$ be the \"mean\" profile of $p_A$ and $p_B$:\n" "\n" " $$ m(r) = (1/2) (p_A(r) + p_B(r)) \\qquad\\hbox{for every kmer $r$}. $$\n" "\n" " The Jensen-Shannon divergence between $p_A$ and $p_B$ is defined in\n" " terms of the KL divergence between $p_A$ and the mean, and $p_B$ and\n" " the mean, as follows:\n" "\n" " * Let $KL(p_A || m) = \\sum_r p_A(r) (\\log_2(p_A(r)) -\n" " \\log_2(m(r)))$.\n" " * Let $KL(p_B || m) = \\sum_r p_B(r) (\\log_2(p_B(r)) -\n" " \\log_2(m(r)))$.\n" " * Let $JS(p_A || p_B) = (1/2) (KL(p_A || m) + KL(p_B || m))$.\n" "\n" " In the output file, these three scores are denoted\n" " (un)weighted_kmer_KL_A_to_M, (un)weighted_kmer_KL_B_to_M, and\n" " (un)weighted_kmer_jensen_shannon, respectively.\n" "\n" " The Hellinger distance between $p_A$ and $p_B$ is defined as\n" "\n" " $$ \\sqrt{ (1/2) \\sum_r (\\sqrt{p_A(r)} - \\sqrt{p_B(r)})^2 } $$\n" "\n" " The total variation distance between $p_A$ and $p_B$ is defined as\n" "\n" " $$ (1/2) \\sum_r |p_A(r) - p_B(r)|, $$\n" "\n" " where $|\\cdot|$ denotes absolute value. Above, $\\sum_r$ denotes a sum\n" " over all possible kmers $r$ (most of which will have $p_A(r) = p_B(r)\n" " = 0$).\n" "\n" "References\n" "\n" " Visible links\n" " 1. http://deweylab.biostat.wisc.edu/detonate/ref-eval-estimate-true-assembly.html\n" " 2. http://genome.ucsc.edu/FAQ/FAQblat.html\n" " 3. http://deweylab.biostat.wisc.edu/rsem/\n" " 4. https://github.com/deweylab/detonate/blob/master/ref-eval/test_re_matched.cpp\n" ; }
44.012363
88
0.549889
fmaguire
c570bfb70284d78d42c5c150e462cd6efd27988e
24,468
cpp
C++
Daniel2.Benchmark/Daniel2.Benchmark.cpp
Cinegy/Cinecoder.Samples
28a567b52ee599307bf797f6420dbb1e54c918e5
[ "Apache-2.0" ]
17
2018-04-06T07:51:30.000Z
2022-03-21T13:38:50.000Z
Daniel2.Benchmark/Daniel2.Benchmark.cpp
Cinegy/Cinecoder.Samples
28a567b52ee599307bf797f6420dbb1e54c918e5
[ "Apache-2.0" ]
9
2019-02-22T10:00:03.000Z
2020-12-11T03:27:46.000Z
Daniel2.Benchmark/Daniel2.Benchmark.cpp
Cinegy/Cinecoder.Samples
28a567b52ee599307bf797f6420dbb1e54c918e5
[ "Apache-2.0" ]
4
2018-06-05T12:37:47.000Z
2020-07-28T08:31:21.000Z
#define _CRT_SECURE_NO_WARNINGS #ifdef _WIN32 #include <windows.h> #include <atlbase.h> #endif #include <stdio.h> #include <stdlib.h> #include <thread> #include <chrono> using namespace std::chrono; using namespace std::chrono_literals; #include "cpu_load_meter.h" #include "../common/cuda_dyn/cuda_dyn_load.h" #include <Cinecoder_h.h> #include <Cinecoder_i.c> #ifdef _WIN32 #include "Cinecoder.Plugin.GpuCodecs.h" #include "Cinecoder.Plugin.GpuCodecs_i.c" #endif #include "cinecoder_errors.h" #include "../common/cinecoder_license_string.h" #include "../common/cinecoder_error_handler.h" #include "../common/com_ptr.h" #include "../common/c_unknown.h" #include "../common/conio.h" LONG g_target_bitrate = 0; bool g_CudaEnabled = false; // variables used for encoder/decoder latency calculation static decltype(system_clock::now()) g_EncoderTimeFirstFrameIn, g_EncoderTimeFirstFrameOut; static decltype(system_clock::now()) g_DecoderTimeFirstFrameIn, g_DecoderTimeFirstFrameOut; // Memory types used in benchmark enum MemType { MEM_SYSTEM, MEM_PINNED, MEM_GPU }; MemType g_mem_type = MEM_SYSTEM; void* mem_alloc(MemType type, size_t size, int device = 0) { if(type == MEM_SYSTEM) { #ifdef _WIN32 BYTE *ptr = (BYTE*)VirtualAlloc(NULL, size + 2*4096, MEM_COMMIT, PAGE_READWRITE); ptr += 4096 - (size & 4095); DWORD oldf; VirtualProtect(ptr + size, 4096, PAGE_NOACCESS, &oldf); return ptr; #elif defined(__APPLE__) return (LPBYTE)malloc(size); #elif defined(__ANDROID__) void *ptr = nullptr; posix_memalign(&ptr, 4096, size); return ptr; #else return (LPBYTE)aligned_alloc(4096, size); #endif } if(!g_CudaEnabled) return fprintf(stderr, "CUDA is disabled\n"), nullptr; if(type == MEM_PINNED) { void *ptr = nullptr; auto err = cudaMallocHost(&ptr, size); if(err) fprintf(stderr, "CUDA error %d\n", err); return ptr; } if(type == MEM_GPU) { printf("Using CUDA GPU memory: %zd byte(s) on Device %d\n", size, device); int old_device; auto err = cudaGetDevice(&old_device); if(err) return fprintf(stderr, "cudaGetDevice() error %d\n", err), nullptr; if(device != old_device && (err = cudaSetDevice(device)) != 0) return fprintf(stderr, "cudaSetDevice(%d) error %d\n", device, err), nullptr; void *ptr = nullptr; err = cudaMalloc(&ptr, size); if(err) return fprintf(stderr, "CUDA error %d\n", err), nullptr; cudaSetDevice(old_device); return ptr; } return nullptr; } #include "file_writer.h" #include "dummy_consumer.h" //----------------------------------------------------------------------------- CC_COLOR_FMT ParseColorFmt(const char *s) //----------------------------------------------------------------------------- { if(0 == strcmp(s, "YUY2")) return CCF_YUY2; if(0 == strcmp(s, "V210")) return CCF_V210; if(0 == strcmp(s, "Y216")) return CCF_Y216; if(0 == strcmp(s, "RGBA")) return CCF_RGBA; if(0 == strcmp(s, "RGBX")) return CCF_RGBX; if(0 == strcmp(s, "NV12")) return CCF_NV12; if(0 == strcmp(s, "NULL")) return CCF_UNKNOWN; return (CC_COLOR_FMT)-1; } //----------------------------------------------------------------------------- int main(int argc, char* argv[]) //----------------------------------------------------------------------------- { g_CudaEnabled = __InitCUDA() == 0; if(argc < 5) { puts("Usage: intra_encoder <codec> <profile.xml> <rawtype> <input_file.raw> [/outfile=<output_file.bin>] [/outfmt=<rawtype>] [/outscale=#] [/fps=#] [/device=#]"); puts("Where the <codec> is one of the following:"); puts("\t'D2' -- Daniel2 CPU codec test"); if(g_CudaEnabled) { puts("\t'D2CUDA' -- Daniel2 CUDA codec test, data is copying from GPU into CPU pinned memory"); puts("\t'D2CUDAGPU' -- Daniel2 CUDA codec test, data is copying from GPU into GPU global memory"); puts("\t'D2CUDANP' -- Daniel2 CUDA codec test, data is copying from GPU into CPU NOT-pinned memory (bad case test)"); } #ifndef __aarch64__ puts("\t'AVCI' -- AVC-Intra CPU codec test"); #endif #ifdef _WIN32 puts("\t'H264_NV' -- H264 NVidia GPU codec test (requires GPU codec plugin)"); puts("\t'HEVC_NV' -- HEVC NVidia GPU codec test (requires GPU codec plugin)"); puts("\t'H264_IMDK' -- H264 Intel QuickSync codec test (requires GPU codec plugin)"); puts("\t'HEVC_IMDK' -- HEVC Intel QuickSync codec test (requires GPU codec plugin)"); puts("\t'H264_IMDK_SW' -- H264 Intel QuickSync codec test (requires GPU codec plugin)"); puts("\t'HEVC_IMDK_SW' -- HEVC Intel QuickSync codec test (requires GPU codec plugin)"); puts("\t'MPEG' -- MPEG s/w encoder"); puts("\t'H264' -- H264 s/w encoder"); #endif puts("\n <rawtype> can be 'YUY2','V210','V216','RGBA' or 'NULL'"); return 1; } CC_VERSION_INFO version = Cinecoder_GetVersion(); printf("Cinecoder version %d.%02d.%02d\n", version.VersionHi, version.VersionLo, version.EditionNo); Cinecoder_SetErrorHandler(new C_CinecoderErrorHandler()); CLSID clsidEnc = {}, clsidDec = {}; const char *strEncName = 0; bool bForceGetFrameOnDecode = false; bool bLoadGpuCodecsPlugin = false; if(0 == strcmp(argv[1], "AVCI")) { clsidEnc = CLSID_CC_AVCIntraEncoder; clsidDec = CLSID_CC_AVCIntraDecoder2; strEncName = "AVC-Intra"; } if(0 == strcmp(argv[1], "D2")) { clsidEnc = CLSID_CC_DanielVideoEncoder; clsidDec = CLSID_CC_DanielVideoDecoder; strEncName = "Daniel2"; bForceGetFrameOnDecode = true; } if(g_CudaEnabled && 0 == strcmp(argv[1], "D2CUDA")) { clsidEnc = CLSID_CC_DanielVideoEncoder_CUDA; clsidDec = CLSID_CC_DanielVideoDecoder_CUDA; strEncName = "Daniel2_CUDA"; g_mem_type = MEM_PINNED; bForceGetFrameOnDecode = true; } if(g_CudaEnabled && 0 == strcmp(argv[1], "D2CUDANP")) { clsidEnc = CLSID_CC_DanielVideoEncoder_CUDA; clsidDec = CLSID_CC_DanielVideoDecoder_CUDA; strEncName = "Daniel2_CUDA (NOT PINNED MEMORY!!)"; //g_mem_type = MEM_PINNED; bForceGetFrameOnDecode = true; } if(g_CudaEnabled && 0 == strcmp(argv[1], "D2CUDAGPU")) { clsidEnc = CLSID_CC_DanielVideoEncoder_CUDA; clsidDec = CLSID_CC_DanielVideoDecoder_CUDA; strEncName = "Daniel2_CUDA (GPU-GPU mode)"; g_mem_type = MEM_GPU; } #ifdef _WIN32 if(0 == strcmp(argv[1], "H264_NV")) { clsidEnc = CLSID_CC_H264VideoEncoder_NV; clsidDec = CLSID_CC_H264VideoDecoder_NV; strEncName = "NVidia H264"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "H264_NV_GPU")) { clsidEnc = CLSID_CC_H264VideoEncoder_NV; clsidDec = CLSID_CC_H264VideoDecoder_NV; strEncName = "NVidia H264"; bLoadGpuCodecsPlugin = true; g_mem_type = MEM_GPU; } if(0 == strcmp(argv[1], "HEVC_NV")) { clsidEnc = CLSID_CC_HEVCVideoEncoder_NV; clsidDec = CLSID_CC_HEVCVideoDecoder_NV; strEncName = "NVidia HEVC"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "HEVC_NV_GPU")) { clsidEnc = CLSID_CC_HEVCVideoEncoder_NV; clsidDec = CLSID_CC_HEVCVideoDecoder_NV; strEncName = "NVidia HEVC"; g_mem_type = MEM_GPU; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "H264_IMDK")) { clsidEnc = CLSID_CC_H264VideoEncoder_IMDK; clsidDec = CLSID_CC_H264VideoDecoder_IMDK; strEncName = "Intel QuickSync H264"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "HEVC_IMDK")) { clsidEnc = CLSID_CC_HEVCVideoEncoder_IMDK; clsidDec = CLSID_CC_HEVCVideoDecoder_IMDK; strEncName = "Intel QuickSync HEVC"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "H264_IMDK_SW")) { clsidEnc = CLSID_CC_H264VideoEncoder_IMDK_SW; clsidDec = CLSID_CC_H264VideoDecoder_IMDK_SW; strEncName = "Intel QuickSync H264 (SOFTWARE)"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "HEVC_IMDK_SW")) { clsidEnc = CLSID_CC_HEVCVideoEncoder_IMDK_SW; clsidDec = CLSID_CC_HEVCVideoDecoder_IMDK_SW; strEncName = "Intel QuickSync HEVC (SOFTWARE)"; bLoadGpuCodecsPlugin = true; } if(0 == strcmp(argv[1], "H264")) { clsidEnc = CLSID_CC_H264VideoEncoder; clsidDec = CLSID_CC_H264VideoDecoder; strEncName = "H264"; } if(0 == strcmp(argv[1], "MPEG")) { clsidEnc = CLSID_CC_MpegVideoEncoder; clsidDec = CLSID_CC_MpegVideoDecoder; strEncName = "MPEG"; } #endif if(!strEncName) return fprintf(stderr, "Unknown encoder type '%s'\n", argv[1]), -1; FILE *profile = fopen(argv[2], "rt"); if(profile == NULL) return fprintf(stderr, "Can't open the profile %s\n", argv[2]), -2; const char *strInputFormat = argv[3], *strOutputFormat = argv[3]; CC_COLOR_FMT cFormat = ParseColorFmt(strInputFormat); if(cFormat == (CC_COLOR_FMT)-1) return fprintf(stderr, "Unknown raw data type '%s'\n", argv[3]), -3; FILE *inpf = fopen(argv[4], "rb"); if(inpf == NULL) return fprintf(stderr, "Can't open the file %s", argv[4]), -4; FILE *outf = NULL; CC_COLOR_FMT cOutputFormat = cFormat; int DecoderScale = 0; double TargetFps = 0; int EncDeviceID = -2, DecDeviceID = -2; int NumThreads = 0; for(int i = 5; i < argc; i++) { if(0 == strncmp(argv[i], "/outfile=", 9)) { outf = fopen(argv[i] + 9, "wb"); if(outf == NULL) return fprintf(stderr, "Can't create the file %s", argv[i] + 9), -i; } else if(0 == strncmp(argv[i], "/outfmt=", 8)) { cOutputFormat = ParseColorFmt(strOutputFormat = argv[i] + 8); if(cOutputFormat == (CC_COLOR_FMT)-1) return fprintf(stderr, "Unknown output raw data type '%s'\n", argv[i]), -i; } else if(0 == strncmp(argv[i], "/outscale=", 10)) { DecoderScale = atoi(argv[i] + 10); } else if(0 == strncmp(argv[i], "/fps=", 5)) { TargetFps = atof(argv[i] + 5); } else if(0 == strncmp(argv[i], "/device=", 8)) { EncDeviceID = atoi(argv[i] + 8); } else if(0 == strncmp(argv[i], "/device2=", 9)) { DecDeviceID = atoi(argv[i] + 9); } else if(0 == strncmp(argv[i], "/numthreads=", 12)) { NumThreads = atoi(argv[i] + 12); } else return fprintf(stderr, "Unknown switch '%s'\n", argv[i]), -i; } // cudaSetDeviceFlags(cudaDeviceMapHost); HRESULT hr = S_OK; com_ptr<ICC_ClassFactory> pFactory; hr = Cinecoder_CreateClassFactory(&pFactory); if(FAILED(hr)) return hr; hr = pFactory->AssignLicense(COMPANYNAME,LICENSEKEY); if(FAILED(hr)) return fprintf(stderr, "Incorrect license"), hr; #ifdef _WIN32 const char *gpu_plugin_name = "Cinecoder.Plugin.GpuCodecs.dll"; if(bLoadGpuCodecsPlugin && FAILED(hr = pFactory->LoadPlugin(CComBSTR(gpu_plugin_name)))) return fprintf(stderr, "Error loading '%s'", gpu_plugin_name), hr; #endif char profile_text[4096] = { 0 }; if (fread(profile_text, 1, sizeof(profile_text), profile) < 0) return fprintf(stderr, "Profile reading error"), -1; #ifdef _WIN32 CComBSTR pProfile = profile_text; #else auto pProfile = profile_text; #endif com_ptr<ICC_VideoEncoder> pEncoder; _fseeki64(inpf, 0, SEEK_SET); hr = pFactory->CreateInstance(clsidEnc, IID_ICC_VideoEncoder, (IUnknown**)&pEncoder); if(FAILED(hr)) return hr; if(NumThreads > 0) { fprintf(stderr, "Setting up specified number of threads = %d for the encoder: ", NumThreads); com_ptr<ICC_ThreadsCountProp> pTCP; if(FAILED(hr = pEncoder->QueryInterface(IID_ICC_ThreadsCountProp, (void**)&pTCP))) fprintf(stderr, "NAK. No ICC_ThreadsCountProp interface found\n"); else if(FAILED(hr = pTCP->put_ThreadsCount(NumThreads))) return fprintf(stderr, "FAILED\n"), hr; fprintf(stderr, "OK\n"); } com_ptr<ICC_DeviceIDProp> pDevId; pEncoder->QueryInterface(IID_ICC_DeviceIDProp, (void**)&pDevId); if(EncDeviceID >= -1) { if(pDevId) { printf("Encoder has ICC_DeviceIDProp interface.\n"); if(EncDeviceID >= -1) { if(FAILED(hr = pDevId->put_DeviceID(EncDeviceID))) return fprintf(stderr, "Failed to assign DeviceId=%d to the encoder", EncDeviceID), hr; } } else { printf("Encoder has no ICC_DeviceIDProp interface. Using default device (unknown)\n"); } } hr = pEncoder->InitByXml(pProfile); if(FAILED(hr)) return hr; if(EncDeviceID < -1) { if(pDevId) { if(FAILED(hr = pDevId->get_DeviceID(&EncDeviceID))) return fprintf(stderr, "Failed to get DeviceId from the encoder"), hr; } else EncDeviceID = 0; } if(EncDeviceID >= -1) printf("Encoder device id = %d\n", EncDeviceID); CC_AMOUNT concur_level = 0; com_ptr<ICC_ConcurrencyLevelProp> pConcur; if(S_OK == pEncoder->QueryInterface(IID_ICC_ConcurrencyLevelProp, (void**)&pConcur)) { printf("Encoder has ICC_ConcurrencyLevelProp interface.\n"); if(FAILED(hr = pConcur->get_ConcurrencyLevel(&concur_level))) return fprintf(stderr, "Failed to get ConcurrencyLevel from the encoder"), hr; printf("Encoder concurrency level = %d\n", concur_level); } CC_VIDEO_FRAME_DESCR vpar = { cFormat }; printf("Encoder: %s\n", strEncName); printf("Footage: type=%s filename=%s\n", argv[3], argv[4]); printf("Profile: %s\n%s\n", argv[2], profile_text); com_ptr<ICC_VideoStreamInfo> pVideoInfo; if(FAILED(hr = pEncoder->GetVideoStreamInfo(&pVideoInfo))) return fprintf(stderr, "Failed to get video stream info the encoder: code=%08x", hr), hr; CC_SIZE frame_size = {}; pVideoInfo->get_FrameSize(&frame_size); DWORD frame_pitch = 0, dec_frame_pitch = 0; if(FAILED(hr = pEncoder->GetStride(cFormat, &frame_pitch))) return fprintf(stderr, "Failed to get frame pitch from the encoder: code=%08x", hr), hr; if(cOutputFormat == CCF_UNKNOWN) dec_frame_pitch = frame_pitch; else if(FAILED(hr = pEncoder->GetStride(cOutputFormat, &dec_frame_pitch))) return fprintf(stderr, "Failed to get frame pitch for the decoder: code=%08x", hr), hr; //__declspec(align(32)) static BYTE buffer[]; size_t uncompressed_frame_size = size_t(frame_pitch) * frame_size.cy; printf("Frame size: %dx%d, pitch=%d, bytes=%zd\n", frame_size.cx, frame_size.cy, frame_pitch, uncompressed_frame_size); BYTE *read_buffer = (BYTE*)mem_alloc(MEM_SYSTEM, uncompressed_frame_size); if(!read_buffer) return fprintf(stderr, "buffer allocation error for %zd byte(s)", uncompressed_frame_size), E_OUTOFMEMORY; else printf("Compressed buffer address : 0x%p\n", read_buffer); std::vector<BYTE*> source_frames; int max_num_frames_in_loop = 32; for(int i = 0; i < max_num_frames_in_loop; i++) { size_t read_size = fread(read_buffer, 1, uncompressed_frame_size, inpf); if(read_size < uncompressed_frame_size) break; BYTE *buf = (BYTE*)mem_alloc(g_mem_type, uncompressed_frame_size, EncDeviceID); if(!buf) return fprintf(stderr, "buffer allocation error for %zd byte(s)", uncompressed_frame_size), E_OUTOFMEMORY; else printf("Uncompressed buffer address: 0x%p, format: %s, size: %zd byte(s)\n", buf, strInputFormat, uncompressed_frame_size); if(g_mem_type == MEM_GPU) cudaMemcpy(buf, read_buffer, uncompressed_frame_size, cudaMemcpyHostToDevice); else memcpy(buf, read_buffer, uncompressed_frame_size); source_frames.push_back(buf); } C_FileWriter *pFileWriter = new C_FileWriter(outf, true, source_frames.size()); hr = pEncoder->put_OutputCallback(static_cast<ICC_ByteStreamCallback*>(pFileWriter)); if(FAILED(hr)) return hr; com_ptr<ICC_VideoConsumerExtAsync> pEncAsync = 0; pEncoder->QueryInterface(IID_ICC_VideoConsumerExtAsync, (void**)&pEncAsync); CpuLoadMeter cpuLoadMeter; auto t00 = system_clock::now(); int frame_count = 0, total_frame_count = 0; auto t0 = t00; auto coded_size0 = pFileWriter->GetTotalBytesWritten(); g_EncoderTimeFirstFrameIn = t00; printf("Performing encoding loop, press ESC to break\n"); int max_frames = 0x7fffffff; int update_mask = 0x07; for(int frame_no = 0; frame_no < max_frames; frame_no++) { size_t idx = frame_no % (source_frames.size()*2-1); if(idx >= source_frames.size()) idx = source_frames.size()*2 - idx - 1; if(pEncAsync) hr = pEncAsync->AddScaleFrameAsync(source_frames[idx], (DWORD)uncompressed_frame_size, &vpar, pEncAsync); else hr = pEncoder->AddFrame(vpar.cFormat, source_frames[idx], (DWORD)uncompressed_frame_size); if(FAILED(hr)) { pEncoder = NULL; return hr; } if(TargetFps > 0) { auto t1 = system_clock::now(); auto Treal = duration_cast<milliseconds>(t1 - t0).count(); auto Tideal = (int)(frame_count * 1000 / TargetFps); if (Tideal > Treal + 1) std::this_thread::sleep_for(milliseconds{ Tideal - Treal }); } if((frame_count & update_mask) == update_mask) { auto t1 = system_clock::now(); auto dT = duration<double>(t1 - t0).count(); auto coded_size = pFileWriter->GetTotalBytesWritten(); fprintf(stderr, " %d, %.3f fps, in %.3f GB/s, out %.3f Mbps, CPU load: %.1f%% \r", frame_no, frame_count / dT, uncompressed_frame_size / 1E9 * frame_count / dT, (coded_size - coded_size0) * 8 / 1E6 / dT, cpuLoadMeter.GetLoad()); t0 = t1; frame_count = 0; coded_size0 = coded_size; if(dT < 0.5) { update_mask = (update_mask<<1) | 1; } else while(dT > 2 && update_mask > 1) { update_mask = (update_mask>>1) | 1; dT /= 2; } } frame_count++; total_frame_count++; if(_kbhit() && _getch() == 27) break; } hr = pEncoder->Done(CC_TRUE); if(FAILED(hr)) return hr; auto t1 = system_clock::now(); pEncoder = NULL; puts("\nDone.\n"); auto dT = duration<double>(t1 - t00).count(); printf("Average performance = %.3f fps (%.1f ms/f), avg data rate = %.3f GB/s\n", total_frame_count / dT, dT * 1000 / total_frame_count, uncompressed_frame_size / 1E9 * total_frame_count / dT); auto time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(g_EncoderTimeFirstFrameOut - g_EncoderTimeFirstFrameIn); printf("Encoder latency = %d ms\n", (int)time_ms.count()); fclose(inpf); if(outf) fclose(outf); // decoder test ================================================================== fprintf(stderr, "\n------------------------------------------------------------\nEntering decoder test loop...\n"); com_ptr<ICC_VideoDecoder> pDecoder; hr = pFactory->CreateInstance(clsidDec, IID_ICC_VideoDecoder, (IUnknown**)&pDecoder); if(FAILED(hr)) return hr; if(NumThreads > 0) { fprintf(stderr, "Setting up specified number of threads = %d for the decoder: ", NumThreads); com_ptr<ICC_ThreadsCountProp> pTCP; if(FAILED(hr = pEncoder->QueryInterface(IID_ICC_ThreadsCountProp, (void**)&pTCP))) fprintf(stderr, "NAK. No ICC_ThreadsCountProp interface found\n"); else if(FAILED(hr = pTCP->put_ThreadsCount(NumThreads))) return fprintf(stderr, "FAILED\n"), hr; fprintf(stderr, "OK\n"); } if(DecDeviceID < -1 && EncDeviceID >= -1) DecDeviceID = EncDeviceID; if(DecDeviceID >= -1 && S_OK == pDecoder->QueryInterface(IID_ICC_DeviceIDProp, (void**)&pDevId)) { printf("Decoder has ICC_DeviceIDProp interface.\n"); if(FAILED(hr = pDevId->put_DeviceID(DecDeviceID))) return fprintf(stderr, "Failed to assign DeviceId %d to the decoder", DecDeviceID), hr; printf("Decoder device id = %d\n", DecDeviceID); } if(concur_level != 0 && S_OK == pDecoder->QueryInterface(IID_ICC_ConcurrencyLevelProp, (void**)&pConcur)) { printf("Decoder has ICC_ConcurrencyLevelProp interface.\n"); if(FAILED(hr = pConcur->put_ConcurrencyLevel(concur_level))) return fprintf(stderr, "Failed to assign ConcurrencyLevel %d to the decoder", concur_level), hr; } hr = pDecoder->Init(); if(FAILED(hr)) return hr; if(pConcur) { if(FAILED(hr = pConcur->get_ConcurrencyLevel(&concur_level))) return fprintf(stderr, "Failed to get ConcurrencyLevel from the decoder"), hr; printf("Decoder concurrency level = %d\n", concur_level); } if(!bForceGetFrameOnDecode) cFormat = CCF_UNKNOWN; uncompressed_frame_size = size_t(dec_frame_pitch) * frame_size.cy; BYTE *dec_buf = (BYTE*)mem_alloc(g_mem_type, uncompressed_frame_size, DecDeviceID); if(!dec_buf) return fprintf(stderr, "buffer allocation error for %zd byte(s)", uncompressed_frame_size), E_OUTOFMEMORY; else printf("Uncompressed buffer address: 0x%p, format: %s, size: %zd byte(s)\n", dec_buf, strOutputFormat, uncompressed_frame_size); com_ptr<ICC_VideoQualityMeter> pPsnrCalc; if(cOutputFormat == cFormat && g_mem_type != MEM_GPU) { if(FAILED(hr = pFactory->CreateInstance(CLSID_CC_VideoQualityMeter, IID_ICC_VideoQualityMeter, (IUnknown**)&pPsnrCalc))) fprintf(stdout, "Can't create VideoQualityMeter, error=%xh, PSNR calculation is disabled\n", hr); } else { fprintf(stdout, "PSNR calculation is disabled due to %s\n", cOutputFormat != cFormat ? "color format mismatch" : "GPU memory"); } hr = pDecoder->put_OutputCallback(new C_DummyWriter(cOutputFormat, dec_buf, (int)uncompressed_frame_size, pPsnrCalc, source_frames[0])); if(FAILED(hr)) return hr; com_ptr<ICC_ProcessDataPolicyProp> pPDP; if(SUCCEEDED(pDecoder->QueryInterface(IID_ICC_ProcessDataPolicyProp, (void**)&pPDP))) pPDP->put_ProcessDataPolicy(CC_PDP_PARSED_DATA); com_ptr<ICC_DanielVideoDecoder_CUDA> pCudaDec; if(SUCCEEDED(pDecoder->QueryInterface(IID_ICC_DanielVideoDecoder_CUDA, (void**)&pCudaDec))) pCudaDec->put_TargetColorFormat(cOutputFormat); t00 = t0 = system_clock::now(); g_DecoderTimeFirstFrameIn = t00; frame_count = total_frame_count = 0; printf("Performing decoding loop, press ESC to break\n"); printf("coded sequence length = %zd\n", pFileWriter->GetCodedSequenceLength()); for(int i = 0; i < pFileWriter->GetCodedSequenceLength(); i++) printf(" %zd", pFileWriter->GetCodedFrame(i).second); puts(""); update_mask = 0x07; int key_pressed = 0; int warm_up_frames = 4; coded_size0 = 0; long long coded_size = 0; if(int num_coded_frames = (int)pFileWriter->GetCodedSequenceLength()) for(int frame_no = 0; frame_no < max_frames; frame_no++) { auto codedFrame = pFileWriter->GetCodedFrame(frame_no % num_coded_frames); hr = pDecoder->ProcessData(codedFrame.first, (DWORD)codedFrame.second); if(FAILED(hr)) { pDecoder = NULL; return hr; } coded_size += codedFrame.second; if(TargetFps > 0) { auto t1 = system_clock::now(); auto Treal = duration_cast<milliseconds>(t1 - t0).count(); auto Tideal = (int)(frame_count * 1000 / TargetFps); if(Tideal > Treal + 1) std::this_thread::sleep_for(milliseconds{Tideal - Treal}); } if(warm_up_frames > 0) { if(--warm_up_frames > 0) continue; t00 = t0 = system_clock::now(); } if((frame_count & update_mask) == update_mask) { auto t1 = system_clock::now(); auto dT = duration<double>(t1 - t0).count(); if(dT < 0.5) update_mask = (update_mask<<1) | 1; else if(dT > 2) update_mask = (update_mask>>1) | 1; fprintf(stderr, " %d, %.3f fps, in %.3f Mbps, out %.3f GB/s, CPU load: %.1f%% \r", frame_no, frame_count / dT, (coded_size - coded_size0) * 8 / 1E6 / dT, uncompressed_frame_size / 1E9 * frame_count / dT, cpuLoadMeter.GetLoad()); t0 = t1; coded_size0 = coded_size; frame_count = 0; } frame_count++; total_frame_count++; if(_kbhit() && _getch() == 27) break; } hr = pDecoder->Done(CC_TRUE); if(FAILED(hr)) return hr; t1 = system_clock::now(); pDecoder = NULL; puts("\nDone.\n"); dT = duration<double>(t1 - t00).count(); printf("Average performance = %.3f fps (%.1f ms/f), avg data rate = %.3f GB/s\n", total_frame_count / dT, dT * 1000 / total_frame_count, uncompressed_frame_size / 1E9 * total_frame_count / dT); time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(g_DecoderTimeFirstFrameOut - g_DecoderTimeFirstFrameIn); printf("Decoder latency = %d ms\n", (int)time_ms.count()); return 0; }
30.932996
166
0.65506
Cinegy
c57320827df3d63551e6259d6cedb1a413afc4c6
71
cpp
C++
test/data/pkg_config_use/program.cpp
thomasrockhu/bfg9000
1cd1226eab9bed2fc2ec6acccf7864fdcf2ed31a
[ "BSD-3-Clause" ]
72
2015-06-23T02:35:13.000Z
2021-12-08T01:47:40.000Z
test/data/pkg_config_use/program.cpp
thomasrockhu/bfg9000
1cd1226eab9bed2fc2ec6acccf7864fdcf2ed31a
[ "BSD-3-Clause" ]
139
2015-03-01T18:48:17.000Z
2021-06-18T15:45:14.000Z
test/data/pkg_config_use/program.cpp
thomasrockhu/bfg9000
1cd1226eab9bed2fc2ec6acccf7864fdcf2ed31a
[ "BSD-3-Clause" ]
19
2015-12-23T21:24:33.000Z
2022-01-06T04:04:41.000Z
#include <hello.hpp> int main() { hello::say_hello(); return 0; }
10.142857
21
0.605634
thomasrockhu
c57601efe76fd07101ca62475a552334f32818e2
1,774
cpp
C++
tests/memRdRspFunc/src_pers/PersF2_src.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
13
2015-02-26T22:46:18.000Z
2020-03-24T11:53:06.000Z
tests/memRdRspFunc/src_pers/PersF2_src.cpp
PacificBiosciences/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
5
2016-02-25T17:08:19.000Z
2018-01-20T15:24:36.000Z
tests/memRdRspFunc/src_pers/PersF2_src.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
12
2015-04-13T21:39:54.000Z
2021-01-15T01:00:13.000Z
#include "Ht.h" #include "PersF2.h" void CPersF2::PersF2() { if (PR1_htValid) { switch (PR1_htInst) { case F2_ENTRY: { if (ReadMemBusy()) { HtRetry(); break; } S_rslt64 = 0; ReadMem_func64(PR1_addr, 0x15, 256); ReadMemPause(F2_RD32); break; } case F2_RD32: { if (ReadMemBusy()) { HtRetry(); break; } HtAssert(SR_rslt64 == 9574400, 0); S_rslt32 = 0; ReadMem_func32(PR1_addr + 256 * 8, 0x75, 64); ReadMemPause(F2_RD16); break; } case F2_RD16: { if (ReadMemBusy()) { HtRetry(); break; } HtAssert(SR_rslt32 == 341376, 0); ReadMem_func16(PR1_addr, 0x9); ReadMemPause(F2_RD64DLY); break; } case F2_RD64DLY: { if (ReadMemBusy()) { HtRetry(); break; } S_rslt64Dly = 0; ReadMem_func64Dly(PR1_addr, 0x19, 32); ReadMemPause(F2_RETURN); break; } case F2_RETURN: { if (SendReturnBusy_f2()) { HtRetry(); break; } HtAssert(SR_rslt64Dly == 71424, 0); SendReturn_f2(); break; } default: assert(0); } } T1_rdRspData = 0; S_rslt64Dly += T11_rdRspData; } void CPersF2::ReadMemResp_func64(ht_uint8 rdRspElemIdx, ht_uint5 ht_noload rdRspInfo, uint64_t rdRspData) { S_rslt64 += (uint64_t)(rdRspData * rdRspElemIdx); } void CPersF2::ReadMemResp_func32(ht_uint6 rdRspElemIdx, ht_uint7 ht_noload rdRspInfo, uint32_t rdRspData) { S_rslt32 += (uint32_t)(rdRspData * rdRspElemIdx); } void CPersF2::ReadMemResp_func16(ht_uint4 ht_noload rdRspInfo, int16_t ht_noload rdRspData) { HtAssert(rdRspData == 123, 0); HtAssert(rdRspInfo == 9, 0); } void CPersF2::ReadMemResp_func64Dly(ht_uint5 rdRspElemIdx, ht_uint5 ht_noload rdRspInfo, uint64_t rdRspData) { T1_rdRspData = (uint64_t)(rdRspData * rdRspElemIdx); }
16.735849
108
0.658399
TonyBrewer
c578dba7f0a93edf0400edcf89b7997f87186002
4,691
cpp
C++
src/core/ATN.cpp
satoshigeyuki/Centaurus
032ffec87fc8ddb129347974d3478fd1ee5f305a
[ "MIT" ]
3
2021-02-23T01:34:28.000Z
2021-07-19T08:07:10.000Z
src/core/ATN.cpp
satoshigeyuki/Centaurus
032ffec87fc8ddb129347974d3478fd1ee5f305a
[ "MIT" ]
null
null
null
src/core/ATN.cpp
satoshigeyuki/Centaurus
032ffec87fc8ddb129347974d3478fd1ee5f305a
[ "MIT" ]
null
null
null
#include "ATN.hpp" namespace Centaurus { template<typename TCHAR> void ATNNode<TCHAR>::parse_literal(Stream& stream) { wchar_t leader = stream.get(); wchar_t ch = stream.get(); for (; ch != L'\0' && ch != leader; ch = stream.get()) { m_literal.push_back(wide_to_target<TCHAR>(ch)); } if (leader != ch) throw stream.unexpected(ch); } template<typename TCHAR> void ATNNode<TCHAR>::parse(Stream& stream) { wchar_t ch = stream.peek(); if (Identifier::is_symbol_leader(ch)) { m_invoke.parse(stream); m_type = ATNNodeType::Nonterminal; } else if (ch == L'/') { stream.discard(); m_nfa.parse(stream); m_type = ATNNodeType::RegularTerminal; } else if (ch == L'\'' || ch == L'"') { parse_literal(stream); m_type = ATNNodeType::LiteralTerminal; } else { throw stream.unexpected(ch); } ch = stream.skip_whitespace(); if (ch == L'{') { stream.discard(); ch = stream.skip_whitespace(); if (ch == L'}') throw stream.unexpected(ch); int id = 0; for (; L'0' <= ch && ch <= L'9'; ch = stream.peek()) { id = id * 10 + static_cast<int>(ch - L'0'); stream.discard(); } ch = stream.skip_whitespace(); if (ch != L'}') throw stream.unexpected(ch); stream.discard(); stream.skip_whitespace(); m_localid = id; } } template<typename TCHAR> void ATNMachine<TCHAR>::parse_atom(Stream& stream) { int origin_state = m_nodes.size() - 1; wchar_t ch = stream.skip_whitespace(); int anchor_state = m_nodes.size(); if (ch == L'(') { stream.discard(); parse_selection(stream); ch = stream.skip_whitespace(); if (ch != L')') throw stream.unexpected(ch); stream.discard(); } else { ATNNode<TCHAR> node(stream); if (m_globalid > 0 && (node.type() == ATNNodeType::LiteralTerminal || node.type() == ATNNodeType::RegularTerminal)) { m_nodes.back().add_transition(m_nodes.size()); m_nodes.emplace_back(ATNNodeType::WhiteSpace); } m_nodes.back().add_transition(m_nodes.size()); m_nodes.push_back(node); } ch = stream.skip_whitespace(); switch (ch) { case L'*': add_node(m_nodes.size() - 1); m_nodes.back().add_transition(anchor_state); add_node(m_nodes.size() - 1); m_nodes[origin_state].add_transition(m_nodes.size() - 1); stream.discard(); break; case L'+': add_node(m_nodes.size() - 1); m_nodes.back().add_transition(anchor_state); stream.discard(); break; case L'?': add_node(m_nodes.size() - 1); m_nodes[origin_state].add_transition(m_nodes.size() - 1); stream.discard(); break; } } template<typename TCHAR> void ATNMachine<TCHAR>::parse_selection(Stream& stream) { add_node(m_nodes.size() - 1); int priority = 0; int origin_state = m_nodes.size() - 1; std::vector<int> terminal_states; for (;;) { terminal_states.push_back(add_node(origin_state, priority)); parse_sequence(stream); terminal_states.back() = m_nodes.size() - 1; wchar_t ch = stream.skip_whitespace(); if (ch == L';' || ch == L')') { break; } else if (ch == L'|') { stream.discard(); ch = stream.peek(); if (ch == L'>') { stream.discard(); priority++; } continue; } else { throw stream.unexpected(ch); } } m_nodes.emplace_back(); int final_node = m_nodes.size() - 1; for (int from : terminal_states) { m_nodes[from].add_transition(final_node); } } template<typename TCHAR> void ATNMachine<TCHAR>::parse_sequence(Stream& stream) { while (true) { wchar_t ch = stream.skip_whitespace(); if (ch == L'|' || ch == L')' || ch == L';') return; parse_atom(stream); } } template<typename TCHAR> void ATNMachine<TCHAR>::parse(Stream& stream) { wchar_t ch = stream.skip_whitespace(); if (ch != L':') throw stream.unexpected(ch); stream.discard(); m_nodes.emplace_back(); parse_selection(stream); ch = stream.skip_whitespace(); if (ch != L';') throw stream.unexpected(ch); stream.discard(); } template<typename TCHAR> bool ATNMachine<TCHAR>::verify_invocations(const std::unordered_map<Identifier, ATNMachine<TCHAR> >& network) const { for (const auto& node : m_nodes) { if (node.type() == ATNNodeType::Nonterminal) { if (network.find(node.get_invoke()) == network.cend()) { return false; } } } return true; } template class ATNMachine<char>; template class ATNMachine<unsigned char>; template class ATNMachine<wchar_t>; }
20.307359
123
0.600938
satoshigeyuki
c57ba4261852f02d3a759d4c8041348a8c49c2a4
390
cpp
C++
components/math/vecmath/tests/utility_quat_to_matrix.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/math/vecmath/tests/utility_quat_to_matrix.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/math/vecmath/tests/utility_quat_to_matrix.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include "shared.h" int main () { printf ("Results of utility_quat_to_matrix_test:\n"); quatf q = to_quat (degree (90.0f), vec3f (0, 0, 1)); dump ("q", q); dump ("to_matrix (q)", to_matrix (q)); mat3f m1; mat4f m2; to_matrix (q, m1); to_matrix (q, m2); dump ("to_matrix (q, m1)", m1); dump ("to_matrix (q, m2)", m2); return 0; }
16.956522
56
0.528205
untgames
c58141e88dc23d1837083adc556f132d7fe48867
901
cc
C++
base/loader/test/gtfs/transfers_test.cc
hockbene/motis
cd6f7b14a4186f4cd6d3082b0af1219b2a59dfb9
[ "MIT" ]
60
2020-04-27T14:06:11.000Z
2022-03-22T14:33:01.000Z
base/loader/test/gtfs/transfers_test.cc
CanThoma/motis
d3e7ae3214110f008fedeef6e90a72adf47fc3a3
[ "MIT" ]
59
2020-04-27T21:12:22.000Z
2022-03-30T09:28:58.000Z
base/loader/test/gtfs/transfers_test.cc
CanThoma/motis
d3e7ae3214110f008fedeef6e90a72adf47fc3a3
[ "MIT" ]
28
2020-05-18T15:47:51.000Z
2022-01-19T17:16:33.000Z
#include "gtest/gtest.h" #include "motis/loader/gtfs/files.h" #include "motis/loader/gtfs/transfers.h" #include "./resources.h" using namespace utl; using namespace motis::loader; using namespace motis::loader::gtfs; stop_pair t(stop_map const& stops, std::string const& s1, std::string const& s2) { return std::make_pair(stops.at(s1).get(), // stops.at(s2).get()); } TEST(loader_gtfs_transfer, read_transfers_example_data) { auto stops = read_stops(loaded_file{SCHEDULES / "example" / STOPS_FILE}); auto transfers = read_transfers( loaded_file{SCHEDULES / "example" / TRANSFERS_FILE}, stops); EXPECT_EQ(2, transfers.size()); EXPECT_EQ(5, transfers[t(stops, "S6", "S7")].minutes_); EXPECT_EQ(transfer::MIN_TRANSFER_TIME, transfers[t(stops, "S6", "S7")].type_); EXPECT_EQ(transfer::NOT_POSSIBLE, transfers[t(stops, "S7", "S6")].type_); }
31.068966
80
0.687014
hockbene
c5837d6982872fcc793d1599fc5d9d5acbddd2ef
27,057
cpp
C++
src/stage/batched/host/KokkosKernels_Test_Trsm.cpp
crtrott/kokkos-kernels
0dba50f62188eb82da35bb4fe0211c7783300903
[ "BSD-3-Clause" ]
null
null
null
src/stage/batched/host/KokkosKernels_Test_Trsm.cpp
crtrott/kokkos-kernels
0dba50f62188eb82da35bb4fe0211c7783300903
[ "BSD-3-Clause" ]
null
null
null
src/stage/batched/host/KokkosKernels_Test_Trsm.cpp
crtrott/kokkos-kernels
0dba50f62188eb82da35bb4fe0211c7783300903
[ "BSD-3-Clause" ]
null
null
null
/// \author Kyungjoo Kim (kyukim@sandia.gov) #include <iomanip> #if defined(__KOKKOSKERNELS_INTEL_MKL__) #include "mkl.h" #endif #include "Kokkos_Core.hpp" #include "impl/Kokkos_Timer.hpp" #include "KokkosKernels_Vector.hpp" #include "KokkosKernels_Trsm_Serial_Decl.hpp" #include "KokkosKernels_Trsm_Serial_Impl.hpp" namespace KokkosKernels { namespace Test { #define FLOP_MUL 1.0 #define FLOP_ADD 1.0 double FlopCountLower(int mm, int nn) { double m = (double)mm; double n = (double)nn; return (FLOP_MUL*(0.5*m*n*(n+1.0)) + FLOP_ADD*(0.5*m*n*(n-1.0))); } double FlopCountUpper(int mm, int nn) { double m = (double)mm; double n = (double)nn; return (FLOP_MUL*(0.5*m*n*(n+1.0)) + FLOP_ADD*(0.5*m*n*(n-1.0))); } template<int test, int BlkSize, int NumCols, typename DeviceSpaceType, typename VectorTagType, typename AlgoTagType> void Trsm(const int N) { typedef Kokkos::Schedule<Kokkos::Static> ScheduleType; //typedef Kokkos::Schedule<Kokkos::Dynamic> ScheduleType; switch (test) { case 0: std::cout << "TestID = Left, Lower, NoTrans, UnitDiag\n"; break; case 1: std::cout << "TestID = Left, Lower, NoTrans, NonUnitDiag\n"; break; case 2: std::cout << "TestID = Right, Upper, NoTrans, UnitDiag\n"; break; case 3: std::cout << "TestID = Right, Upper, NoTrans, NonUnitDiag\n"; break; case 4: std::cout << "TestID = Left, Upper, NoTrans, NonUnitDiag\n"; break; } //constexpr int N = 100; typedef typename VectorTagType::value_type ValueType; constexpr int VectorLength = VectorTagType::length; // when m == n, lower upper does not matter (unit and nonunit) double flop = 0; switch (test) { case 0: case 1: flop = FlopCountLower(BlkSize,NumCols); break; case 2: case 3: case 4: flop = FlopCountUpper(BlkSize,NumCols); break; } flop *= (N*VectorLength); const double tmax = 1.0e15; typedef typename Kokkos::Impl::is_space<DeviceSpaceType>::host_mirror_space::execution_space HostSpaceType ; const int iter_begin = -10, iter_end = 100; Kokkos::Impl::Timer timer; /// /// Reference version using MKL DTRSM /// Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> bref; Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> amat("amat", N*VectorLength, BlkSize, BlkSize), bmat("bmat", N*VectorLength, BlkSize, NumCols); Random random; for (int k=0;k<N*VectorLength;++k) { for (int i=0;i<BlkSize;++i) for (int j=0;j<BlkSize;++j) amat(k, i, j) = random.value() + 4.0*(i==j); for (int i=0;i<BlkSize;++i) for (int j=0;j<NumCols;++j) bmat(k, i, j) = random.value(); } typedef Vector<VectorTagType> VectorType; Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType> amat_simd("amat_simd", N, BlkSize, BlkSize), bmat_simd("bmat_simd", N, BlkSize, NumCols); for (int k0=0;k0<N;++k0) for (int k1=0;k1<VectorLength;++k1) { for (int i=0;i<BlkSize;++i) for (int j=0;j<BlkSize;++j) amat_simd(k0, i, j)[k1] = amat(k0*VectorLength+k1, i, j); for (int i=0;i<BlkSize;++i) for (int j=0;j<NumCols;++j) bmat_simd(k0, i, j)[k1] = bmat(k0*VectorLength+k1, i, j); } // for KNL constexpr size_t LLC_CAPACITY = 34*1024*1024; Flush<LLC_CAPACITY> flush; /// /// Reference version using MKL DTRSM /// #if defined(__KOKKOSKERNELS_INTEL_MKL__) { Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> a("a", N*VectorLength, BlkSize, BlkSize), b("b", N*VectorLength, BlkSize, NumCols); { double tavg = 0, tmin = tmax; for (int iter=iter_begin;iter<iter_end;++iter) { // flush flush.run(); // initialize matrices Kokkos::deep_copy(a, amat); Kokkos::deep_copy(b, bmat); DeviceSpaceType::fence(); timer.reset(); Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N*VectorLength); Kokkos::parallel_for (policy, KOKKOS_LAMBDA(const int k) { auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL()); auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL()); switch (test) { case 0: cblas_dtrsm(CblasRowMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit, BlkSize, NumCols, 1.0, (double*)aa.data(), aa.stride_0(), (double*)bb.data(), bb.stride_0()); break; case 1: cblas_dtrsm(CblasRowMajor, CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit, BlkSize, NumCols, 1.0, (double*)aa.data(), aa.stride_0(), (double*)bb.data(), bb.stride_0()); break; case 2: cblas_dtrsm(CblasRowMajor, CblasRight, CblasUpper, CblasNoTrans, CblasUnit, BlkSize, NumCols, 1.0, (double*)aa.data(), aa.stride_0(), (double*)bb.data(), bb.stride_0()); break; case 3: cblas_dtrsm(CblasRowMajor, CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, BlkSize, NumCols, 1.0, (double*)aa.data(), aa.stride_0(), (double*)bb.data(), bb.stride_0()); break; case 4: cblas_dtrsm(CblasRowMajor, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, BlkSize, NumCols, 1.0, (double*)aa.data(), aa.stride_0(), (double*)bb.data(), bb.stride_0()); break; } }); DeviceSpaceType::fence(); const double t = timer.seconds(); tmin = std::min(tmin, t); tavg += (iter >= 0)*t; } tavg /= iter_end; double sum = 0; for (int i=0;i<b.dimension(0);++i) for (int j=0;j<b.dimension(1);++j) for (int k=0;k<b.dimension(2);++k) sum += std::abs(bmat(i,j,k)); std::cout << std::setw(10) << "MKL TRSM" << " BlkSize = " << std::setw(3) << BlkSize << " NumCols = " << std::setw(3) << NumCols << " time = " << std::scientific << tmin << " avg flop/s = " << (flop/tavg) << " max flop/s = " << (flop/tmin) << " sum abs(B) = " << sum << std::endl; bref = b; } } #if defined(__KOKKOSKERNELS_INTEL_MKL_BATCHED__) { Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> a("a", N*VectorLength, BlkSize, BlkSize), b("b", N*VectorLength, BlkSize, NumCols); ValueType *aa[N*VectorLength], *bb[N*VectorLength]; for (int k=0;k<N*VectorLength;++k) { aa[k] = &a(k, 0, 0); bb[k] = &b(k, 0, 0); } { double tavg = 0, tmin = tmax; MKL_INT blksize[1] = { BlkSize }; MKL_INT numcols[1] = { NumCols }; MKL_INT lda[1] = { a.stride_1() }; MKL_INT ldb[1] = { b.stride_1() }; double one[1] = { 1.0 }; MKL_INT size_per_grp[1] = { N*VectorLength }; for (int iter=iter_begin;iter<iter_end;++iter) { // flush flush.run(); // initialize matrices Kokkos::deep_copy(a, amat); Kokkos::deep_copy(b, bmat); DeviceSpaceType::fence(); timer.reset(); switch (test) { case 0: { CBLAS_SIDE side[1] = {CblasLeft}; CBLAS_UPLO uplo[1] = {CblasLower}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasUnit}; cblas_dtrsm_batch(CblasRowMajor, side, uplo, transA, diag, blksize, numcols, one, (const double**)aa, lda, (double**)bb, ldb, 1, size_per_grp); break; } case 1: { CBLAS_SIDE side[1] = {CblasLeft}; CBLAS_UPLO uplo[1] = {CblasLower}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasNonUnit}; cblas_dtrsm_batch(CblasRowMajor, side, uplo, transA, diag, blksize, numcols, one, (const double**)aa, lda, (double**)bb, ldb, 1, size_per_grp); break; } case 2: { CBLAS_SIDE side[1] = {CblasRight}; CBLAS_UPLO uplo[1] = {CblasUpper}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasUnit}; cblas_dtrsm_batch(CblasRowMajor, side, uplo, transA, diag, blksize, numcols, one, (const double**)aa, lda, (double**)bb, ldb, 1, size_per_grp); break; } case 3: { CBLAS_SIDE side[1] = {CblasRight}; CBLAS_UPLO uplo[1] = {CblasUpper}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasNonUnit}; cblas_dtrsm_batch(CblasRowMajor, side, uplo, transA, diag, blksize, numcols, one, (const double**)aa, lda, (double**)bb, ldb, 1, size_per_grp); break; } case 4: { CBLAS_SIDE side[1] = {CblasLeft}; CBLAS_UPLO uplo[1] = {CblasUpper}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasNonUnit}; cblas_dtrsm_batch(CblasRowMajor, side, uplo, transA, diag, blksize, numcols, one, (const double**)aa, lda, (double**)bb, ldb, 1, size_per_grp); break; } } DeviceSpaceType::fence(); const double t = timer.seconds(); tmin = std::min(tmin, t); tavg += (iter >= 0)*t; } tavg /= iter_end; double diff = 0; for (int i=0;i<bref.dimension(0);++i) for (int j=0;j<bref.dimension(1);++j) for (int k=0;k<bref.dimension(2);++k) diff += std::abs(bref(i,j,k) - b(i,j,k)); std::cout << std::setw(10) << "MKL Batch" << " BlkSize = " << std::setw(3) << BlkSize << " NumCols = " << std::setw(3) << NumCols << " time = " << std::scientific << tmin << " avg flop/s = " << (flop/tavg) << " max flop/s = " << (flop/tmin) << " diff to ref = " << diff << std::endl; } } #endif #if defined(__KOKKOSKERNELS_INTEL_MKL_COMPACT_BATCHED__) { Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType> a("a", N, BlkSize, BlkSize), b("b", N, BlkSize, NumCols); { double tavg = 0, tmin = tmax; MKL_INT blksize[1] = { BlkSize }; MKL_INT numcols[1] = { NumCols }; MKL_INT lda[1] = { a.stride_1() }; MKL_INT ldb[1] = { b.stride_1() }; double one[1] = { 1.0 }; MKL_INT size_per_grp[1] = { N*VectorLength }; compact_t A_p, B_p; A_p.layout = CblasRowMajor; A_p.rows = blksize; A_p.cols = blksize; A_p.stride = lda; A_p.group_count = 1; A_p.size_per_group = size_per_grp; A_p.format = VectorLength; A_p.mat = (double*)a.data(); B_p.layout = CblasRowMajor; B_p.rows = blksize; B_p.cols = numcols; B_p.stride = ldb; B_p.group_count = 1; B_p.size_per_group = size_per_grp; B_p.format = VectorLength; B_p.mat = (double*)b.data(); for (int iter=iter_begin;iter<iter_end;++iter) { // flush flush.run(); // initialize matrices Kokkos::deep_copy(a, amat_simd); Kokkos::deep_copy(b, bmat_simd); DeviceSpaceType::fence(); timer.reset(); switch (test) { case 0: { CBLAS_SIDE side[1] = {CblasLeft}; CBLAS_UPLO uplo[1] = {CblasLower}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasUnit}; cblas_dtrsm_compute_batch(side, uplo, transA, diag, one, &A_p, &B_p); break; } case 1: { CBLAS_SIDE side[1] = {CblasLeft}; CBLAS_UPLO uplo[1] = {CblasLower}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasNonUnit}; cblas_dtrsm_compute_batch(side, uplo, transA, diag, one, &A_p, &B_p); break; } case 2: { CBLAS_SIDE side[1] = {CblasRight}; CBLAS_UPLO uplo[1] = {CblasUpper}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasUnit}; cblas_dtrsm_compute_batch(side, uplo, transA, diag, one, &A_p, &B_p); break; } case 3: { CBLAS_SIDE side[1] = {CblasRight}; CBLAS_UPLO uplo[1] = {CblasUpper}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasNonUnit}; cblas_dtrsm_compute_batch(side, uplo, transA, diag, one, &A_p, &B_p); break; } case 4: { CBLAS_SIDE side[1] = {CblasLeft}; CBLAS_UPLO uplo[1] = {CblasUpper}; CBLAS_TRANSPOSE transA[1] = {CblasNoTrans}; CBLAS_DIAG diag[1] = {CblasNonUnit}; cblas_dtrsm_compute_batch(side, uplo, transA, diag, one, &A_p, &B_p); break; } } DeviceSpaceType::fence(); const double t = timer.seconds(); tmin = std::min(tmin, t); tavg += (iter >= 0)*t; } tavg /= iter_end; double diff = 0; for (int i=0;i<bref.dimension(0);++i) for (int j=0;j<bref.dimension(1);++j) for (int k=0;k<bref.dimension(2);++k) diff += std::abs(bref(i,j,k) - b(i/VectorLength,j,k)[i%VectorLength]); std::cout << std::setw(10) << "MKL Cmpt" << " BlkSize = " << std::setw(3) << BlkSize << " NumCols = " << std::setw(3) << NumCols << " time = " << std::scientific << tmin << " avg flop/s = " << (flop/tavg) << " max flop/s = " << (flop/tmin) << " diff to ref = " << diff << std::endl; } } #endif #endif // /// // /// Plain version (comparable to micro BLAS version) // /// // { // Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> // a("a", N*VectorLength, BlkSize, BlkSize), // b("b", N*VectorLength, BlkSize, NumCols); // { // double tavg = 0, tmin = tmax; // for (int iter=iter_begin;iter<iter_end;++iter) { // // flush // flush.run(); // // initialize matrices // Kokkos::deep_copy(a, amat); // Kokkos::deep_copy(b, bmat); // DeviceSpaceType::fence(); // timer.reset(); // Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N*VectorLength); // Kokkos::parallel_for // (policy, // KOKKOS_LAMBDA(const int k) { // auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL()); // auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL()); // switch (test) { // case 0: // Serial::Trsm<Side::Left,Uplo::Lower,Trans::NoTranspose,Diag::Unit,AlgoTagType>:: // invoke(1.0, aa, bb); // break; // case 1: // Serial::Trsm<Side::Left,Uplo::Lower,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>:: // invoke(1.0, aa, bb); // break; // case 2: // Serial::Trsm<Side::Right,Uplo::Upper,Trans::NoTranspose,Diag::Unit,AlgoTagType>:: // invoke(1.0, aa, bb); // break; // case 3: // Serial::Trsm<Side::Right,Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>:: // invoke(1.0, aa, bb); // break; // case 4: // Serial::Trsm<Side::Left,Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>:: // invoke(1.0, aa, bb); // break; // } // }); // DeviceSpaceType::fence(); // const double t = timer.seconds(); // tmin = std::min(tmin, t); // tavg += (iter >= 0)*t; // } // tavg /= iter_end; // double diff = 0; // for (int i=0;i<bref.dimension(0);++i) // for (int j=0;j<bref.dimension(1);++j) // for (int k=0;k<bref.dimension(2);++k) // diff += std::abs(bref(i,j,k) - b(i,j,k)); // std::cout << std::setw(10) << "Plain" // << " BlkSize = " << std::setw(3) << BlkSize // << " NumCols = " << std::setw(3) << NumCols // << " time = " << std::scientific << tmin // << " avg flop/s = " << (flop/tavg) // << " max flop/s = " << (flop/tmin) // << " diff to ref = " << diff // << std::endl; // } // } /// /// SIMD with appropriate data layout /// { typedef Vector<VectorTagType> VectorType; Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType> a("a", N, BlkSize, BlkSize), b("b", N, BlkSize, NumCols); { double tavg = 0, tmin = tmax; for (int iter=iter_begin;iter<iter_end;++iter) { // flush flush.run(); // initialize matrices Kokkos::deep_copy(a, amat_simd); Kokkos::deep_copy(b, bmat_simd); DeviceSpaceType::fence(); timer.reset(); Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N); Kokkos::parallel_for (policy, KOKKOS_LAMBDA(const int k) { auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL()); auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL()); switch (test) { case 0: Serial::Trsm<Side::Left,Uplo::Lower,Trans::NoTranspose,Diag::Unit,AlgoTagType>:: invoke(1.0, aa, bb); break; case 1: Serial::Trsm<Side::Left,Uplo::Lower,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>:: invoke(1.0, aa, bb); break; case 2: Serial::Trsm<Side::Right,Uplo::Upper,Trans::NoTranspose,Diag::Unit,AlgoTagType>:: invoke(1.0, aa, bb); break; case 3: Serial::Trsm<Side::Right,Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>:: invoke(1.0, aa, bb); break; case 4: Serial::Trsm<Side::Left,Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>:: invoke(1.0, aa, bb); break; } }); DeviceSpaceType::fence(); const double t = timer.seconds(); tmin = std::min(tmin, t); tavg += (iter >= 0)*t; } tavg /= iter_end; double diff = 0; for (int i=0;i<bref.dimension(0);++i) for (int j=0;j<bref.dimension(1);++j) for (int k=0;k<bref.dimension(2);++k) diff += std::abs(bref(i,j,k) - b(i/VectorLength,j,k)[i%VectorLength]); std::cout << std::setw(10) << "SIMD" << " BlkSize = " << std::setw(3) << BlkSize << " NumCols = " << std::setw(3) << NumCols << " time = " << std::scientific << tmin << " avg flop/s = " << (flop/tavg) << " max flop/s = " << (flop/tmin) << " diff to ref = " << diff << std::endl; } } std::cout << "\n\n"; } } } using namespace KokkosKernels; template<typename VectorType, typename AlgoTagType> void run(const int N) { typedef Kokkos::OpenMP ExecSpace; std::cout << "ExecSpace:: "; if (std::is_same<ExecSpace,Kokkos::Serial>::value) std::cout << "Kokkos::Serial " << std::endl; else ExecSpace::print_configuration(std::cout, false); std::cout << "\n\n Used for Factorization \n\n"; /// Left, Lower, NoTrans, UnitDiag (used in LU factorization and LU solve) Test::Trsm<0, 3, 3, ExecSpace,VectorType,AlgoTagType>(N); Test::Trsm<0, 5, 5, ExecSpace,VectorType,AlgoTagType>(N); Test::Trsm<0,10,10, ExecSpace,VectorType,AlgoTagType>(N); Test::Trsm<0,15,15, ExecSpace,VectorType,AlgoTagType>(N); // /// Left, Lower, NoTrans, NonUnitDiag // Test::Trsm<1, 3, 3, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<1, 5, 5, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<1,10,10, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<1,15,15, ExecSpace,VectorType,AlgoTagType>(N); // /// Right, Upper, NoTrans, UnitDiag // Test::Trsm<2, 3, 3, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<2, 5, 5, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<2,10,10, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<2,15,15, ExecSpace,VectorType,AlgoTagType>(N); // /// Right, Upper, NoTrans, NonUnitDiag (used in LU factorization) // Test::Trsm<3, 3, 3, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<3, 5, 5, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<3,10,10, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<3,15,15, ExecSpace,VectorType,AlgoTagType>(N); // std::cout << "\n\n Used for Solve \n\n"; // /// Left, Lower, NoTrans, UnitDiag (used in LU solve) // Test::Trsm<0, 5, 1, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<0, 9, 1, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<0,15, 1, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<0,20, 1, ExecSpace,VectorType,AlgoTagType>(N); // /// Left, Upper, Notrans, NonUnitDiag (user in LU solve) // Test::Trsm<4, 5, 1, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<4, 9, 1, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<4,15, 1, ExecSpace,VectorType,AlgoTagType>(N); // Test::Trsm<4,20, 1, ExecSpace,VectorType,AlgoTagType>(N); } int main(int argc, char *argv[]) { Kokkos::initialize(argc, argv); int N = 128*128; for (int i=1;i<argc;++i) { const std::string& token = argv[i]; if (token == std::string("-N")) N = std::atoi(argv[++i]); } #if defined(__AVX512F__) constexpr int VectorLength = 8; #elif defined(__AVX2__) || defined(__AVX__) constexpr int VectorLength = 4; #else static_assert(false, "AVX is not supported"); #endif { std::cout << " N = " << N << std::endl; // std::cout << "\n Testing SIMD-" << VectorLength << " and Algo::Trsm::Unblocked\n"; // run<VectorTag<SIMD<double>,VectorLength>,Algo::Trsm::Unblocked>(N/VectorLength); // std::cout << "\n Testing AVX-" << VectorLength << " and Algo::Trsm::Unblocked\n"; // run<VectorTag<AVX<double>,VectorLength>,Algo::Trsm::Unblocked>(N/VectorLength); // std::cout << "\n Testing SIMD-" << VectorLength << " and Algo::Trsm::Blocked\n"; // run<VectorTag<SIMD<double>,VectorLength>,Algo::Trsm::Blocked>(N/VectorLength); std::cout << "\n Testing AVX-" << VectorLength << " and Algo::Trsm::Blocked\n"; run<VectorTag<AVX<double>,VectorLength>,Algo::Trsm::Blocked>(N/VectorLength); // std::cout << "\n Testing AVX-" << VectorLength << " and Algo::Trsm::CompactMKL\n"; // run<VectorTag<AVX<double>,VectorLength>,Algo::Trsm::CompactMKL>(N/VectorLength); } Kokkos::finalize(); return 0; }
36.076
120
0.465684
crtrott
c58ad934d4ed6e4fb6e24e1d071af8e48ba586bf
126
hpp
C++
motor-control-firmware/src/uavcan/Torque_handler.hpp
greck2908/robot-software
2e1e8177148a089e8883967375dde7f8ed3d878b
[ "MIT" ]
40
2016-10-04T19:59:22.000Z
2020-12-25T18:11:35.000Z
motor-control-firmware/src/uavcan/Torque_handler.hpp
greck2908/robot-software
2e1e8177148a089e8883967375dde7f8ed3d878b
[ "MIT" ]
209
2016-09-21T21:54:28.000Z
2022-01-26T07:42:37.000Z
motor-control-firmware/src/uavcan/Torque_handler.hpp
greck2908/robot-software
2e1e8177148a089e8883967375dde7f8ed3d878b
[ "MIT" ]
21
2016-11-07T14:40:16.000Z
2021-11-02T09:53:37.000Z
#ifndef TORQUE_HANDLER_HPP #define TORQUE_HANDLER_HPP #include "uavcan_node.h" int Torque_handler_start(Node& node); #endif
15.75
37
0.81746
greck2908
c58fed8c8d5a08b6977399826871e6f95f7cdf70
5,719
cpp
C++
src_db/random_access_file/RandomAccessFile.cpp
alinous-core/codable-cash
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
[ "MIT" ]
1
2020-10-15T08:24:35.000Z
2020-10-15T08:24:35.000Z
src_db/random_access_file/RandomAccessFile.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
null
null
null
src_db/random_access_file/RandomAccessFile.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
null
null
null
/* * RandomAccessFile.cpp * * Created on: 2018/04/26 * Author: iizuka */ #include "random_access_file/RandomAccessFile.h" #include "base/UnicodeString.h" #include "base_io/File.h" #include "base_io_stream/exceptions.h" #include "random_access_file/MMapSegments.h" #include "random_access_file/MMapSegment.h" #include "random_access_file/DiskCacheManager.h" #include "base/StackRelease.h" #include "debug/debugMacros.h" namespace alinous { constexpr uint64_t RandomAccessFile::PAGE_NUM_CACHE; RandomAccessFile::RandomAccessFile(const File* file, DiskCacheManager* diskCacheManager) noexcept { this->position = 0; this->fileSize = 0; this->diskCacheManager = diskCacheManager; this->file = new File(*file); this->segments = nullptr; this->pageSize = Os::getSystemPageSize(); } RandomAccessFile::RandomAccessFile(const File* file, DiskCacheManager* diskCacheManager, uint64_t pageSize) noexcept { this->position = 0; this->fileSize = 0; this->diskCacheManager = diskCacheManager; this->file = new File(*file); this->segments = nullptr; this->pageSize = pageSize; } RandomAccessFile::~RandomAccessFile() noexcept { close(); delete this->file; } void RandomAccessFile::open(bool sync) { ERROR_POINT(L"RandomAccessFile::open") this->fd = Os::openFile2ReadWrite(this->file, sync); if(!this->fd.isOpened()){ throw new FileOpenException(__FILE__, __LINE__); } this->position = 0; this->fileSize = this->file->length(); uint64_t segmentSize = getSegmentSize(); this->segments = new MMapSegments(this->fileSize, segmentSize); if(this->fileSize == 0){ setLength(this->pageSize * PAGE_NUM_CACHE); } } void RandomAccessFile::close() noexcept { if(!this->fd.isOpened()){ return; } if(this->segments != nullptr){ this->segments->clearElements(this->diskCacheManager, this->fd); delete this->segments; this->segments = nullptr; } Os::closeFileDescriptor(&this->fd); } int RandomAccessFile::read(uint64_t fpos, char* buff, int count) { uint64_t segSize = getSegmentSize(); int count2Read = count; int currentfpos = fpos; while(count2Read > 0){ MMapSegment* seg = this->segments->getSegment(currentfpos, this->diskCacheManager, this->fd); MMapSegmentStackRelease dec(seg); uint64_t offset = currentfpos % segSize; char* ptr = seg->getPtr(offset); int cnt = seg->remains(offset); cnt = cnt > count2Read ? count2Read : cnt; Mem::memcpy(buff, ptr, cnt); count2Read -= cnt; currentfpos += cnt; buff += cnt; } return count; } #ifdef __TEST_CPP_UNIT__ static int errorHook(){ CAUSE_ERROR_BY_RETURN(L"RandomAccessFile::write", -1) return 0; } #endif int RandomAccessFile::write(uint64_t fpos, const char* buff, int count) { #ifdef __TEST_CPP_UNIT__ if(errorHook() < 0){ throw new FileIOException(__FILE__, __LINE__); } #endif uint64_t segSize = getSegmentSize(); int count2Write = count; int currentfpos = fpos; while(count2Write > 0){ // check capacity { uint64_t currentSize = this->fileSize; uint64_t writeEndPos = currentfpos + count2Write; if(writeEndPos >= currentSize){ uint64_t newLength = currentSize + this->pageSize * 4; setLength(newLength); } } MMapSegment* seg = this->segments->getSegment(currentfpos, this->diskCacheManager, this->fd); MMapSegmentStackRelease dec(seg); uint64_t offset = currentfpos % segSize; char* ptr = seg->getPtr(offset); int cnt = seg->remains(offset); cnt = cnt > count2Write ? count2Write : cnt; Mem::memcpy(ptr, buff, cnt); seg->setDirty(true); count2Write -= cnt; currentfpos += cnt; buff += cnt; } return count; } void RandomAccessFile::sync(bool flushDisk) { ERROR_POINT(L"RandomAccessFile::sync") this->segments->sync(flushDisk, this->fd); if(flushDisk){ int code = Os::syncFile(&this->fd); if(code < 0){ throw new FileIOException(L"Failed in synchronizing file.", __FILE__, __LINE__); } } } uint64_t RandomAccessFile::getSegmentSize() const noexcept { return this->pageSize * PAGE_NUM_CACHE; } void RandomAccessFile::setLength(uint64_t newLength) noexcept(false) { if(!this->fd.isOpened()){ UnicodeString* path = this->file->getAbsolutePath(); StackRelease<UnicodeString> r_path(path); UnicodeString msg(path); msg.append(L" is not opened at setLength()"); throw new FileIOException(msg.towString(), __FILE__, __LINE__); } if(newLength <= this->fileSize){ return; } uint64_t newSize = newLength - this->fileSize; const uint64_t numBlocks = newSize / this->pageSize; const uint64_t modBytes = newSize % this->pageSize; Os::seekFile(&this->fd, 0, Os::SeekOrigin::FROM_END); int n; char *tmp = new char[this->pageSize]{}; StackArrayRelease<char> t_tmp(tmp); ERROR_POINT(L"RandomAccessFile::setLength::01") for(int i = 0; i != numBlocks; ++i){ n = Os::write2File(&this->fd, tmp, this->pageSize); if(n != this->pageSize){ UnicodeString* path = this->file->getAbsolutePath(); StackRelease<UnicodeString> r_path(path); throw new FileIOException(path->towString(), __FILE__, __LINE__); } } ERROR_POINT(L"RandomAccessFile::setLength::02") n = Os::write2File(&this->fd, tmp, modBytes); if(n != modBytes){ UnicodeString* path = this->file->getAbsolutePath(); StackRelease<UnicodeString> r_path(path); throw new FileIOException(path->towString(), __FILE__, __LINE__); } this->fileSize = this->file->length(); this->segments->onResized(this->fileSize, this->fd, this->diskCacheManager); } MMapSegment* RandomAccessFile::getSegment(uint64_t fpos) noexcept(false) { return this->segments->getSegment(fpos, this->diskCacheManager, this->fd); } bool RandomAccessFile::exists() const noexcept { return this->file->exists(); } } /* namespace alinous */
24.440171
118
0.715335
alinous-core
c590c230a6c90ad6494de571cb3c2919d9261094
2,901
hpp
C++
include/picture.hpp
Andrew15-5/walk-game
550f4adeb4933fd298866cde0dd30dca11559334
[ "MIT" ]
null
null
null
include/picture.hpp
Andrew15-5/walk-game
550f4adeb4933fd298866cde0dd30dca11559334
[ "MIT" ]
null
null
null
include/picture.hpp
Andrew15-5/walk-game
550f4adeb4933fd298866cde0dd30dca11559334
[ "MIT" ]
null
null
null
#ifndef PICTURE_HPP #define PICTURE_HPP #include "include/texture_functions.hpp" #include "include/vector2.hpp" #include "include/vector3.hpp" #include <IL/il.h> #include <IL/ilu.h> class Picture { GLuint texture_id; Vector2 size; Vector3 position; GLfloat angle; const std::string texture_path = "res/textures"; void load_texture(const std::string &path) { ilLoadImage(path.c_str()); ILinfo image_info; iluGetImageInfo(&image_info); iluFlipImage(); size.x = image_info.Width; size.y = image_info.Height; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, size.x, size.y, 0, GL_RGB, GL_UNSIGNED_BYTE, ilGetData()); ilDeleteImage(texture_id); } public: Picture(std::string texture_file_name, GLfloat x = 0, GLfloat y = 0, GLfloat z = 0) { texture_id = ::texture_id.last + 1; position = Vector3(x, y, z); angle = M_PI / 2; load_texture(texture_path + '/' + texture_file_name); } Vector3 get_position() { return position; } GLuint get_texture_id() { return texture_id; } Vector2 get_size() { return size; } void set_angle_rad(GLfloat angle) { this->angle = angle; } void set_angle_deg(GLfloat angle) { this->angle = angle / 180 * M_PI; } void set_position(GLfloat x, GLfloat y, GLfloat z) { position = Vector3(x, y, z); } void set_size(GLfloat width, GLfloat height) { size = Vector2(width, height); } void draw() { change_current_texture(texture_id); glNormal3f(0.0f, 0.0f, 1.0f); Vector3 look_vector(sin(angle), 0, -cos(angle)); Vector3 up_vector = Vector3(0, 1, 0); Vector3 right_vector = look_vector.cross(up_vector); GLfloat half_length = size.x * 0.5f; GLfloat half_height = size.y * 0.5f; glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex3f(position.x - right_vector.x * half_length, position.y - half_height, position.z - right_vector.z * half_length); glTexCoord2f(1.0f, 0.0f); glVertex3f(position.x + right_vector.x * half_length, position.y - half_height, position.z + right_vector.z * half_length); glTexCoord2f(1.0f, 1.0f); glVertex3f(position.x + right_vector.x * half_length, position.y + half_height, position.z + right_vector.z * half_length); glTexCoord2f(0.0f, 1.0f); glVertex3f(position.x - right_vector.x * half_length, position.y + half_height, position.z - right_vector.z * half_length); glEnd(); if (texture_id) disable_texture(); } }; #endif
28.165049
89
0.599104
Andrew15-5
c590e975c9615eaa7016c5d2b80dd1a7528eefa5
1,254
cpp
C++
UnicornRender/source/Loggers.cpp
GrapefruitTechnique/R7
3eaa97ac63bbc1b42e4cabf97d4d12649e36f665
[ "MIT" ]
12
2017-02-18T15:17:53.000Z
2020-02-03T16:20:33.000Z
UnicornRender/source/Loggers.cpp
GrapefruitTechnique/R7
3eaa97ac63bbc1b42e4cabf97d4d12649e36f665
[ "MIT" ]
93
2017-02-15T21:05:31.000Z
2020-08-19T06:46:27.000Z
UnicornRender/source/Loggers.cpp
GrapefruitTechnique/R-7
3eaa97ac63bbc1b42e4cabf97d4d12649e36f665
[ "MIT" ]
4
2015-10-23T11:55:07.000Z
2016-11-30T10:00:52.000Z
#include <unicorn/Loggers.hpp> #include <unicorn/utility/InternalLoggers.hpp> #include <algorithm> #include <cassert> namespace unicorn { std::array<mule::LoggerPtr, Log::size> g_loggers; namespace { static std::array<char const*, Log::size> s_logger_names = {{ "unicorn" , "unicorn_profile" , "unicorn_input" , "unicorn_video" , "unicorn_vulkan" }}; } std::vector<std::string> Loggers::GetDefaultLoggerNames() const { std::vector<std::string> result; result.reserve(Log::size); std::transform( s_logger_names.begin(), s_logger_names.end() , std::back_inserter(result) , [](char const* name) -> std::string { return std::string(name); } ); return result; } Loggers::Loggers() : mule::LoggerConfigBase(Log::size) , mule::templates::Singleton<Loggers>() { } void Loggers::InitializeLogger(uint32_t index, Settings const& settings) { assert(index < Log::size); g_loggers[index] = std::make_shared<mule::Logger>( (!settings.name.empty() ? settings.name : s_logger_names[index]) , settings.sinks.begin() , settings.sinks.end() ); g_loggers[index]->SetLevel(settings.level); g_loggers[index]->SetPattern(settings.pattern); } }
19.904762
75
0.655502
GrapefruitTechnique
c590f4d58677b8f942caa6dbedd7c45ffd3527c0
15,483
cpp
C++
StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996.cpp
TetrisAI/StandardTetris
b5cbe25541ceb45517472fe7feabea0c81fd55b0
[ "MIT" ]
7
2016-11-28T13:42:44.000Z
2021-08-05T02:34:11.000Z
StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996.cpp
PowerOlive/StandardTetris
b5cbe25541ceb45517472fe7feabea0c81fd55b0
[ "MIT" ]
null
null
null
StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996.cpp
PowerOlive/StandardTetris
b5cbe25541ceb45517472fe7feabea0c81fd55b0
[ "MIT" ]
8
2015-07-31T02:53:14.000Z
2020-04-12T04:36:23.000Z
// All contents of this file written by Colin Fahey ( http://colinfahey.com ) // 2007 June 4 ; Visit web site to check for any updates to this file. #include "CPF.StandardTetris.STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996.h" #include "CPF.StandardTetris.STBoard.h" #include "CPF.StandardTetris.STPiece.h" #include <stdlib.h> // Disable unimportant "symbol too long" error for debug builds of STL string #pragma warning( disable : 4786 ) #include <string> #include <vector> using namespace std; namespace CPF { namespace StandardTetris { string STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::GetStrategyName ( ) { return ((string)"Roger LLima, Laurent Bercot, Sebastien Blondeel (one-piece, 1996)"); } // WARNING: Moves requiring rotation must wait until piece has fallen by // at least one row! // Perform all rotations, and then perform translations. This // avoids the problem of getting the piece jammed on the sides // of the board where rotation is impossible. *** // Also, the following strategy does not take advantage of the // possibility of using free-fall and future movements to // slide under overhangs and fill them in. void STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::GetBestMoveOncePerPiece ( STBoard & board, STPiece & piece, int nextPieceFlag, // 0 == no next piece available or known int nextPieceShape, // 0 == no piece available or known int & bestRotationDelta, // 0 or {0,1,2,3} int & bestTranslationDelta // 0 or {...,-2,-1,0,1,2,...} ) { // We are given the current board, and the current piece // configuration. Our goal is to evaluate various possible // moves and return the best move we explored. // Clear suggested move values to "do nothing" values. bestRotationDelta = 0; bestTranslationDelta = 0; // ONE-PLY Analysis STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::PrivateStrategy ( 0, // Not called from parent ply; Just this one ply. board, piece, bestRotationDelta, // 0 or {0,1,2,3} bestTranslationDelta // 0 or {...,-2,-1,0,1,2,...} ); } float STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::PrivateStrategy ( int flagCalledFromParentPly, // True if called from a parent level STBoard & board, STPiece & piece, int & bestRotationDelta, // 0 or {0,1,2,3} int & bestTranslationDelta // 0 or {...,-2,-1,0,1,2,...} ) { // If board or piece is invalid, return. if (0 == board.IsValid()) return(0.0f); if (0 == piece.IsValid()) return(0.0f); // Get dimensions of board int width = 0; int height = 0; width = board.GetWidth(); height = board.GetHeight(); int currentBestTranslationDelta = 0; int currentBestRotationDelta = 0; float currentBestMerit = (-1.0e20f); int currentBestPriority = 0; int trialTranslationDelta = 0; int trialRotationDelta = 0; float trialMerit = 0.0f; int trialPriority = 0; int maxOrientations = 0; int moveAcceptable = 0; int count = 0; STBoard tempBoard; STPiece tempPiece; maxOrientations = STPiece::GetMaxOrientations( piece.GetKind() ); for ( trialRotationDelta = 0; trialRotationDelta < maxOrientations; trialRotationDelta++ ) { // Make temporary copy of piece, and rotate the copy. tempPiece.CopyFromPiece( piece ); for ( count = 0; count < trialRotationDelta; count++ ) { tempPiece.Rotate(); } // Determine the translation limits for this rotated piece. int moveIsPossible = 0; int minDeltaX = 0; int maxDeltaX = 0; board.DetermineAccessibleTranslationsForPieceOrientation ( tempPiece, moveIsPossible, // OUT: 0==NONE POSSIBLE minDeltaX, // Left limit maxDeltaX // Right limit ); // Consider all allowed translations for the current rotation. if (moveIsPossible) { for ( trialTranslationDelta = minDeltaX; trialTranslationDelta <= maxDeltaX; trialTranslationDelta++ ) { // Evaluate this move // Copy piece to temp and rotate and translate tempPiece.CopyFromPiece( piece ); for ( count = 0; count < trialRotationDelta; count++ ) { tempPiece.Rotate(); } tempPiece.Translate( trialTranslationDelta, 0 ); moveAcceptable = board.IsGoalAcceptable( tempPiece ); if (0 != moveAcceptable) { // Since the piece can be (not necessarily GET) at the goal // horizontal translation and orientation, it's worth trying // out a drop and evaluating the move. tempBoard.CopyFromBoard( board ); int dropDistance = 0; dropDistance = tempPiece.GetY(); tempBoard.FullDropAndAddPieceToBoard( tempPiece ); dropDistance -= tempPiece.GetY(); trialMerit = STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::PrivateStrategyEvaluate ( tempBoard, dropDistance ); trialPriority = 0; // Pierre Dellacherie's Move Priority // Adding the following, taken from Pierre Dellacherie's research, // dramatically improves the performance of Roger Espel Llima's // algorithm -- but keep in mind that ANYTHING borrowed from // Pierre Dellacherie's algorithm would improve an inferior // algorithm! /* trialPriority += 16 * abs( temp_Piece.GetX() - TempBoard.GetPieceSpawnX() ); if (temp_Piece.GetX() < TempBoard.GetPieceSpawnX()) trialPriority -= 8; trialPriority -= (trialRotationDelta); */ // If this move is better than any move considered before, // or if this move is equally ranked but has a higher priority, // then update this to be our best move. if ( (trialMerit > currentBestMerit) || ((trialMerit == currentBestMerit) && (trialPriority > currentBestPriority)) ) { currentBestPriority = trialPriority; currentBestMerit = trialMerit; currentBestTranslationDelta = trialTranslationDelta; currentBestRotationDelta = trialRotationDelta; } } } } } // Commit to this move bestTranslationDelta = currentBestTranslationDelta; bestRotationDelta = currentBestRotationDelta; return( currentBestMerit ); } // The following one-ply board evaluation function is adapted from the // "xtris" application (multi-player Tetris for the X Window system), // created by Roger Espel Llima <roger.espel.llima@pobox.com> // // From the "xtris" documentation: // // "The values for the coefficients were obtained with a genetic algorithm // using a population of 50 sets of coefficients, calculating 18 generations // in about 500 machine-hours distributed among 20-odd Sparc workstations. // This resulted in an average of about 50,000 completed lines." // // The following people contributed "ideas for the bot's decision algorithm": // // Laurent Bercot <Laurent.Bercot@ens.fr> // Sebastien Blondeel <Sebastien.Blondeel@ens.fr> // // // The algorithm computes 6 values on the whole pile: // // [1] height = max height of the pieces in the pile // [2] holes = number of holes (empty positions with a full position somewhere // above them) // [3] frontier = length of the frontier between all full and empty zones // (for each empty position, add 1 for each side of the position // that touches a border or a full position). // [4] drop = how far down we're dropping the current brick // [5] pit = sum of the depths of all places where a long piece ( ====== ) // would be needed. // [6] ehole = a kind of weighted sum of holes that attempts to calculate // how hard they are to fill. // // droppedPieceRow is the row where we're dropping the piece, // which is already in the board. Note that full lines have not been // dropped, so we need to do special tests to skip them. float STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::PrivateStrategyEvaluate ( STBoard & board, int pieceDropDistance ) { int coeff_f = 260; int coeff_height = 110; int coeff_hole = 450; int coeff_y = 290; int coeff_pit = 190; int coeff_ehole = 80; int width = 0; int height = 0; width = board.GetWidth(); height = board.GetHeight(); int lineCellTotal [ (1 + 20 + 200) ]; // HACK: Should be dynamic! int lin [ (1 + 20 + 200) ]; // HACK: Should be dynamic! int hol [ (1 + 10 + 200) * (1 + 20 + 400) ]; // HACK: Should be dynamic! int blockedS [ (1 + 10 + 200) ]; // HACK: Should be dynamic! // If width is greater than 200, or height is greater than 400, // just give up. I'd rather not use malloc() for Roger's algorithm. // Really, this algorithm needs to be repaired to avoid the use of // memory! if (width > 200) return(0.0f); if (height > 400) return(0.0f); int x = 0; int y = 0; // ****** NOTE: ALL ARRAYS ARE ACCESSED WITH 0 BEING FIRST ELEMENT ******** // Fill lineCellTotal[] with total cells in each row. for ( y = 1; y <= height; y++ ) { lineCellTotal[ (y-1) ] = 0; for ( x = 1; x <= width; x++ ) { if (board.GetCell( x, y ) > 0) lineCellTotal[ (y-1) ]++; } } // Clobber blocked column array for ( x = 1; x <= width; x++ ) { blockedS[ (x-1) ] = (-1); } // Clear Lin array. for ( y = 1; y <= height; y++ ) { lin[ (y-1) ] = 0; } // Embedded Holes int eHoles = 0; for ( y = height; y >= 1; y-- ) // Top-to-Bottom { for ( x = 1; x <= width; x++ ) { if (board.GetCell( x, y ) > 0) { hol [ (width * (y-1)) + (x-1) ] = 0; blockedS[ (x-1) ] = y; } else { hol [ (width * (y-1)) + (x-1) ] = 1; if (blockedS[ (x-1) ] >= 0) { int y2 = 0; y2 = blockedS[ (x-1) ]; // If this more than two rows ABOVE current row, set // to exactly two rows above. if (y2 > (y + 2)) { y2 = (y + 2); } // Descend to current row for ( ; y2 > y; y2-- ) { if (board.GetCell( x, y2 ) > 0) { hol[ (width * (y-1)) + (x-1) ] += lin[ (y2-1) ]; } } } lin[ (y-1) ] += hol[ (width * (y-1)) + (x-1) ]; eHoles += hol[ (width * (y-1)) + (x-1) ]; } } } // Determine Max Height int maxHeight = 0; for ( x = 1; x <= width; x++ ) { for ( y = height; y >= 1; y-- ) // Top-to-Bottom { // If line is complete, ignore it for Max Height purposes... if (width == lineCellTotal[ (y-1) ]) continue; if ( (y > maxHeight) && (board.GetCell( x, y ) > 0) ) { maxHeight = y; } } } // Count buried holes int holes = 0; int blocked = 0; for ( x = 1; x <= width; x++ ) { blocked = 0; for ( y = height; y >= 1; y-- ) // Top-to-Bottom { // If line is complete, skip it! if (width == lineCellTotal[ (y-1) ]) continue; if (board.GetCell( x, y ) > 0) { blocked = 1; // We encountered an occupied cell; all below is blocked } else { // All of the following is in the context of the cell ( x, y ) // being UN-occupied. // If any upper row had an occupied cell in this column, this // unoccupied cell is considered blocked. if (blocked) { holes++; // This unoccupied cell is buried; it's a hole. } } } } // Count Frontier int frontier = 0; for ( x = 1; x <= width; x++ ) { for ( y = height; y >= 1; y-- ) // Top-to-Bottom { // If line is complete, skip it! if (width == lineCellTotal[ (y-1) ]) continue; if (0 == board.GetCell( x, y )) { // All of the following is in the context of the cell ( x, y ) // being UN-occupied. // If row is not the top, and row above this one is occupied, // then this unoccupied cell counts as a frontier. if ( (y < height) && (board.GetCell( x, (y + 1) ) > 0) ) { frontier++; } // If this row is not the bottom, and the row below is occupied, // this unoccupied cell counts as a frontier. if ( (y > 1) && (board.GetCell( x, (y - 1) ) > 0) ) { frontier++; } // If the column is not the first, and the column to the left is // occupied, then this unoccupied cell counts as a frontier. // Or, if this *is* the left-most cell, it is an automatic frontier. // (since the beyond the board is in a sense "occupied") if ( ((x > 1) && (board.GetCell( x - 1, y ) > 0)) || (1 == x) ) { frontier++; } // If the column is not the right-most, and the column to the right is // occupied, then this unoccupied cell counts as a frontier. // Or, if this *is* the right-most cell, it is an automatic frontier. // (since the beyond the board is in a sense "occupied") if ( ((x < width) && (board.GetCell( x + 1, y ) > 0)) || (width == x) ) { frontier++; } } } } int v = 0; for ( x = 1; x <= width; x++ ) { // NOTE: The following seems to descend as far as a 2-column-wide // profile can fall for each column. // Scan Top-to-Bottom y = height; while ( // Line is not below bottom row... (y >= 1) && // Cell is unoccupied or line is full... ( (0 == board.GetCell( x, y )) || (width == lineCellTotal[ (y-1) ]) ) && ( // (Not left column AND (left is empty OR line full)) ((x > 1) && ((0 == board.GetCell( x - 1, y )) || (width == lineCellTotal[ (y-1) ]))) || // ...OR... // (Not right column AND (right is empty OR line full)) ((x < width) && ((0 == board.GetCell( x + 1, y )) || (width == lineCellTotal[ (y-1) ])))) ) { y--; // Descend } // Count how much further we can fall just considering obstacles // in our column. int p = 0; p = 0; for ( ; ((y >= 1) && (0 == board.GetCell( x, y ))); y--, p++ ) ; // If this is a deep well, it's worth punishing. if (p >= 2) { v -= (coeff_pit * ( p - 1 )); } } float rating = 0.0f; rating = (float)(v); rating -= (float)(coeff_f * frontier ); rating -= (float)(coeff_height * maxHeight ); rating -= (float)(coeff_hole * holes ); rating -= (float)(coeff_ehole * eHoles ); rating += (float)(coeff_y * pieceDropDistance ); // Reward drop depth! return( rating ); } } }
24.57619
97
0.564942
TetrisAI
c59528f6199ab531fc6e2039c5b782c1789c25dd
2,538
cpp
C++
src/condor_collector.V6/collector_main.cpp
clalancette/condor-dcloud
70d1b1896ea0e5cfb4f051c7fb73cf4d12cd9727
[ "Apache-2.0" ]
2
2018-06-18T23:11:20.000Z
2021-01-11T06:30:00.000Z
src/condor_collector.V6/collector_main.cpp
clalancette/condor-dcloud
70d1b1896ea0e5cfb4f051c7fb73cf4d12cd9727
[ "Apache-2.0" ]
null
null
null
src/condor_collector.V6/collector_main.cpp
clalancette/condor-dcloud
70d1b1896ea0e5cfb4f051c7fb73cf4d12cd9727
[ "Apache-2.0" ]
1
2021-08-29T14:03:53.000Z
2021-08-29T14:03:53.000Z
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "condor_debug.h" #include "view_server.h" #include "subsystem_info.h" #if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT) #if defined(HAVE_DLOPEN) #include "CollectorPlugin.h" #endif #endif //------------------------------------------------------------- // about self DECL_SUBSYSTEM("COLLECTOR", SUBSYSTEM_TYPE_COLLECTOR ); // the heart of the collector ... CollectorDaemon* Daemon; //------------------------------------------------------------- void usage(char* name) { dprintf(D_ALWAYS,"Usage: %s [-f] [-b] [-t] [-p <port>]\n",name ); exit( 1 ); } //------------------------------------------------------------- void main_init(int argc, char *argv[]) { // handle collector-specific command line args if(argc > 2) { usage(argv[0]); } Daemon=new ViewServer(); Daemon->Init(); #if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT) #if defined(HAVE_DLOPEN) CollectorPluginManager::Load(); CollectorPluginManager::Initialize(); #endif #endif } //------------------------------------------------------------- void main_config() { Daemon->Config(); } //------------------------------------------------------------- void main_shutdown_fast() { Daemon->Exit(); #if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT) #if defined(HAVE_DLOPEN) CollectorPluginManager::Shutdown(); #endif #endif DC_Exit(0); } //------------------------------------------------------------- void main_shutdown_graceful() { Daemon->Shutdown(); #if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT) #if defined(HAVE_DLOPEN) CollectorPluginManager::Shutdown(); #endif #endif DC_Exit(0); } void main_pre_dc_init( int argc, char* argv[] ) { } void main_pre_command_sock_init( ) { }
22.263158
75
0.576044
clalancette
c5984c9becabf026deb1fb70e3e29fa9e35d81d6
564
hpp
C++
include/io/IOBase.hpp
get9/sipl
ae139f25516aed54f0e04c72288198850f48298a
[ "Apache-2.0" ]
1
2019-10-17T12:05:18.000Z
2019-10-17T12:05:18.000Z
include/io/IOBase.hpp
get9/sipl
ae139f25516aed54f0e04c72288198850f48298a
[ "Apache-2.0" ]
1
2016-03-03T17:39:54.000Z
2016-03-05T08:48:17.000Z
include/io/IOBase.hpp
get9/sipl
ae139f25516aed54f0e04c72288198850f48298a
[ "Apache-2.0" ]
null
null
null
#pragma once #ifndef SIPL_IO_IOBASE_HPP #define SIPL_IO_IOBASE_HPP #include <stdexcept> #include <string> namespace sipl { // Current supported file types enum class FileType { PGM, PPM, BMP, UNKNOWN }; // From: http://stackoverflow.com/a/8152888 class IOException : public std::exception { public: explicit IOException(const char* msg) : msg_(msg) {} explicit IOException(const std::string& msg) : msg_(msg) {} virtual const char* what() const noexcept { return msg_.c_str(); } protected: std::string msg_; }; class IOBase { }; } #endif
16.114286
70
0.703901
get9
c598b41954851370883a4876885e36af02fa6e61
2,857
cc
C++
src/eic_evgen/reaction_routine.cc
sjdkay/DEMPGen
a357cfcd89978db3323435111cb1e327b191352d
[ "MIT" ]
null
null
null
src/eic_evgen/reaction_routine.cc
sjdkay/DEMPGen
a357cfcd89978db3323435111cb1e327b191352d
[ "MIT" ]
1
2022-03-07T21:30:26.000Z
2022-03-07T21:30:26.000Z
src/eic_evgen/reaction_routine.cc
sjdkay/DEMPGen
a357cfcd89978db3323435111cb1e327b191352d
[ "MIT" ]
3
2022-03-07T21:19:40.000Z
2022-03-10T15:37:25.000Z
///*--------------------------------------------------*/ /// Reaction_routine.cc /// /// Creator: Wenliang (Bill) Li /// Date: Mar 12 2020 /// Email: wenliang.billlee@gmail.com /// /// Comment: Mar 12, 2020: Subroutine Exclusive_Omega_Prodoction is created /// modeled off the Exclusive_Omega_Prodoction routine written by /// A. Zafar /// #include "reaction_routine.h" #include "eic.h" #include "particleType.h" using namespace std; /*--------------------------------------------------*/ /// Reaction Reaction::Reaction(TString particle_str) { rParticle = particle_str; cout << "Produced particle is: " << GetParticle() << endl; cout << "Generated process: e + p -> e' + p' + " << GetParticle() << endl; tTime.Start(); cout << "/*--------------------------------------------------*/" << endl; cout << "Starting setting up process" << endl; cout << endl; TDatime dsTime; cout << "Start Time: " << dsTime.GetHour() << ":" << dsTime.GetMinute() << endl; } // SJDK 09/02/22 - New reaction where the particle and hadron are specified Reaction::Reaction(TString particle_str, TString hadron_str) { rParticle = particle_str; rHadron = hadron_str; cout << "Produced particle is: " << GetParticle() << endl; cout << "Produced hadron is: " << GetHadron() << endl; cout << "Generated process: e + p -> e'+ " << GetHadron() << " + " << GetParticle() << endl; tTime.Start(); cout << "/*--------------------------------------------------*/" << endl; cout << "Starting setting up process" << endl; cout << endl; TDatime dsTime; cout << "Start Time: " << dsTime.GetHour() << ":" << dsTime.GetMinute() << endl; } Reaction::Reaction(){}; Reaction::~Reaction() { // ppiOut.close(); // ppiDetails.close(); cout << endl; cout << "Ending the process" << endl; cout << "/*--------------------------------------------------*/" << endl; tTime.Stop(); tTime.Print(); TDatime deTime; cout << "End Time: " << deTime.GetHour() << ":" << deTime.GetMinute() << endl; } /*--------------------------------------------------*/ /// void Reaction::process_reaction() { if (rParticle == "Pi+") { PiPlus_Production* rr1 = new PiPlus_Production(rParticle); rr1->process_reaction(); delete rr1; } else if (rParticle == "Pi0") { // Pi0_Production* r1 = new Pi0_Production("Eta"); Pi0_Production* rr1 = new Pi0_Production(rParticle); rr1->process_reaction(); delete rr1; } // 09/02/22 - SJDK - K+ production, initialises with particle and hadron specified else if (rParticle == "K+") { KPlus_Production* rr1 = new KPlus_Production(rParticle, rHadron); rr1->process_reaction(); delete rr1; } // SJDK - 08/02/22 - Deleted large block of commented code that was below, was only there as reference? }
28.57
105
0.547427
sjdkay
c59eec8d9e32e294c484a57dbba628de6cab8f2a
763
cpp
C++
src/band_list.cpp
peterus/ESP32_WSPR
979ba33f855141ac85dbbf7ac3606bdb06301985
[ "MIT" ]
null
null
null
src/band_list.cpp
peterus/ESP32_WSPR
979ba33f855141ac85dbbf7ac3606bdb06301985
[ "MIT" ]
null
null
null
src/band_list.cpp
peterus/ESP32_WSPR
979ba33f855141ac85dbbf7ac3606bdb06301985
[ "MIT" ]
null
null
null
#include "band_list.h" String BandConfig::getName() const { return _name; } BandConfig::BandConfig(String const &name, ConfigBool *enable, ConfigInt *frequency) { _name = name; _enable = enable; _frequency = frequency; } bool BandConfig::isEnabled() const { return _enable->getValue(); } long BandConfig::getFrequency() const { return _frequency->getValue(); } BandList::BandList() : _nextEntry(_frequencyList.begin()) { } void BandList::add(BandConfig frequency) { _frequencyList.push_back(frequency); _nextEntry = _frequencyList.begin(); } BandConfig BandList::getNext() { BandConfig value = *_nextEntry; _nextEntry++; if (_nextEntry == _frequencyList.end()) { _nextEntry = _frequencyList.begin(); } return value; }
20.621622
86
0.706422
peterus
c5a4ccc2bb96d10ddec421b138061ef514cdbe68
4,018
cpp
C++
OpenSees/SRC/tcl/tkAppInit.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
8
2019-03-05T16:25:10.000Z
2020-04-17T14:12:03.000Z
SRC/tcl/tkAppInit.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
null
null
null
SRC/tcl/tkAppInit.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
3
2019-09-21T03:11:11.000Z
2020-01-19T07:29:37.000Z
/* * tkAppInit.c -- * * Provides a default version of the Tcl_AppInit procedure for * use in wish and similar Tk-based applications. * * Copyright (c) 1993 The Regents of the University of California. * Copyright (c) 1994-1997 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) $Id: tkAppInit.cpp,v 1.7 2009-01-16 19:40:36 fmk Exp $ */ extern "C" { #include "tk.h" #include "locale.h" } extern void Tk_MainOpenSees(int argc, char **argv, Tcl_AppInitProc *appInitProc, Tcl_Interp *interp); #include "commands.h" /* * The following variable is a special hack that is needed in order for * Sun shared libraries to be used for Tcl. */ #ifdef _UNIX //extern "C" int matherr(); //int *tclDummyMathPtr = (int *) matherr; #endif #ifdef TK_TEST extern "C" int Tcltest_Init _ANSI_ARGS_((Tcl_Interp *interp)); extern "C" int Tktest_Init _ANSI_ARGS_((Tcl_Interp *interp)); #endif /* TK_TEST */ /* *---------------------------------------------------------------------- * * main -- * * This is the main program for the application. * * Results: * None: Tk_Main never returns here, so this procedure never * returns either. * * Side effects: * Whatever the application does. * *---------------------------------------------------------------------- */ int main(int argc, char **argv) { /* * The following #if block allows you to change the AppInit * function by using a #define of TCL_LOCAL_APPINIT instead * of rewriting this entire file. The #if checks for that * #define and uses Tcl_AppInit if it doesn't exist. */ #ifndef TK_LOCAL_APPINIT #define TK_LOCAL_APPINIT Tcl_AppInit #endif /* extern int TK_LOCAL_APPINIT _ANSI_ARGS_((Tcl_Interp *interp)); */ /* * The following #if block allows you to change how Tcl finds the startup * script, prime the library or encoding paths, fiddle with the argv, * etc., without needing to rewrite Tk_Main() */ #ifdef TK_LOCAL_MAIN_HOOK extern int TK_LOCAL_MAIN_HOOK _ANSI_ARGS_((int *argc, char ***argv)); TK_LOCAL_MAIN_HOOK(&argc, &argv); #endif Tk_MainOpenSees(argc, argv, TK_LOCAL_APPINIT, Tcl_CreateInterp()); return 0; /* Needed only to prevent compiler warning. */ } /* *---------------------------------------------------------------------- * * Tcl_AppInit -- * * This procedure performs application-specific initialization. * Most applications, especially those that incorporate additional * packages, will have their own version of this procedure. * * Results: * Returns a standard Tcl completion code, and leaves an error * message in the interp's result if an error occurs. * * Side effects: * Depends on the startup script. * *---------------------------------------------------------------------- */ int Tcl_AppInit(Tcl_Interp *interp) { if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Tk_Init(interp) == TCL_ERROR) { return TCL_ERROR; } Tcl_StaticPackage(interp, "Tk", Tk_Init, Tk_SafeInit); /* * Call the init procedures for included packages. Each call should * look like this: * * if (Mod_Init(interp) == TCL_ERROR) { * return TCL_ERROR; * } * * where "Mod" is the name of the module. */ /* * Call Tcl_CreateCommand for application-specific commands, if * they weren't already created by the init procedures called above. */ if (OpenSeesAppInit(interp) < 0) return TCL_ERROR; /* * Specify a user-specific startup file to invoke if the application * is run interactively. Typically the startup file is "~/.apprc" * where "app" is the name of the application. If this line is deleted * then no user-specific startup file will be run under any conditions. */ Tcl_SetVar(interp, "tcl_rcFileName", "~/.wishrc", TCL_GLOBAL_ONLY); return TCL_OK; }
26.609272
89
0.630164
kuanshi